import numpy as np

import astropy.units as u
from astropy import time

from poliastro import iod
from poliastro.bodies import Sun
from poliastro.twobody import Orbit

from poliastro.util import time_range

"""
Explanation: Going to Mars with Python using poliastro
<img src="http://docs.poliastro.space/en/latest/_images/logo_text.png" />
This is an example on how to use poliastro, a little library I've been working on to use in my Astrodynamics lessons. It features conversion between classical orbital elements and position vectors, propagation of Keplerian orbits, initial orbit determination using the solution of the Lambert's problem and orbit plotting.
In this example we're going to draw the trajectory of the mission Mars Science Laboratory (MSL), which carried the rover Curiosity to the surface of Mars in a period of something less than 9 months.
Note: This is a very simplistic analysis which doesn't take into account many important factors of the mission, but can serve as an starting point for more serious computations (and as a side effect produces a beautiful plot at the end).
<div class="alert alert-info">An earlier version of this notebook allowed for more flexibility and interactivity, but was considerably more complex. Future versions of poliastro and plotly might bring back part of that functionality, depending on user feedback. You can still download the older version <a href="https://github.com/poliastro/poliastro/blob/0.7.x/docs/source/examples/Going%20to%20Mars%20with%20Python%20using%20poliastro.ipynb">here</a>.</div>

First of all, we import the necessary modules. Apart from poliastro we will make use of astropy to deal with physical units and time definitions and jplephem to compute the positions and velocities of the planets.
End of explanation
"""


from astropy.coordinates import solar_system_ephemeris, get_body_barycentric_posvel
solar_system_ephemeris.set("jpl")

"""
Explanation: We need a binary file from NASA called SPICE kernel to compute the position and velocities of the planets. Astropy downloads it for us:
End of explanation
"""


# Initial data
N = 50

date_launch = time.Time('2011-11-26 15:02', scale='utc')
date_arrival = time.Time('2012-08-06 05:17', scale='utc')
tof = (date_arrival - date_launch)

tof.to(u.h)

"""
Explanation: The initial data was gathered from Wikipedia: the date of the launch was on November 26, 2011 at 15:02 UTC and landing was on August 6, 2012 at 05:17 UTC. We compute then the time of flight, which is exactly what it sounds. It is a crucial parameter of the mission.
End of explanation
"""


times_vector = time_range(date_launch, end=date_arrival, periods=N)
times_vector[:5]

rr_earth, vv_earth = get_body_barycentric_posvel("earth", times_vector)

rr_earth[:3]

vv_earth[:3]

rr_mars, vv_mars = get_body_barycentric_posvel("mars", times_vector)

rr_mars[:3]

vv_mars[:3]

"""
Explanation: Once we have the vector of times we can use get_body_barycentric_posvel to compute the array of positions and velocities of the Earth and Mars.
End of explanation
"""


# Compute the transfer orbit!
r0 = rr_earth[0].xyz
rf = rr_mars[-1].xyz

(va, vb), = iod.lambert(Sun.k, r0, rf, tof)

ss0_trans = Orbit.from_vectors(Sun, r0, va, date_launch)
ssf_trans = Orbit.from_vectors(Sun, rf, vb, date_arrival)

"""
Explanation: <div class="alert alert-info">The positions and velocities are in the <strong>International Standard Reference Frame</strong>, which has the Equator as the fundamental plane</div>

To compute the transfer orbit, we have the useful function lambert: according to a theorem with the same name, the transfer orbit between two points in space only depends on those two points and the time it takes to go from one to the other. We have the starting and final position and we have the time of flight: there we go!
End of explanation
"""


from plotly.offline import init_notebook_mode
init_notebook_mode(connected=True)

from poliastro.plotting import OrbitPlotter3D
from poliastro.bodies import Earth, Mars

# I like color
color_earth0 = '#3d4cd5'
color_earthf = '#525fd5'
color_mars0 = '#ec3941'
color_marsf = '#ec1f28'
color_sun = '#ffcc00'
color_orbit = '#888888'
color_trans = '#444444'

frame = OrbitPlotter3D()

frame.set_attractor(Sun)

frame.plot_trajectory(rr_earth, label=Earth, color=color_earth0)
frame.plot_trajectory(rr_mars, label=Mars, color=color_marsf)

frame.plot_trajectory(ss0_trans.sample(times_vector), label="MSL trajectory", color=color_trans)

frame.set_view(30 * u.deg, 260 * u.deg, distance=3 * u.km)
frame.show(title="MSL Mission: from Earth to Mars")

"""
Explanation: And finally, we can plot the figure! There is no more magic here, just passing the position vectors to matplotlib plot function and adding some style to the plot.
End of explanation
"""


#frame.savefig("msl3d.png", title="MSL Mission: from Earth to Mars")

"""
Explanation: This line opens a new browser tab and saves the resulting image:
End of explanation
"""


from IPython.display import YouTubeVideo
YouTubeVideo('zSgiXGELjbc')

"""
Explanation: Not bad! Let's celebrate with some music!
End of explanation
"""


