Esempio n. 1
0
 def test_kernel_download(self, kernel):
     if 'TRAVIS' in os.environ:
         for url in spice.kernel_dict[kernel].urls:
             if url[:3] == 'ftp':
                 pytest.skip("FTP doesn't work on travis")
     with pytest.warns(None) as record:
         spice.get_kernel(kernel)
     assert len(record) == 0
Esempio n. 2
0
def test_kernel_download(kernel):
    if 'TRAVIS' in os.environ:
        for url in spice.kernel_dict[kernel].urls:
            if url[:3] == 'ftp':
                pytest.skip("FTP doesn't work on travis")
    if 'AZURE' in os.environ and 'psp' in kernel:
        pytest.skip("PSP kernels don't work on Azure")
    with pytest.warns(None) as record:
        spice.get_kernel(kernel)
    assert len(record) == 0
Esempio n. 3
0
    def extractSolOrbit(self):
        """
        Get the SPICE orbit data for SolO and put into coordsCarrington
        """
        import heliopy.data.spice as spicedata
        import heliopy.spice as spice

        spicedata.get_kernel("solo")
        solo = spice.Trajectory("Solar Orbiter")
        times = list(self.df.index.to_pydatetime())
        solo.generate_positions(times, 'Sun', 'IAU_SUN')  # Is in KM
        self.coordsCarrington = solo.coords.transform_to(
            frame=frames.HeliographicCarrington)
Esempio n. 4
0
def get_sc_lonlat_test(kernel, scname, frame, starttime, endtime, res_in_days):
    '''
 make spacecraft positions
 
 kernel,scname,frame,starttime, endtime,res_in_days
 'psp_pred','SPP','HEEQ',datetime(2018, 8,13),'datetime(2024, 8,13), 1

 kernels: psp_pred, stereoa_pred, 
 frames: ECLIPJ2000 HEE HEEQ, HCI
 frames https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/frames.html  Appendix. ``Built in'' Inertial Reference Frames

 '''
    spice.furnish(spicedata.get_kernel(kernel))
    sc = spice.Trajectory(scname)
    sc_time = []
    while starttime < endtime:
        sc_time.append(starttime)
        starttime += timedelta(days=res_in_days)

    sc_time_num = mdates.date2num(sc_time)
    sc.generate_positions(sc_time, 'Sun', frame)
    sc.change_units(astropy.units.AU)
    sc_r, sc_lat, sc_lon = cart2sphere(sc.x, sc.y, sc.z)
    screc = np.rec.array([sc_time_num, sc_r, sc_lon, sc_lat, sc.x, sc.y, sc.z],
                         dtype=[('time', 'f8'), ('r', 'f8'), ('lon', 'f8'),
                                ('lat', 'f8'), ('x', 'f8'), ('y', 'f8'),
                                ('z', 'f8')])

    return screc
Esempio n. 5
0
def _setup_spice():
    '''
    Method to download some common files that spice needs to do orbit
    calculations.
    '''
    for kernel in ['lsk', 'planet_trajectories']:
        loc = dataspice.get_kernel(kernel)
        spiceypy.furnsh(loc)
Esempio n. 6
0
def _setup_spice():
    '''
    Method to download some common files that spice needs to do orbit
    calculations.
    '''
    for kernel in dataspice.generic_kernels:
        loc = dataspice.get_kernel(kernel.short_name)
        spiceypy.furnsh(loc)
Esempio n. 7
0
    def load(self, body_name):
        if body_name not in self.loaded_kernels:
            if not self.setup_has_been_run:
                spice.setup_spice()
                self.setup_has_been_run = True

            if body_name == 'psp':
                kernels = spicedata.get_kernel('psp')
                kernels += spicedata.get_kernel('psp_pred')
                spice.furnish(kernels)
                self.loaded_kernels.append(body_name)

            if body_name == 'stereo_a':
                kernels = spicedata.get_kernel('stereo_a')
                kernels += spicedata.get_kernel('stereo_a_pred')
                spice.furnish(kernels)
                self.loaded_kernels.append(body_name)

            if body_name == 'stereo_b':
                kernels = spicedata.get_kernel('stereo_b')
                kernels += spicedata.get_kernel('stereo_b_pred')
                spice.furnish(kernels)
                self.loaded_kernels.append(body_name)

            if body_name == 'soho':
                kernels = spicedata.get_kernel('soho')
                spice.furnish(kernels)
                self.loaded_kernels.append(body_name)
Esempio n. 8
0
def test_kernel():
    kernel = spicedata.get_kernel('helios1')[0]
    solo = spice.Body('helios 1')
    assert len(kernel.bodies) == 1
    assert kernel.bodies[0] == solo

    assert kernel.coverage(solo) == [
        datetime.datetime(1974, 12, 10, 23, 50, 1, 662,
                          tzinfo=datetime.timezone.utc),
        datetime.datetime(1981, 9, 30, 1, 29, 54, 1651,
                          tzinfo=datetime.timezone.utc)
    ]
