Created
July 16, 2022 15:57
-
-
Save omaraflak/ebc3801b0e5a7b5e328d9b27e36c4e38 to your computer and use it in GitHub Desktop.
Moon API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from datetime import datetime, timezone, timedelta | |
from pylunar import MoonInfo | |
def datetime_to_tuple(date: datetime) -> tuple[int, int, int, int, int, int]: | |
return (date.year, date.month, date.day, date.hour, date.minute, date.second) | |
def min_points(x: list[int], y: list[float]) -> tuple[list[int], list[float]]: | |
min_x = [] | |
min_y = [] | |
for i in range(1, len(y) - 1): | |
if y[i - 1] > y[i] and y[i] < y[i + 1]: | |
min_x.append(x[i]) | |
min_y.append(y[i]) | |
return min_x, min_y | |
@dataclass | |
class ClosestMoon: | |
# time to event in days | |
time: int | |
# distance to earth in km | |
distance: int | |
@dataclass | |
class Moon: | |
# visibility of the moon in % | |
visibility: int | |
# time to full moon in days | |
time_to_full_moon: int | |
# distance to earth in km | |
distance_to_earth: int | |
# next closest moon | |
local_closest_moon: ClosestMoon | |
# next yearly closest moon | |
global_closest_moon: ClosestMoon | |
@classmethod | |
def get(cls, latitude: tuple[int, int, int], longitude: tuple[int, int, int]) -> 'Moon': | |
now = datetime.now(timezone.utc) | |
mi = MoonInfo(latitude, longitude) | |
mi.update(datetime_to_tuple(now)) | |
visibility = int(round(mi.fractional_phase(), 2) * 100) | |
time_to_full_moon = int(mi.time_to_full_moon()) | |
distance_to_earth = int(mi.earth_distance()) | |
time = [] | |
distance = [] | |
for i in range(365): | |
now += timedelta(days=1) | |
mi.update(datetime_to_tuple(now)) | |
time.append(i) | |
distance.append(mi.earth_distance()) | |
min_time, min_distance = min_points(time, distance) | |
global_min_time, global_min_distance = min_points(min_time, min_distance) | |
local_closest_moon = ClosestMoon(min_time[0], int(min_distance[0])) | |
global_closest_moon = ClosestMoon(global_min_time[0], int(global_min_distance[0])) | |
return Moon(visibility, time_to_full_moon, distance_to_earth, local_closest_moon, global_closest_moon) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment