






"""simple docstring"""





import collections
import gzip
import os
import urllib

import numpy
from tensorflow.python.framework import dtypes, random_seed
from tensorflow.python.platform import gfile
from tensorflow.python.util.deprecation import deprecated

UpperCamelCase_	:				Optional[int]										= collections.namedtuple("""_Datasets""", ["""train""", """validation""", """test"""])

# CVDF mirror of http://yann.lecun.com/exdb/mnist/
UpperCamelCase_	:				Dict										= """https://storage.googleapis.com/cvdf-datasets/mnist/"""



def     __lowercase					(    a :				Optional[Any] )					->					Union[str, Any]:
      __snake_case      :    Dict  			=numpy.dtype(numpy.uintaa ).newbyteorder('''>''' )
      return numpy.frombuffer(bytestream.read(4 )       ,		dtype=a )[0]



@deprecated(a       ,		'''Please use tf.data to implement this functionality.''' )
def     __lowercase					(    a :				Dict )					->					List[str]:
      print('''Extracting'''       ,		f.name )
      with gzip.GzipFile(fileobj=a ) as bytestream:
            __snake_case      :    Union[str, Any]  			=_readaa(a )
            if magic != 2_051:
                  raise ValueError(
                      '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) )
            __snake_case      :    int  			=_readaa(a )
            __snake_case      :    Optional[Any]  			=_readaa(a )
            __snake_case      :    List[str]  			=_readaa(a )
            __snake_case      :    Tuple  			=bytestream.read(rows * cols * num_images )
            __snake_case      :    Optional[Any]  			=numpy.frombuffer(a       ,		dtype=numpy.uinta )
            __snake_case      :    Union[str, Any]  			=data.reshape(a       ,		a       ,		a       ,		1 )
            return data



@deprecated(a       ,		'''Please use tf.one_hot on tensors.''' )
def     __lowercase					(    a :				str       ,		a :				Any )					->					List[Any]:
      __snake_case      :    Optional[Any]  			=labels_dense.shape[0]
      __snake_case      :    List[str]  			=numpy.arange(a ) * num_classes
      __snake_case      :    Union[str, Any]  			=numpy.zeros((num_labels, num_classes) )
      __snake_case      :    Optional[int]  			=1
      return labels_one_hot



@deprecated(a       ,		'''Please use tf.data to implement this functionality.''' )
def     __lowercase					(    a :				List[str]       ,		a :				Tuple=False       ,		a :				Any=10 )					->					Optional[Any]:
      print('''Extracting'''       ,		f.name )
      with gzip.GzipFile(fileobj=a ) as bytestream:
            __snake_case      :    int  			=_readaa(a )
            if magic != 2_049:
                  raise ValueError(
                      '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) )
            __snake_case      :    List[str]  			=_readaa(a )
            __snake_case      :    Optional[int]  			=bytestream.read(a )
            __snake_case      :    Tuple  			=numpy.frombuffer(a       ,		dtype=numpy.uinta )
            if one_hot:
                  return _dense_to_one_hot(a       ,		a )
            return labels


class      _lowercase :


      @deprecated(
          UpperCamelCase__							,   '''Please use alternatives such as official/mnist/_DataSet.py'''
          ''' from tensorflow/models.'''							,   )
      def __init__(    self				:	List[str]							,   a				:	Optional[Any]							,   a				:	str							,   a				:	Any=False							,   a				:	List[Any]=False							,   a				:	List[Any]=dtypes.floataa							,   a				:	Union[str, Any]=True							,   a				:	Any=None							,   ):





            """simple docstring"""







            __snake_case			,				__snake_case      :    str  			=random_seed.get_seed(UpperCamelCase__						)
            # If op level seed is not set, use whatever graph level seed is returned
            numpy.random.seed(seeda if seed is None else seeda						)
            __snake_case      :    Any  			=dtypes.as_dtype(UpperCamelCase__						).base_dtype
            if dtype not in (dtypes.uinta, dtypes.floataa):
                  raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype						)
            if fake_data:
                  __snake_case      :    Union[str, Any]  			=1_0_0_0_0
                  __snake_case      :    int  			=one_hot
            else:
                  assert (
                      images.shape[0] == labels.shape[0]
                  ), f'''images.shape: {images.shape} labels.shape: {labels.shape}'''
                  __snake_case      :    Dict  			=images.shape[0]

                  # Convert shape from [num examples, rows, columns, depth]
                  # to [num examples, rows*columns] (assuming depth == 1)
                  if reshape:
                        assert images.shape[3] == 1
                        __snake_case      :    int  			=images.reshape(
                            images.shape[0]							,   images.shape[1] * images.shape[2]						)
                  if dtype == dtypes.floataa:
                        # Convert from [0, 255] -> [0.0, 1.0].
                        __snake_case      :    Union[str, Any]  			=images.astype(numpy.floataa						)
                        __snake_case      :    Any  			=numpy.multiply(UpperCamelCase__							,   1.0 / 2_5_5.0						)
            __snake_case      :    Dict  			=images
            __snake_case      :    Dict  			=labels
            __snake_case      :    Optional[int]  			=0
            __snake_case      :    Optional[Any]  			=0


      @property
      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            return self._images


      @property
      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            return self._labels


      @property
      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            return self._num_examples


      @property
      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return self._epochs_completed







      def _UpperCamelCase						(    self				:	List[Any]							,   a				:	str							,   a				:	Optional[Any]=False							,   a				:	Union[str, Any]=True						):





            """simple docstring"""







            if fake_data:
                  __snake_case      :    Union[str, Any]  			=[1] * 7_8_4
                  __snake_case      :    Dict  			=[1] + [0] * 9 if self.one_hot else 0
                  return (
                      [fake_image for _ in range(UpperCamelCase__						)],
                      [fake_label for _ in range(UpperCamelCase__						)],
                  )
            __snake_case      :    int  			=self._index_in_epoch
            # Shuffle for the first epoch
            if self._epochs_completed == 0 and start == 0 and shuffle:
                  __snake_case      :    List[str]  			=numpy.arange(self._num_examples						)
                  numpy.random.shuffle(UpperCamelCase__						)
                  __snake_case      :    Union[str, Any]  			=self.images[perma]
                  __snake_case      :    Optional[Any]  			=self.labels[perma]
            # Go to the next epoch
            if start + batch_size > self._num_examples:
                  # Finished epoch
                  self._epochs_completed += 1
                  # Get the rest examples in this epoch
                  __snake_case      :    Any  			=self._num_examples - start
                  __snake_case      :    List[str]  			=self._images[start : self._num_examples]
                  __snake_case      :    Optional[int]  			=self._labels[start : self._num_examples]
                  # Shuffle the data
                  if shuffle:
                        __snake_case      :    List[Any]  			=numpy.arange(self._num_examples						)
                        numpy.random.shuffle(UpperCamelCase__						)
                        __snake_case      :    int  			=self.images[perm]
                        __snake_case      :    Optional[Any]  			=self.labels[perm]
                  # Start next epoch
                  __snake_case      :    List[Any]  			=0
                  __snake_case      :    Optional[int]  			=batch_size - rest_num_examples
                  __snake_case      :    Tuple  			=self._index_in_epoch
                  __snake_case      :    Dict  			=self._images[start:end]
                  __snake_case      :    Any  			=self._labels[start:end]
                  return (
                      numpy.concatenate((images_rest_part, images_new_part)							,   axis=0						),
                      numpy.concatenate((labels_rest_part, labels_new_part)							,   axis=0						),
                  )
            else:
                  self._index_in_epoch += batch_size
                  __snake_case      :    Optional[int]  			=self._index_in_epoch
                  return self._images[start:end], self._labels[start:end]



@deprecated(a       ,		'''Please write your own downloading logic.''' )
def     __lowercase					(    a :				Any       ,		a :				List[str]       ,		a :				Optional[Any] )					->					List[Any]:
      if not gfile.Exists(a ):
            gfile.MakeDirs(a )
      __snake_case      :    Dict  			=os.path.join(a       ,		a )
      if not gfile.Exists(a ):
            urllib.request.urlretrieve(a       ,		a )  # noqa: S310
            with gfile.GFile(a ) as f:
                  __snake_case      :    Optional[int]  			=f.size()
            print('''Successfully downloaded'''       ,		a       ,		a       ,		'''bytes.''' )
      return filepath



@deprecated(
    a       ,		'''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' )
def     __lowercase					(    a :				Dict       ,		a :				Optional[int]=False       ,		a :				Optional[Any]=False       ,		a :				List[Any]=dtypes.floataa       ,		a :				Dict=True       ,		a :				List[str]=5_000       ,		a :				Optional[Any]=None       ,		a :				Union[str, Any]=DEFAULT_SOURCE_URL       ,		)					->					int:
      if fake_data:

            def fake():
                  return _DataSet(
                      []       ,		[]       ,		fake_data=a       ,		one_hot=a       ,		dtype=a       ,		seed=a )

            __snake_case      :    Tuple  			=fake()
            __snake_case      :    Optional[Any]  			=fake()
            __snake_case      :    List[str]  			=fake()
            return _Datasets(train=a       ,		validation=a       ,		test=a )

      if not source_url:  # empty string check
            __snake_case      :    Union[str, Any]  			=DEFAULT_SOURCE_URL

      __snake_case      :    int  			='''train-images-idx3-ubyte.gz'''
      __snake_case      :    Any  			='''train-labels-idx1-ubyte.gz'''
      __snake_case      :    List[str]  			='''t10k-images-idx3-ubyte.gz'''
      __snake_case      :    List[Any]  			='''t10k-labels-idx1-ubyte.gz'''

      __snake_case      :    List[Any]  			=_maybe_download(
          a       ,		a       ,		source_url + train_images_file )
      with gfile.Open(a       ,		'''rb''' ) as f:
            __snake_case      :    List[Any]  			=_extract_images(a )

      __snake_case      :    Dict  			=_maybe_download(
          a       ,		a       ,		source_url + train_labels_file )
      with gfile.Open(a       ,		'''rb''' ) as f:
            __snake_case      :    Optional[Any]  			=_extract_labels(a       ,		one_hot=a )

      __snake_case      :    List[str]  			=_maybe_download(
          a       ,		a       ,		source_url + test_images_file )
      with gfile.Open(a       ,		'''rb''' ) as f:
            __snake_case      :    Dict  			=_extract_images(a )

      __snake_case      :    Tuple  			=_maybe_download(
          a       ,		a       ,		source_url + test_labels_file )
      with gfile.Open(a       ,		'''rb''' ) as f:
            __snake_case      :    Any  			=_extract_labels(a       ,		one_hot=a )

      if not 0 <= validation_size <= len(a ):
            __snake_case      :    Dict  			=(
                '''Validation size should be between 0 and '''
                f'''{len(a )}. Received: {validation_size}.'''
            )
            raise ValueError(a )

      __snake_case      :    Tuple  			=train_images[:validation_size]
      __snake_case      :    str  			=train_labels[:validation_size]
      __snake_case      :    Any  			=train_images[validation_size:]
      __snake_case      :    str  			=train_labels[validation_size:]

      __snake_case      :    Optional[int]  			={'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed}

      __snake_case      :    List[Any]  			=_DataSet(a       ,		a       ,		**a )
      __snake_case      :    str  			=_DataSet(a       ,		a       ,		**a )
      __snake_case      :    Any  			=_DataSet(a       ,		a       ,		**a )

      return _Datasets(train=a       ,		validation=a       ,		test=a )












"""simple docstring"""





from math import atan, cos, radians, sin, tan

from .haversine_distance import haversine_distance

UpperCamelCase_	:				Optional[Any]										= 6_37_81_37.0
UpperCamelCase_	:				Optional[Any]										= 6_35_67_52.31_42_45
UpperCamelCase_	:				Union[str, Any]										= 6378137



def     __lowercase					(    a :				float       ,		a :				float       ,		a :				float       ,		a :				float )					->					float:
      __snake_case      :    Optional[Any]  			=(AXIS_A - AXIS_B) / AXIS_A
      # Parametric latitudes
      # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
      __snake_case      :    List[str]  			=atan((1 - flattening) * tan(radians(a ) ) )
      __snake_case      :    Any  			=atan((1 - flattening) * tan(radians(a ) ) )

      # Compute central angle between two points
      # using haversine theta. sigma =  haversine_distance / equatorial radius
      __snake_case      :    Optional[Any]  			=haversine_distance(a       ,		a       ,		a       ,		a ) / EQUATORIAL_RADIUS

      # Intermediate P and Q values
      __snake_case      :    List[str]  			=(b_lata + b_lata) / 2
      __snake_case      :    Dict  			=(b_lata - b_lata) / 2

      # Intermediate X value
      # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
      __snake_case      :    Optional[int]  			=(sin(a ) ** 2) * (cos(a ) ** 2)
      __snake_case      :    Any  			=cos(sigma / 2 ) ** 2
      __snake_case      :    Optional[Any]  			=(sigma - sin(a )) * (x_numerator / x_demonimator)

      # Intermediate Y value
      # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
      __snake_case      :    Tuple  			=(cos(a ) ** 2) * (sin(a ) ** 2)
      __snake_case      :    Dict  			=sin(sigma / 2 ) ** 2
      __snake_case      :    Tuple  			=(sigma + sin(a )) * (y_numerator / y_denominator)

      return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value)))


if __name__ == "__main__":
    import doctest

    doctest.testmod()


