



"""simple docstring"""
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin
@dataclass
class     lowerCamelCase  (      lowerCAmelCase__    ):






					'''simple docstring'''





					_A		:      torch.FloatTensor
					_A		:      torch.FloatTensor

def        A_  (      _lowercase, _lowercase=0.999, _lowercase="cosine", ):







						'''simple docstring'''


						if alpha_transform_type == "cosine":

												def alpha_bar_fn(_lowercase     ):
																		return math.cos((t + 0.008) / 1.008 * math.pi / 2     ) ** 2

						elif alpha_transform_type == "exp":

												def alpha_bar_fn(_lowercase     ):
																		return math.exp(t * -12.0     )

						else:
												raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}"""     )

						snake_case_			:Dict						=      []
						for i in range(_lowercase     ):
												snake_case_			:Any						=      i / num_diffusion_timesteps
												snake_case_			:List[Any]						=      (i + 1) / num_diffusion_timesteps
												betas.append(min(1 - alpha_bar_fn(_lowercase     ) / alpha_bar_fn(_lowercase     ), _lowercase     )     )
						return torch.tensor(_lowercase, dtype=torch.floataa     )

class     lowerCamelCase  (      lowerCAmelCase__   ,						lowerCAmelCase__    ):






					'''simple docstring'''





					_A		:      List[str]						=					1






					@register_to_config
					def __init__(	self:							Optional[Any]						,					snake_case:							int = 1_000						,					snake_case:							float = 0.0_0_0_1						,					snake_case:							float = 0.0_2						,					snake_case:							str = "linear"						,					snake_case:							float = 0.0						,					snake_case:							Optional[np.ndarray] = None						,					snake_case:							bool = True						,					)       ->     Tuple:


											if trained_betas is not None:
																	snake_case_			:List[Any]						=      torch.from_numpy(_UpperCAmelCase						)
											elif beta_schedule == "linear":
																	snake_case_			:Dict						=      torch.linspace(_UpperCAmelCase						,					_UpperCAmelCase						,					_UpperCAmelCase						,					dtype=torch.floataa						)
											elif beta_schedule == "scaled_linear":
																	# this schedule is very specific to the latent diffusion model.
																	snake_case_			:Union[str, Any]						=      (
																	    torch.linspace(beta_start**0.5						,					beta_end**0.5						,					_UpperCAmelCase						,					dtype=torch.floataa						) ** 2
																	)
											elif beta_schedule == "squaredcos_cap_v2":
																	# Glide cosine schedule
																	snake_case_			:Union[str, Any]						=      betas_for_alpha_bar(_UpperCAmelCase						)
											elif beta_schedule == "sigmoid":
																	# GeoDiff sigmoid schedule
																	snake_case_			:int						=      torch.linspace(-6						,					6						,					_UpperCAmelCase						)
																	snake_case_			:str						=      torch.sigmoid(_UpperCAmelCase						) * (beta_end - beta_start) + beta_start
											else:
																	raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""						)

											snake_case_			:Union[str, Any]						=      1.0 - self.betas
											snake_case_			:str						=      torch.cumprod(self.alphas						,					dim=0						)
											snake_case_			:Union[str, Any]						=      torch.tensor(1.0						)

											snake_case_			:str						=      torch.tensor(1.0						)

											# standard deviation of the initial noise distribution
											snake_case_			:Optional[Any]						=      1.0

											# setable values
											snake_case_			:int						=      None
											snake_case_			:Dict						=      torch.from_numpy(np.arange(0						,					_UpperCAmelCase						)[::-1].copy()						)

											snake_case_			:List[str]						=      eta






					def        lowerCAmelCase_    (	self:							int						,					snake_case:							torch.FloatTensor						,					snake_case:							Optional[int] = None						)       ->     torch.FloatTensor:
											return sample






					def        lowerCAmelCase_    (	self:							int						,					snake_case:							int						,					snake_case:							int = 10						,					snake_case:							int = 10						,					snake_case:							Union[str, torch.device] = None						,					)       ->     Optional[int]:
											snake_case_			:str						=      min(self.config.num_train_timesteps						,					_UpperCAmelCase						)
											snake_case_			:List[str]						=      num_inference_steps

											snake_case_			:Tuple						=      []

											snake_case_			:List[str]						=      {}
											for j in range(0						,					num_inference_steps - jump_length						,					_UpperCAmelCase						):
																	snake_case_			:Tuple						=      jump_n_sample - 1

											snake_case_			:List[str]						=      num_inference_steps
											while t >= 1:
																	snake_case_			:str						=      t - 1
																	timesteps.append(_UpperCAmelCase						)

																	if jumps.get(_UpperCAmelCase						,					0						) > 0:
																							snake_case_			:Optional[Any]						=      jumps[t] - 1
																							for _ in range(_UpperCAmelCase						):
																													snake_case_			:Optional[Any]						=      t + 1
																													timesteps.append(_UpperCAmelCase						)

											snake_case_			:Optional[Any]						=      np.array(_UpperCAmelCase						) * (self.config.num_train_timesteps // self.num_inference_steps)
											snake_case_			:List[Any]						=      torch.from_numpy(_UpperCAmelCase						).to(_UpperCAmelCase						)






					def        lowerCAmelCase_    (	self:							str						,					snake_case:							List[Any]						)       ->     Union[str, Any]:
											snake_case_			:List[str]						=      t - self.config.num_train_timesteps // self.num_inference_steps

											snake_case_			:List[str]						=      self.alphas_cumprod[t]
											snake_case_			:Union[str, Any]						=      self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
											snake_case_			:Dict						=      1 - alpha_prod_t
											snake_case_			:Union[str, Any]						=      1 - alpha_prod_t_prev

											# For t > 0, compute predicted variance βt (see formula (6) and (7) from
											# https://arxiv.org/pdf/2006.11239.pdf) and sample from it to get
											# previous sample x_{t-1} ~ N(pred_prev_sample, variance) == add
											# variance to pred_sample
											# Is equivalent to formula (16) in https://arxiv.org/pdf/2010.02502.pdf
											# without eta.
											# variance = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * self.betas[t]
											snake_case_			:Optional[Any]						=      (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)

											return variance






					def        lowerCAmelCase_    (	self:							List[Any]						,					snake_case:							torch.FloatTensor						,					snake_case:							int						,					snake_case:							torch.FloatTensor						,					snake_case:							torch.FloatTensor						,					snake_case:							torch.FloatTensor						,					snake_case:							Optional[torch.Generator] = None						,					snake_case:							bool = True						,					)       ->     Union[RePaintSchedulerOutput, Tuple]:
											snake_case_			:List[Any]						=      timestep
											snake_case_			:Optional[Any]						=      timestep - self.config.num_train_timesteps // self.num_inference_steps

											# 1. compute alphas, betas
											snake_case_			:Tuple						=      self.alphas_cumprod[t]
											snake_case_			:Union[str, Any]						=      self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
											snake_case_			:Union[str, Any]						=      1 - alpha_prod_t

											# 2. compute predicted original sample from predicted noise also called
											# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
											snake_case_			:Union[str, Any]						=      (sample - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5

											# 3. Clip "predicted x_0"
											if self.config.clip_sample:
																	snake_case_			:Tuple						=      torch.clamp(_UpperCAmelCase						,					-1						,					1						)

											# We choose to follow RePaint Algorithm 1 to get x_{t-1}, however we
											# substitute formula (7) in the algorithm coming from DDPM paper
											# (formula (4) Algorithm 2 - Sampling) with formula (12) from DDIM paper.
											# DDIM schedule gives the same results as DDPM with eta = 1.0
											# Noise is being reused in 7. and 8., but no impact on quality has
											# been observed.

											# 5. Add noise
											snake_case_			:List[Any]						=      model_output.device
											snake_case_			:Dict						=      randn_tensor(model_output.shape						,					generator=_UpperCAmelCase						,					device=_UpperCAmelCase						,					dtype=model_output.dtype						)
											snake_case_			:str						=      self.eta * self._get_variance(_UpperCAmelCase						) ** 0.5

											snake_case_			:Tuple						=      0
											if t > 0 and self.eta > 0:
																	snake_case_			:int						=      std_dev_t * noise

											# 6. compute "direction pointing to x_t" of formula (12)
											# from https://arxiv.org/pdf/2010.02502.pdf
											snake_case_			:Union[str, Any]						=      (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output

											# 7. compute x_{t-1} of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
											snake_case_			:Union[str, Any]						=      alpha_prod_t_prev**0.5 * pred_original_sample + pred_sample_direction + variance

											# 8. Algorithm 1 Line 5 https://arxiv.org/pdf/2201.09865.pdf
											snake_case_			:List[str]						=      (alpha_prod_t_prev**0.5) * original_image + ((1 - alpha_prod_t_prev) ** 0.5) * noise

											# 9. Algorithm 1 Line 8 https://arxiv.org/pdf/2201.09865.pdf
											snake_case_			:Any						=      mask * prev_known_part + (1.0 - mask) * prev_unknown_part

											if not return_dict:
																	return (
																	    pred_prev_sample,
																	    pred_original_sample,
																	)

											return RePaintSchedulerOutput(prev_sample=_UpperCAmelCase						,					pred_original_sample=_UpperCAmelCase						)






					def        lowerCAmelCase_    (	self:							Optional[int]						,					snake_case:							List[str]						,					snake_case:							List[str]						,					snake_case:							Dict=None						)       ->     List[Any]:
											snake_case_			:Optional[Any]						=      self.config.num_train_timesteps // self.num_inference_steps

											for i in range(_UpperCAmelCase						):
																	snake_case_			:Union[str, Any]						=      self.betas[timestep + i]
																	if sample.device.type == "mps":
																							# randn does not work reproducibly on mps
																							snake_case_			:Any						=      randn_tensor(sample.shape						,					dtype=sample.dtype						,					generator=_UpperCAmelCase						)
																							snake_case_			:List[Any]						=      noise.to(sample.device						)
																	else:
																							snake_case_			:Dict						=      randn_tensor(sample.shape						,					generator=_UpperCAmelCase						,					device=sample.device						,					dtype=sample.dtype						)

																	# 10. Algorithm 1 Line 10 https://arxiv.org/pdf/2201.09865.pdf
																	snake_case_			:Optional[int]						=      (1 - beta) ** 0.5 * sample + beta**0.5 * noise

											return sample






					def        lowerCAmelCase_    (	self:							Tuple						,					snake_case:							torch.FloatTensor						,					snake_case:							torch.FloatTensor						,					snake_case:							torch.IntTensor						,					)       ->     torch.FloatTensor:
											raise NotImplementedError("""Use `DDPMScheduler.add_noise()` to train for sampling with RePaint."""						)






					def __len__(	self:							Tuple						)       ->     Union[str, Any]:
											return self.config.num_train_timesteps








"""simple docstring"""
from math import radians as angle_to_radians
from math import sin

# Acceleration Constant on Earth (unit m/s^2)
__a     =    9.8_06_65
def        A_  (      _lowercase, _lowercase     ):







						'''simple docstring'''


						if not isinstance(_lowercase, (int, float)     ):
												raise TypeError("""Invalid velocity. Should be a positive number."""     )

						if not isinstance(_lowercase, (int, float)     ):
												raise TypeError("""Invalid angle. Range is 1-90 degrees."""     )

						# Ensure valid angle
						if angle > 90 or angle < 1:
												raise ValueError("""Invalid angle. Range is 1-90 degrees."""     )

						# Ensure valid velocity
						if init_velocity < 0:
												raise ValueError("""Invalid velocity. Should be a positive number."""     )
def        A_  (      _lowercase, _lowercase     ):







						'''simple docstring'''


						check_args(_lowercase, _lowercase     )
						snake_case_			:str						=      angle_to_radians(2 * angle     )
						return round(init_velocity**2 * sin(_lowercase     ) / g, 2     )
def        A_  (      _lowercase, _lowercase     ):







						'''simple docstring'''


						check_args(_lowercase, _lowercase     )
						snake_case_			:str						=      angle_to_radians(_lowercase     )
						return round(init_velocity**2 * sin(_lowercase     ) ** 2 / (2 * g), 2     )
def        A_  (      _lowercase, _lowercase     ):







						'''simple docstring'''


						check_args(_lowercase, _lowercase     )
						snake_case_			:Optional[int]						=      angle_to_radians(_lowercase     )
						return round(2 * init_velocity * sin(_lowercase     ) / g, 2     )
def        A_  (      ):







						'''simple docstring'''


						snake_case_,	snake_case_			:List[str]						=      25, 20
						assert horizontal_distance(_lowercase, _lowercase     ) == 40.97
						assert max_height(_lowercase, _lowercase     ) == 3.73
						assert total_time(_lowercase, _lowercase     ) == 1.74


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

						testmod()

						# Get input from user
						__a     =    float(input("Initial Velocity: ").strip())

						# Get input from user
						__a     =    float(input("angle: ").strip())

						# Print results
						print()
						print("Results: ")
						print(F"""Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]""")
						print(F"""Maximum Height: {max_height(init_vel, angle)!s} [m]""")
						print(F"""Total Time: {total_time(init_vel, angle)!s} [s]""")
