def __init__(self, file):
        
            # Get the speed relative to MU69

        file_tm = 'kernels_kem_prime.tm'
        
        # Start up SPICE if needed
        
        if (sp.ktotal('ALL') == 0):
            sp.furnsh(file_tm)    
            
        utc_ca = '2019 1 Jan 05:33:00'
        et_ca  = sp.utc2et(utc_ca) 
        (st,lt) = sp.spkezr('New Horizons', et_ca, 'J2000', 'LT', 'MU69')
        
        velocity = sp.vnorm(st[3:6])*u.km/u.s
    
        # Save the velocity (relative to MU69)

        self.velocity = velocity

        # Save the name of file to read
        
        self.file = file

        # Save the area of the s/c
        
        self.area_sc = (1*u.m)**2
        
        return
Example #2
0
def f():

    here = path.abspath(path.dirname(__file__))

    PathtoMetaKernel1 = here[:-39] + \
        '/git/exomars2016/kernels/mk/em16_ops.tm'
    PathtoMetaKernel2 = here[:-39] + \
        '/git/mars-express/kernels/mk/MEX_OPS.tm'
    print(PathtoMetaKernel1)
    print(PathtoMetaKernel2)
    spice.furnsh(PathtoMetaKernel1)
    spice.furnsh(PathtoMetaKernel2)

    sv = main.SpiceVariables()
    et = 657605100
    # get an actual occultation trace
    [trace, altTrace] = main.occSurfaceTrace(et, sv)
    #lattrace = np.linspace(10, 40, 10)
    #lontrace = np.linspace(90, 170, 10)
#    print('the starting locations are ', lontrace[1] + ',', lattrace[1])

    lattrace = trace[:, 0]
    lontrace = trace[:, 1]
    print('the starting locations are ', lontrace[1], ',', lattrace[1])

    GlobePlotter(20, 10, lattrace, lontrace)
Example #3
0
    def nightlystates(self,timerange):
        
        """ Generate asteroid state at every midnight within the input time range
        
        Expects integer MJD dates (midnight). Generates geocentric coordinates
        (range, RA, DEC, rangerate, dRA, dDec) for the asteroid at each midnight
        between, and including, start and end.

        Parameters
        ----------
            timerange: 2 element float numpy array
                [Starting time, Ending time] (MJD)
                
        """

        # Converting from MJD to JD and computing number of days including endpoints
        start=int(timerange[0])+shared.mjd2jd
        stop =int(timerange[-1])+shared.mjd2jd
        ndays=int(stop-start)+1

        # Loading SPK
        try:
            sp.furnsh(self.spkname)
        except:
            sys.exit("Cannot load %s" %(self.spkname))

        # Initializing state variables
        self.nightlyt=np.zeros(ndays)
        self.nightlyr=np.zeros(ndays)
        self.nightlydr=np.zeros(ndays)
        self.nightlyra=np.zeros(ndays)
        self.nightlydra=np.zeros(ndays)
        self.nightlydec=np.zeros(ndays)
        self.nightlyddec=np.zeros(ndays)
 
        counter = -1

        for i in np.linspace(start,stop,num=ndays):

            counter += 1

            # Converting from UTC to ET
            timeet=sp.str2et('JD '+repr(i))

            # Finding direction of asteroids from geocenter
            # Finding states wrt station adds 4 days for 1e6 objects

            asteroidsvec=sp.spkezr(str(self.spiceid),timeet,"J2000","LT","Earth") # Units are km and km/s
            
            # Converting from Rectangular to Latitudinal coordinates.
            # tmp is a 6 element vector (R, Long, Lat, Dr, Dlong, Dlat) Units are radians and radians/s
            tmp=sp.xfmsta(asteroidsvec[0][0:6],"RECTANGULAR","LATITUDINAL"," ")

            self.nightlyt[counter]   = i
            self.nightlyr[counter]   = tmp[0]
            self.nightlydr[counter]  = tmp[3]
            self.nightlyra[counter]  = tmp[1]
            self.nightlydra[counter] = tmp[4]
            self.nightlydec[counter] = tmp[2]
            self.nightlyddec[counter]= tmp[5]