Esempio n. 9
0
def kernel_loader(spacecraft: Union[int, str] = 2) -> spice.Trajectory:
    """
    :param spacecraft: 1 or 2 for Helios 1  or 2, can also be 'ulysses'
    :return: unfurnished  orbiter
    """
    if spacecraft == 1 or spacecraft == 2:
        if spacecraft == 1:
            orbiter_kernel = spice_data.get_kernel('helios1_rec')
        else:
            orbiter_kernel = spice_data.get_kernel('helios2')
        spice.furnish(orbiter_kernel)
        orbiter = spice.Trajectory('Helios ' + str(spacecraft))

    # elif spacecraft == 'ulysses':
    #     orbiter_kernel = spice_data.get_kernel(str(spacecraft))
    #     spice.furnish(orbiter_kernel)
    #     orbiter = spice.Trajectory(spacecraft)
    else:
        raise NotImplementedError('The only probes that can be imported are Helios 1 , Helios 2 and Ulysses')

    return orbiter
Esempio n. 10
0
def test_spice():
    orbiter_kernel = spicedata.get_kernel('solo_2020')
    spice.furnish(orbiter_kernel)
    orbiter = spice.Trajectory('Solar Orbiter')

    # Generate 1000 days of data
    starttime = datetime(2020, 3, 1)
    times = [starttime + n * timedelta(days=1) for n in range(1000)]

    orbiter.generate_positions(times, 'Sun', 'ECLIPJ2000')
    assert orbiter.times == times

    # Check it works with numpy arrays too
    times = np.array(times)
    orbiter.generate_positions(times, 'Sun', 'ECLIPJ2000')
Esempio n. 11
0
def test_kernel_download(kernel):
    if 'TRAVIS' in os.environ:
        for url in spicedata.kernel_dict[kernel].urls:
            if url[:3] == 'ftp':
                pytest.skip("FTP doesn't work on travis")
    if 'AZURE' in os.environ and 'psp' in kernel:
        pytest.skip("PSP kernels don't work on Azure")

    # Test download
    with pytest.warns(None) as record:
        kernel = spicedata.get_kernel(kernel)[0]
    assert len(record) == 0

    # Check that kernel is valid
    if isinstance(kernel, spice.SPKKernel):
        kernel.bodies
Esempio n. 12
0
def get_planet_orbit(planet: str, start_date: str = '20/01/1976', end_date: str = '01/10/1979',
                     interval: float = 1) -> spice.Trajectory:
    """
    Finds the orbiter for a given planet
    :param planet: planet that we want to analyse
    :param start_date: start date of analysis
    :param end_date: end date of analysis
    :param interval: interval between each date in the orbiter, defaults to 1
    :return: orbiter of the planet
    """
    orbiter_kernel = spice_data.get_kernel('planet_trajectories')
    spice.furnish(orbiter_kernel)
    orbiter = spice.Trajectory(planet)
    start_time = datetime.strptime(start_date, '%d/%m/%Y')
    end_time = datetime.strptime(end_date, '%d/%m/%Y')
    times = []
    while start_time < end_time:
        times.append(start_time)
        start_time = start_time + timedelta(days=interval)
    orbiter.generate_positions(times, 'Sun', 'ECLIPJ2000')
    orbiter.change_units(u.au)
    return orbiter
Esempio n. 13
0
def test_kernel():
    kernel = spicedata.get_kernel('solo')[0]
    solo = spice.Body('solar orbiter')
    assert len(kernel.bodies) == 1
    assert kernel.bodies[0] == solo

    assert kernel.coverage(solo) == [
        datetime.datetime(2020,
                          2,
                          10,
                          4,
                          55,
                          49,
                          670002,
                          tzinfo=datetime.timezone.utc),
        datetime.datetime(2030,
                          11,
                          20,
                          10,
                          54,
                          51,
                          644258,
                          tzinfo=datetime.timezone.utc)
    ]
Esempio n. 14
0
def solo_trajectory():
    orbiter_kernel = spicedata.get_kernel('solo')
    spice.furnish(orbiter_kernel)
    return spice.Trajectory('Solar Orbiter')
Esempio n. 15
0
# ---
# - Working with SPICE kernels
# - Built-in support for:
#     - Helios, Juno, **PSP**, **Solar Orbiter**, STEREO, Ulysses
# - Can work with custom SPICE kernels

# ``heliopy.spice`` example
# ---

# In[5]:

from heliopy import spice
import heliopy.data.spice as spicedata

# Download and load Solar Orbiter predicted SPICE kernel
spice.furnish(spicedata.get_kernel('solo_2020'))
solo = spice.Trajectory('Solar Orbiter')

# Specify times at which to sample the trajectory
from datetime import datetime, timedelta
starttime = datetime(2020, 2, 20)
times = [starttime + timedelta(days=i) for i in range(365)]

# Generate the trajectory
solo.generate_positions(times, 'Sun', 'ECLIPJ2000')

# Print first 3 positions
print('Positions:', solo.x[:3], solo.y[:3], solo.z[:3], sep='\n')

