You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

302 lines
10 KiB

  1. #!/usr/bin/env python3
  2. # Kosmorro - Compute The Next Ephemerides
  3. # Copyright (C) 2019 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from abc import ABC, abstractmethod
  18. from typing import Union
  19. from datetime import datetime
  20. from numpy import pi, arcsin
  21. from skyfield.api import Topos, Time
  22. from skyfield.vectorlib import VectorSum as SkfPlanet
  23. from .core import get_skf_objects, get_timescale
  24. from .i18n import _
  25. MOON_PHASES = {
  26. 'NEW_MOON': _('New Moon'),
  27. 'WAXING_CRESCENT': _('Waxing crescent'),
  28. 'FIRST_QUARTER': _('First Quarter'),
  29. 'WAXING_GIBBOUS': _('Waxing gibbous'),
  30. 'FULL_MOON': _('Full Moon'),
  31. 'WANING_GIBBOUS': _('Waning gibbous'),
  32. 'LAST_QUARTER': _('Last Quarter'),
  33. 'WANING_CRESCENT': _('Waning crescent'),
  34. 'UNKNOWN': _('Unavailable')
  35. }
  36. EVENTS = {
  37. 'OPPOSITION': {'message': _('%s is in opposition')},
  38. 'CONJUNCTION': {'message': _('%s and %s are in conjunction')},
  39. 'OCCULTATION': {'message': _('%s occults %s')},
  40. 'MAXIMAL_ELONGATION': {'message': _("%s's largest elongation")},
  41. 'MOON_PERIGEE': {'message': _("%s is at its perigee")},
  42. 'MOON_APOGEE': {'message': _("%s is at its apogee")},
  43. }
  44. class Serializable(ABC):
  45. @abstractmethod
  46. def serialize(self) -> dict:
  47. pass
  48. class MoonPhase(Serializable):
  49. def __init__(self, identifier: str, time: datetime = None, next_phase_date: datetime = None):
  50. if identifier not in MOON_PHASES.keys():
  51. raise ValueError('identifier parameter must be one of %s (got %s)' % (', '.join(MOON_PHASES.keys()),
  52. identifier))
  53. self.identifier = identifier
  54. self.time = time
  55. self.next_phase_date = next_phase_date
  56. def get_phase(self):
  57. return MOON_PHASES[self.identifier]
  58. def get_next_phase_name(self):
  59. next_identifier = self.get_next_phase()
  60. return MOON_PHASES[next_identifier]
  61. def get_next_phase(self):
  62. if self.identifier == 'NEW_MOON' or self.identifier == 'WAXING_CRESCENT':
  63. next_identifier = 'FIRST_QUARTER'
  64. elif self.identifier == 'FIRST_QUARTER' or self.identifier == 'WAXING_GIBBOUS':
  65. next_identifier = 'FULL_MOON'
  66. elif self.identifier == 'FULL_MOON' or self.identifier == 'WANING_GIBBOUS':
  67. next_identifier = 'LAST_QUARTER'
  68. else:
  69. next_identifier = 'NEW_MOON'
  70. return next_identifier
  71. def serialize(self) -> dict:
  72. return {
  73. 'phase': self.identifier,
  74. 'time': self.time.isoformat() if self.time is not None else None,
  75. 'next': {
  76. 'phase': self.get_next_phase(),
  77. 'time': self.next_phase_date.isoformat()
  78. }
  79. }
  80. class Object(Serializable):
  81. """
  82. An astronomical object.
  83. """
  84. def __init__(self,
  85. name: str,
  86. skyfield_name: str,
  87. radius: float = None):
  88. """
  89. Initialize an astronomical object
  90. :param str name: the official name of the object (may be internationalized)
  91. :param str skyfield_name: the internal name of the object in Skyfield library
  92. :param float radius: the radius (in km) of the object
  93. :param AsterEphemerides ephemerides: the ephemerides associated to the object
  94. """
  95. self.name = name
  96. self.skyfield_name = skyfield_name
  97. self.radius = radius
  98. def __repr__(self):
  99. return '<Object type=%s name=%s />' % (self.get_type(), self.name)
  100. def get_skyfield_object(self) -> SkfPlanet:
  101. return get_skf_objects()[self.skyfield_name]
  102. @abstractmethod
  103. def get_type(self) -> str:
  104. pass
  105. def get_apparent_radius(self, time: Time, from_place) -> float:
  106. """
  107. Calculate the apparent radius, in degrees, of the object from the given place at a given time.
  108. :param time:
  109. :param from_place:
  110. :return:
  111. """
  112. if self.radius is None:
  113. raise ValueError('Missing radius for %s object' % self.name)
  114. return 360 / pi * arcsin(self.radius / from_place.at(time).observe(self.get_skyfield_object()).distance().km)
  115. def serialize(self) -> dict:
  116. return {
  117. 'name': self.name,
  118. 'type': self.get_type(),
  119. 'radius': self.radius,
  120. }
  121. class Star(Object):
  122. def get_type(self) -> str:
  123. return 'star'
  124. class Planet(Object):
  125. def get_type(self) -> str:
  126. return 'planet'
  127. class DwarfPlanet(Planet):
  128. def get_type(self) -> str:
  129. return 'dwarf_planet'
  130. class Satellite(Object):
  131. def get_type(self) -> str:
  132. return 'satellite'
  133. class Event(Serializable):
  134. def __init__(self, event_type: str, objects: [Object], start_time: datetime,
  135. end_time: Union[datetime, None] = None, details: str = None):
  136. if event_type not in EVENTS.keys():
  137. accepted_types = ', '.join(EVENTS.keys())
  138. raise ValueError('event_type parameter must be one of the following: %s (got %s)' % (accepted_types,
  139. event_type))
  140. self.event_type = event_type
  141. self.objects = objects
  142. self.start_time = start_time
  143. self.end_time = end_time
  144. self.details = details
  145. def __repr__(self):
  146. return '<Event type=%s objects=[%s] start=%s end=%s details=%s>' % (self.event_type,
  147. self.objects,
  148. self.start_time,
  149. self.end_time,
  150. self.details)
  151. def get_description(self, show_details: bool = True) -> str:
  152. description = EVENTS[self.event_type]['message'] % self._get_objects_name()
  153. if show_details and self.details is not None:
  154. description += ' ({:s})'.format(self.details)
  155. return description
  156. def _get_objects_name(self):
  157. if len(self.objects) == 1:
  158. return self.objects[0].name
  159. return tuple(object.name for object in self.objects)
  160. def serialize(self) -> dict:
  161. return {
  162. 'objects': [object.serialize() for object in self.objects],
  163. 'event': self.event_type,
  164. 'starts_at': self.start_time.isoformat(),
  165. 'ends_at': self.end_time.isoformat() if self.end_time is not None else None,
  166. 'details': self.details
  167. }
  168. def skyfield_to_moon_phase(times: [Time], vals: [int], now: Time) -> Union[MoonPhase, None]:
  169. tomorrow = get_timescale().utc(now.utc_datetime().year, now.utc_datetime().month, now.utc_datetime().day + 1)
  170. phases = list(MOON_PHASES.keys())
  171. current_phase = None
  172. current_phase_time = None
  173. next_phase_time = None
  174. i = 0
  175. if len(times) == 0:
  176. return None
  177. for i, time in enumerate(times):
  178. if now.utc_iso() <= time.utc_iso():
  179. if vals[i] in [0, 2, 4, 6]:
  180. if time.utc_datetime() < tomorrow.utc_datetime():
  181. current_phase_time = time
  182. current_phase = phases[vals[i]]
  183. else:
  184. i -= 1
  185. current_phase_time = None
  186. current_phase = phases[vals[i]]
  187. else:
  188. current_phase = phases[vals[i]]
  189. break
  190. for j in range(i + 1, len(times)):
  191. if vals[j] in [0, 2, 4, 6]:
  192. next_phase_time = times[j]
  193. break
  194. return MoonPhase(current_phase,
  195. current_phase_time.utc_datetime() if current_phase_time is not None else None,
  196. next_phase_time.utc_datetime() if next_phase_time is not None else None)
  197. class AsterEphemerides(Serializable):
  198. def __init__(self,
  199. rise_time: Union[datetime, None],
  200. culmination_time: Union[datetime, None],
  201. set_time: Union[datetime, None],
  202. aster: Object):
  203. self.rise_time = rise_time
  204. self.culmination_time = culmination_time
  205. self.set_time = set_time
  206. self.object = aster
  207. def serialize(self) -> dict:
  208. return {
  209. 'object': self.object.serialize(),
  210. 'rise_time': self.rise_time.isoformat() if self.rise_time is not None else None,
  211. 'culmination_time': self.culmination_time.isoformat() if self.culmination_time is not None else None,
  212. 'set_time': self.set_time.isoformat() if self.set_time is not None else None
  213. }
  214. MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
  215. EARTH = Planet('Earth', 'EARTH')
  216. ASTERS = [Star(_('Sun'), 'SUN', radius=696342),
  217. Satellite(_('Moon'), 'MOON', radius=1737.4),
  218. Planet(_('Mercury'), 'MERCURY', radius=2439.7),
  219. Planet(_('Venus'), 'VENUS', radius=6051.8),
  220. Planet(_('Mars'), 'MARS', radius=3396.2),
  221. Planet(_('Jupiter'), 'JUPITER BARYCENTER', radius=71492),
  222. Planet(_('Saturn'), 'SATURN BARYCENTER', radius=60268),
  223. Planet(_('Uranus'), 'URANUS BARYCENTER', radius=25559),
  224. Planet(_('Neptune'), 'NEPTUNE BARYCENTER', radius=24764),
  225. Planet(_('Pluto'), 'PLUTO BARYCENTER', radius=1185)]
  226. class Position:
  227. def __init__(self, latitude: float, longitude: float, aster: Object):
  228. self.latitude = latitude
  229. self.longitude = longitude
  230. self.aster = aster
  231. self._topos = None
  232. def get_planet_topos(self) -> Topos:
  233. if self.aster is None:
  234. raise TypeError('Observation planet must be set.')
  235. if self._topos is None:
  236. self._topos = self.aster.get_skyfield_object() + Topos(latitude_degrees=self.latitude,
  237. longitude_degrees=self.longitude)
  238. return self._topos