Example #4
0
def sunDistanceAU(time: str, target: str) -> float:
    """Returns distance in AU between Sun and observed body from MRO."""

    base_kernel_path = Path(isis.environ["ISIS3DATA"]) / "base" / "kernels"
    lsk = sorted(Path(base_kernel_path / "lsk").glob("naif*.tls"))[-1]
    pck = sorted(Path(base_kernel_path / "spk").glob("de*.bsp"))[-1]
    sat = sorted(Path(base_kernel_path / "spk").glob("mar*.bsp"))[-1]

    sclk = sorted(
        Path(
            Path(isis.environ["ISIS3DATA"]) / "mro" / "kernels" / "sclk"
        ).glob("MRO_SCLKSCET.*.65536.tsc")
    )[-1]

    spiceypy.furnsh([str(lsk), str(pck), str(sat), str(sclk)])

    et = spiceypy.scs2e(-74999, time)

    targ = target.lower()
    if targ == "sky" or targ == "cal" or targ == "phobos" or targ == "deimos":
        targ = "mars"

    (sunv, lt) = spiceypy.spkpos(targ, et, "J2000", "LT+S", "sun")

    sunkm = spiceypy.vnorm(sunv)
    # Return in AU units
    return sunkm / 1.49597870691e8
Example #5
0
 def test_spicepy_state_transformation(self):
     spice.furnsh(self.cass.metakernel)
     T = spice.sxform('IAU_EARTH', 'IAU_SATURN', self.etOne)
     R = spice.pxform('IAU_EARTH', 'IAU_SATURN', self.etOne)
     (Rout, wout) = spice.xf2rav(T)
     np.testing.assert_array_almost_equal(Rout, R)
     spice.kclear()
Example #6
0
    def __init__(self, meta_kernel_path):
        """Create an instance loading the spice kernel in the given meta kernel file.

        Parameters
        ----------
        meta_kernel_path : `str` or `pathlib.Path`
            Path to the meta kernel

        """
        self.meta_kernel_path = Path(meta_kernel_path)
        if not self.meta_kernel_path.exists():
            raise ValueError(f'Meta kernel not found: {self.meta_kernel_path}')

        curdir = os.getcwd()
        try:
            # change to the 'kernels' dir
            os.chdir(self.meta_kernel_path.parent)
            # unload all old kernels
            spiceypy.kclear()
            # load the meta kernel
            spiceypy.furnsh(str(self.meta_kernel_path))
            # spiceypy.unload(str(self.mod_meta_kernel_path))
        finally:
            # change back to the old working directory
            os.chdir(curdir)
Example #7
0
def MET(Date, ut):
    '''
	This might return Mission Elapsed Time, but who knows if it actually
	works!
	
	'''

    ut = np.array([ut]).flatten()
    n = ut.size
    if np.size(Date) == 1:
        Date = np.array([Date] * n)
    else:
        Date = np.array([Date]).flatten()

    et = np.zeros((n, ), dtype='float64')

    sp.furnsh(lsk_path)
    sp.furnsh(sclk_kernel)

    ud = np.unique(Date)
    for i in range(0, ud.size):
        use = np.where(Date == ud[i])[0]
        tmp = utc2et(ud[i], 0.0)
        et[use] = tmp + ut[use] * 3600.0

    met = np.zeros(n, dtype='float64')
    for i in range(0, n):
        met[i] = sp.sce2t(-236, et[i])

    return met / 1e6
def getNacCenterAndRotationAtTime(imname):
    '''
    Extract the rotation of the spacecraft and its position for the given picture
    Notice that WAV and NAC can be considered aligned on the same axis and centred in the spacecraft
    so it can be used the same way independently by the camera
    :param imname: the input picture filename
    :return: the centre and the rotation matrix of the spacecraft
    '''
    os.chdir(spice_kernels_dir)  # or spyceypy will not work
    spiceypy.furnsh(spice_kernels_dir + os.path.sep +
                    furnsh_file)  #load the kernels from furnsh

    tstr = extractTimeString(
        imname)  # get only the time string from the filename
    t = spiceypy.str2et(tstr)  # transform the string to a time

    # get the position of Rosetta spacecraft in 67p refence frame, centred in 67P + light time corr (not really needed)
    pos = spiceypy.spkpos("ROSETTA", t, "67P/C-G_CK", "LT+S", "67P/C-G")[0]
    # pos = spiceypy.spkpos("ROSETTA", t, "ROS_OSIRIS_NAC", "LT+S", "67P/C-G")[0]

    print("Found position: {}".format(pos))

    #and the rotation - we use NAC but it is the same for the WAC
    # R = spiceypy.pxform("67P/C-G_CK", "ROS_OSIRIS_NAC", t);
    # rotation matrix of the nac camera, in respect to 67P reference frame
    R = spiceypy.pxform("ROS_OSIRIS_NAC", "67P/C-G_CK", t)
    return np.array(pos), np.array(R)
