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.

5 年之前
5 年之前
5 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. }
  42. class Serializable(ABC):
  43. @abstractmethod
  44. def serialize(self) -> dict:
  45. pass
  46. class MoonPhase(Serializable):
  47. def __init__(self, identifier: str, time: datetime = None, next_phase_date: datetime = None):
  48. if identifier not in MOON_PHASES.keys():
  49. raise ValueError('identifier parameter must be one of %s (got %s)' % (', '.join(MOON_PHASES.keys()),
  50. identifier))
  51. self.identifier = identifier
  52. self.time = time
  53. self.next_phase_date = next_phase_date
  54. def get_phase(self):
  55. return MOON_PHASES[self.identifier]
  56. def get_next_phase_name(self):
  57. next_identifier = self.get_next_phase()
  58. return MOON_PHASES[next_identifier]
  59. def get_next_phase(self):
  60. if self.identifier == 'NEW_MOON' or self.identifier == 'WAXING_CRESCENT':
  61. next_identifier = 'FIRST_QUARTER'
  62. elif self.identifier == 'FIRST_QUARTER' or self.identifier == 'WAXING_GIBBOUS':
  63. next_identifier = 'FULL_MOON'
  64. elif self.identifier == 'FULL_MOON' or self.identifier == 'WANING_GIBBOUS':
  65. next_identifier = 'LAST_QUARTER'
  66. else:
  67. next_identifier = 'NEW_MOON'
  68. return next_identifier
  69. def serialize(self) -> dict:
  70. return {
  71. 'phase': self.identifier,
  72. 'time': self.time.isoformat() if self.time is not None else None,
  73. 'next': {
  74. 'phase': self.get_next_phase(),
  75. 'time': self.next_phase_date.isoformat()
  76. }
  77. }
  78. class Object(Serializable):
  79. """
  80. An astronomical object.
  81. """
  82. def __init__(self,
  83. name: str,
  84. skyfield_name: str,
  85. radius: float = None):
  86. """
  87. Initialize an astronomical object
  88. :param str name: the official name of the object (may be internationalized)
  89. :param str skyfield_name: the internal name of the object in Skyfield library
  90. :param float radius: the radius (in km) of the object
  91. :param AsterEphemerides ephemerides: the ephemerides associated to the object
  92. """
  93. self.name = name
  94. self.skyfield_name = skyfield_name
  95. self.radius = radius
  96. def get_skyfield_object(self) -> SkfPlanet:
  97. return get_skf_objects()[self.skyfield_name]
  98. @abstractmethod
  99. def get_type(self) -> str:
  100. pass
  101. def get_apparent_radius(self, time: Time, from_place) -> float:
  102. """
  103. Calculate the apparent radius, in degrees, of the object from the given place at a given time.
  104. :param time:
  105. :param from_place:
  106. :return:
  107. """
  108. if self.radius is None:
  109. raise ValueError('Missing radius for %s object' % self.name)
  110. return 360 / pi * arcsin(self.radius / from_place.at(time).observe(self.get_skyfield_object()).distance().km)
  111. def serialize(self) -> dict:
  112. return {
  113. 'name': self.name,
  114. 'type': self.get_type(),
  115. 'radius': self.radius,
  116. }
  117. class Star(Object):
  118. def get_type(self) -> str:
  119. return 'star'
  120. class Planet(Object):
  121. def get_type(self) -> str:
  122. return 'planet'
  123. class DwarfPlanet(Planet):
  124. def get_type(self) -> str:
  125. return 'dwarf_planet'
  126. class Satellite(Object):
  127. def get_type(self) -> str:
  128. return 'satellite'
  129. class Event(Serializable):
  130. def __init__(self, event_type: str, objects: [Object], start_time: datetime,
  131. end_time: Union[datetime, None] = None, details: str = None):
  132. if event_type not in EVENTS.keys():
  133. accepted_types = ', '.join(EVENTS.keys())
  134. raise ValueError('event_type parameter must be one of the following: %s (got %s)' % (accepted_types,
  135. event_type))
  136. self.event_type = event_type
  137. self.objects = objects
  138. self.start_time = start_time
  139. self.end_time = end_time
  140. self.details = details
  141. def get_description(self, show_details: bool = True) -> str:
  142. description = EVENTS[self.event_type]['message'] % self._get_objects_name()
  143. if show_details and self.details is not None:
  144. description += ' ({:s})'.format(self.details)
  145. return description
  146. def _get_objects_name(self):
  147. if len(self.objects) == 1:
  148. return self.objects[0].name
  149. return tuple(object.name for object in self.objects)
  150. def serialize(self) -> dict:
  151. return {
  152. 'objects': [object.serialize() for object in self.objects],
  153. 'event': self.event_type,
  154. 'starts_at': self.start_time.isoformat(),
  155. 'ends_at': self.end_time.isoformat() if self.end_time is not None else None,
  156. 'details': self.details
  157. }
  158. def skyfield_to_moon_phase(times: [Time], vals: [int], now: Time) -> Union[MoonPhase, None]:
  159. tomorrow = get_timescale().utc(now.utc_datetime().year, now.utc_datetime().month, now.utc_datetime().day + 1)
  160. phases = list(MOON_PHASES.keys())
  161. current_phase = None
  162. current_phase_time = None
  163. next_phase_time = None
  164. i = 0
  165. if len(times) == 0:
  166. return None
  167. for i, time in enumerate(times):
  168. if now.utc_iso() <= time.utc_iso():
  169. if vals[i] in [0, 2, 4, 6]:
  170. if time.utc_datetime() < tomorrow.utc_datetime():
  171. current_phase_time = time
  172. current_phase = phases[vals[i]]
  173. else:
  174. i -= 1
  175. current_phase_time = None
  176. current_phase = phases[vals[i]]
  177. else:
  178. current_phase = phases[vals[i]]
  179. break
  180. for j in range(i + 1, len(times)):
  181. if vals[j] in [0, 2, 4, 6]:
  182. next_phase_time = times[j]
  183. break
  184. return MoonPhase(current_phase,
  185. current_phase_time.utc_datetime() if current_phase_time is not None else None,
  186. next_phase_time.utc_datetime() if next_phase_time is not None else None)
  187. class AsterEphemerides(Serializable):
  188. def __init__(self,
  189. rise_time: Union[datetime, None],
  190. culmination_time: Union[datetime, None],
  191. set_time: Union[datetime, None],
  192. aster: Object):
  193. self.rise_time = rise_time
  194. self.culmination_time = culmination_time
  195. self.set_time = set_time
  196. self.object = aster
  197. def serialize(self) -> dict:
  198. return {
  199. 'object': self.object.serialize(),
  200. 'rise_time': self.rise_time.isoformat() if self.rise_time is not None else None,
  201. 'culmination_time': self.culmination_time.isoformat() if self.culmination_time is not None else None,
  202. 'set_time': self.set_time.isoformat() if self.set_time is not None else None
  203. }
  204. MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
  205. EARTH = Planet('Earth', 'EARTH')
  206. ASTERS = [Star(_('Sun'), 'SUN', radius=696342),
  207. Satellite(_('Moon'), 'MOON', radius=1737.4),
  208. Planet(_('Mercury'), 'MERCURY', radius=2439.7),
  209. Planet(_('Venus'), 'VENUS', radius=6051.8),
  210. Planet(_('Mars'), 'MARS', radius=3396.2),
  211. Planet(_('Jupiter'), 'JUPITER BARYCENTER', radius=71492),
  212. Planet(_('Saturn'), 'SATURN BARYCENTER', radius=60268),
  213. Planet(_('Uranus'), 'URANUS BARYCENTER', radius=25559),
  214. Planet(_('Neptune'), 'NEPTUNE BARYCENTER', radius=24764),
  215. Planet(_('Pluto'), 'PLUTO BARYCENTER', radius=1185)]
  216. class Position:
  217. def __init__(self, latitude: float, longitude: float, aster: Object):
  218. self.latitude = latitude
  219. self.longitude = longitude
  220. self.aster = aster
  221. self._topos = None
  222. def get_planet_topos(self) -> Topos:
  223. if self.aster is None:
  224. raise TypeError('Observation planet must be set.')
  225. if self._topos is None:
  226. self._topos = self.aster.get_skyfield_object() + Topos(latitude_degrees=self.latitude,
  227. longitude_degrees=self.longitude)
  228. return self._topos