Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

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