Example #9
0
def get_sun_sizes(utc_start, utc_end, step_size):
    """get sun angular size and time steps given start and end times"""
    #spice constants
    abcorr = "None"
    #tolerance = "1"
    #method = "Intercept: ellipsoid"
    #prec = 3
    #shape = "Ellipsoid"

    #load spiceypy kernels
    os.chdir(KERNEL_DIRECTORY)
    sp.furnsh(KERNEL_DIRECTORY + os.sep + METAKERNEL_NAME)
    print(sp.tkvrsn("toolkit"))
    os.chdir(BASE_DIRECTORY)
    utctimestart = sp.str2et(utc_start)
    utctimeend = sp.str2et(utc_end)

    durationseconds = utctimeend - utctimestart
    nsteps = int(np.floor(durationseconds / step_size))
    timesteps = np.arange(nsteps) * step_size + utctimestart

    ref = "J2000"
    observer = "-143"
    target = "SUN"
    #get TGO-SUN pos
    tgo2sunpos = [
        sp.spkpos(target, time, ref, abcorr, observer)[0] for time in timesteps
    ]
    sunaxes = sp.bodvrd("SUN", "RADII", 3)[1][0]  #get mars axis values

    return ([np.arctan((sunaxes*2.0)/np.linalg.norm(tgo2sunVector))*sp.dpr()*60.0 \
                for tgo2sunVector in tgo2sunpos], timesteps)
Example #10
0
    def load_kernels(self):
        #cwd=os.getcwd()
        spice_folder = config.get_path('spice')
        mk_folder = os.path.join(spice_folder, 'mk')
        #os.chdir(mk_folder)
        self.latest_mk = None
        for filename in glob.glob(f'{mk_folder}/solo_ANC_soc-flown-mk*.tm'):
            date_str = re.findall(r"\d{4}\d{2}\d{2}", filename)
            if date_str:
                fdt = datetime.strptime(date_str[0], "%Y%m%d")
                if fdt > self.version_date:
                    self.latest_mk = filename
                    self.version_date = fdt
        if self.loaded_kernel_filename != self.latest_mk and self.latest_mk != None:
            print(f'Loading spice kernels from {self.latest_mk}...')
            fnames = self.get_kernel_files_from_mk(self.latest_mk)
            for fname in fnames:
                try:
                    spiceypy.furnsh(os.path.join(spice_folder, fname))
                except spiceypy.utils.exceptions.SpiceNOSUCHFILE:
                    print('Failed to load kernel:', fname)

            self.loaded_kernel_filename = self.latest_mk

        self.refresh_times += 1
Example #11
0
def load_kernel(filename):
    """Load the named kernel into memory.

    The kernel must be in the current directory, or in the path given
    by the mskpy config file.

    No-op if the kernel is already loaded.

    Parameters
    ----------
    filename : string

    Returns
    -------
    None

    Raises
    ------
    `OSError` if the file is not found.

    """

    import os.path
    from ..config import config

    kernel_path = config.get('ephem.core', 'kernel_path')
    if not os.path.exists(filename):
        filename = os.path.join(kernel_path, filename)
        if not os.path.exists(filename):
            raise OSError("{} not found".format(filename))

    try:
        spice.kinfo(filename, 512, 512)
    except SpiceyError:
        spice.furnsh(filename)
Example #12
0
 def __init__(self, time=None):
     super(Spicer, self).__init__()
     if time is None:
         self.time = dt.datetime.now()
     else:
         self.time = tparser.parse(time)
     spice.furnsh("/Users/klay6683/Dropbox/NotPublic/spice/cosp_1000_040701_040701/cas_2004_v21_040701_040701.tm")
Example #13
0
def check(mk, time=False, report=False):

    frames_to_check = False
    if not time:
        today = datetime.datetime.now()
        time = today.strftime("%Y-%m-%dT%H:%M:%S")

    frame_dict = gen_frame_dict(mk, report=report)

    spiceypy.furnsh(mk)
    et = spiceypy.utc2et(time)

    for key in frame_dict.keys():
        if frame_dict[key]['class'] == 4:
            fname = frame_dict[key]['name']
            try:
                spiceypy.pxform(fname, 'J2000', et)
            except SpiceyError:
                frames_to_check = True
                print( f'Frame {fname} not properly defined at {time}\n' +
                       f'   NAME:     {frame_dict[key]["name"]}\n' +
                       f'   CLASS:    {frame_dict[key]["class"]}\n' +
                       f'   ID:       {frame_dict[key]["id"]}\n' +
                       f'   CENTER:   {frame_dict[key]["center"]}\n' +
                       f'   RELATIVE: {frame_dict[key]["relative"]}\n'
                     )
                pass

    spiceypy.kclear()

    if not frames_to_check:
        print(f'All {len(frame_dict)} frames are correct @ {time}')

    return