# In[6]:
Esempio n. 16
0
In this example we download the Solar Orbiter SPICE kernel, and plot it's orbit
from 2020 to 2028.
"""


import heliopy.data.spice as spicedata
import heliopy.spice as spice
from datetime import datetime, timedelta
import astropy.units as u
import numpy as np

###############################################################################
# Load the solar orbiter spice kernel. HelioPy will automatically fetch the
# latest kernel
orbiter_kernel = spicedata.get_kernel('solo_2020')
spice.furnish(orbiter_kernel)
orbiter = spice.Trajectory('Solar Orbiter')

###############################################################################
# Generate a time for every day between starttime and endtime
starttime = datetime(2020, 3, 1)
endtime = datetime(2028, 1, 1)
times = []
while starttime < endtime:
    times.append(starttime)
    starttime += timedelta(days=1)

###############################################################################
# Generate positions
orbiter.generate_positions(times, 'Sun', 'ECLIPJ2000')
Esempio n. 17
0
def make_positions():

    ##########################################  PSP

    starttime =datetime(2018, 8,13)
    endtime = datetime(2025, 8, 31)
    psp_time = []
    while starttime < endtime:
        psp_time.append(starttime)
        starttime += timedelta(days=res_in_days)
    psp_time_num=mdates.date2num(psp_time)     

    spice.furnish(spicedata.get_kernel('psp_pred'))
    psp=spice.Trajectory('SPP')
    psp.generate_positions(psp_time,'Sun',frame)
    print('PSP pos')

    psp.change_units(astropy.units.AU)  
    [psp_r, psp_lat, psp_lon]=cart2sphere(psp.x,psp.y,psp.z)
    print('PSP conv')


    ############################################## BepiColombo

    starttime =datetime(2018, 10, 21)
    endtime = datetime(2025, 11, 2)
    bepi_time = []
    while starttime < endtime:
        bepi_time.append(starttime)
        starttime += timedelta(days=res_in_days)
    bepi_time_num=mdates.date2num(bepi_time) 

    spice.furnish(spicedata.get_kernel('bepi_pred'))
    bepi=spice.Trajectory('BEPICOLOMBO MPO') # or BEPICOLOMBO MMO
    bepi.generate_positions(bepi_time,'Sun',frame)
    bepi.change_units(astropy.units.AU)  
    [bepi_r, bepi_lat, bepi_lon]=cart2sphere(bepi.x,bepi.y,bepi.z)
    print('Bepi')



    #################################################### Solar Orbiter

    starttime = datetime(2020, 3, 1)
    endtime = datetime(2026, 1, 1)
    solo_time = []
    while starttime < endtime:
        solo_time.append(starttime)
        starttime += timedelta(days=res_in_days)
    solo_time_num=mdates.date2num(solo_time) 

    spice.furnish(spicedata.get_kernel('solo_2020'))
    solo=spice.Trajectory('Solar Orbiter')
    solo.generate_positions(solo_time, 'Sun',frame)
    solo.change_units(astropy.units.AU)
    [solo_r, solo_lat, solo_lon]=cart2sphere(solo.x,solo.y,solo.z)
    print('Solo')






    plt.figure(1, figsize=(12,9))
    plt.plot_date(psp_time,psp_r,'-', label='R')
    plt.plot_date(psp_time,psp_lat,'-',label='lat')
    plt.plot_date(psp_time,psp_lon,'-',label='lon')
    plt.ylabel('AU / RAD')
    plt.legend()




    plt.figure(2, figsize=(12,9))
    plt.plot_date(bepi_time,bepi_r,'-', label='R')
    plt.plot_date(bepi_time,bepi_lat,'-',label='lat')
    plt.plot_date(bepi_time,bepi_lon,'-',label='lon')
    plt.title('Bepi Colombo position '+frame)
    plt.ylabel('AU / RAD')
    plt.legend()




    plt.figure(3, figsize=(12,9))
    plt.plot_date(solo_time,solo_r,'-', label='R')
    plt.plot_date(solo_time,solo_lat,'-',label='lat')
    plt.plot_date(solo_time,solo_lon,'-',label='lon')
    plt.title('Solar Orbiter position '+frame)
    plt.ylabel('AU / RAD')
    plt.legend()


    ########### plots


    ######## R with all three
    plt.figure(4, figsize=(16,10))
    plt.plot_date(psp_time,psp.r,'-',label='PSP')
    plt.plot_date(bepi_time,bepi.r,'-',label='Bepi Colombo')
    plt.plot_date(solo_time,solo.r,'-',label='Solar Orbiter')
    plt.legend()
    plt.title('Heliocentric distance of heliospheric observatories')
    plt.ylabel('AU')
    plt.savefig('results/positions_plots/bepi_psp_solo_R.png')

    ##### Longitude all three
    plt.figure(5, figsize=(16,10))
    plt.plot_date(psp_time,psp_lon*180/np.pi,'-',label='PSP')
    plt.plot_date(bepi_time,bepi_lon*180/np.pi,'-',label='Bepi Colombo')
    plt.plot_date(solo_time,solo_lon*180/np.pi,'-',label='Solar Orbiter')
    plt.legend()
    plt.title(frame+' longitude')
    plt.ylabel('DEG')
    plt.savefig('results/positions_plots/bepi_psp_solo_longitude_'+frame+'.png')


    ############# Earth for mercury, venusus, STA
    #https://docs.heliopy.org/en/stable/data/spice.html


    planet_kernel=spicedata.get_kernel('planet_trajectories')

    starttime =datetime(2018, 1, 1)
    endtime = datetime(2028, 12, 31)
    earth_time = []
    while starttime < endtime:
        earth_time.append(starttime)
        starttime += timedelta(days=res_in_days)
    earth_time_num=mdates.date2num(earth_time)     

    earth=spice.Trajectory('399')  #399 for Earth, not barycenter (because of moon)
    earth.generate_positions(earth_time,'Sun',frame)
    earth.change_units(astropy.units.AU)  
    [earth_r, earth_lat, earth_lon]=cart2sphere(earth.x,earth.y,earth.z)
    print('Earth')

    ################ mercury
    mercury_time_num=earth_time_num
    mercury=spice.Trajectory('1')  #barycenter
    mercury.generate_positions(earth_time,'Sun',frame)  
    mercury.change_units(astropy.units.AU)  
    [mercury_r, mercury_lat, mercury_lon]=cart2sphere(mercury.x,mercury.y,mercury.z)
    print('mercury') 

    ################# venus
    venus_time_num=earth_time_num
    venus=spice.Trajectory('2')  
    venus.generate_positions(earth_time,'Sun',frame)  
    venus.change_units(astropy.units.AU)  
    [venus_r, venus_lat, venus_lon]=cart2sphere(venus.x,venus.y,venus.z)
    print('venus') 


    ############### Mars

    mars_time_num=earth_time_num
    mars=spice.Trajectory('4')  
    mars.generate_positions(earth_time,'Sun',frame)  
    mars.change_units(astropy.units.AU)  
    [mars_r, mars_lat, mars_lon]=cart2sphere(mars.x,mars.y,mars.z)
    print('mars') 

    #############stereo-A
    sta_time_num=earth_time_num
    spice.furnish(spicedata.get_kernel('stereo_a_pred'))
    sta=spice.Trajectory('-234')  
    sta.generate_positions(earth_time,'Sun',frame)  
    sta.change_units(astropy.units.AU)  
    [sta_r, sta_lat, sta_lon]=cart2sphere(sta.x,sta.y,sta.z)
    print('STEREO-A') 



    #save positions 
    if high_res_mode:
     pickle.dump([psp_time,psp_time_num,psp_r,psp_lon,psp_lat,bepi_time,bepi_time_num,bepi_r,bepi_lon,bepi_lat,solo_time,solo_time_num,solo_r,solo_lon,solo_lat], open( 'positions_plots/psp_solo_bepi_'+frame+'_1min.p', "wb" ) )
     sys.exit()
    else: 
     psp=np.rec.array([psp_time_num,psp_r,psp_lon,psp_lat, psp.x, psp.y,psp.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     bepi=np.rec.array([bepi_time_num,bepi_r,bepi_lon,bepi_lat,bepi.x, bepi.y,bepi.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     solo=np.rec.array([solo_time_num,solo_r,solo_lon,solo_lat,solo.x, solo.y,solo.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     sta=np.rec.array([sta_time_num,sta_r,sta_lon,sta_lat,sta.x, sta.y,sta.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     earth=np.rec.array([earth_time_num,earth_r,earth_lon,earth_lat, earth.x, earth.y,earth.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     venus=np.rec.array([venus_time_num,venus_r,venus_lon,venus_lat, venus.x, venus.y,venus.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     mars=np.rec.array([mars_time_num,mars_r,mars_lon,mars_lat, mars.x, mars.y,mars.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     mercury=np.rec.array([mercury_time_num,mercury_r,mercury_lon,mercury_lat,mercury.x, mercury.y,mercury.z],dtype=[('time','f8'),('r','f8'),('lon','f8'),('lat','f8'),('x','f8'),('y','f8'),('z','f8')])
     pickle.dump([psp, bepi, solo, sta, earth, venus, mars, mercury,frame], open( 'results/positions_psp_solo_bepi_sta_planets_'+frame+'_2hours.p', "wb" ) )
     #load with [psp, bepi, solo, sta, earth, venus, mars, mercury,frame]=pickle.load( open( 'positions_psp_solo_bepi_sta_planets_HCI_6hours_2018_2025.p', "rb" ) )
 
 
    end=time.time()
    print( 'generate position took time in seconds:', round((end-start),1) )
Esempio n. 18
0
In this example we download the Parker Solar Probe SPICE kernel, and plot
its orbit for the first year.
"""


