A library that computes the ephemerides.
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.
 
 

255 regels
7.6 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
  24. from .enum import MoonPhaseType, EventType
  25. class Serializable(ABC):
  26. @abstractmethod
  27. def serialize(self) -> dict:
  28. pass
  29. class MoonPhase(Serializable):
  30. def __init__(
  31. self,
  32. phase_type: MoonPhaseType,
  33. time: datetime = None,
  34. next_phase_date: datetime = None,
  35. ):
  36. self.phase_type = phase_type
  37. self.time = time
  38. self.next_phase_date = next_phase_date
  39. def get_next_phase(self):
  40. if self.phase_type in [MoonPhaseType.NEW_MOON, MoonPhaseType.WAXING_CRESCENT]:
  41. return MoonPhaseType.FIRST_QUARTER
  42. if self.phase_type in [
  43. MoonPhaseType.FIRST_QUARTER,
  44. MoonPhaseType.WAXING_GIBBOUS,
  45. ]:
  46. return MoonPhaseType.FULL_MOON
  47. if self.phase_type in [MoonPhaseType.FULL_MOON, MoonPhaseType.WANING_GIBBOUS]:
  48. return MoonPhaseType.LAST_QUARTER
  49. return MoonPhaseType.NEW_MOON
  50. def serialize(self) -> dict:
  51. return {
  52. "phase": self.phase_type.name,
  53. "time": self.time.isoformat() if self.time is not None else None,
  54. "next": {
  55. "phase": self.get_next_phase().name,
  56. "time": self.next_phase_date.isoformat(),
  57. },
  58. }
  59. class Object(Serializable):
  60. """
  61. An astronomical object.
  62. """
  63. def __init__(self, name: str, skyfield_name: str, radius: float = None):
  64. """
  65. Initialize an astronomical object
  66. :param str name: the official name of the object (may be internationalized)
  67. :param str skyfield_name: the internal name of the object in Skyfield library
  68. :param float radius: the radius (in km) of the object
  69. :param AsterEphemerides ephemerides: the ephemerides associated to the object
  70. """
  71. self.name = name
  72. self.skyfield_name = skyfield_name
  73. self.radius = radius
  74. def __repr__(self):
  75. return "<Object type=%s name=%s />" % (self.get_type(), self.name)
  76. def get_skyfield_object(self) -> SkfPlanet:
  77. return get_skf_objects()[self.skyfield_name]
  78. @abstractmethod
  79. def get_type(self) -> str:
  80. pass
  81. def get_apparent_radius(self, time: Time, from_place) -> float:
  82. """
  83. Calculate the apparent radius, in degrees, of the object from the given place at a given time.
  84. :param time:
  85. :param from_place:
  86. :return:
  87. """
  88. if self.radius is None:
  89. raise ValueError("Missing radius for %s object" % self.name)
  90. return (
  91. 360
  92. / pi
  93. * arcsin(
  94. self.radius
  95. / from_place.at(time).observe(self.get_skyfield_object()).distance().km
  96. )
  97. )
  98. def serialize(self) -> dict:
  99. return {
  100. "name": self.name,
  101. "type": self.get_type(),
  102. "radius": self.radius,
  103. }
  104. class Star(Object):
  105. def get_type(self) -> str:
  106. return "star"
  107. class Planet(Object):
  108. def get_type(self) -> str:
  109. return "planet"
  110. class DwarfPlanet(Planet):
  111. def get_type(self) -> str:
  112. return "dwarf_planet"
  113. class Satellite(Object):
  114. def get_type(self) -> str:
  115. return "satellite"
  116. class Event(Serializable):
  117. def __init__(
  118. self,
  119. event_type: EventType,
  120. objects: [Object],
  121. start_time: datetime,
  122. end_time: Union[datetime, None] = None,
  123. details: str = None,
  124. ):
  125. self.event_type = event_type
  126. self.objects = objects
  127. self.start_time = start_time
  128. self.end_time = end_time
  129. self.details = details
  130. def __repr__(self):
  131. return "<Event type=%s objects=%s start=%s end=%s details=%s />" % (
  132. self.event_type.name,
  133. self.objects,
  134. self.start_time,
  135. self.end_time,
  136. self.details,
  137. )
  138. def get_description(self, show_details: bool = True) -> str:
  139. description = self.event_type.value % self._get_objects_name()
  140. if show_details and self.details is not None:
  141. description += " ({:s})".format(self.details)
  142. return description
  143. def _get_objects_name(self):
  144. if len(self.objects) == 1:
  145. return self.objects[0].name
  146. return tuple(object.name for object in self.objects)
  147. def serialize(self) -> dict:
  148. return {
  149. "objects": [object.serialize() for object in self.objects],
  150. "EventType": self.event_type.name,
  151. "starts_at": self.start_time.isoformat(),
  152. "ends_at": self.end_time.isoformat() if self.end_time is not None else None,
  153. "details": self.details,
  154. }
  155. class AsterEphemerides(Serializable):
  156. def __init__(
  157. self,
  158. rise_time: Union[datetime, None],
  159. culmination_time: Union[datetime, None],
  160. set_time: Union[datetime, None],
  161. aster: Object,
  162. ):
  163. self.rise_time = rise_time
  164. self.culmination_time = culmination_time
  165. self.set_time = set_time
  166. self.object = aster
  167. def serialize(self) -> dict:
  168. return {
  169. "object": self.object.serialize(),
  170. "rise_time": self.rise_time.isoformat()
  171. if self.rise_time is not None
  172. else None,
  173. "culmination_time": self.culmination_time.isoformat()
  174. if self.culmination_time is not None
  175. else None,
  176. "set_time": self.set_time.isoformat()
  177. if self.set_time is not None
  178. else None,
  179. }
  180. EARTH = Planet("Earth", "EARTH")
  181. ASTERS = [
  182. Star("Sun", "SUN", radius=696342),
  183. Satellite("Moon", "MOON", radius=1737.4),
  184. Planet("Mercury", "MERCURY", radius=2439.7),
  185. Planet("Venus", "VENUS", radius=6051.8),
  186. Planet("Mars", "MARS", radius=3396.2),
  187. Planet("Jupiter", "JUPITER BARYCENTER", radius=71492),
  188. Planet("Saturn", "SATURN BARYCENTER", radius=60268),
  189. Planet("Uranus", "URANUS BARYCENTER", radius=25559),
  190. Planet("Neptune", "NEPTUNE BARYCENTER", radius=24764),
  191. Planet("Pluto", "PLUTO BARYCENTER", radius=1185),
  192. ]
  193. class Position:
  194. def __init__(self, latitude: float, longitude: float, aster: Object):
  195. self.latitude = latitude
  196. self.longitude = longitude
  197. self.aster = aster
  198. self._topos = None
  199. def get_planet_topos(self) -> Topos:
  200. if self.aster is None:
  201. raise TypeError("Observation planet must be set.")
  202. if self._topos is None:
  203. self._topos = self.aster.get_skyfield_object() + Topos(
  204. latitude_degrees=self.latitude, longitude_degrees=self.longitude
  205. )
  206. return self._topos