from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers.models.swin.modeling_tf_swin import (
         TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
         TFSwinForImageClassification,
         TFSwinForMaskedImageModeling,
         TFSwinModel,
     )


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Any			,			_lowerCAmelCase					:     List[str]			,			_lowerCAmelCase					:     List[str]=13			,			_lowerCAmelCase					:     Optional[int]=32			,			_lowerCAmelCase					:     Any=2			,			_lowerCAmelCase					:     Dict=3			,			_lowerCAmelCase					:     int=16			,			_lowerCAmelCase					:     List[Any]=[1, 2, 1]			,			_lowerCAmelCase					:     List[Any]=[2, 2, 4]			,			_lowerCAmelCase					:     Union[str, Any]=2			,			_lowerCAmelCase					:     Dict=2.0			,			_lowerCAmelCase					:     List[str]=True			,			_lowerCAmelCase					:     Any=0.0			,			_lowerCAmelCase					:     List[str]=0.0			,			_lowerCAmelCase					:     Optional[Any]=0.1			,			_lowerCAmelCase					:     Optional[int]="gelu"			,			_lowerCAmelCase					:     int=False			,			_lowerCAmelCase					:     Tuple=True			,			_lowerCAmelCase					:     List[Any]=0.02			,			_lowerCAmelCase					:     List[str]=1e-5			,			_lowerCAmelCase					:     Tuple=True			,			_lowerCAmelCase					:     Tuple=None			,			_lowerCAmelCase					:     List[Any]=True			,			_lowerCAmelCase					:     str=10			,			_lowerCAmelCase					:     str=8			,			):
           __snake_case       :				int 			=    parent
           __snake_case       :				List[Any] 			=    batch_size
           __snake_case       :				Any 			=    image_size
           __snake_case       :				str 			=    patch_size
           __snake_case       :				Optional[int] 			=    num_channels
           __snake_case       :				Union[str, Any] 			=    embed_dim
           __snake_case       :				Union[str, Any] 			=    depths
           __snake_case       :				Optional[Any] 			=    num_heads
           __snake_case       :				str 			=    window_size
           __snake_case       :				Any 			=    mlp_ratio
           __snake_case       :				Optional[int] 			=    qkv_bias
           __snake_case       :				Union[str, Any] 			=    hidden_dropout_prob
           __snake_case       :				Tuple 			=    attention_probs_dropout_prob
           __snake_case       :				int 			=    drop_path_rate
           __snake_case       :				Optional[int] 			=    hidden_act
           __snake_case       :				Any 			=    use_absolute_embeddings
           __snake_case       :				List[str] 			=    patch_norm
           __snake_case       :				List[Any] 			=    layer_norm_eps
           __snake_case       :				int 			=    initializer_range
           __snake_case       :				List[str] 			=    is_training
           __snake_case       :				Any 			=    scope
           __snake_case       :				Any 			=    use_labels
           __snake_case       :				Dict 			=    type_sequence_label_size
           __snake_case       :				str 			=    encoder_stride

       def 			snake_case__    (							self					:     Optional[int]			):
           __snake_case       :				int 			=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

           __snake_case       :				str 			=    None
           if self.use_labels:
               __snake_case       :				str 			=    ids_tensor([self.batch_size]			,			self.type_sequence_label_size			)

           __snake_case       :				int 			=    self.get_config()

           return config, pixel_values, labels

       def 			snake_case__    (							self					:     List[Any]			):
           return SwinConfig(
               image_size=self.image_size			,			patch_size=self.patch_size			,			num_channels=self.num_channels			,			embed_dim=self.embed_dim			,			depths=self.depths			,			num_heads=self.num_heads			,			window_size=self.window_size			,			mlp_ratio=self.mlp_ratio			,			qkv_bias=self.qkv_bias			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			drop_path_rate=self.drop_path_rate			,			hidden_act=self.hidden_act			,			use_absolute_embeddings=self.use_absolute_embeddings			,			path_norm=self.patch_norm			,			layer_norm_eps=self.layer_norm_eps			,			initializer_range=self.initializer_range			,			encoder_stride=self.encoder_stride			,			)

       def 			snake_case__    (							self					:     Any			,			_lowerCAmelCase					:     Union[str, Any]			,			_lowerCAmelCase					:     List[str]			,			_lowerCAmelCase					:     List[str]			):
           __snake_case       :				Optional[Any] 			=    TFSwinModel(config=_lowerCAmelCase			)
           __snake_case       :				List[Any] 			=    model(_lowerCAmelCase			)

           __snake_case       :				Tuple 			=    ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
           __snake_case       :				Any 			=    int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

           self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, expected_seq_len, expected_dim)			)

       def 			snake_case__    (							self					:     List[Any]			,			_lowerCAmelCase					:     List[str]			,			_lowerCAmelCase					:     List[Any]			,			_lowerCAmelCase					:     str			):
           __snake_case       :				Optional[int] 			=    TFSwinForMaskedImageModeling(config=_lowerCAmelCase			)
           __snake_case       :				Tuple 			=    model(_lowerCAmelCase			)
           self.parent.assertEqual(
               result.logits.shape			,			(self.batch_size, self.num_channels, self.image_size, self.image_size)			)

           # test greyscale images
           __snake_case       :				List[Any] 			=    1
           __snake_case       :				List[Any] 			=    TFSwinForMaskedImageModeling(_lowerCAmelCase			)

           __snake_case       :				Dict 			=    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
           __snake_case       :				List[str] 			=    model(_lowerCAmelCase			)
           self.parent.assertEqual(result.logits.shape			,			(self.batch_size, 1, self.image_size, self.image_size)			)

       def 			snake_case__    (							self					:     Optional[Any]			,			_lowerCAmelCase					:     Optional[int]			,			_lowerCAmelCase					:     Tuple			,			_lowerCAmelCase					:     Any			):
           __snake_case       :				Dict 			=    self.type_sequence_label_size
           __snake_case       :				Dict 			=    TFSwinForImageClassification(_lowerCAmelCase			)
           __snake_case       :				Union[str, Any] 			=    model(_lowerCAmelCase			,			labels=_lowerCAmelCase			)
           self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.type_sequence_label_size)			)

           # test greyscale images
           __snake_case       :				List[Any] 			=    1
           __snake_case       :				Optional[int] 			=    TFSwinForImageClassification(_lowerCAmelCase			)
           __snake_case       :				List[str] 			=    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
           __snake_case       :				List[str] 			=    model(_lowerCAmelCase			)
           self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.type_sequence_label_size)			)





       def 			snake_case__    (							self					:     Dict			):
           __snake_case       :				Optional[int] 			=    self.prepare_config_and_inputs()
           __snake_case			, __snake_case			, __snake_case       :				Union[str, Any] 			=    config_and_inputs
           __snake_case       :				List[Any] 			=    {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_tf
class      SCREAMING_SNAKE_CASE__					(  __UpperCamelCase   ,							__UpperCamelCase   ,							unittest.TestCase    ):
       A							:	List[Any]          =	(
           (
               TFSwinModel,
               TFSwinForImageClassification,
               TFSwinForMaskedImageModeling,
           )
           if is_tf_available()
           else ()
       )
       A							:	Tuple          =	(
           {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
           if is_tf_available()
           else {}
       )

       A							:	int          =	False
       A							:	str          =	False
       A							:	int          =	False
       A							:	Any          =	False

       def 			snake_case__    (							self					:     Optional[Any]			):
           __snake_case       :				Dict 			=    TFSwinModelTester(self			)
           __snake_case       :				int 			=    ConfigTester(self			,			config_class=_lowerCAmelCase			,			embed_dim=37			)

       def 			snake_case__    (							self					:     Union[str, Any]			):
           self.create_and_test_config_common_properties()
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()

       def 			snake_case__    (							self					:     Dict			):
           return

       def 			snake_case__    (							self					:     str			):
           __snake_case       :				Any 			=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowerCAmelCase			)

       def 			snake_case__    (							self					:     List[Any]			):
           __snake_case       :				List[Any] 			=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase			)

       def 			snake_case__    (							self					:     Any			):
           __snake_case       :				Dict 			=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase			)

       @unittest.skip(reason="""Swin does not use inputs_embeds"""			)
       def 			snake_case__    (							self					:     List[Any]			):
           pass

       def 			snake_case__    (							self					:     Union[str, Any]			):
           __snake_case			, __snake_case       :				Dict 			=    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __snake_case       :				Union[str, Any] 			=    model_class(_lowerCAmelCase			)
               self.assertIsInstance(model.get_input_embeddings()			,			tf.keras.layers.Layer			)
               __snake_case       :				Optional[Any] 			=    model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(_lowerCAmelCase			,			tf.keras.layers.Dense			)			)

       def 			snake_case__    (							self					:     Tuple			):
           __snake_case			, __snake_case       :				Dict 			=    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __snake_case       :				Union[str, Any] 			=    model_class(_lowerCAmelCase			)
               __snake_case       :				List[Any] 			=    inspect.signature(model.call			)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __snake_case       :				List[Any] 			=    [*signature.parameters.keys()]

               __snake_case       :				int 			=    ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]			,			_lowerCAmelCase			)

       def 			snake_case__    (							self					:     int			):
           __snake_case			, __snake_case       :				Optional[int] 			=    self.model_tester.prepare_config_and_inputs_for_common()
           __snake_case       :				Optional[Any] 			=    True

           for model_class in self.all_model_classes:
               __snake_case       :				Dict 			=    True
               __snake_case       :				Optional[int] 			=    False
               __snake_case       :				Tuple 			=    True
               __snake_case       :				Union[str, Any] 			=    model_class(_lowerCAmelCase			)
               __snake_case       :				Optional[int] 			=    model(**self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)			)
               __snake_case       :				Any 			=    outputs.attentions
               __snake_case       :				Any 			=    len(self.model_tester.depths			)
               self.assertEqual(len(_lowerCAmelCase			)			,			_lowerCAmelCase			)

               # check that output_attentions also work using config
               del inputs_dict["output_attentions"]
               __snake_case       :				Dict 			=    True
               __snake_case       :				Dict 			=    config.window_size**2
               __snake_case       :				Dict 			=    model_class(_lowerCAmelCase			)
               __snake_case       :				str 			=    model(**self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)			)
               __snake_case       :				List[str] 			=    outputs.attentions
               self.assertEqual(len(_lowerCAmelCase			)			,			_lowerCAmelCase			)

               self.assertListEqual(
                   list(attentions[0].shape[-3:]			)			,			[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,			)
               __snake_case       :				List[Any] 			=    len(_lowerCAmelCase			)

               # Check attention is always last and order is fine
               __snake_case       :				List[Any] 			=    True
               __snake_case       :				Optional[int] 			=    True
               __snake_case       :				Optional[Any] 			=    model_class(_lowerCAmelCase			)
               __snake_case       :				Any 			=    model(**self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)			)

               if hasattr(self.model_tester			,			"""num_hidden_states_types"""			):
                   __snake_case       :				int 			=    self.model_tester.num_hidden_states_types
               else:
                   # also another +1 for reshaped_hidden_states
                   __snake_case       :				Any 			=    2
               self.assertEqual(out_len + added_hidden_states			,			len(_lowerCAmelCase			)			)

               __snake_case       :				Any 			=    outputs.attentions

               self.assertEqual(len(_lowerCAmelCase			)			,			_lowerCAmelCase			)

               self.assertListEqual(
                   list(self_attentions[0].shape[-3:]			)			,			[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,			)

       def 			snake_case__    (							self					:     Optional[Any]			,			_lowerCAmelCase					:     Any			,			_lowerCAmelCase					:     List[Any]			,			_lowerCAmelCase					:     List[Any]			,			_lowerCAmelCase					:     Any			):
           __snake_case       :				List[Any] 			=    model_class(_lowerCAmelCase			)
           __snake_case       :				int 			=    model(**self._prepare_for_class(_lowerCAmelCase			,			_lowerCAmelCase			)			)
           __snake_case       :				List[str] 			=    outputs.hidden_states

           __snake_case       :				Tuple 			=    getattr(
               self.model_tester			,			"""expected_num_hidden_layers"""			,			len(self.model_tester.depths			) + 1			)
           self.assertEqual(len(_lowerCAmelCase			)			,			_lowerCAmelCase			)

           # Swin has a different seq_length
           __snake_case       :				List[str] 			=    to_atuple(config.patch_size			)

           __snake_case       :				List[Any] 			=    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

           self.assertListEqual(
               list(hidden_states[0].shape[-2:]			)			,			[num_patches, self.model_tester.embed_dim]			,			)

           __snake_case       :				Dict 			=    outputs.reshaped_hidden_states
           self.assertEqual(len(_lowerCAmelCase			)			,			_lowerCAmelCase			)

           __snake_case			, __snake_case			, __snake_case			, __snake_case       :				str 			=    reshaped_hidden_states[0].shape

           __snake_case       :				List[Any] 			=    tf.reshape(reshaped_hidden_states[0]			,			(batch_size, num_channels, height * width)			)
           __snake_case       :				List[Any] 			=    tf.transpose(_lowerCAmelCase			,			(0, 2, 1)			)

           self.assertListEqual(
               list(reshaped_hidden_states.shape[-2:]			)			,			[num_patches, self.model_tester.embed_dim]			,			)

       def 			snake_case__    (							self					:     Union[str, Any]			):
           __snake_case			, __snake_case       :				Optional[int] 			=    self.model_tester.prepare_config_and_inputs_for_common()

           __snake_case       :				str 			=    to_atuple(self.model_tester.image_size			)

           for model_class in self.all_model_classes:
               __snake_case       :				Optional[int] 			=    True
               self.check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __snake_case       :				List[Any] 			=    True

               self.check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			)

       def 			snake_case__    (							self					:     Tuple			):
           __snake_case			, __snake_case       :				int 			=    self.model_tester.prepare_config_and_inputs_for_common()
           __snake_case       :				int 			=    3

           __snake_case       :				Optional[Any] 			=    to_atuple(self.model_tester.image_size			)
           __snake_case       :				str 			=    to_atuple(config.patch_size			)

           __snake_case       :				str 			=    image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
           __snake_case       :				Optional[int] 			=    image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

           for model_class in self.all_model_classes:
               __snake_case       :				str 			=    True
               self.check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			(padded_height, padded_width)			)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __snake_case       :				Optional[Any] 			=    True
               self.check_hidden_states_output(_lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase			,			(padded_height, padded_width)			)





       @slow
       def 			snake_case__    (							self					:     int			):
           for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __snake_case       :				Any 			=    TFSwinModel.from_pretrained(_lowerCAmelCase			)
               self.assertIsNotNone(_lowerCAmelCase			)