import heliopy.data.spice as spicedata
import heliopy.spice as spice
from datetime import datetime, timedelta
import astropy.units as u
import numpy as np

###############################################################################
# Load the solar orbiter spice kernel. heliopy will automatically fetch and
# load the latest kernel
spicedata.get_kernel('psp')
spicedata.get_kernel('psp_pred')
psp = spice.Trajectory('SPP')

###############################################################################
# Generate a time for every day between starttime and endtime
starttime = datetime(2018, 8, 14)
endtime = starttime + timedelta(days=365)
times = []
while starttime < endtime:
    times.append(starttime)
    starttime += timedelta(hours=6)

###############################################################################
# Generate positions
psp.generate_positions(times, 'Sun', 'ECLIPJ2000')
Esempio n. 19
0
How to plot orbits from SPICE kernels.

In this example we download the Solar Orbiter SPICE kernel, and plot it's orbit
from 2020 to 2028.
"""

import heliopy.data.spice as spicedata
import heliopy.spice as spice
from datetime import datetime, timedelta
import astropy.units as u
import numpy as np

###############################################################################
# Load the solar orbiter spice kernel. HelioPy will automatically fetch the
# latest kernel
orbiter_kernel = spicedata.get_kernel('solar orbiter 2020')
spice.furnish(orbiter_kernel)
orbiter = spice.Trajectory('Solar Orbiter')

###############################################################################
# Generate a time for every day between starttime and endtime
starttime = datetime(2020, 3, 1)
endtime = datetime(2028, 1, 1)
times = []
while starttime < endtime:
    times.append(starttime)
    starttime += timedelta(days=1)

###############################################################################
# Generate positions
orbiter.generate_positions(times, 'Sun', 'ECLIPJ2000')
Esempio n. 20
0
#print( 'generate test position took time in seconds:', (end-start) )
#sys.exit()

########################################## MAKE TRAJECTORIES ############################

##########################################  PSP

starttime = datetime(2018, 8, 13)
endtime = datetime(2025, 8, 31)
psp_time = []
while starttime < endtime:
    psp_time.append(starttime)
    starttime += timedelta(days=res_in_days)
psp_time_num = mdates.date2num(psp_time)

spice.furnish(spicedata.get_kernel('psp_pred'))
psp = spice.Trajectory('SPP')
psp.generate_positions(psp_time, 'Sun', frame)
print('PSP pos')

psp.change_units(astropy.units.AU)
[psp_r, psp_lat, psp_lon] = cart2sphere(psp.x, psp.y, psp.z)
print('PSP conv')

############################################## BepiColombo

starttime = datetime(2018, 10, 21)
endtime = datetime(2025, 11, 2)
bepi_time = []
while starttime < endtime:
    bepi_time.append(starttime)
Esempio n. 21
0
def solo_trajectory():
    orbiter_kernel = spicedata.get_kernel('helios1')
    spice.furnish(orbiter_kernel)
    return spice.Trajectory('Helios 1')
Esempio n. 22
0
"""
Overview
--------
`SPICE`_ is a NASA toolkit for calculating the position of bodies
(including planets and spacecraft) within the solar system. This module builds
on the `spiceypy`_ package to provide a high level interface to the SPICE
toolkit for performing orbital calculations using spice kernels.

Integration with :mod:`astropy.coordinates`
-------------------------------------------
As well as allowing positions to be calculated in any coordinate system defined
in the `SPICE`_ toolkit, :mod:`heliopy.spice` can also construct
:class:`astropy.coordinates.SkyCoord` objects if the frame is implemented in
astropy or SunPy. See the documentaiton of
:meth:`heliopy.spice.Trajectory.coords()` for information on which frames are
supported.

.. _SPICE: https://naif.jpl.nasa.gov/naif/toolkit.html
.. _spiceypy: https://spiceypy.readthedocs.io/en/master/
"""
import heliopy.data.spice as dataspice
from .spice import *

for kernel in dataspice.generic_kernels:
    k = dataspice.get_kernel(kernel.short_name)
    furnish(k)
Esempio n. 23
0
# ---
# - Working with SPICE kernels
# - Built-in support for:
#     - Helios, Juno, **PSP**, **Solar Orbiter**, STEREO, Ulysses
# - Can work with custom SPICE kernels

# ``heliopy.spice`` example
# ---

# In[11]:

from heliopy import spice
import heliopy.data.spice as spicedata

# Download and load Solar Orbiter predicted SPICE kernel
spice.furnish(spicedata.get_kernel('solo_2020'))
solo = spice.Trajectory('Solar Orbiter')

# In[12]:

# Specify times at which to sample the trajectory
from datetime import datetime, timedelta
starttime = datetime(2020, 2, 20)
times = [starttime + timedelta(days=i) for i in range(365)]

# Generate the trajectory
solo.generate_positions(times, 'Sun', 'ECLIPJ2000')

# Print first 3 positions
print('Positions:', solo.x[:3], solo.y[:3], solo.z[:3], sep='\n')
Esempio n. 24
0
 def test_built_in(self):
     for kernel in spice.available_kernels:
         spice.get_kernel(kernel)
Esempio n. 25
0
import astropy.units as u
import astropy.constants as const
import astropy.coordinates as coord
import sunpy.coordinates.frames as frames
import heliopy.data.spice as spicedata
from heliopy import spice

for kernel in [
        'psp', 'planet_trajectories', 'planet_orientations', 'psp_pred', 'solo'
]:
    k = spicedata.get_kernel(kernel)
    spice.furnish(k)


def loc(dtime, body):
    traj = spice.Trajectory(body)
    traj.generate_positions([dtime], 'Sun', 'IAU_SUN')
    traj_coord = traj.coords
    traj_coord.representation_type = 'spherical'
    return traj_coord


def spiral_correction(psp_coord, vsw):
    omega_sun = 14.713 * u.deg / u.d

    def delta_long(r):
        return omega_sun * (r - 2.5 * const.R_sun) / vsw

    psp_solar_lon = psp_coord.lon + delta_long(psp_coord.radius)
    psp_solar_surface = coord.SkyCoord(radius=2.49 * const.R_sun,
                                       lat=psp_coord.lat,
Esempio n. 26
0
 def test_built_in(self):
     for kernel in spice.kernel_dict:
         spice.get_kernel(kernel)
Esempio n. 27
0
 def test_kernel_download(self, kernel):
     spice.get_kernel(kernel)
Esempio n. 28
0
def make_arrival_catalog_insitu_ssef30(higeocat,arrcat,ac_old, insitu_location_string, column_list):
    
    #get parameters from HIGEOCAT for arrival catalog

    higeocat_time=parse_time(higeocat['Date']).datetime    #first HI observation
    higeocat_t0=parse_time(higeocat['SSE Launch']).datetime   #backprojected launch time
    higeocat_t0_num=parse_time(higeocat_t0).plot_date
    higeocat_vsse=np.array(higeocat['SSE Speed'])
    higeocat_vsse_err=np.array(higeocat['SSE Speed Err'])
    higeocat_sse_lon=np.array(higeocat['SSE HEEQ Long' ])
    higeocat_sse_lat=np.array(higeocat['SSE HEEQ Lat' ])
    higeocat_id=np.array(higeocat['ID'])
    higeocat_sc=np.array(higeocat['SC'])
    higeocat_pan=np.array(higeocat['PA-N'])
    higeocat_pas=np.array(higeocat['PA-S'])
    higeocat_pafit=np.array(higeocat['PA-fit'])
    higeocat_pacenter=abs((higeocat_pan+higeocat_pas)/2)
  
    
    
    #load spice here once for each spacecraft
        
    if insitu_location_string=='STB': 
        insitu_str='-235'
        insitu_kernel=spicedata.get_kernel('stereo_b')    
        target_name='STEREO-B'
    
    if insitu_location_string=='STA': 
        insitu_str='-234'
        insitu_kernel=spicedata.get_kernel('stereo_a_pred')
        target_name='STEREO-A'
       
    if insitu_location_string=='Mercury': 
        insitu_str='1'
        insitu_kernel=spicedata.get_kernel('planet_trajectories')
        target_name='Mercury'
        
    if insitu_location_string=='Venus': 
        insitu_str='2'
        insitu_kernel=spicedata.get_kernel('planet_trajectories')
        target_name='Venus'
       
    if insitu_location_string=='Earth': 
        insitu_str='3'
        insitu_kernel=spicedata.get_kernel('planet_trajectories')
        target_name='Earth_L1'
        
    if insitu_location_string=='Mars': 
        insitu_str='4'
        insitu_kernel=spicedata.get_kernel('planet_trajectories')        
        target_name='Mars'
        
    if insitu_location_string=='PSP': 
        insitu_str='-96'
        insitu_kernel=spicedata.get_kernel('psp_pred')
        target_name='PSP'

    if insitu_location_string=='Solo': 
        insitu_str='Solar Orbiter'
        insitu_kernel=spicedata.get_kernel('solo_2020')   
        target_name='SolarOrbiter'        
        
    if insitu_location_string=='Bepi': 
        insitu_str='BEPICOLOMBO MPO'
        insitu_kernel=spicedata.get_kernel('bepi_pred')
        target_name='BepiColombo'

    if insitu_location_string=='Ulysses': 
        insitu_str='ulysses'
        insitu_kernel=spicedata.get_kernel('ulysses')
        target_name='Ulysses'


        
    spice.furnish(insitu_kernel)
 
           

    #half width for SSEF30
    lamda=30.0

    #new version of ARRCAT with iteration
    arrcat_insitu_list = []
    #old version without iteration
    arrcat_insitu_list_old = []



    #go through all HIGEOCAT CME events and check for hit at insitu, with 4 iterations in total
    for i in np.arange(len(higeocat_time)):

        #get insitu position for launch time t0    
        [insitu_time,insitu_r,insitu_lat,insitu_lon]=get_insitu_position_time(higeocat_t0[i], insitu_location_string,insitu_str, insitu_kernel)            
        delta=abs(higeocat_sse_lon[i]-insitu_lon)
        #print([insitu_time,insitu_r,insitu_lat,insitu_lon])

        if delta < 30:               

            #calculate arrival time 
            #print(delta,lamda,insitu_r)
            [ta,visse]=calculate_arrival(higeocat_vsse[i],delta, lamda, insitu_r,higeocat_t0_num[i])                
            
            #make old version of ARRCAT without iteration and errors
            list_old=[higeocat_id[i].decode(),higeocat_sc[i].decode(),target_name,\
                   parse_time(higeocat_t0[i]).iso[:-7],parse_time(ta).iso[:-7],0,\
                   np.round(insitu_r,3), np.round(insitu_lon,2), np.round(insitu_lat,2),np.round(insitu_lon-higeocat_sse_lon[i],1),\
                   higeocat_sse_lon[i],higeocat_sse_lat[i],higeocat_vsse[i],\
                   higeocat_vsse_err[i], int(np.rint(visse)),0,higeocat_pafit[i],higeocat_pan[i],higeocat_pas[i],higeocat_pacenter[i]]
                   #print(list1)
            arrcat_insitu_list_old.append(list_old)
            
        

            [insitu_time2,insitu_r2,insitu_lat2,insitu_lon2]=get_insitu_position_time(ta, insitu_location_string,insitu_str, insitu_kernel)       
            #print(insitu_lon-insitu_lon2)               
            delta2=abs(higeocat_sse_lon[i]-insitu_lon2)
            if delta2 <30:

                [ta2,visse2]=calculate_arrival(higeocat_vsse[i],delta2, lamda, insitu_r2,higeocat_t0_num[i])
                #print(int((parse_time(ta2).plot_date-parse_time(ta).plot_date)*24))

                [insitu_time3,insitu_r3,insitu_lat3,insitu_lon3]=get_insitu_position_time(ta2, insitu_location_string,insitu_str, insitu_kernel)       
                delta3=abs(higeocat_sse_lon[i]-insitu_lon3)

                if delta3 <30:
                    [ta3,visse3]=calculate_arrival(higeocat_vsse[i],delta3, lamda, insitu_r3,higeocat_t0_num[i])
                    #print(np.round((parse_time(ta3).plot_date-parse_time(ta2).plot_date)*24,1),int(delta3))

                    [insitu_time4,insitu_r4,insitu_lat4,insitu_lon4]=get_insitu_position_time(ta3, insitu_location_string,insitu_str, insitu_kernel)       
                    delta4=abs(higeocat_sse_lon[i]-insitu_lon4)

                    if delta4 <30:
                        
                        #calculate finally iterated arrival time
                        [ta4,visse4]=calculate_arrival(higeocat_vsse[i],delta4, lamda, insitu_r4,higeocat_t0_num[i])
                        #print(np.round((parse_time(ta4).plot_date-parse_time(ta3).plot_date)*24,1),int(delta4))                                               
                        #print(int(delta4-delta))                                            
                                                
                        #estimate error bar on arrival time adding or subtracting the error in the Vsse speed
                        [ta4_low,visse4_low]=calculate_arrival(higeocat_vsse[i]-higeocat_vsse_err[i],delta4, lamda, insitu_r4,higeocat_t0_num[i])
                        [ta4_high,visse4_high]=calculate_arrival(higeocat_vsse[i]+higeocat_vsse_err[i],delta4, lamda, insitu_r4,higeocat_t0_num[i])
                        
                        #calculate difference in ours high / low to original arrival time and convert to hours
                        ta4_err_low=abs(parse_time(ta4).plot_date-parse_time(ta4_low).plot_date)*24
                        ta4_err_high=abs(parse_time(ta4).plot_date-parse_time(ta4_high).plot_date)*24
                        ta4_err=np.round(np.mean([ta4_err_high,ta4_err_low]),1)
                        #print(ta4_err_low,ta4_err_high,ta4_err)
                 
                  
                        #same for arrival speed error
                        visse4_err_low=abs(visse4_low-visse4)
                        visse4_err_high=abs(visse4_high-visse4)
                        visse4_err=int(np.rint(np.mean([visse4_err_high,visse4_err_low])))
                        #print(visse4_err_low,visse4_err_high,visse4_err,higeocat_vsse_err[i])
                        #print()

                        
                        list1=[higeocat_id[i].decode(),higeocat_sc[i].decode(),target_name,\
                                parse_time(higeocat_t0[i]).iso[:-7],parse_time(ta4).iso[:-7],ta4_err,\
                                np.round(insitu_r4,3), np.round(insitu_lon4,2), np.round(insitu_lat4,2),np.round(insitu_lon4-higeocat_sse_lon[i],1),\
                                higeocat_sse_lon[i],higeocat_sse_lat[i],higeocat_vsse[i],\
                                higeocat_vsse_err[i], int(np.rint(visse4)),visse4_err,higeocat_pafit[i],higeocat_pan[i],higeocat_pas[i],higeocat_pacenter[i]]
                        #print(list1)
                        arrcat_insitu_list.append(list1)



                    

    #arrcat_insitu=np.array(arrcat_insitu_list)    
    #print(arrcat_insitu_list)

    
    #make dataframe out of list
    ac_old1 = pd.DataFrame(arrcat_insitu_list_old, columns = column_list)    
    ac_old=ac_old.append(ac_old1)   

    
    #make dataframe out of list
    ac1 = pd.DataFrame(arrcat_insitu_list, columns = column_list)    
    arrcat=arrcat.append(ac1)   
    
    
    print('SSEF30 events: ',len(arrcat_insitu_list)   ) 
    print(insitu_location_string,' SSEF30 arrival catalog finished.')
    print()
        
    
    return [arrcat,ac_old]
Esempio n. 29
0
def get_satellite_position_heliopy(satname, timestamp, refframe='J2000', refobject='Sun', rlonlat=False, returnobj=False):
    """Uses Heliopy's spice to get position information. Will automatically download
    required kernels. Returns positions in km.

    Parameters
    ==========
    satname : str
        Satellite name. Currently available: ['stereo_a', 'stereo_a_pred', 'earth']
    timestamp : datetime / list of datetimes
        Datetime objects to iterate through and return positions for.
    refframe : str
        String denoting reference frame to use for position.
    refobject : str (default='Sun')
        String for reference onject, e.g. 'Sun' or 'Earth'
    rlonlat : bool (default=False)
        If True, returns coordinates in (r, lon, lat) format, not (x,y,z).
    returnobj : bool (default=False)
        If True, returns heliopy.Trajectory object instead of arrays.

    Returns
    =======
    If returnobj: returns heliopy.spice.Trajectory object.
    else: returns tuple of (x,y,z) or (r,lon,lat) if rlonlat=True
    """

    if isinstance(timestamp, datetime):
        timestamp = [timestamp]
    elif isinstance(timestamp, list):
        pass
    else:
        logger.warning("get_satellite_position_heliopy: Don't recognise input timestamp format!")

    if 'stereoa' in satname.lower().replace('-','').replace('_',''):
        if 'pred' in satname.lower():
            heliostr = 'stereo_a_pred'
        else:
            heliostr = 'stereo_a'
        satstr = 'STEREO AHEAD'
    elif 'stereob' in satname.lower().replace('-','').replace('_',''):
        if 'pred' in satname.lower():
            heliostr = 'stereo_b_pred'
        else:
            heliostr = 'stereo_b'
        satstr = 'STEREO BEHIND'
    elif satname.lower() in ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']:
        heliostr = 'planet_trajectories'
        satstr = satname

    hspice.furnish(spicedata.get_kernel(heliostr))
    pos = hspice.Trajectory(satstr)
    pos.generate_positions(timestamp, refobject, refframe)

    if returnobj:
        return pos

    #pos.change_units('AU')
    if rlonlat:
        r, theta, phi = cart2sphere(pos.x, pos.y, pos.z)
        return (r, phi, theta)
    else:
        return (pos.x, pos.y, pos.z)
Esempio n. 30
0
"""

