"""simple docstring"""


import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

    from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
    UpperCAmelCase__     						=  False

if is_vision_available():
    from PIL import Image

    from transformers import PixaStructImageProcessor


class 				a (						unittest.TestCase      ):


    def __init__(    self		:     Optional[int]      , __lowerCAmelCase		:     List[Any]      , __lowerCAmelCase		:     Dict=7      , __lowerCAmelCase		:     List[Any]=3      , __lowerCAmelCase		:     Tuple=18      , __lowerCAmelCase		:     Optional[int]=30      , __lowerCAmelCase		:     int=400      , __lowerCAmelCase		:     Optional[int]=None      , __lowerCAmelCase		:     Dict=True      , __lowerCAmelCase		:     Optional[int]=True      , __lowerCAmelCase		:     int=None      , ):
      _UpperCAmelCase         =					size if size is not None else {"""height""": 20, """width""": 20}
      _UpperCAmelCase         =					parent
      _UpperCAmelCase         =					batch_size
      _UpperCAmelCase         =					num_channels
      _UpperCAmelCase         =					image_size
      _UpperCAmelCase         =					min_resolution
      _UpperCAmelCase         =					max_resolution
      _UpperCAmelCase         =					size
      _UpperCAmelCase         =					do_normalize
      _UpperCAmelCase         =					do_convert_rgb
      _UpperCAmelCase         =					[512, 1024, 2048, 4096]
      _UpperCAmelCase         =					patch_size if patch_size is not None else {"""height""": 16, """width""": 16}


    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}


    def    lowerCAmelCase_     (    self		:     List[Any]    ):
      _UpperCAmelCase         =					"""https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
      _UpperCAmelCase         =					Image.open(requests.get(__lowerCAmelCase      , stream=__lowerCAmelCase    ).raw    ).convert("""RGB"""    )
      return raw_image



@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11		,							reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'		,							)
@require_torch
@require_vision
class 				a (						lowerCAmelCase_		,							unittest.TestCase      ):
    _snake_case   :     Tuple   							=							PixaStructImageProcessor if is_vision_available() else None


    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					PixaStructImageProcessingTester(self    )


    @property
    def    lowerCAmelCase_     (    self		:     List[str]    ):
      return self.image_processor_tester.prepare_image_processor_dict()


    def    lowerCAmelCase_     (    self		:     List[str]    ):
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      self.assertTrue(hasattr(__lowerCAmelCase      , """do_normalize"""    )    )
      self.assertTrue(hasattr(__lowerCAmelCase      , """do_convert_rgb"""    )    )


    def    lowerCAmelCase_     (    self		:     List[Any]    ):
      _UpperCAmelCase         =					self.image_processor_tester.prepare_dummy_image()

      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      _UpperCAmelCase         =					2048

      _UpperCAmelCase         =					image_processor(__lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    )
      self.assertTrue(torch.allclose(inputs.flattened_patches.mean()      , torch.tensor(0.0_606    )      , atol=1e-3      , rtol=1e-3    )    )


    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      # Initialize image_processor
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      # create random PIL images
      _UpperCAmelCase         =					prepare_image_inputs(self.image_processor_tester      , equal_resolution=__lowerCAmelCase    )
      for image in image_inputs:
        self.assertIsInstance(__lowerCAmelCase      , Image.Image    )

      # Test not batched input
      _UpperCAmelCase         =					(
          (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        _UpperCAmelCase         =					image_processor(
            image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (1, max_patch, expected_hidden_dim)      , )

        # Test batched
        _UpperCAmelCase         =					image_processor(
            __lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      , )


    def    lowerCAmelCase_     (    self		:     Optional[Any]    ):
      # Initialize image_processor
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      # create random PIL images
      _UpperCAmelCase         =					prepare_image_inputs(self.image_processor_tester      , equal_resolution=__lowerCAmelCase    )
      for image in image_inputs:
        self.assertIsInstance(__lowerCAmelCase      , Image.Image    )

      # Test not batched input
      _UpperCAmelCase         =					(
          (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
          * self.image_processor_tester.num_channels
      ) + 2

      _UpperCAmelCase         =					True

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        with self.assertRaises(__lowerCAmelCase    ):
          _UpperCAmelCase         =					image_processor(
              image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches

        _UpperCAmelCase         =					"""Hello"""

        _UpperCAmelCase         =					image_processor(
            image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase      , header_text=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (1, max_patch, expected_hidden_dim)      , )

        # Test batched
        _UpperCAmelCase         =					image_processor(
            __lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase      , header_text=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      , )


    def    lowerCAmelCase_     (    self		:     Union[str, Any]    ):
      # Initialize image_processor
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      # create random numpy tensors
      _UpperCAmelCase         =					prepare_image_inputs(self.image_processor_tester      , equal_resolution=__lowerCAmelCase      , numpify=__lowerCAmelCase    )
      for image in image_inputs:
        self.assertIsInstance(__lowerCAmelCase      , np.ndarray    )

      _UpperCAmelCase         =					(
          (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        _UpperCAmelCase         =					image_processor(
            image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (1, max_patch, expected_hidden_dim)      , )

        # Test batched
        _UpperCAmelCase         =					image_processor(
            __lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      , )


    def    lowerCAmelCase_     (    self		:     Dict    ):
      # Initialize image_processor
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      # create random PyTorch tensors
      _UpperCAmelCase         =					prepare_image_inputs(self.image_processor_tester      , equal_resolution=__lowerCAmelCase      , torchify=__lowerCAmelCase    )
      for image in image_inputs:
        self.assertIsInstance(__lowerCAmelCase      , torch.Tensor    )

      # Test not batched input
      _UpperCAmelCase         =					(
          (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        _UpperCAmelCase         =					image_processor(
            image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (1, max_patch, expected_hidden_dim)      , )

        # Test batched
        _UpperCAmelCase         =					image_processor(
            __lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      , )



@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11		,							reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'		,							)
@require_torch
@require_vision
class 				a (						lowerCAmelCase_		,							unittest.TestCase      ):
    _snake_case   :     Union[str, Any]   							=							PixaStructImageProcessor if is_vision_available() else None


    def    lowerCAmelCase_     (    self		:     List[str]    ):
      _UpperCAmelCase         =					PixaStructImageProcessingTester(self      , num_channels=4    )
      _UpperCAmelCase         =					3


    @property
    def    lowerCAmelCase_     (    self		:     List[Any]    ):
      return self.image_processor_tester.prepare_image_processor_dict()


    def    lowerCAmelCase_     (    self		:     List[str]    ):
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      self.assertTrue(hasattr(__lowerCAmelCase      , """do_normalize"""    )    )
      self.assertTrue(hasattr(__lowerCAmelCase      , """do_convert_rgb"""    )    )


    def    lowerCAmelCase_     (    self		:     Any    ):
      # Initialize image_processor
      _UpperCAmelCase         =					self.image_processing_class(**self.image_processor_dict    )
      # create random PIL images
      _UpperCAmelCase         =					prepare_image_inputs(self.image_processor_tester      , equal_resolution=__lowerCAmelCase    )
      for image in image_inputs:
        self.assertIsInstance(__lowerCAmelCase      , Image.Image    )

      # Test not batched input
      _UpperCAmelCase         =					(
          (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
          * (self.image_processor_tester.num_channels - 1)
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        _UpperCAmelCase         =					image_processor(
            image_inputs[0]      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (1, max_patch, expected_hidden_dim)      , )

        # Test batched
        _UpperCAmelCase         =					image_processor(
            __lowerCAmelCase      , return_tensors="""pt"""      , max_patches=__lowerCAmelCase    ).flattened_patches
        self.assertEqual(
            encoded_images.shape      , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      , )

"""simple docstring"""


import math


class 				a :


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     list[list[float]]      , __lowerCAmelCase		:     list[int]    ):
      _UpperCAmelCase         =					0.0
      _UpperCAmelCase         =					0.0
      for i in range(len(__lowerCAmelCase    )    ):
        da += math.pow((sample[i] - weights[0][i])      , 2    )
        da += math.pow((sample[i] - weights[1][i])      , 2    )
        return 0 if da > da else 1
      return 0


    def    lowerCAmelCase_     (    self		:     Union[str, Any]      , __lowerCAmelCase		:     list[list[int | float]]      , __lowerCAmelCase		:     list[int]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     float    ):
      for i in range(len(__lowerCAmelCase    )    ):
        weights[j][i] += alpha * (sample[i] - weights[j][i])
      return weights






def 			__UpperCAmelCase    (	):







  """simple docstring"""
  # Training Examples ( m, n )
  _UpperCAmelCase         =					[[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

  # weight initialization ( n, C )
  _UpperCAmelCase         =					[[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

  # training
  _UpperCAmelCase         =					SelfOrganizingMap()
  _UpperCAmelCase         =					3
  _UpperCAmelCase         =					0.5

  for _ in range(lowercase						):
    for j in range(len(lowercase						)						):
      # training sample
      _UpperCAmelCase         =					training_samples[j]

      # Compute the winning vector
      _UpperCAmelCase         =					self_organizing_map.get_winner(lowercase      ,lowercase						)

      # Update the winning vector
      _UpperCAmelCase         =					self_organizing_map.update(lowercase      ,lowercase      ,lowercase      ,lowercase						)

    # classify test sample
  _UpperCAmelCase         =					[0, 0, 0, 1]
  _UpperCAmelCase         =					self_organizing_map.get_winner(lowercase      ,lowercase						)

  # results
  print(f'''Clusters that the test sample belongs to : {winner}'''						)
  print(f'''Weights that have been trained : {weights}'''						)


# running the main() function
if __name__ == "__main__":
    main()
