
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
   import torch






class     UpperCAmelCase						(		TensorFormatter[Mapping, "torch.Tensor", Mapping]					):



   def __init__(self						:   Optional[Any]       ,		snake_case__						:   Dict=None       ,		**snake_case__						:   List[str]					)						->      List[Any]:


          '''simple docstring'''


          super().__init__(features=snake_case__					)
          snake_case			:  Any     							= torch_tensor_kwargs
          import torch  # noqa import torch at initialization



   def 							_SCREAMING_SNAKE_CASE  (self						:   Union[str, Any]       ,		snake_case__						:   Tuple					)						->      Optional[Any]:


          '''simple docstring'''


          import torch

          if isinstance(snake_case__       ,		snake_case__					) and column:
                 if all(
                     isinstance(snake_case__       ,		torch.Tensor					) and x.shape == column[0].shape and x.dtype == column[0].dtype
                     for x in column					):
                        return torch.stack(snake_case__					)
          return column



   def 							_SCREAMING_SNAKE_CASE  (self						:   Dict       ,		snake_case__						:   str					)						->      Dict:


          '''simple docstring'''


          import torch

          if isinstance(snake_case__       ,		(str, bytes, type(snake_case__					))					):
                 return value
          elif isinstance(snake_case__       ,		(np.character, np.ndarray)					) and np.issubdtype(value.dtype       ,		np.character					):
                 return value.tolist()

          snake_case			:  int     							= {}

          if isinstance(snake_case__       ,		(np.number, np.ndarray)					) and np.issubdtype(value.dtype       ,		np.integer					):
                 snake_case			:  Any     							= {"dtype": torch.intaa}
          elif isinstance(snake_case__       ,		(np.number, np.ndarray)					) and np.issubdtype(value.dtype       ,		np.floating					):
                 snake_case			:  Tuple     							= {"dtype": torch.floataa}
          elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(snake_case__       ,		PIL.Image.Image					):
                        snake_case			:  Union[str, Any]     							= np.asarray(snake_case__					)
          return torch.tensor(snake_case__       ,		**{**default_dtype, **self.torch_tensor_kwargs}					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str       ,		snake_case__						:   Any					)						->      Tuple:


          '''simple docstring'''


          import torch

          # support for torch, tf, jax etc.
          if hasattr(snake_case__       ,		"__array__"					) and not isinstance(snake_case__       ,		torch.Tensor					):
                 snake_case			:  str     							= data_struct.__array__()
          # support for nested types like struct of list of struct
          if isinstance(snake_case__       ,		np.ndarray					):
                 if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                        return self._consolidate([self.recursive_tensorize(snake_case__					) for substruct in data_struct]					)
          elif isinstance(snake_case__       ,		(list, tuple)					):
                 return self._consolidate([self.recursive_tensorize(snake_case__					) for substruct in data_struct]					)
          return self._tensorize(snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str       ,		snake_case__						:   dict					)						->      str:


          '''simple docstring'''


          return map_nested(self._recursive_tensorize       ,		snake_case__       ,		map_list=snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   int       ,		snake_case__						:   pa.Table					)						->      Mapping:


          '''simple docstring'''


          snake_case			:  Optional[int]     							= self.numpy_arrow_extractor().extract_row(snake_case__					)
          snake_case			:  Optional[int]     							= self.python_features_decoder.decode_row(snake_case__					)
          return self.recursive_tensorize(snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Dict       ,		snake_case__						:   pa.Table					)						->      "torch.Tensor":


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= self.numpy_arrow_extractor().extract_column(snake_case__					)
          snake_case			:  Union[str, Any]     							= self.python_features_decoder.decode_column(snake_case__       ,		pa_table.column_names[0]					)
          snake_case			:  Tuple     							= self.recursive_tensorize(snake_case__					)
          snake_case			:  List[str]     							= self._consolidate(snake_case__					)
          return column



   def 							_SCREAMING_SNAKE_CASE  (self						:   Union[str, Any]       ,		snake_case__						:   pa.Table					)						->      Mapping:


          '''simple docstring'''


          snake_case			:  Optional[int]     							= self.numpy_arrow_extractor().extract_batch(snake_case__					)
          snake_case			:  Any     							= self.python_features_decoder.decode_batch(snake_case__					)
          snake_case			:  Union[str, Any]     							= self.recursive_tensorize(snake_case__					)
          for column_name in batch:
                 snake_case			:  Tuple     							= self._consolidate(batch[column_name]					)
          return batch







from math import factorial


def      UpperCamelCase   (       __lowerCamelCase	:					int							,   __lowerCamelCase	:					int							,   __lowerCamelCase	:					float       ):
       if successes > trials:
              raise ValueError("successes must be lower or equal to trials"       )
       if trials < 0 or successes < 0:
              raise ValueError("the function is defined for non-negative integers"       )
       if not isinstance(__lowerCamelCase							,   __lowerCamelCase       ) or not isinstance(__lowerCamelCase							,   __lowerCamelCase       ):
              raise ValueError("the function is defined for non-negative integers"       )
       if not 0 < prob < 1:
              raise ValueError("prob has to be in range of 1 - 0"       )
       snake_case			:  Tuple     							= (prob**successes) * ((1 - prob) ** (trials - successes))
       # Calculate the binomial coefficient: n! / k!(n-k)!
       snake_case			:  str     							= float(factorial(__lowerCamelCase       )       )
       coefficient /= factorial(__lowerCamelCase       ) * factorial(trials - successes       )
       return probability * coefficient


if __name__ == "__main__":
   from doctest import testmod

   testmod()
   print("""Probability of 2 successes out of 4 trails""")
   print("""with probability of 0.75 is:""", end=""" """)
   print(binomial_distribution(2, 4, 0.75))





