


'''simple docstring'''
from math import atan, cos, radians, sin, tan

from .haversine_distance import haversine_distance

__snake_case							      =     637_8137.0
__snake_case							      =     635_6752.31_4245
__snake_case							      =     6378137


def 			a      (			__a ,					__a ,					__a ,					__a   )  ->	float:



					'''simple docstring'''






					UpperCamelCase__   :Dict												= (AXIS_A - AXIS_B) / AXIS_A
					# Parametric latitudes
					# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
					UpperCamelCase__   :Optional[Any]												= atan((1 - flattening) * tan(radians(__a   )   )   )
					UpperCamelCase__   :List[str]												= atan((1 - flattening) * tan(radians(__a   )   )   )

					# Compute central angle between two points
					# using haversine theta. sigma =  haversine_distance / equatorial radius
					UpperCamelCase__   :Dict												= haversine_distance(__a ,					__a ,					__a ,					__a   ) / EQUATORIAL_RADIUS

					# Intermediate P and Q values
					UpperCamelCase__   :Tuple												= (b_lata + b_lata) / 2
					UpperCamelCase__   :Union[str, Any]												= (b_lata - b_lata) / 2

					# Intermediate X value
					# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
					UpperCamelCase__   :Tuple												= (sin(__a   ) ** 2) * (cos(__a   ) ** 2)
					UpperCamelCase__   :List[Any]												= cos(sigma / 2   ) ** 2
					UpperCamelCase__   :Optional[Any]												= (sigma - sin(__a   )) * (x_numerator / x_demonimator)

					# Intermediate Y value
					# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
					UpperCamelCase__   :Union[str, Any]												= (cos(__a   ) ** 2) * (sin(__a   ) ** 2)
					UpperCamelCase__   :List[str]												= sin(sigma / 2   ) ** 2
					UpperCamelCase__   :int												= (sigma + sin(__a   )) * (y_numerator / y_denominator)

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


if __name__ == "__main__":
		import doctest

		doctest.testmod()






'''simple docstring'''




import inspect
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch
import torch.utils.checkpoint

from ...models import UNetaDModel, VQModel
from ...schedulers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def 	UpperCAmelCase_							(					__lowercase							:      str       )		->       List[str]:


     '''simple docstring'''



     _UpperCAmelCase							,  _UpperCAmelCase     							=   image.size
     _UpperCAmelCase							,  _UpperCAmelCase     							=   (x - x % 32 for x in (w, h))  # resize to integer multiple of 32
     _UpperCAmelCase     							=   image.resize((w, h)			,     resample=PIL_INTERPOLATION["lanczos"]       )
     _UpperCAmelCase     							=   np.array(__lowercase       ).astype(np.floataa       ) / 255.0
     _UpperCAmelCase     							=   image[None].transpose(0			,     3			,     1			,     2       )
     _UpperCAmelCase     							=   torch.from_numpy(__lowercase       )
     return 2.0 * image - 1.0







class   A_	(  lowerCAmelCase_			):




 def __init__(					self       :    Optional[Any]	,			snake_case_       :    VQModel	,			snake_case_       :    UNetaDModel	,			snake_case_       :    Union[
         DDIMScheduler,
         PNDMScheduler,
         LMSDiscreteScheduler,
         EulerDiscreteScheduler,
         EulerAncestralDiscreteScheduler,
         DPMSolverMultistepScheduler,
     ]	,			):
      super().__init__()
      self.register_modules(vqvae=snake_case_	,			unet=snake_case_	,			scheduler=snake_case_    )




 @torch.no_grad()
 def __call__(					self       :    Any	,			snake_case_       :    Union[torch.Tensor, PIL.Image.Image] = None	,			snake_case_       :    Optional[int] = 1	,			snake_case_       :    Optional[int] = 1_0_0	,			snake_case_       :    Optional[float] = 0.0	,			snake_case_       :    Optional[Union[torch.Generator, List[torch.Generator]]] = None	,			snake_case_       :    Optional[str] = "pil"	,			snake_case_       :    bool = True	,			):
      if isinstance(snake_case_	,			PIL.Image.Image    ):
           _UpperCAmelCase     							=   1
      elif isinstance(snake_case_	,			torch.Tensor    ):
           _UpperCAmelCase     							=   image.shape[0]
      else:
           raise ValueError(f'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(snake_case_    )}'    )

      if isinstance(snake_case_	,			PIL.Image.Image    ):
           _UpperCAmelCase     							=   preprocess(snake_case_    )

      _UpperCAmelCase							,  _UpperCAmelCase     							=   image.shape[-2:]

      # in_channels should be 6: 3 for latents, 3 for low resolution image
      _UpperCAmelCase     							=   (batch_size, self.unet.config.in_channels // 2, height, width)
      _UpperCAmelCase     							=   next(self.unet.parameters()    ).dtype

      _UpperCAmelCase     							=   randn_tensor(snake_case_	,			generator=snake_case_	,			device=self.device	,			dtype=snake_case_    )

      _UpperCAmelCase     							=   image.to(device=self.device	,			dtype=snake_case_    )

      # set timesteps and move to the correct device
      self.scheduler.set_timesteps(snake_case_	,			device=self.device    )
      _UpperCAmelCase     							=   self.scheduler.timesteps

      # scale the initial noise by the standard deviation required by the scheduler
      _UpperCAmelCase     							=   latents * self.scheduler.init_noise_sigma

      # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
      # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
      # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
      # and should be between [0, 1]
      _UpperCAmelCase     							=   "eta" in set(inspect.signature(self.scheduler.step    ).parameters.keys()    )
      _UpperCAmelCase     							=   {}
      if accepts_eta:
           _UpperCAmelCase     							=   eta

      for t in self.progress_bar(snake_case_    ):
           # concat latents and low resolution image in the channel dimension.
           _UpperCAmelCase     							=   torch.cat([latents, image]	,			dim=1    )
           _UpperCAmelCase     							=   self.scheduler.scale_model_input(snake_case_	,			snake_case_    )
           # predict the noise residual
           _UpperCAmelCase     							=   self.unet(snake_case_	,			snake_case_    ).sample
           # compute the previous noisy sample x_t -> x_t-1
           _UpperCAmelCase     							=   self.scheduler.step(snake_case_	,			snake_case_	,			snake_case_	,			**snake_case_    ).prev_sample

      # decode the image latents with the VQVAE
      _UpperCAmelCase     							=   self.vqvae.decode(snake_case_    ).sample
      _UpperCAmelCase     							=   torch.clamp(snake_case_	,			-1.0	,			1.0    )
      _UpperCAmelCase     							=   image / 2 + 0.5
      _UpperCAmelCase     							=   image.cpu().permute(0	,			2	,			3	,			1    ).numpy()

      if output_type == "pil":
           _UpperCAmelCase     							=   self.numpy_to_pil(snake_case_    )

      if not return_dict:
           return (image,)

      return ImagePipelineOutput(images=snake_case_    )