Example #14
0
def load_kernels(name: str = "generic", external_path: str = None):
    """
    Load all SPICE kernels listed in the "kernellist.txt" file for a specific folder. Optionally a external folder can
    be specified which contains the required SPICE kernels.

    Note that not all SPICE kernels are part of the repository and may have to be downloaded from the official sources.
    The locations of the required kernels are listed in the respective "kernellist_url.txt" files.

    :param name: folder name
    :param external_path: external directory for SPICE kernels (optional)
    """
    path = os.path.join(os.path.dirname(__file__), "kernels", name.lower(),
                        "kernellist.txt")

    if not os.path.isfile(path):
        raise FileNotFoundError(
            "kernellist.txt file not found for: {}.".format(name))

    with open(path) as fh:
        lines = fh.read().splitlines()

    for line in lines:
        if external_path:
            spiceypy.furnsh(os.path.join(external_path, line))
        else:
            spiceypy.furnsh(
                os.path.join(os.path.dirname(__file__), "kernels",
                             name.lower(), line))
Example #15
0
def dataToPickle():
    orbits_begin = {1:'2016-07-31T19:46:02',
                            2:'2016-09-23T03:44:48',
                            3:'2016-11-15T05:36:45',
                            4:'2017-01-07T03:11:30',
                            5:'2017-02-28T22:55:48',
                            6:'2017-04-22T19:14:57'}
    
    file_dict = {}
    metaKernel = 'juno_2019_v03.tm'
    spice.furnsh(metaKernel)

    start_time = datetime.datetime.strptime(orbits_begin[1],'%Y-%m-%dT%H:%M:%S')
    
    end_time = datetime.datetime.strptime(orbits_begin[2],'%Y-%m-%dT%H:%M:%S')
    
    data_folder = pathlib.Path(r'..\data\fgm')
    p = re.compile(r'\d{7}')
    
    for parent,child,files in os.walk(data_folder):
        for name in files:
            if name.endswith('.csv'):
                file_path = os.path.join(data_folder,name)
                
                search = p.search(name).group()
                date = datetime.datetime.strptime(search,'%Y%j')
                
                if date.date() >= start_time.date() and date.date() <= end_time.date():
                    iso_date = date.strftime('%Y-%m-%d')
                    if iso_date not in file_dict.keys():
                        file_dict[iso_date] = [file_path]
                    elif iso_date in file_dict.keys() and file_dict[iso_date] != file_path: 
                        file_dict[iso_date].append(file_path)
    
    for date in file_dict.keys():
        fgmdf = pd.DataFrame(data={'TIME':[],'BX':[],'BY':[],'BZ':[],'LAT':[]})
        save_date = datetime.datetime.strptime(date,'%Y-%m-%d')
        file_list = file_dict[date]
        for file in file_list:
            
            temp = pd.read_csv(file)
            datetime_list = temp['SAMPLE UTC']
            time_list = [datetime.datetime.fromisoformat(i).strftime('%H:%M:%S') for i in datetime_list]
            
            for index,time in enumerate(datetime_list):
                
                position, lighttime = spice.spkpos('JUNO',spice.utc2et(time),'IAU_JUPITER','NONE','JUPITER')
            
                vectorPos = spice.vpack(position[0],position[1],position[2])
                radii,longitude,latitude = spice.reclat(vectorPos)
                lat = latitude*spice.dpr()
                
                if lat >= -10 and lat <= 10:
                    fgmdf = fgmdf.append({'TIME':time,'BX':temp['BX PLANETOCENTRIC'][index],'BY':temp['BY PLANETOCENTRIC'][index],'BZ':temp['BZ PLANETOCENTRIC'][index],'LAT':lat},ignore_index=True)
        fgmdf = fgmdf.sort_values(by=['TIME'])
        save_name = f'{save_date.strftime("%Y%m%d")}'
        save_path = pathlib.Path(f'..\data\pickledfgm\jno_fgm_{save_name}.pkl')
        pickledf = fgmdf.to_pickle(save_path)
        print(f'Saved pickle {date}')                                     