@require_vision
@require_tf
class      SCREAMING_SNAKE_CASE__					(  unittest.TestCase    ):

       @cached_property
       def 			snake_case__    (							self					:     str			):
           return (
               AutoImageProcessor.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""			)
               if is_vision_available()
               else None
           )





       @slow
       def 			snake_case__    (							self					:     Dict			):
           __snake_case       :				Optional[int] 			=    TFSwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""			)
           __snake_case       :				Optional[int] 			=    self.default_image_processor

           __snake_case       :				Optional[Any] 			=    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
           __snake_case       :				Dict 			=    image_processor(images=_lowerCAmelCase			,			return_tensors="""tf"""			)

           # forward pass
           __snake_case       :				Tuple 			=    model(_lowerCAmelCase			)

           # verify the logits
           __snake_case       :				Optional[Any] 			=    tf.TensorShape((1, 10_00)			)
           self.assertEqual(outputs.logits.shape			,			_lowerCAmelCase			)
           __snake_case       :				int 			=    tf.constant([-0.0948, -0.6454, -0.0921]			)
           self.assertTrue(np.allclose(outputs.logits[0, :3]			,			_lowerCAmelCase			,			atol=1e-4			)			)




from __future__ import annotations

from collections.abc import Iterable







class      SCREAMING_SNAKE_CASE__					:

       def __init__(							self					:     Optional[Any]			,			_lowerCAmelCase					:     Tuple			,			_lowerCAmelCase					:     Tuple			):
           __snake_case			, __snake_case       :				str 			=    float(_lowerCAmelCase			), float(_lowerCAmelCase			)

       def __eq__(							self					:     List[Any]			,			_lowerCAmelCase					:     List[str]			):
           return self.x == other.x and self.y == other.y

       def __ne__(							self					:     Any			,			_lowerCAmelCase					:     Optional[Any]			):
           return not self == other

       def __gt__(							self					:     Union[str, Any]			,			_lowerCAmelCase					:     int			):
           if self.x > other.x:
               return True
           elif self.x == other.x:
               return self.y > other.y
           return False

       def __lt__(							self					:     List[str]			,			_lowerCAmelCase					:     List[str]			):
           return not self > other

       def __ge__(							self					:     List[Any]			,			_lowerCAmelCase					:     List[Any]			):
           if self.x > other.x:
               return True
           elif self.x == other.x:
               return self.y >= other.y
           return False

       def __le__(							self					:     List[Any]			,			_lowerCAmelCase					:     List[Any]			):
           if self.x < other.x:
               return True
           elif self.x == other.x:
               return self.y <= other.y
           return False

       def __repr__(							self					:     str			):
           return f'''({self.x}, {self.y})'''





       def __hash__(							self					:     List[str]			):
           return hash(self.x			)







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					list[Point] | list[list[float]] | Iterable[list[float]]		,							):







    '''simple docstring'''
    __snake_case       :				list[Point] 			=    []
    if list_of_tuples:
        for p in list_of_tuples:
            if isinstance(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE   ):
                points.append(__SCREAMING_SNAKE_CASE   )
            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				(		__SCREAMING_SNAKE_CASE       :					list[Point] | list[list[float]]   ):







    '''simple docstring'''

    if not hasattr(__SCREAMING_SNAKE_CASE		,							"""__iter__"""   ):
        __snake_case       :				List[str] 			=    F'''Expecting an iterable object but got an non-iterable type {points}'''
        raise ValueError(__SCREAMING_SNAKE_CASE   )

    if not points:
        __snake_case       :				Tuple 			=    F'''Expecting a list of points but got {points}'''
        raise ValueError(__SCREAMING_SNAKE_CASE   )

    return _construct_points(__SCREAMING_SNAKE_CASE   )







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					Point		,							__SCREAMING_SNAKE_CASE       :					Point		,							__SCREAMING_SNAKE_CASE       :					Point   ):







    '''simple docstring'''
    __snake_case       :				List[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 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					list[Point]   ):







    '''simple docstring'''
    __snake_case       :				List[Any] 			=    sorted(_validate_input(__SCREAMING_SNAKE_CASE   )   )
    __snake_case       :				Optional[Any] 			=    len(__SCREAMING_SNAKE_CASE   )
    __snake_case       :				Dict 			=    set()

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

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

                if points_left_of_ij and points_right_of_ij:
                    __snake_case       :				int 			=    False
                    break

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

    return sorted(__SCREAMING_SNAKE_CASE   )







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					list[Point]   ):







    '''simple docstring'''
    __snake_case       :				Union[str, Any] 			=    sorted(_validate_input(__SCREAMING_SNAKE_CASE   )   )
    __snake_case       :				Any 			=    len(__SCREAMING_SNAKE_CASE   )

    # 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

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

    __snake_case       :				Optional[Any] 			=    {left_most_point, right_most_point}
    __snake_case       :				Optional[int] 			=    []
    __snake_case       :				List[str] 			=    []

    for i in range(1		,							n - 1   ):
        __snake_case       :				Tuple 			=    _det(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							points[i]   )

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

    _construct_hull(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE   )
    _construct_hull(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE   )

    return sorted(__SCREAMING_SNAKE_CASE   )







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					list[Point]		,							__SCREAMING_SNAKE_CASE       :					Point		,							__SCREAMING_SNAKE_CASE       :					Point		,							__SCREAMING_SNAKE_CASE       :					set[Point]   ):







    '''simple docstring'''
    if points:
        __snake_case       :				List[str] 			=    None
        __snake_case       :				Tuple 			=    float("""-inf"""   )
        __snake_case       :				List[Any] 			=    []

        for p in points:
            __snake_case       :				Union[str, Any] 			=    _det(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE   )

            if det > 0:
                candidate_points.append(__SCREAMING_SNAKE_CASE   )

                if det > extreme_point_distance:
                    __snake_case       :				List[str] 			=    det
                    __snake_case       :				List[str] 			=    p

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







