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.
 
 
 
 

225 lines
7.5 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 skyfield.api import Topos, Time
  21. from skyfield.vectorlib import VectorSum as SkfPlanet
  22. from .core import get_skf_objects, get_timescale
  23. from .i18n import _
  24. MOON_PHASES = {
  25. 'NEW_MOON': _('New Moon'),
  26. 'WAXING_CRESCENT': _('Waxing crescent'),
  27. 'FIRST_QUARTER': _('First Quarter'),
  28. 'WAXING_GIBBOUS': _('Waxing gibbous'),
  29. 'FULL_MOON': _('Full Moon'),
  30. 'WANING_GIBBOUS': _('Waning gibbous'),
  31. 'LAST_QUARTER': _('Last Quarter'),
  32. 'WANING_CRESCENT': _('Waning crescent')
  33. }
  34. EVENTS = {
  35. 'OPPOSITION': {'message': _('%s is in opposition')},
  36. 'CONJUNCTION': {'message': _('%s and %s are in conjunction')},
  37. 'MAXIMAL_ELONGATION': {'message': _("%s's largest elongation")}
  38. }
  39. class MoonPhase:
  40. def __init__(self, identifier: str, time: Union[datetime, None], next_phase_date: Union[datetime, None]):
  41. if identifier not in MOON_PHASES.keys():
  42. raise ValueError('identifier parameter must be one of %s (got %s)' % (', '.join(MOON_PHASES.keys()),
  43. identifier))
  44. self.identifier = identifier
  45. self.time = time
  46. self.next_phase_date = next_phase_date
  47. def get_phase(self):
  48. return MOON_PHASES[self.identifier]
  49. def get_next_phase(self):
  50. if self.identifier == 'NEW_MOON' or self.identifier == 'WAXING_CRESCENT':
  51. next_identifier = 'FIRST_QUARTER'
  52. elif self.identifier == 'FIRST_QUARTER' or self.identifier == 'WAXING_GIBBOUS':
  53. next_identifier = 'FULL_MOON'
  54. elif self.identifier == 'FULL_MOON' or self.identifier == 'WANING_GIBBOUS':
  55. next_identifier = 'LAST_QUARTER'
  56. else:
  57. next_identifier = 'NEW_MOON'
  58. return MOON_PHASES[next_identifier]
  59. class Position:
  60. def __init__(self, latitude: float, longitude: float):
  61. self.latitude = latitude
  62. self.longitude = longitude
  63. self.observation_planet = None
  64. self._topos = None
  65. def get_planet_topos(self) -> Topos:
  66. if self.observation_planet is None:
  67. raise TypeError('Observation planet must be set.')
  68. if self._topos is None:
  69. self._topos = self.observation_planet + Topos(latitude_degrees=self.latitude,
  70. longitude_degrees=self.longitude)
  71. return self._topos
  72. class AsterEphemerides:
  73. def __init__(self,
  74. rise_time: Union[datetime, None],
  75. culmination_time: Union[datetime, None],
  76. set_time: Union[datetime, None]):
  77. self.rise_time = rise_time
  78. self.culmination_time = culmination_time
  79. self.set_time = set_time
  80. class Object(ABC):
  81. """
  82. An astronomical object.
  83. """
  84. def __init__(self,
  85. name: str,
  86. skyfield_name: str,
  87. ephemerides: AsterEphemerides or None = 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 AsterEphemerides ephemerides: the ephemerides associated to the object
  93. """
  94. self.name = name
  95. self.skyfield_name = skyfield_name
  96. self.ephemerides = ephemerides
  97. def get_skyfield_object(self) -> SkfPlanet:
  98. return get_skf_objects()[self.skyfield_name]
  99. @abstractmethod
  100. def get_type(self) -> str:
  101. pass
  102. class Star(Object):
  103. def get_type(self) -> str:
  104. return 'star'
  105. class Planet(Object):
  106. def get_type(self) -> str:
  107. return 'planet'
  108. class DwarfPlanet(Planet):
  109. def get_type(self) -> str:
  110. return 'dwarf_planet'
  111. class Satellite(Object):
  112. def get_type(self) -> str:
  113. return 'satellite'
  114. class Event:
  115. def __init__(self, event_type: str, objects: [Object], start_time: datetime,
  116. end_time: Union[datetime, None] = None, details: str = None):
  117. if event_type not in EVENTS.keys():
  118. accepted_types = ', '.join(EVENTS.keys())
  119. raise ValueError('event_type parameter must be one of the following: %s (got %s)' % (accepted_types,
  120. event_type))
  121. self.event_type = event_type
  122. self.objects = objects
  123. self.start_time = start_time
  124. self.end_time = end_time
  125. self.details = details
  126. def get_description(self, show_details: bool = True) -> str:
  127. description = EVENTS[self.event_type]['message'] % self._get_objects_name()
  128. if show_details and self.details is not None:
  129. description += ' ({:s})'.format(self.details)
  130. return description
  131. def _get_objects_name(self):
  132. if len(self.objects) == 1:
  133. return self.objects[0].name
  134. return tuple(object.name for object in self.objects)
  135. def skyfield_to_moon_phase(times: [Time], vals: [int], now: Time) -> Union[MoonPhase, None]:
  136. tomorrow = get_timescale().utc(now.utc_datetime().year, now.utc_datetime().month, now.utc_datetime().day + 1)
  137. phases = list(MOON_PHASES.keys())
  138. current_phase = None
  139. current_phase_time = None
  140. next_phase_time = None
  141. i = 0
  142. if len(times) == 0:
  143. return None
  144. for i, time in enumerate(times):
  145. if now.utc_iso() <= time.utc_iso():
  146. if vals[i] in [0, 2, 4, 6]:
  147. if time.utc_datetime() < tomorrow.utc_datetime():
  148. current_phase_time = time
  149. current_phase = phases[vals[i]]
  150. else:
  151. i -= 1
  152. current_phase_time = None
  153. current_phase = phases[vals[i]]
  154. else:
  155. current_phase = phases[vals[i]]
  156. break
  157. for j in range(i + 1, len(times)):
  158. if vals[j] in [0, 2, 4, 6]:
  159. next_phase_time = times[j]
  160. break
  161. return MoonPhase(current_phase,
  162. current_phase_time.utc_datetime() if current_phase_time is not None else None,
  163. next_phase_time.utc_datetime() if next_phase_time is not None else None)
  164. MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
  165. ASTERS = [Star(_('Sun'), 'SUN'),
  166. Satellite(_('Moon'), 'MOON'),
  167. Planet(_('Mercury'), 'MERCURY'),
  168. Planet(_('Venus'), 'VENUS'),
  169. Planet(_('Mars'), 'MARS'),
  170. Planet(_('Jupiter'), 'JUPITER BARYCENTER'),
  171. Planet(_('Saturn'), 'SATURN BARYCENTER'),
  172. Planet(_('Uranus'), 'URANUS BARYCENTER'),
  173. Planet(_('Neptune'), 'NEPTUNE BARYCENTER'),
  174. Planet(_('Pluto'), 'PLUTO BARYCENTER')]