Example #16
0
def Calculate_SCoords(run):

    #setup
    import spiceypy as spice
    import numpy as np
    import math
    spice.furnsh("./MetDat/MoonMetdat.txt")

    #import ~_setup.txt and SPK (~.bsp) file
    slines = []
    with open(run + '_setup.txt') as f:
        slines = f.read().splitlines()
    spice.furnsh(run + '.bsp')

    #get TLE_SPK_OBJ_ID and et (time, seconds past J2000) from TLE File
    obj_id = slines[5].split('=')[1]
    et = float(slines[28].split('=')[1])
    print ''
    #read out date as yyyy mmm dd hr:min:sec.millisecond
    print '\n', spice.et2utc(et, 'C', 3)

    #Calculate sub-observer point and distance
    state = spice.spkezr(obj_id, et, "MOON_PA", "LT+S", "Moon")
    s_obs = spice.reclat(state[0][0:3])
    print '\nSub-Observer Point:'
    print ' Sat-Moon distance: ', s_obs[0], 'km'
    print ' Satellite sub-long: ', s_obs[1] * 180 / math.pi, 'deg'
    print ' Satellite sub-lat:  ', s_obs[2] * 180 / math.pi, 'deg'

    #Calculate sub-Earth point and distance
    state = spice.spkezr("Earth", et, "MOON_PA", "LT+S", "Moon")
    s_eat = spice.reclat(state[0][0:3])
    print '\nSub-Earth Point:'
    print ' Earth-Moon distance: ', s_eat[0], 'km'
    print ' Earth sub-long: ', s_eat[1] * 180 / math.pi, 'deg'
    print ' Earth sub-lat:  ', s_eat[2] * 180 / math.pi, 'deg'

    #Calculate sub-Sun point and distance
    state = spice.spkezr("Sun", et, "MOON_PA", "LT+S", "Moon")
    s_sun = spice.reclat(state[0][0:3])
    print '\nSub-Sun Point:'
    print ' Sun-Moon distance: ', s_sun[0], 'km'
    print ' Sun sub-long: ', 90 - s_sun[1] * 180 / math.pi, 'deg'
    print ' Sun sub-lat:  ', s_sun[2] * 180 / math.pi, 'deg\n'

    #Writes selenographic coordiantes to a file named 'run'+_spoints.txt
    with open(run + '_spoints.txt', 'w') as f:
        f.write('' + '\n#Sub-Observer Point:' + '\n\t Sat-Moon distance: ' +
                str(s_obs[0]) + '\n\t slong: ' +
                str(s_obs[1] * 180 / math.pi) + '\n\t slat: ' +
                str(s_obs[2] * 180 / math.pi) + '\n\n#Sub-Earth Point:' +
                '\n\t Earth-Moon distance: ' + str(s_eat[0]) + '\n\t slong: ' +
                str(s_eat[1] * 180 / math.pi) + '\n\t slat: ' +
                str(s_eat[2] * 180 / math.pi) + '\n\n#Sub-Sun Point:' +
                '\n\t Sun-Moon distance: ' + str(s_sun[0]) + '\n\t slong: ' +
                str(90 - s_sun[1] * 180 / math.pi) + '\n\t slat: ' +
                str(s_sun[2] * 180 / math.pi))

    return [slines[21].split('=')[1][1:], et, s_obs, s_eat, s_sun]
Example #17
0
def write_positions(
    utc_start,
    utc_end,
    steps,
):
    """
    Write positions of earth and moon in output file.
    Input:
        -utc_start              str (format YYYYmmdd)
        -utc_end                str (format YYYYmmdd)
        -steps                  int
    """

    # read kernel files paths and some constants from config
    dark_side_path = os.path.dirname(
        os.path.dirname(os.path.realpath(__file__)))
    config = configparser.ConfigParser()
    config.read(os.path.join(dark_side_path, "config", "config.ini"))
    spk_kernel = config["spice"]["spk_kernel"]
    lsk_kernel = config["spice"]["lsk_kernel"]
    reference_frame = config["spice"]["reference_frame"]
    aberration_correction = config["spice"]["aberration_correction"]

    # load kernels
    spice.furnsh(spk_kernel)
    spice.furnsh(lsk_kernel)

    # compute ET times
    et_start = spice.str2et(format_date_for_spice(utc_start))
    et_end = spice.str2et(format_date_for_spice(utc_end))
    times = [x * (et_end - et_start) / steps + et_start for x in range(steps)]

    # load positions
    earth_positions, _ = spice.spkpos("EARTH", times, reference_frame,
                                      aberration_correction, "SUN")
    moon_positions, _ = spice.spkpos("MOON", times, reference_frame,
                                     aberration_correction, "EARTH")

    # create output dir
    output_dir = os.path.join(
        dark_side_path,
        "data",
    )
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # write results in output files
    write_output_file(os.path.join(output_dir, "earth.txt"), [
        "{:15.8f}, {:15.8f}, {:15.8f}".format(pos[0], pos[1], pos[2])
        for pos in earth_positions
    ])
    write_output_file(os.path.join(output_dir, "moon.txt"), [
        "{:15.8f}, {:15.8f}, {:15.8f}".format(pos[0], pos[1], pos[2])
        for pos in moon_positions
    ])
    write_output_file(os.path.join(output_dir, "times.txt"), [
        "{}".format(format_date_from_spice(spice.et2utc(time, "C", 0)))
        for time in times
    ])