from datetime import datetime, timedelta

import matplotlib.pyplot as plt
import numpy as np

import astropy.units as u
import heliopy.data.spice as spicedata
import heliopy.spice as spice

###############################################################################
# Load the Solar Orbiter spice kernel. HelioPy will automatically fetch and
# load the latest kernel. We can then inspect the kernel to check what the
# date coverage is for Solar Orbiter.
kernels = spicedata.get_kernel('solo')
solo = spice.Trajectory('Solar Orbiter')
coverage = kernels[0].coverage(spice.Body('Solar Orbiter'))
print(coverage)

###############################################################################
# Next we define a set of times at which to sample the orbit.
starttime = coverage[0]
times = [starttime + timedelta(days=i) for i in range(1, 5 * 365)]

###############################################################################
# Generate positions. "IAU_SUN" is a Carrington frame of reference.
solo.generate_positions(times, 'Sun', 'IAU_SUN')
coords = solo.coords

###############################################################################
Esempio n. 31
0
How to plot orbits from SPICE kernels.

In this example we download the Parker Solar Probe SPICE kernel, and plot
its orbit for the first year.
"""

import heliopy.data.spice as spicedata
import heliopy.spice as spice
from datetime import datetime, timedelta
import astropy.units as u
import numpy as np

###############################################################################
# Load the solar orbiter spice kernel. HelioPy will automatically fetch the
# latest kernel
kernels = spicedata.get_kernel('psp')
kernels += spicedata.get_kernel('psp_pred')
spice.furnish(kernels)
psp = spice.Trajectory('SPP')

###############################################################################
# Generate a time for every day between starttime and endtime
starttime = datetime(2018, 8, 14)
endtime = starttime + timedelta(days=365)
times = []
while starttime < endtime:
    times.append(starttime)
    starttime += timedelta(hours=6)

###############################################################################
# Generate positions