

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

import numpy as np
import pyarrow as pa

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


if TYPE_CHECKING:
  import jax
  import jaxlib

UpperCAmelCase__ :     Tuple				    =    get_logger()

UpperCAmelCase__ :     Optional[dict]				    =    None







class        a__       (   TensorFormatter[Mapping, """jax.Array""", Mapping]       ):







  """simple docstring"""




  def __init__(			self    : Union[str, Any]				,				UpperCAmelCase__    : Tuple=None				,				UpperCAmelCase__    : List[Any]=None				,				**UpperCAmelCase__    : List[str]		)					->Tuple:
        """simple docstring"""







        super().__init__(features=UpperCAmelCase__		)
        import jax
        from jaxlib.xla_client import Device

        if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		):
              raise ValueError(
                  f"Expected {device} to be a `str` not {type(UpperCAmelCase__		)}, as `jaxlib.xla_extension.Device` "
                  """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """
                  """the device with `str()` to get its string identifier that will be internally mapped """
                  """to the actual `jaxlib.xla_extension.Device`."""		)
        SCREAMING_SNAKE_CASE :      Any       =   device if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		) else str(jax.devices()[0]		)
        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
        global DEVICE_MAPPING
        if DEVICE_MAPPING is None:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   self._map_devices_to_str()
        if self.device not in list(DEVICE_MAPPING.keys()		):
              logger.warning(
                  f"Device with string identifier {self.device} not listed among the available "
                  f"devices: {list(DEVICE_MAPPING.keys()		)}, so falling back to the default "
                  f"device: {str(jax.devices()[0]		)}."		)
              SCREAMING_SNAKE_CASE :      List[str]       =   str(jax.devices()[0]		)
        SCREAMING_SNAKE_CASE :      str       =   jnp_array_kwargs


  @staticmethod
  def  _lowercase      (			)					->Dict[str, "jaxlib.xla_extension.Device"]:
        """simple docstring"""







        import jax

        return {str(UpperCAmelCase__		): device for device in jax.devices()}


  def  _lowercase      (			self    : Union[str, Any]				,				UpperCAmelCase__    : Dict		)					->Any:
        """simple docstring"""







        import jax
        import jax.numpy as jnp

        if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		) and column:
              if all(
                  isinstance(UpperCAmelCase__				,				jax.Array		) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column		):
                    return jnp.stack(UpperCAmelCase__				,				axis=0		)
        return column


  def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : Tuple		)					->Any:
        """simple docstring"""







        import jax
        import jax.numpy as jnp

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

        SCREAMING_SNAKE_CASE :      str       =   {}

        if isinstance(UpperCAmelCase__				,				(np.number, np.ndarray)		) and np.issubdtype(value.dtype				,				np.integer		):
              # the default int precision depends on the jax config
              # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
              if jax.config.jax_enable_xaa:
                    SCREAMING_SNAKE_CASE :      Optional[Any]       =   {"""dtype""": jnp.intaa}
              else:
                    SCREAMING_SNAKE_CASE :      List[str]       =   {"""dtype""": jnp.intaa}
        elif isinstance(UpperCAmelCase__				,				(np.number, np.ndarray)		) and np.issubdtype(value.dtype				,				np.floating		):
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   {"""dtype""": jnp.floataa}
        elif config.PIL_AVAILABLE and "PIL" in sys.modules:
              import PIL.Image

              if isinstance(UpperCAmelCase__				,				PIL.Image.Image		):
                    SCREAMING_SNAKE_CASE :      List[Any]       =   np.asarray(UpperCAmelCase__		)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
        global DEVICE_MAPPING
        if DEVICE_MAPPING is None:
              SCREAMING_SNAKE_CASE :      List[Any]       =   self._map_devices_to_str()

        with jax.default_device(DEVICE_MAPPING[self.device]		):
              # calling jnp.array on a np.ndarray does copy the data
              # see https://github.com/google/jax/issues/4486
              return jnp.array(UpperCAmelCase__				,				**{**default_dtype, **self.jnp_array_kwargs}		)


  def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : Optional[int]		)					->List[Any]:
        """simple docstring"""







        import jax

        # support for torch, tf, jax etc.
        if config.TORCH_AVAILABLE and "torch" in sys.modules:
              import torch

              if isinstance(UpperCAmelCase__				,				torch.Tensor		):
                    return self._tensorize(data_struct.detach().cpu().numpy()[()]		)
        if hasattr(UpperCAmelCase__				,				"""__array__"""		) and not isinstance(UpperCAmelCase__				,				jax.Array		):
              SCREAMING_SNAKE_CASE :      List[str]       =   data_struct.__array__()
        # support for nested types like struct of list of struct
        if isinstance(UpperCAmelCase__				,				np.ndarray		):
              if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
                    return self._consolidate([self.recursive_tensorize(UpperCAmelCase__		) for substruct in data_struct]		)
        elif isinstance(UpperCAmelCase__				,				(list, tuple)		):
              return self._consolidate([self.recursive_tensorize(UpperCAmelCase__		) for substruct in data_struct]		)
        return self._tensorize(UpperCAmelCase__		)


  def  _lowercase      (			self    : List[Any]				,				UpperCAmelCase__    : dict		)					->Optional[int]:
        """simple docstring"""







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


  def  _lowercase      (			self    : int				,				UpperCAmelCase__    : pa.Table		)					->Mapping:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   self.numpy_arrow_extractor().extract_row(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Dict       =   self.python_features_decoder.decode_row(UpperCAmelCase__		)
        return self.recursive_tensorize(UpperCAmelCase__		)


  def  _lowercase      (			self    : int				,				UpperCAmelCase__    : pa.Table		)					->"jax.Array":
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.numpy_arrow_extractor().extract_column(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Dict       =   self.python_features_decoder.decode_column(UpperCAmelCase__				,				pa_table.column_names[0]		)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.recursive_tensorize(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   self._consolidate(UpperCAmelCase__		)
        return column




  def  _lowercase      (			self    : Tuple				,				UpperCAmelCase__    : pa.Table		)					->Mapping:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   self.numpy_arrow_extractor().extract_batch(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Dict       =   self.python_features_decoder.decode_batch(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[str]       =   self.recursive_tensorize(UpperCAmelCase__		)
        for column_name in batch:
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   self._consolidate(batch[column_name]		)
        return batch







from math import ceil






def 					__lowercase      (     _A = 1001			)     ->						int:
      SCREAMING_SNAKE_CASE :      Union[str, Any]       =   1

      for i in range(1						,    int(ceil(n / 2.0			)			)			):
            SCREAMING_SNAKE_CASE :      Dict       =   2 * i + 1
            SCREAMING_SNAKE_CASE :      Optional[int]       =   2 * i
            SCREAMING_SNAKE_CASE :      str       =   total + 4 * odd**2 - 6 * even

      return total


if __name__ == "__main__":
  import sys

  if len(sys.argv) == 1:
    print(solution())
  else:
    try:
      UpperCAmelCase__ :     str				    =    int(sys.argv[1])
      print(solution(n))
    except ValueError:
      print("""Invalid entry - please enter a number""")