Example #18
0
def test_get_spiceypy_exceptions():
    with pytest.raises((
            spice.exceptions.SpiceyError,
            spice.exceptions.SpiceyPyError,
            spice.exceptions.SpiceyPyIOError,
    )):
        spice.furnsh(os.path.join(cwd, "_null_kernel.txt"))
    spice.reset()
Example #19
0
 def __enter__(self):
     """
     Called when the context is created. This is used
     to get the kernels furnished.
     """
     if self.metakernel:
         spice.furnsh(self.metakernel)
     return self
Example #20
0
 def test_near_landing_coverage(self):
     spice.furnsh(self.near.metakernel)
     utc = ['Feb 12, 2001 12:00:00 UTC', 'Feb 12, 2001 20:05:00 UTC']
     etone = 35251264.18507089
     ettwo = 35280364.18507829
     np.testing.assert_almost_equal(spice.str2et(utc[0]), etone)
     np.testing.assert_almost_equal(spice.str2et(utc[1]), ettwo)
     spice.kclear()
def cspice_utc2et(kernelfile, ctime):
    spice_ver = spice.tkvrsn('TOOLKIT')
    spice.furnsh(kernelfile)
    kernels_loaded = spice.ktotal("ALL")
    #print(kernels_loaded)
    ntime = spice.utc2et(ctime.value)
    #print(spice_ver)
    return ntime
Example #22
0
def load_kernels():

    import spiceypy as spice
    import os

    dirAppend = "kernels" + os.sep

    spice.furnsh(dirAppend + "gm_de431.tpc")
Example #23
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)
Example #24
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)
Example #25
0
def _load_kernels_():
    global __kernels_loaded__
    if __kernels_loaded__:
        return
    base_dir = os.path.dirname(os.path.abspath(__file__))
    krnls = ['de430.bsp', 'naif0012.tls', 'pck00010.tpc']
    for krnl in krnls:
        spice.furnsh(base_dir + '/spicekernels/' + krnl)
    __kernels_loaded__ = True
 def __init__(self, dir, timestr='', verbose = True) : 
     self.verbose = verbose
     self.ckdir = dir + '/ck/'
     self.spkdir = dir + '/spk/'
     self.kernels = ["/fk/juno_v09.tf", "/ik/juno_jiram_v01.ti", "/ik/juno_struct_v01.ti", 
                  "/lsk/naif0012.tls", "/pck/pck00010.tpc", "/sclk/JNO_SCLKSCET.00058.tsc", 
                  "/spk/de436s.bsp", "/spk/juno_struct_v02.bsp", "/spk/jup310.bsp"]        
     for k in self.kernels : spice.furnsh(dir + k)
     if (timestr != '') : self.load(timestr)
Example #27
0
 def test_earth_spk_coverage(self):
     spice.furnsh(self.near.metakernel)
     spkids = spice.spkobj(self.near.SpkPlanet)
     cover = spice.stypes.SPICEDOUBLE_CELL(1000)
     spice.spkcov(self.near.SpkPlanet, 399, cover)
     result = [x for x in cover]
     expected_result = [-633873600.0, 347630400.0] 
     np.testing.assert_array_almost_equal(result, expected_result)
     spice.kclear()
Example #28
0
 def test_eros_spk1_coverage(self):
     spice.furnsh(self.near.metakernel)
     code = spice.bodn2c('EROS')
     cover = spice.stypes.SPICEDOUBLE_CELL(1000)
     spice.spkcov(self.near.SpkEros, code, cover)
     result = [x for x in cover]
     expected_result = [-126273600.0, 37886400.0]
     np.testing.assert_array_almost_equal(result, expected_result)
     spice.kclear()