def 					__lowerCAmelCase				(		__SCREAMING_SNAKE_CASE       :					list[Point]   ):







    '''simple docstring'''
    __snake_case       :				Tuple 			=    sorted(_validate_input(__SCREAMING_SNAKE_CASE   )   )
    __snake_case       :				str 			=    len(__SCREAMING_SNAKE_CASE   )

    __snake_case       :				Optional[int] 			=    points[:2]
    for i in range(2		,							__SCREAMING_SNAKE_CASE   ):
        __snake_case       :				List[str] 			=    _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:
            __snake_case       :				Union[str, Any] 			=    points[i]
    i += 1

    for j in range(__SCREAMING_SNAKE_CASE		,							__SCREAMING_SNAKE_CASE   ):
        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(__SCREAMING_SNAKE_CASE   ) > 3 else convex_hull   )







def 					__lowerCAmelCase				(		):







    '''simple docstring'''
    __snake_case       :				str 			=    [
        (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)]
    __snake_case       :				Optional[Any] 			=    convex_hull_bf(__SCREAMING_SNAKE_CASE   )

    __snake_case       :				List[Any] 			=    convex_hull_recursive(__SCREAMING_SNAKE_CASE   )
    assert results_bf == results_recursive

    __snake_case       :				Tuple 			=    convex_hull_melkman(__SCREAMING_SNAKE_CASE   )
    assert results_bf == results_melkman

    print(__SCREAMING_SNAKE_CASE   )


if __name__ == "__main__":
     main()