Example #29
0
def run(mk, time_start='', time_finish='', step=60, target='MERCURY',
        frame='', sensor='MPO_MERTIS_TIR_PLANET', pixel_line='',
        pixel_sample='', observer='MPO'):

    spiceypy.furnsh(mk)

    target = target.upper()
    if not time_start: time_start = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
    if not frame: frame = f'IAU_{target}'
    if not time_finish: time_finish = time_start
    if not pixel_sample: pixel_sample = np.floor(ccd_center(sensor)[0])
    if not pixel_line: pixel_line = np.floor(ccd_center(sensor)[1])

    if pixel_sample == 'all':
        pixel_sample = np.arange(1, pixel_samples(sensor), 1)
    else:
        pixel_sample = [pixel_sample]
    if pixel_line == 'all':
        pixel_line = np.arange(1, pixel_lines(sensor), 1)
    else:
        pixel_line = [pixel_line]


    et_start = spiceypy.utc2et(time_start)
    et_finish = spiceypy.utc2et(time_finish)

    if et_start != et_finish:
        interval = np.arange(et_start, et_finish, step)
    else:
        interval = [et_start]

    # Time tag [UTC]
    # pixel id [(x,y)]
    # corner id [(x,y)]

    # Requested geometry

    # lat lon intersection (planetocentric)
    # lat lon subspacecraft
    # lat lon subsolar
    # target distance intersection
    # target angular diameter
    # local solar time intersection
    # phase angle intersection
    # emission angle intersection
    # incidence angle intersection

    with open('spice4mertis.csv', 'w') as o:
        o.write('utc,et,pixlin,pixsam,tarlon,tarlat,sublon,sublat,sunlon,sunlat,tardis,tarang,ltime,phase,emissn,incdnc\n')
        for et in interval:
            utc = spiceypy.et2utc(et, 'ISOC', 3)
            for line in pixel_line:
                for sample in pixel_sample:
                    pixelGeometry = pixel_geometry(et, sensor, line, sample, target, frame, observer=observer)
                    print(utc,line,sample,str(pixelGeometry)[1:-1].replace(',',' '))
                    o.write(f'{utc},{et},{line},{sample},{str(pixelGeometry)[1:-1].replace(" ","")}\n')
    return
Example #30
0
def load_spice_kernels(planning=False):

    os.chdir(paths["KERNEL_DIRECTORY"])

    if planning:
        sp.furnsh(os.path.join(paths["KERNEL_DIRECTORY"], "em16_plan.tm"))
    else:
        sp.furnsh(os.path.join(paths["KERNEL_DIRECTORY"], "em16_ops.tm"))
    print(sp.tkvrsn("toolkit"))
    os.chdir(paths["BASE_DIRECTORY"])
Example #31
0
def find_spice_kernels(kernel_path):
    pcks = sorted(glob.glob(kernel_path + "pck/*.tpc"))
    spks1 = sorted(glob.glob(kernel_path + "spk/planets/de*.bsp"))
    spks2 = sorted(glob.glob(kernel_path + "spk/satellites/*.bsp"))
    fks = sorted(glob.glob(kernel_path + "fk/planets/*.tf"))
    lsks = sorted(glob.glob(kernel_path + "lsk/naif*.tls"))

    kernels = [pcks[-1], spks1[-1], *spks2, lsks[-1]]
    for kernel in kernels:
        spiceypy.furnsh(kernel)
Example #32
0
def furnish_kernels():
    kernel_names = ['pck/moon_pa_de421_1900-2050.bpc',
                    'fk/satellites/moon_080317.tf',
                    'fk/satellites/moon_assoc_me.tf']

    kernel_paths = [os.path.join(DATA_PATH, kn) for kn in kernel_names]
    for kp in kernel_paths:
        spice.furnsh(kp)

    return kernel_paths
Example #33
0
def cal2et(time, format='UTC', support_ker=False, unload=False):
    """
    Converts UTC or Calendar TDB (CAL) time to Ephemeris Time (ET). Accepts
    a single time or a lists of times. This function assumes that the support
    kernels (meta-kernel or leapseconds) kernel has been loaded.

    :param time: Input UTC or CAL time
    :type time: Union[float, list]
    :param format: Input format; 'UTC' or 'CAL'
    :type format: str
    :param unload: If True it will unload the input meta-kernel
    :type unload: bool
    :return: Output ET
    :rtype: Union[str, list]
    """
    out_list = []

    if isinstance(time, str):
        time = [time]

    #
    # We need to specify that is Calendar format in TDB. If it is UTC we need
    # to load the support kernels
    #
    if support_ker:
        spiceypy.furnsh(support_ker)

    if format == 'CAL':
        time[:] = [x.replace('T', ' ') for x in time]
        time[:] = [x + ' TDB' for x in time]

    for element in time:

        try:
            if format == 'UTC':
                out_elm = spiceypy.utc2et(element)

            elif format == 'CAL':
                out_elm = spiceypy.str2et(element)
            else:
                out_elm = element
        except:
            out_elm = spiceypy.str2et(element)

        out_list.append(out_elm)

    if len(out_list) == 1:
        out_time = out_list[0]
    else:
        out_time = out_list

    if unload:
        spiceypy.unload(support_ker)

    return out_time
def add_backplanes():
  
    dir = '/Users/throop/data/NH_LORRI_Ring/'
    
    files = glob.glob(dir + '/*_header_wcs.fits')
    
    file_tm           = "/Users/throop/gv/dev/gv_kernels_new_horizons.txt"  # SPICE metakernel
 
    # Make sure SPICE is running
    
    sp.furnsh(file_tm)
    
    for i,file in enumerate(files):

        file_out = file.replace('.fits', '_pl.fits')
        
        print("{}/{}: Generating backplane for {}".format(i, np.size(files), file))
    
        # Create the backplanes
    
        print("Generating backplane...")
                
        (planes,descs) = hbt.compute_backplanes(
                             file, frame = 'IAU_PLUTO', name_target='Pluto', name_observer='New Horizons')
            
    # Create a new FITS file, made of an existing file plus these new planes
    
        hdulist = fits.open(file)  # Read in the file we've just created, which has full fixed header
    
        type_out = 'float32'        # Write backplane in single precision, to save space.
        hdu_out = fits.HDUList()    # Create a brand new FITS file
        hdu_out.append(hdulist['PRIMARY'])
        hdu_out.append(fits.ImageHDU(planes['RA'].astype(type_out), name = 'RA'))
        hdu_out.append(fits.ImageHDU(planes['Dec'].astype(type_out), name = 'Dec'))
        hdu_out.append(fits.ImageHDU(planes['Phase'].astype(type_out), name = 'Phase'))
        hdu_out.append(fits.ImageHDU(planes['Longitude_eq'].astype(type_out), name = 'Longitude_eq'))
        hdu_out.append(fits.ImageHDU(planes['Radius_eq'].astype(type_out), name = 'Radius_eq'))
        
        hdu_out.writeto(file_out, clobber=True)
        print("Wrote file: " + file_out)
Example #35
0
def unload_kernels():
    """Unload kernels"""

    # global last_spice_time_window

    try:
        spiceypy.kclear()

        # But, we always want the LSK loaded.  This should be safe provided
        # a) celsius was loaded first (safe assertion, this code won't work
        # without it), meaning that the latest.tls was updated if needs be
        # b) uptime for this instance is less than the lifetime of a tls kernel
        # (years?)
        spiceypy.furnsh(
            os.getenv("SC_DATA_DIR", default=expanduser('~/data/')) + \
            'latest.tls'
        )

        spiceypy.last_spice_time_window = 'MVN:NONE_UNLOADED'
    except RuntimeError as e:
        spiceypy.last_spice_time_window = 'MVN:NONE_ERROR'
        raise e
Example #36
0
def load_kernels():
    kernels_to_load = [
        'fk/maven_v06.tf',
        'ik/maven_iuvs_v01.ti',
        'ck/mvn_app_rel_131118_141010_v1.bc',
        'sclk/MVN_SCLKSCET.file.tsc',
        'spk/trj_c_131118-140923_rec_v1.bsp',
    ]
    spicedir = Path('/home/klay6683/IUVS-ITF-SW/anc/spice')
    mvnkerneldir = spicedir / 'mvn'
    lskdir = spicedir / 'generic_kernels/lsk'
    sclkdir = mvnkerneldir / 'sclk'
    for kernel in kernels_to_load:
        spice.furnsh(str(mvnkerneldir / kernel))
    for fname in sclkdir.iterdir():
        spice.furnsh(str(sclkdir / fname))
    spice.furnsh(str(lskdir / 'naif0011.tls'))
import spiceypy as sp

# These data files were obtained from
# http://naif.jpl.nasa.gov/pub/naif/generic_kernels
LEAP_SECOND_FILE = "data/naif0011.tls"
EPHEMERIDES_FILE = "data/de432s.bsp"


if __name__ == "__main__":
    # Script expects first argument to be a UTC timestamp
    if len(sys.argv) > 1:
        input_utc = sys.argv[1]
    else:
        input_utc = "2000-01-01T00:00:00"  # default for testing
    # Load the necessary data files
    sp.furnsh([LEAP_SECOND_FILE, EPHEMERIDES_FILE])
    # Convert UTC to ephemeris time
    epoch = sp.utc2et(input_utc)
    # State (position and velocity in cartesian coordinates)
    # of EARTH as seen from SUN in the ecliptic J2000 coordinate frame.
    state, lt, = sp.spkezr("EARTH", epoch, "ECLIPJ2000", "NONE", "SUN")
    # Show the output
    print("Input time = {}".format(input_utc))
    print("")
    print("# Position of the Earth in the heliocentric ecliptic (J2000) frame")
    print("X = {} km".format(state[0]))
    print("Y = {} km".format(state[1]))
    print("Z = {} km".format(state[2]))
    print("")
    print("# Velocity of the Earth in the same frame")
    print("dX = {} km/s".format(state[3]))