Esempio n. 1
0
def load_kernel(filename):
    """Load the named kernel into memory.

    The kernel must be in the current directory, or in `_kernel_path`.

    No-op if the kernel is already loaded.

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

    Returns
    -------
    None

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

    """

    import os.path
    global _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))

    if spice.kinfo(filename) is None:
        spice.furnsh(filename)
Esempio n. 2
0
    def compute_posvels(self, ephem="DE405", planets=False):
        """Compute positions and velocities of observatory and Earth.

        Compute the positions and velocities of the observatory (wrt
        the Geocenter) and the center of the Earth (referenced to the
        SSB) for each TOA.  The JPL solar system ephemeris can be set
        using the 'ephem' parameter.  The positions and velocities are
        set with PosVel class instances which have astropy units.
        """
        # Load the appropriate JPL ephemeris
        load_kernels()
        pth = os.path.join(pintdir, "datafiles")
        ephem_file = os.path.join(pth, "%s.bsp"%ephem.lower())
        spice.furnsh(ephem_file)
        log.info("Loaded ephemeris from %s" % ephem_file)
        j2000 = time.Time('2000-01-01 12:00:00', scale='utc')
        j2000_mjd = utils.time_to_mjd_mpf(j2000)
        for toa in self.toas:
            xyz = observatories[toa.obs].xyz
            toa.obs_pvs = erfautils.topo_posvels(xyz, toa)
            # SPICE expects ephemeris time to be in sec past J2000 TDB
            # We need to figure out how to get the correct time...
            et = (toa.mjd.TDB - j2000_mjd) * SECS_PER_DAY

            # SSB to observatory position/velocity:
            toa.earth_pvs = objPosVel("EARTH", "SSB", et)
            toa.pvs = toa.obs_pvs + toa.earth_pvs

            # Obs to Sun PV:
            toa.obs_sun_pvs = objPosVel("SUN", "EARTH", et) - toa.obs_pvs
            if planets:
                for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                    pv = objPosVel(p.upper()+" BARYCENTER",
                            "EARTH", et) - toa.obs_pvs
                    setattr(toa, 'obs_'+p+'_pvs', pv)
Esempio n. 3
0
def get_v_sun(kernelMetaFile, utcStartTime):
    '''
    compute radial component of CG towards/away from sun for given utcTime.
    v_sun: velocity component on the comet-sun-line.
    '''

    spice.furnsh(kernelMetaFile)
    et = spice.str2et(utcStartTime)
    state, lightTime = spice.spkezr("CHURYUMOV-GERASIMENKO",
                                    et, "J2000", "NONE", "SUN")

    x = state[0]
    y = state[1]
    z = state[2]
    vx = state[3]
    vy = state[4]
    vz = state[5]

    r_length = np.sqrt(x**2 + y**2 + z**2)

    r_hat = np.zeros(3)
    v = np.zeros(3)

    r_hat[0] = x / r_length
    r_hat[1] = y / r_length
    r_hat[2] = z / r_length

    v[0] = r_hat[0] * vx
    v[1] = r_hat[1] * vy
    v[2] = r_hat[2] * vz

    v_sun = v[0] + v[1] + v[2]

    return v_sun
Esempio n. 4
0
    def setUp(self):
        mydir = os.path.dirname(__file__)
        self.kernels = [
            os.path.join(mydir, i.strip()) for i in """
### Lines in this string that start with '#' are comments
### The other lines in this string are paths to kernels,
###   relative to the parent directory of this Python script, __file__
###
kernels/naif0010.tls
kernels/smap_v00.tf
kernels/pck00009.tpc
kernels/spk_drm239_WithBurn-full.bsp
kernels/smap_test.bsp
###
### kernels/SMAP_ref_150529_180529.bsp
###
### That commented SMAP SPK kernel, or one like it, should be under this URL:
###
###   http://naif.jpl.nasa.gov/pub/naif/SMAP/kernels/spk/
###
###
""".strip().split('\n') if i[0] != '#'
        ]

        ### Load default kernels (string variable "kernels" above")
        for kernel in self.kernels:
            spice.furnsh(kernel)
Esempio n. 5
0
  def setUp(self):
    ### Load default kernels
    mydir = os.path.dirname(__file__)
    self.kernels = [ os.path.join( mydir,i.strip()) for i in
      """
kernels/naif0010.tls
kernels/spk_drm239_WithBurn-full.bsp
      """.strip().split('\n') ]
    for kernel in self.kernels: spice.furnsh( kernel )
Esempio n. 6
0
    def setUp(self):
        ### Load default kernels
        mydir = os.path.dirname(__file__)
        self.kernels = [
            os.path.join(mydir, i.strip()) for i in """
kernels/naif0010.tls
kernels/spk_drm239_WithBurn-full.bsp
      """.strip().split('\n')
        ]
        for kernel in self.kernels:
            spice.furnsh(kernel)
Esempio n. 7
0
def loadKernel(filenames):
    """
    loadKernel(filenames)
    
    Read SPICE kernels in filenames (including full paths)
    """
    if type(filenames) is str:
        spice.furnsh(filenames)
    else:
        for name in filenames:
            spice.furnsh(name)
Esempio n. 8
0
def transform(fname, metadata=False):
    """
    This function reads a Mission Analysis Orbit file and performs a matrix
    transformation on it. Currently only from the Mercury Equatorial frame to
    the Earth Equatorial frame.

    :param fname: The path to the orbit file.
    :type fname: str.
    :param metadata: Flag to return the metadata dictionary
    :type state: bool.
    :returns:  numpy.array -- the return code.
    """

    furnsh("/Users/jmcaulif/Code/naif/generic/lsk/naif0010.tls")

    logging.basicConfig(level=logging.INFO)

    mdata = {}
    data = {}

    with open(fname, "r") as fh:
        for line in fh:
            t, x, y, z, vx, vy, vz = [float(x) for x in line.split()]

            T = np.array(
                [
                    [0.98159386604468, 0.19098031873327, 0.0],
                    [-0.16775718426422, 0.86223242348167, 0.47792549108063],
                    [0.09127436261733, -0.46912873047114, 0.87840037851502],
                ]
            )

            Tinv = linalg.inv(T)

            r = np.array([[x, y, z]])
            v = np.array([[vx, vy, vz]])

            r_new = Tinv.dot(r.T).T
            v_new = Tinv.dot(v.T).T

            x, y, z = r_new[0]
            vx, vy, vz = v_new[0]

            t = et2utc(t * 86400, "isoc", 2)

            print("{} {:9.2f} {:9.2f} {:9.2f} {:9.6f} {:9.6f} {:9.6f}".format(t, x, y, z, vx, vy, vz))

    fh.close()

    if metadata:
        return data, mdata
    else:
        return data
Esempio n. 9
0
  def setUp(self):
    ### Variables for comparison
    self.Ddtp = ( 1, 'N', )
    self.Idtp = ( 2, 'N', )
    self.Cdtp = ( 3, 'C', )
    self.var399 = ( 3, ( 1000.0, 2000.0, 3000.0, ), )
    self.var99 = (4, ( 1099.5, 2099.25, 3099.125, 4099.0625, ), )

    ### Load the kernel
    spice.furnsh( __file__ )

    ### Load a private name/code pair
    spice.boddef( 'MYBOD', 99 )
Esempio n. 10
0
  def setUp(self):

    ### Load the kernel
    spice.furnsh( __file__ )

    ### Convert MPC constants to CONICS_C elements
    ison = MPC_ISON_C_2012_S1()
    self.rpKM     = spice.convrt( ison.qAU, 'AU', 'KM')
    self.ecc      = ison.e
    self.incRAD   = spice.convrt( ison.InclDEG, 'DEGREES', 'RADIANS')
    self.lnodeRAD = spice.convrt( ison.NodeDEG, 'DEGREES', 'RADIANS')
    self.argpRAD  = spice.convrt( ison.PeriDEG, 'DEGREES', 'RADIANS')
    self.m0RAD    = spice.convrt( ison.M0, 'DEGREES', 'RADIANS')
    self.t0       = spice.str2et( ison.T0_TDT[0] ) + spice.convrt( ison.T0_TDT[1], 'DAYS', 'SECONDS' )
    self.mu       = ison.MuM3S2 * 1e-9
    self.elts = ( self.rpKM, self.ecc, self.incRAD, self.lnodeRAD, self.argpRAD, self.m0RAD, self.t0, self.mu )

    self.ditime       = spice.utc2et( '2013-01-16 12:00:00' )
Esempio n. 11
0
    def __init__(self, argv=None, verbose=True):

        rf = readtemps.__file__
        if rf[-4:-1] == '.py': rf = rf[:-1]
        spice.furnsh(rf)  ### metakernel

        if argv and os.path.isfile(argv[0]):
            fArg = argv[0]
            fName = fArg
        else:
            fArg = sys.stdin
            fName = 'STDIN'

        if verbose:
            print("Reading DI temperature data from %s ..." % (fName, ))

        tts = readtemps.readtemps(fArg)

        self.dii = readtemps.DiScuTemps(tts, which=-70)
        self.dif = readtemps.DiScuTemps(tts, which=-140)
Esempio n. 12
0
  def __init__(self,argv=None,verbose=True):

    rf = readtemps.__file__
    if rf[-4:-1]=='.py': rf = rf[:-1]
    spice.furnsh( rf )   ### metakernel

    if argv and os.path.isfile(argv[0]):
      fArg = argv[0]
      fName = fArg
    else:
      fArg = sys.stdin
      fName = 'STDIN'

    if verbose:
      print( "Reading DI temperature data from %s ..."%(fName,) )

    tts = readtemps.readtemps( fArg )

    self.dii = readtemps.DiScuTemps( tts, which=-70 )
    self.dif = readtemps.DiScuTemps( tts, which=-140 )
Esempio n. 13
0
  def setUp(self):
    mydir = os.path.dirname(__file__)
    self.kernels = [ os.path.join( mydir, i.strip() ) for i in """
### Lines in this string that start with '#' are comments
### The other lines in this string are paths to kernels,
###   relative to the parent directory of this Python script, __file__
###
kernels/naif0010.tls
kernels/smap_v00.tf
kernels/pck00009.tpc
kernels/spk_drm239_WithBurn-full.bsp
kernels/smap_test.bsp
###
### kernels/SMAP_ref_150529_180529.bsp
###
### That commented SMAP SPK kernel, or one like it, should be under this URL:
###
###   http://naif.jpl.nasa.gov/pub/naif/SMAP/kernels/spk/
###
###
""".strip().split('\n') if i[0]!='#' ]

    ### Load default kernels (string variable "kernels" above")
    for kernel in self.kernels: spice.furnsh( kernel )
Esempio n. 14
0
def load_kernels(ephem="DE421"):
    """Ensure all kernels are loaded.

    State is kept in the kernels_loaded module-global variable, so that this
    function can (should!) be called any time the user anticipates needing
    SPICE kernels.
    """
    global kernels_loaded
    if not kernels_loaded:
        spice.furnsh(os.path.join(pintdir, "datafiles/pck00010.tpc"))
        log.info("SPICE loaded planetary constants.")
        spice.furnsh(os.path.join(pintdir, "datafiles/naif0010.tls"))
        log.info("SPICE loaded leap seconds.")
        spice.furnsh(os.path.join(pintdir,
                                  "datafiles/earth_latest_high_prec.bpc"))
        log.info("SPICE loaded Earth rotation parameters.")
        spice.furnsh(os.path.join(pintdir, "datafiles/%s.bsp" % ephem.lower()))
        log.info("SPICE loaded DE%s Planetary Ephemeris." % ephem[2:])
        kernels_loaded = True
Esempio n. 15
0
def load_kernels(ephem="DE421"):
    """Ensure all kernels are loaded.

    State is kept in the kernels_loaded module-global variable, so that this
    function can (should!) be called any time the user anticipates needing
    SPICE kernels.
    """
    global kernels_loaded
    if not kernels_loaded:
        spice.furnsh(datapath("pck00010.tpc"))
        log.info("SPICE loaded planetary constants.")
        try:
            spice.furnsh(datapath("naif0012.tls"))
        except:
            log.error("Download updated leap second file (naif0012.tls)" +
                      " using download script in $PINT/datafiles directory.")
            sys.exit()
        log.info("SPICE loaded leap seconds.")
        spice.furnsh(datapath("earth_latest_high_prec.bpc"))
        log.info("SPICE loaded Earth rotation parameters.")
        spice.furnsh(datapath("%s.bsp" % ephem.lower()))
        log.info("SPICE loaded DE%s Planetary Ephemeris." % ephem[2:])
        kernels_loaded = True
Esempio n. 16
0
def load_kernels(ephem="DE421"):
    """Ensure all kernels are loaded.

    State is kept in the kernels_loaded module-global variable, so that this
    function can (should!) be called any time the user anticipates needing
    SPICE kernels.
    """
    global kernels_loaded
    if not kernels_loaded:
        spice.furnsh(datapath("pck00010.tpc"))
        log.info("SPICE loaded planetary constants.")
        try:
            spice.furnsh(datapath("naif0012.tls"))
        except:
            log.error("Download updated leap second file (naif0012.tls)"+
                      " using download script in $PINT/datafiles directory.")
            sys.exit()
        log.info("SPICE loaded leap seconds.")
        spice.furnsh(datapath("earth_latest_high_prec.bpc"))
        log.info("SPICE loaded Earth rotation parameters.")
        spice.furnsh(datapath("%s.bsp" % ephem.lower()))
        log.info("SPICE loaded DE%s Planetary Ephemeris." % ephem[2:])
        kernels_loaded = True
Esempio n. 17
0
\begindata
KERNELS_TO_LOAD = (
'kernels/naif0010.tls'
'kernels/dif_sclkscet_00015_science.tsc'
'kernels/dii_sclkscet_00008_science_btc.tsc'
)
ETTOIPSEUDO = @2005-07-04T05:44:34.2
\begintext
========================================================================
"""

import spice
import pprint

spice.furnsh(__file__)

### Get UTC and SCLKs of TOI as strings

utctoi = '2005-07-04T05:44:34.2'
diitoi = '1/0173727875.105'
diftoi = '1/0173727702.218'
### N.B. Old code:  pseudo-ET to non-leapsecond-corrected calendar time
###utctoi = spice.etcal( spice.gdpool( 'ETTOIPSEUDO', 0, 1 )[1] )

### Convert UTC and SCLKs strings to ETs
toiet = spice.utc2et( utctoi )
diiet = spice.scs2e(  -70, diitoi )
difet = spice.scs2e( -140, diftoi )

### Output __doc__ string
Esempio n. 18
0
def _gatherorbitdata(delta="1d", scale=15, verbose=False):

    # print("Building orbit for planets with SPICE...")

    spice.kclear()

    # Load the kernels that this program requires.
    this_dir = os.path.dirname(os.path.realpath(__file__))
    spice.furnsh(os.path.join(this_dir, 'epys.mk'))

    # convert starting epoch to ET
    et0 = spice.str2et('2024/05/07 00:00')
    rate = 24 * 2  # Every 30 mins
    days = [(et0 + (day * (86400 / rate))) for day in range(366 * rate)]

    # internal variables and constants
    planets = ("MERCURY", "VENUS", "EARTH")
    AU = consts.AU / 1000.  # AU [km]
    argps = []
    argpxys = []
    xyvecs = []
    nuvecs = []

    for planet in planets:

        # print("     > {}".format(planet))

        dates = []
        rvec = []   # vector of centric radii
        xyvec = []  # vector of (x,y) coordinates
        nuvec = []  # vector of nu (True Anomaly) values
        incvec = []  # vector of inclination values

        for et in days:

            if verbose:
                print('ET Seconds Past J2000: {}'.format(et))

            # Compute the apparent state of MERCURY as seen from
            # the SUN in ECLIPJ2000
            starg, ltime = spice.spkezr(planet, et, 'ECLIPJ2000',
                                        'NONE', 'SUN')

            x, y, z, vx, vy, vz = [el / AU * scale for el in starg]
            r = math.sqrt(x ** 2 + y ** 2 + z ** 2)

            if verbose:
                print('\nApparent state of MERCURY as seen from',
                      ' Sun in the J2000:')
                print(' X = {:10.4f} km (LT+S)'.format(x))
                print(' Y = {:10.4f} km (LT+S)'.format(y))
                print(' Z = {:10.4f} km (LT+S)'.format(z))
                print('VX = {:10.4f} km/s (LT+S)'.format(vx))
                print('VY = {:10.4f} km/s (LT+S)'.format(vy))
                print('VZ = {:10.4f} km/s (LT+S)'.format(vz))

            # calculate orbital elements from the starg state vector
            elts = spice.oscelt(starg, et, planetmu('Sun'))

            # define a solver for Kepler's equation
            ks = pyasl.MarkleyKESolver()

            # solve for the Eccentric Anomaly (E) with the
            # Mean Anomaly (M = elts[5]) and the
            # Eccentricity (ecc = elts[1])
            E = ks.getE(elts[5], elts[1])

            # calculate the True Anomaly (nu) from E and ecc (elts[1])
            nuarg1 = math.sqrt(1 - elts[1]) * math.cos(E / 2)
            nuarg2 = math.sqrt(1 + elts[1]) * math.sin(E / 2)

            # atan2 in python needs the arguments as (y,x)
            # rather than (x,y) ...?
            nu = 2 * math.atan2(nuarg2, nuarg1)

            rvec.append(r)  # append r for each day
            xyvec.append((x, y))  # append (x,y) coords for each day
            nuvec.append(nu)  # append True anomaly for each day

            # build date in ISO format
            date = '{} {}'.format(spice.et2utc(et, 'ISOC', 0).split('T')[0],
                                  spice.et2utc(et, 'ISOC', 0).split('T')[1])
            dates.append(date)  # append date for each day
            incvec.append(elts[2])  # append inc. for each day (rads)

            # print(date, nu * spice.dpr(), x, y, z, r, elts[0])

        # for this planet find the argument of pericenter (argp):
        # find the index of the min. r value for calculated range.
        argpi = rvec.index(min(rvec))

        # calculate argp x and y values and argp using atan2
        argpxy = (xyvec[argpi][0], xyvec[argpi][1] * math.cos(incvec[argpi]))
        argp = math.degrees(math.atan2(argpxy[1], argpxy[0]))

        argpxys.append(argpxy)  # append argp (x,y) coords.
        argps.append(argp)  # append argp
        xyvecs.append(xyvec)  # append (x,y) coords. vector
        nuvecs.append(nuvec)  # append true anomaly vector

    spice.kclear()

    return days, dates, xyvecs, argps, argpxys, nuvecs
Esempio n. 19
0
if nPixelsX > 1:
    Dx = Lx / (nPixelsX - 1)
else:
    Dx = Lx

if nPixelsY > 1:
    Dy = Ly / (nPixelsY - 1)
else:
    Dy = Ly


if iPointingCase == spice_:
    #################################################
    # get rosetta coordinates from spice
    #################################################
    spice.furnsh(StringKernelMetaFile)
    Et = spice.str2et(StringUtcStartTime)
    #R = spice.pxform("ROS_SPACECRAFT", "67P/C-G_CSO", Et)      # create rotation matrix R to go from instrument reference frame to CSO
    if ((iDim == 2) or (iDim == 1)):
        rRosetta, lightTime = spice.spkpos("ROSETTA", Et, "67P/C-G_CSO", "NONE", "CHURYUMOV-GERASIMENKO")        # s/c coordinates in CSO frame of reference
        R = spice.pxform(InstrumentFrame, "67P/C-G_CSO", Et)      # create rotation matrix R to go from instrument reference frame to CSO
    elif iDim == 3:
        print "iDim = 3"
        rRosetta, lightTime = spice.spkpos("ROSETTA", Et, "67P/C-G_CK", "NONE", "CHURYUMOV-GERASIMENKO")        # s/c coordinates in CSO frame of reference
        R = spice.pxform(InstrumentFrame, "67P/C-G_CK", Et)
        # do 3d stuff from here?
        rSun, lt = spice.spkpos("SUN", Et, "67P/C-G_CK", "NONE", "CHURYUMOV-GERASIMENKO")
        rSun = np.array(rSun)
        rSun = rSun / np.sqrt((rSun**2).sum())
        # quick and dirty fix --> andre  needs to define instrument object for all instruments!
        try:
Esempio n. 20
0
File: vj.py Progetto: drbitboy/vj
  'naif0010.tls'
  'pck00010.tpc'
)
ETLO = @1900-01-01T12:00:00
ETHI = @2099-12-31T12:00:00
\begintext
"""

### https://github.com/rca/PySPICE , or
### https://github.com/drbitboy/PySPICE
import spice

dot = '.'

### Load kernels using this source as SPICE meta-kernel
spice.furnsh(dot.join(__file__.split(dot)[:-1] + ['py']))

### Set arguments for Geometry Finder call
### - Times when VENUS crosses equator of Jupiter (Zjup = 0)
### - abcorr='LT+S' - correct for light time and stellar aberration
### - Timestep of 10 days (spice.spd() = seconds per day)
### - nintvls - 450 seems to work here
target, frame, abcorr, obsrvr = 'VENUS', 'IAU_JUPITER', 'LT+S', 'JUPITER'
relate, crdsys, coord = '=', 'RECTANGULAR', 'Z'
refval, adjust, step, nintvls = 0.0, 0.0, spice.spd()*10, 450

### Range of ETs to test
etlo,ethi = [spice.gdpool(s,0,1)[1] for s in 'ETLO ETHI'.split()]
cnfine = spice.wninsd( etlo, ethi, spice.objects.Cell(spice.DataType.SPICE_DP,2))

### Create DP window to receive results
Esempio n. 21
0
def test_example_loading():
    currentdir = os.getcwd()
    os.chdir(kernelpath)
    spice.furnsh("ck/moc42_2010100_2010100_v01.bc")
    spice.furnsh("fk/lro_frames_2012255_v02.tf")
    spice.furnsh("fk/lro_dlre_frames_2010132_v04.tf")
    spice.furnsh("ick/lrodv_2010090_2010121_v01.bc")
    spice.furnsh("lsk/naif0010.tls")
    spice.furnsh('sclk/lro_clkcor_2010096_v00.tsc')
    spice.furnsh("spk/fdf29_2010100_2010101_n01.bsp")
    spice.furnsh('./planet_spk/de421.bsp')

    utc = dt.strptime('2010100 05', '%Y%j %H').isoformat()
    et = spice.utc2et(utc)
    t = spice.spkpos('sun', et, 'LRO_DLRE_SCT_REF', 'lt+s', 'lro')
    print(t)
    answer = ((-63972935.85033857, -55036272.7848299, 123524941.9877458),
                499.009424105693)
    for i, j in zip(t[0], answer[0]):
        assert_equals(round(i, 3), round(j, 3))
    os.chdir(currentdir)
Esempio n. 22
0
ETTOI-108d is TOI(tparse('2005-07-04T05:44:34.2')) + 64.184s - 108d
Alternate DII SCLK kernels:
'$K/dii_sclkscet_00008_science.tsc'
'$K/dii_sclkscet_00008.tsc'
========================================================================
"""

import os
import sys
import spice
import pprint
import timediffs
import matplotlib.pyplot as plt

### Load meta-kernel, get start time ETTOI-108d
spice.furnsh(__file__)

### Override any kernels with sys.argv[1:]
for sclkk in sys.argv[1:]: spice.furnsh(sclkk)

### Get TEXT kernel list
ks = '\n'.join([os.path.basename(spice.kdata(i,'text')[0]) for i in range(spice.ktotal('TEXT'))])

### Get TOI-108d, set up for one point per day for 108d
et = spice.gdpool( 'ETTOI-108d', 0, 1 )[1]
spanDays = 108
diffs = range(spanDays+1)
doys = [ i+185-spanDays for i in diffs ]

### Spacecraft IDs to plot
scids = [-70,-140]
Esempio n. 23
0
KERNELS_TO_LOAD = (
'$K/naif0010.tls'
'$K/dif_sclkscet_00015_science.tsc'
'$K/dii_sclkscet_00008_science_btc.tsc'
)
ETSTART = @2005-06-19T05:45:38.384
\begintext
N.B. ETSTART is TOI(tparse('2005-07-04T05:44:34.2')) + 64.184s - 15d
========================================================================
"""

import spice
import pprint

print(__doc__.replace('\b', '\\b'))
spice.furnsh(__file__)

### ET of TOI-15d
found, et = spice.gdpool('ETSTART', 0, 1)

### S/C IDs
scids = [-70, -140]
n = len(scids)
rn = range(len(scids))

### for 15 days leading up to TOI
for i in range(16):
    ### Convert
    ### - ET to ISO Calendar and DOY UTCs
    ### - ET to DII and DIF SCLKs
    ### - SCLKs to encoded SCLK, scale by 1/256 to get s past J2k epoch
Esempio n. 24
0
from __future__ import division, print_function
import spice
import os
from diviner.file_utils import kernelpath
from datetime import datetime as dt
from numpy import degrees, arccos

currentdir = os.getcwd()
os.chdir(kernelpath)
spice.furnsh("fk/lro_frames_2012255_v02.tf")
spice.furnsh("fk/lro_dlre_frames_2010132_v04.tf")
spice.furnsh("ick/lrodv_2010090_2010121_v01.bc")
spice.furnsh("lsk/naif0010.tls")
spice.furnsh('sclk/lro_clkcor_2009182_v00.tsc')
spice.furnsh("spk/fdf29_2010100_2010101_n01.bsp")
spice.furnsh('./planet_spk/de421.bsp')
# spice.furnsh("ck/moc42_2010100_2010100_v01.bc")

time = dt(2009,6,24,0,1,8)

print("Testing for time ", time, '\nIn kernel-time: ', time.strftime("%Y%j"),
      'plus {0} hours.'.format(time.hour))
et = spice.utc2et(time.isoformat())

# ckernels = ['moc42_2010100_2010100_v01.bc', 'moc42_2010100_2010101_v01.bc',
            # 'moc42_2010100_2010101_v02.bc']
ckernels = ['moc42_2009174_2009175_v01.bc','moc42_2009175_2009176_v02.bc']

for ck in ckernels:
    spice.furnsh('ck/'+ck)
    print("Loading {0}".format(ck))
Esempio n. 25
0
def planetsplot(userdates=None, delta="1d", master_scale=15, demo=False,
                showplots=False):
    """
    ... explain what this does...
    """

    outdir = './sample_data/output'
    # if demo:
    #     shutil.rmtree(outdir)
    #     os.makedirs(outdir)
    # else:
    #     if not os.path.exists(outdir):
    #         os.makedirs(outdir)
    #     else:
    #         print('\n   Uh-oh! The directory {} already exists.'.format(
    #             outdir))
    #         if yesno('   Do you want to replace it?'):
    #             shutil.rmtree(outdir)
    #             os.makedirs(outdir)
    #         else:
    #             return

    orbitdata = _gatherorbitdata(delta=delta, scale=master_scale)
    ets, dates, orbits, argps, argpxys, nus = orbitdata

    if userdates is None:
        userdates = dates

    if showplots:
        plt.subplot(1, 1, 1)
        for xy in orbits:
            plt.plot([x[0] for x in xy], [y[1] for y in xy],
                     'rx', label='SPICE')
        for xy in argpxys:
            plt.plot(xy[0], xy[1], 'go')
        plt.show()

    if len(orbits[0]) == len(dates) == len(ets):

        # This rotation will put the Hermean perihelion on the X-axis.
        rotang = -argps[0]

        # Load the kernels that this program requires.
        spice.kclear()
        this_dir = os.path.dirname(os.path.realpath(__file__))
        spice.furnsh(os.path.join(this_dir, 'epys.mk'))

        output_files = []

        # A graphic will be created for each 'date' in 'userdates':
        for date in userdates:

            # get the position-index of the 'et' in the 'orbitdata' list
            # of 'ets' that is closest to the 'date' in the 'userdates'
            et = spice.str2et(date)
            dx = ets.index(getclosest(ets, et))

            # -- Outer frame -------------------------------------------------

            # Opacity of degree frame and Venus graphic
            frame_op = 0.8

            # Process calendar time strings
            date = '{} {}'.format(spice.et2utc(et, 'ISOC', 0).split('T')[0],
                                  spice.et2utc(et, 'ISOC', 0).split('T')[1])
            edate, etime = date.split()
            eyear = "{}".format(edate.split('-')[0])
            emonth = "{0:02d}".format(int(edate.split('-')[1]))
            eday = "{0:02d}".format(int(edate.split('-')[2]))
            epoch = "{}/{}/{}".format(eday, emonth, eyear)
            ep_name = "{}{}{}_{}".format(eyear, emonth, eday,
                                         etime.replace(':', ''))

            frame = _outerframe(epoch, frmSize=master_scale, frm_op=frame_op)

            # -- First Point of Aires ----------------------------------------

            # merc_loan = 48.331
            # merc_argp = 29.124
            arend = svg.make_marker("fopa_arrowend", "arrow_end",
                                    fill_opacity=0.4)

            x1, y1 = 10, 0
            x2, y2 = master_scale * 1.3, 0

            fpoa = svg.Line(x1, y1, x2, y2, stroke_width=".4pt",
                            stroke_opacity=0.4, arrow_end=arend)

            xp = (x2 * math.cos(math.radians(rotang)) -
                  y2 * math.sin(math.radians(rotang)))
            yp = (x2 * math.sin(math.radians(rotang)) +
                  y2 * math.cos(math.radians(rotang)))

            fpoa_text = svg.Text(xp + 6.5, yp - 1.0, "First Point of Aries",
                                 font_size=3, opacity=0.75)
            fpoa = svg.Fig(svg.Fig(fpoa, trans=svg.rotate(rotang, 0, 0)),
                           fpoa_text)

            # -- Some containers ---------------------------------------------

            orbs = []
            circles = []
            defs = svg.SVG("defs")

            # -- Orbit circles -----------------------------------------------

            # Build the SVG for each orbit.
            for orbit in orbits:

                if orbits.index(orbit) == 1:
                    orbit_op = 0.4
                else:
                    orbit_op = 1.0

                # Mercury's orbit will have perihelion on the X-axis
                circles.append(svg.Fig(svg.Poly(orbit, stroke_width=".25pt",
                                                stroke_opacity=orbit_op),
                                       trans=svg.rotate(rotang, 0, 0)))

            # -- Planet orbs -------------------------------------------------

            points = [orbits[0][dx], orbits[1][dx], orbits[2][dx]]

            # Build the planet orb for each planet for this chart.
            for point in points:

                # Planetary inputs ...
                if points.index(point) == 0:
                    name = "MERCURY"
                    nu = math.degrees(math.atan2(point[1], point[0])) + rotang
                    if nu < 0:
                        nu = nu + 360
                    # print(nu, nu-rotang, rotang)
                    nu = "{0:03d}".format(int(nu))
                if points.index(point) == 1:
                    name = "VENUS"
                if points.index(point) == 2:
                    name = "EARTH"

                # point_r  = [x/AU for x in point]

                orb, grad = _planetdiag(name, point, rotang)

                orbs.append(orb)
                defs.append(grad)

            # -- Build final figure ------------------------------------------

            wa = master_scale * 1.5
            svgout = svg.Fig(fpoa, frame,
                             circles[0], circles[1], circles[2],
                             orbs[0], orbs[1], orbs[2]
                             ).SVG(svg.window(-wa, wa, -wa, wa))

            svgout.prepend(defs)
            out_path = os.path.join(outdir,
                                    "merc_orbit_plot_{}_{}.svg".format(
                                        ep_name, nu))
            svgout.save(out_path)
            output_files.append(out_path)

        spice.kclear()

        return output_files

    else:
        # You'll jump to hear if the epochs for all 3 planets are not equal.
        print("There is an epoch error between the planet time values...")
Esempio n. 26
0
  def test_horizons(self):
    import horizons

    target = 'C/2013 S1'
    target = 'C/2011 L4'

    spkFilename,spiceId,status = horizons.gomain(target)

    spice.furnsh( spkFilename )
    self.kernels += [spkFilename]

    target_ = '_'.join( target.split() )

    et0 = spice.utc2et( '2013-01-10T12:00:00' )

    ls2au = spice.convrt( spice.clight(), 'KM', 'AU' )
    dpr = spice.dpr()
    spd = spice.spd()

    deltatime = None

    while deltatime is None or abs(deltatime) > 5e-7:
      stS2I,lsS2I = spice.spkgeo( spiceId, et0, 'J2000', 10 )
      posn, veloc = stS2I[:3], stS2I[3:]
      deltatime = - spice.vdot( posn, veloc ) / spice.vdot( veloc, veloc )
      et0 += deltatime


    valarrs = [ ]
    print( (deltatime,spice.et2utc(et0,'ISOC',3),) )

    deltatime = 1.0
    sixmonths = spice.pi() * 1e7

    while deltatime < sixmonths:
      for pmdet in (-deltatime,deltatime):
        et = et0 + pmdet
        utc = spice.et2utc(et,'ISOC',1)

        stD2I,lsD2I = spice.spkgeo( spiceId, et, 'J2000', -140)
        stI2S,lsI2S = spice.spkgeo( 10, et, 'J2000', spiceId )
        stD2S,lsD2S = spice.spkgeo( 10, et, 'J2000', -140 )

        rD2I, rI2S = [ ls * ls2au for ls in [lsD2I,lsI2S] ]
        aDIS, aSDI = [ ang * dpr for ang in 
                       [ spice.vsep( spice.vminus(stD2I[:3]), stI2S[:-3] )
                       , spice.vsep( stD2S[:3], stD2I[:-3] )
                       ]
                     ]
        valarrs += [ (et,pmdet,rD2I,rI2S,aDIS,aSDI,utc,) ]

      deltatime *= 1.2

    valarrs.sort()
    for valarr in valarrs:
      print( '%12.1f %9.3f %9.3f %7.2f %7.2f %s' % valarr[1:] )

    days = [i[1]/spd for i in valarrs]

    titles = [ i % (target_,) for i in """
    Range, %s-DI, AU
    Range, %s-Sun, AU
    Phase, DI-%s-Sun, deg
    Elongation, Sun-DI-%s, deg
    """.strip().split('\n')]

    try:
      ### Moved matplotlib import to here so test runs to here at least
      from matplotlib import pyplot as plt
      plt.figure(1)
      for idx in range(len(titles)):
        ordinate = [i[idx+2] for i in valarrs]
        plt.subplot( 221+idx )
        plt.plot( days, ordinate )
        plt.plot( days, ordinate, '.')
        plt.title( titles[idx] )
        plt.ylabel( titles[idx] )
        if idx>1: plt.xlabel( 'T-Tperi, d' )

      plt.show()

    except:
      print( "Bypassed, or failed, matplotlib tests" )
Esempio n. 27
0
    def compute_posvels(self, ephem="DE421", planets=False):
        """Compute positions and velocities of the observatories and Earth.

        Compute the positions and velocities of the observatory (wrt
        the Geocenter) and the center of the Earth (referenced to the
        SSB) for each TOA.  The JPL solar system ephemeris can be set
        using the 'ephem' parameter.  The positions and velocities are
        set with PosVel class instances which have astropy units.
        """
        # Record the planets choice for this instance
        self.planets = planets
        
        # Remove any existing columns
        cols_to_remove = ['ssb_obs_pos', 'ssb_obs_vel', 'obs_sun_pos']
        for c in cols_to_remove:
            if c in self.table.colnames:
                log.info('Column {0} already exists. Removing...'.format(c))
                self.table.remove_column(c)
        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
            name = 'obs_'+p+'_pos'
            if name in self.table.colnames:
                log.info('Column {0} already exists. Removing...'.format(name))
                self.table.remove_column(name)
                
        load_kernels(ephem)
        pth = os.path.join(pintdir, "datafiles")
        ephem_file = os.path.join(pth, "%s.bsp"%ephem.lower())
        log.info("Loading %s ephemeris." % ephem_file)
        spice.furnsh(ephem_file)
        self.table.meta['ephem'] = ephem
        ssb_obs_pos = table.Column(name='ssb_obs_pos',
                                    data=numpy.zeros((self.ntoas, 3), dtype=numpy.float64),
                                    unit=u.km, meta={'origin':'SSB', 'obj':'OBS'})
        ssb_obs_vel = table.Column(name='ssb_obs_vel',
                                    data=numpy.zeros((self.ntoas, 3), dtype=numpy.float64),
                                    unit=u.km/u.s, meta={'origin':'SSB', 'obj':'OBS'})
        obs_sun_pos = table.Column(name='obs_sun_pos',
                                    data=numpy.zeros((self.ntoas, 3), dtype=numpy.float64),
                                    unit=u.km, meta={'origin':'OBS', 'obj':'SUN'})
        if planets:
            plan_poss = {}
            for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                name = 'obs_'+p+'_pos'
                plan_poss[name] = table.Column(name=name,
                                    data=numpy.zeros((self.ntoas, 3), dtype=numpy.float64),
                                    unit=u.km, meta={'origin':'OBS', 'obj':p})
        # Now step through in observatory groups
        for ii, key in enumerate(self.table.groups.keys):
            grp = self.table.groups[ii]
            obs = self.table.groups.keys[ii]['obs']
            loind, hiind = self.table.groups.indices[ii:ii+2]
            if (key['obs'] == 'Barycenter'):
                for jj, grprow in enumerate(grp):
                    ind = jj+loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    obs_sun = objPosVel("SSB", "SUN", et)
                    obs_sun_pos[ind,:] = obs_sun.pos
            elif (key['obs'] == 'Spacecraft'):
                # For a time recorded at a spacecraft, use the position of
                # the spacecraft recorded in the TOA to compute the needed
                # vectors.
                pass
            elif (key['obs'] == 'Geocenter'):
                for jj, grprow in enumerate(grp):
                    ind = jj+loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    ssb_earth = objPosVel("SSB", "EARTH", et)
                    obs_sun = objPosVel("EARTH", "SUN", et)
                    obs_sun_pos[ind,:] = obs_sun.pos
                    ssb_obs = ssb_earth
                    ssb_obs_pos[ind,:] = ssb_obs.pos
                    ssb_obs_vel[ind,:] = ssb_obs.vel
                    if planets:
                        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                            name = 'obs_'+p+'_pos'
                            dest = p.upper()+" BARYCENTER"
                            pv = objPosVel("EARTH", dest, et)
                            plan_poss[name][ind,:] = pv.pos
            elif (key['obs'] in observatories):
                earth_obss = erfautils.topo_posvels(obs, grp)
                for jj, grprow in enumerate(grp):
                    ind = jj+loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    ssb_earth = objPosVel("SSB", "EARTH", et)
                    obs_sun = objPosVel("EARTH", "SUN", et) - earth_obss[jj]
                    obs_sun_pos[ind,:] = obs_sun.pos
                    ssb_obs = ssb_earth + earth_obss[jj]
                    ssb_obs_pos[ind,:] = ssb_obs.pos
                    ssb_obs_vel[ind,:] = ssb_obs.vel
                    if planets:
                        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                            name = 'obs_'+p+'_pos'
                            dest = p.upper()+" BARYCENTER"
                            pv = objPosVel("EARTH", dest, et) - earth_obss[jj]
                            plan_poss[name][ind,:] = pv.pos
            else:
                log.error("Unknown observatory {0}".format(key['obs']))
        cols_to_add = [ssb_obs_pos, ssb_obs_vel, obs_sun_pos]
        if planets:
            cols_to_add += plan_poss.values()
        self.table.add_columns(cols_to_add)
Esempio n. 28
0
iceyfp.close()

modelFP = open(cfg['SERVERS'][server]['DOCROOT']+"/"+cfg['TYPES']['Coma']['CONFIG'])
Models = json.load(modelFP)
modelFP.close()

pathToExecutable = cfg['SERVERS'][server]['DOCROOT']+"/"+cfg['MODELS']+"/LoS/pyComa/bin"
#pathToExecutable = '/Users/ices/www-dev/htdocs/ICES/Models/LoS/pyComa/bin'
#pathToExecutable = '/Users/abieler/pyComa/bin'

if args.StringMeasurement == 'LOS':
    print 'LOS hybrid case...'
    #####################################################################
    # get position of s/c and pointing towards Earth from SPICE
    #####################################################################
    spice.furnsh(args.StringKernelMetaFile)
    Et = spice.str2et(args.StringUtcStartTime)
    rEarth, lightTime = spice.spkpos("EARTH", Et, "67P/C-G_CSO", "NONE", "ROSETTA")
    rRosetta, lightTime = spice.spkpos("ROSETTA", Et, "67P/C-G_CSO", "NONE", "CHURYUMOV-GERASIMENKO")
    rEarth = np.array(rEarth)
    rRosetta = np.array(rRosetta) * 1000  # transform km to m
    print 'Distance from comet: %.2e' % (np.sqrt(np.sum(rRosetta ** 2)))

    # p = normalized vector pointing from s/c to Earth in cso coordinates
    p = rEarth / np.sqrt(np.sum(rEarth**2))

    # rRay = position of rosetta s/c in cso coordinates
    rRay = np.array([value for value in rRosetta])

    ######################################################################
    # build line of sight ray xTravel, and extract x, y, z coordinates
Esempio n. 29
0
    def compute_posvels(self, ephem="DE421", planets=False):
        """Compute positions and velocities of the observatories and Earth.

        Compute the positions and velocities of the observatory (wrt
        the Geocenter) and the center of the Earth (referenced to the
        SSB) for each TOA.  The JPL solar system ephemeris can be set
        using the 'ephem' parameter.  The positions and velocities are
        set with PosVel class instances which have astropy units.
        """
        # Record the planets choice for this instance
        self.planets = planets

        # Remove any existing columns
        cols_to_remove = ['ssb_obs_pos', 'ssb_obs_vel', 'obs_sun_pos']
        for c in cols_to_remove:
            if c in self.table.colnames:
                log.info('Column {0} already exists. Removing...'.format(c))
                self.table.remove_column(c)
        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
            name = 'obs_' + p + '_pos'
            if name in self.table.colnames:
                log.info('Column {0} already exists. Removing...'.format(name))
                self.table.remove_column(name)

        load_kernels(ephem)
        ephem_file = datapath("%s.bsp" % ephem.lower())
        log.info("Loading %s ephemeris." % ephem_file)
        spice.furnsh(ephem_file)
        self.table.meta['ephem'] = ephem
        ssb_obs_pos = table.Column(name='ssb_obs_pos',
                                   data=numpy.zeros((self.ntoas, 3),
                                                    dtype=numpy.float64),
                                   unit=u.km,
                                   meta={
                                       'origin': 'SSB',
                                       'obj': 'OBS'
                                   })
        ssb_obs_vel = table.Column(name='ssb_obs_vel',
                                   data=numpy.zeros((self.ntoas, 3),
                                                    dtype=numpy.float64),
                                   unit=u.km / u.s,
                                   meta={
                                       'origin': 'SSB',
                                       'obj': 'OBS'
                                   })
        obs_sun_pos = table.Column(name='obs_sun_pos',
                                   data=numpy.zeros((self.ntoas, 3),
                                                    dtype=numpy.float64),
                                   unit=u.km,
                                   meta={
                                       'origin': 'OBS',
                                       'obj': 'SUN'
                                   })
        if planets:
            plan_poss = {}
            for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                name = 'obs_' + p + '_pos'
                plan_poss[name] = table.Column(name=name,
                                               data=numpy.zeros(
                                                   (self.ntoas, 3),
                                                   dtype=numpy.float64),
                                               unit=u.km,
                                               meta={
                                                   'origin': 'OBS',
                                                   'obj': p
                                               })
        # Now step through in observatory groups
        for ii, key in enumerate(self.table.groups.keys):
            grp = self.table.groups[ii]
            obs = self.table.groups.keys[ii]['obs']
            loind, hiind = self.table.groups.indices[ii:ii + 2]
            if (key['obs'] == 'Barycenter'):
                for jj, grprow in enumerate(grp):
                    ind = jj + loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    obs_sun = objPosVel("SSB", "SUN", et)
                    obs_sun_pos[ind, :] = obs_sun.pos
            elif (key['obs'] == 'Spacecraft'):
                # For a time recorded at a spacecraft, use the position of
                # the spacecraft recorded in the TOA to compute the needed
                # vectors.
                pass
            elif (key['obs'] == 'Geocenter'):
                for jj, grprow in enumerate(grp):
                    ind = jj + loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    ssb_earth = objPosVel("SSB", "EARTH", et)
                    obs_sun = objPosVel("EARTH", "SUN", et)
                    obs_sun_pos[ind, :] = obs_sun.pos
                    ssb_obs = ssb_earth
                    ssb_obs_pos[ind, :] = ssb_obs.pos
                    ssb_obs_vel[ind, :] = ssb_obs.vel
                    if planets:
                        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                            name = 'obs_' + p + '_pos'
                            dest = p.upper() + " BARYCENTER"
                            pv = objPosVel("EARTH", dest, et)
                            plan_poss[name][ind, :] = pv.pos
            elif (key['obs'] in observatories):
                earth_obss = erfautils.topo_posvels(obs, grp)
                for jj, grprow in enumerate(grp):
                    ind = jj + loind
                    et = float((grprow['tdbld'] - J2000ld) * SECS_PER_DAY)
                    ssb_earth = objPosVel("SSB", "EARTH", et)
                    obs_sun = objPosVel("EARTH", "SUN", et) - earth_obss[jj]
                    obs_sun_pos[ind, :] = obs_sun.pos
                    ssb_obs = ssb_earth + earth_obss[jj]
                    ssb_obs_pos[ind, :] = ssb_obs.pos
                    ssb_obs_vel[ind, :] = ssb_obs.vel
                    if planets:
                        for p in ('jupiter', 'saturn', 'venus', 'uranus'):
                            name = 'obs_' + p + '_pos'
                            dest = p.upper() + " BARYCENTER"
                            pv = objPosVel("EARTH", dest, et) - earth_obss[jj]
                            plan_poss[name][ind, :] = pv.pos
            else:
                log.error("Unknown observatory {0}".format(key['obs']))
        cols_to_add = [ssb_obs_pos, ssb_obs_vel, obs_sun_pos]
        if planets:
            cols_to_add += plan_poss.values()
        self.table.add_columns(cols_to_add)
Esempio n. 30
0
def mpoplot(userdates, master_scale=15, demo=False):
    """
    ... explain what this does...
    """

    outdir = '../sample_data/output'
    # if demo:
    #     shutil.rmtree(outdir)
    #     os.makedirs(outdir)
    # else:
    #     if not os.path.exists(outdir):
    #         os.makedirs(outdir)
    #     else:
    #         print('\n   Uh-oh! The directory {} already exists.'.format(
    #             outdir))
    #         if yesno('   Do you want to replace it?'):
    #             shutil.rmtree(outdir)
    #             os.makedirs(outdir)
    #         else:
    #             return

    # Clear and load the kernels that this program requires.
    spice.kclear()
    spice.furnsh('epys.mk')

    # A graphic will be created for each 'date' in 'dates':
    for date in userdates:

        et = spice.str2et(date)
        datestr = (spice.et2utc(et, 'ISOC', 0))

        # -- Outer frame -------------------------------------------------

        dist_scl = 250.0

        elts = getorbelts(date)
        arg_peri = elts[4]

        # Opacity of degree frame and Venus graphic
        frame_op = 0.5

        # # Process JD time into calendar time strings
        # datestr = spice.et2utc(et, 'ISOC', 0)
        date = '{} {}'.format(datestr.split('T')[0],
                              datestr.split('T')[1])
        edate, etime = date.split()
        eyear = "{}".format(edate.split('-')[0])
        emonth = "{0:02d}".format(int(edate.split('-')[1]))
        eday = "{0:02d}".format(int(edate.split('-')[2]))
        epoch = "{}/{}/{}".format(eday, emonth, eyear)
        ep_name = "{}{}{}".format(eyear, emonth, eday)

        frame = _outerframe(epoch, frmSize=master_scale, frm_op=frame_op,
                            mpoargp=arg_peri)

        # -- Mercury Planet --------------------------------------------------

        # tru_ano = 90
        # look_from = 270

        # x1 = "{}%".format((100*math.sin(math.radians((tru_ano+90)/2.))))
        # x2 = "{}%".format(100-(100*sin(radians((tru_ano+90)/2.))))

        angs = range(0, 360, 1)

        plt.plot(angs, ["{}".format((100 * math.sin(math.radians(x / 2))))
                        for x in angs], 'yo-')
        plt.plot(angs, ["{}".format(100 - (100 *
                        math.sin(math.radians(x / 2)))) for x in angs], 'ro-')
        # plt.show()

        stop1 = "#C8C5E2"
        # stop2 = "#373163"

        defs = svg.SVG("defs",
                       svg.SVG("linearGradient",
                               svg.SVG("stop", stop_color=stop1,
                                       stop_opacity=1, offset="45%"),
                               svg.SVG("stop", stop_color=stop1,
                                       stop_opacity=1, offset="55%"),
                               x1="0%", y1="0%", x2="100%", y2="0%",
                               spreadMethod="pad",
                               id="mercGrad")
                       )

        # defs = svg.SVG('defs',
        #                svg.SVG('radialGradient',
        #                        svg.SVG('stop',
        #                                stop_color=stop1,
        #                                stop_opacity=1,
        #                                offset='38%'),
        #                        svg.SVG('stop',
        #                                stop_color=stop2,
        #                                stop_opacity=1,
        #                                offset='40%'),
        #                        cx='50%', cy='50%',
        #                        fx='230%', fy='50%',
        #                        r='300%',
        #                        spreadMethod='pad',
        #                        id='mercGrad')
        #                )

        merc_rad = 2439.99  # km
        merc_rad_scl = merc_rad / dist_scl
        merc_ball = svg.Ellipse(0, 0, 0, merc_rad_scl, merc_rad_scl,
                                fill="url(#mercGrad)", stroke_width="0.15pt")

        # -- MPO Orbit --

        mpo_orb_ecc = 0.163229
        mpo_orb_sma = 3394.0  # km
        mpo_orb_sma_scl = mpo_orb_sma / dist_scl
        mpo_orb_smi_scl = mpo_orb_sma_scl * math.sqrt(1 - mpo_orb_ecc ** 2)

        # Make things cleaner
        a = mpo_orb_sma_scl
        b = mpo_orb_smi_scl

        mpo_orb = svg.Ellipse(-math.sqrt(a ** 2 - b ** 2), 0, 0, a, b,
                              fill="none", stroke_width="0.25pt")
        # apof = 8
        mpo_orb_apses = svg.Line(-_rellipse(a, b, 180) - 5, 0,
                                 _rellipse(a, b, 0) + 10, 0,
                                 stroke_width="0.15pt",
                                 stroke_dasharray="2, 2")

        dot_angs = range(0, 360, 20)
        dots = [_orbitdot(a, b, x, color="black") for x in dot_angs]
        mpo_orb_dots = svg.Fig()
        for dot in dots:
            mpo_orb_dots.d.append(dot)

        mpo_orb_trans = svg.rotate(arg_peri, 0, 0)
        mpo_orb_plot = svg.Fig(mpo_orb, mpo_orb_apses, mpo_orb_dots,
                               trans=mpo_orb_trans)

        # -- Direction arrow -------------------------------------------------

        dirarend = svg.make_marker("dirarrowend", "arrow_end",
                                   fill_opacity=0.2)
        dirarend.attr["markerWidth"] = 7.5

        x1, y1 = master_scale + 1, 0.4,
        x2, y2 = master_scale + 1, 1

        dirarwstrt = svg.Line(x1, y1, x2, y2, stroke_width=".4pt",
                              stroke_opacity=0.2, arrow_end=dirarend)

        dirarw = svg.Fig(dirarwstrt, trans="x*cos(y), x*sin(y)")

        # -- Apsis view ------------------------------------------------------

        apvx, apvy = master_scale + 3, -master_scale - 3
        apsisviewball = svg.Ellipse(apvx, apvy,
                                    0, merc_rad_scl * 0.25,
                                    merc_rad_scl * 0.25,
                                    fill="url(#mercGrad)",
                                    stroke_width="0.15pt")

        apsisviewlats = svg.Fig()

        for x in range(-9, 10, 3):

            hscl = math.sin(math.radians(x * 10))
            wscl = math.cos(math.radians(x * 10))

            x1 = apvx - (merc_rad_scl * 0.25 * wscl)
            y1 = apvy + (merc_rad_scl * 0.25 * hscl)
            x2 = apvx + (merc_rad_scl * 0.25 * wscl)
            y2 = apvy + (merc_rad_scl * 0.25 * hscl)

            apsisviewlats.d.append(svg.Line(x1, y1, x2, y2,
                                   stroke_width=".2pt",
                                   stroke_opacity=0.4))

        apvarend = svg.make_marker("apvarrowend",
                                   "arrow_end",
                                   fill_opacity=0.6)
        apvarend.attr["markerWidth"] = 3.0
        apvarend.attr["markerHeight"] = 3.0

        x1, y1 = apvx, apvy - 3
        x2, y2 = apvx, apvy + 3
        apsisvieworbit = svg.Line(x1, y1, x2, y2,
                                  stroke_width=".4pt",
                                  stroke_opacity=0.6,
                                  arrow_end=apvarend)

        xd = apvx
        yd = apvy + (merc_rad_scl * 0.25 * math.sin(math.radians(arg_peri)))
        apsisviewdot = svg.Fig(svg.Dots([(xd, yd)],
                                        svg.make_symbol("apsisdot",
                                                        fill="black",
                                                        fill_opacity=0.6
                                                        ),
                                        0.6, 0.6
                                        )
                               )

        apsisview = svg.Fig(apsisviewball,
                            apsisviewlats,
                            apsisvieworbit,
                            apsisviewdot)

        # -- Build final figure ----------------------------------------------

        wa = master_scale * 1.5
        svgout = svg.Fig(frame,
                         merc_ball,
                         mpo_orb_plot,
                         dirarw,
                         apsisview
                         ).SVG(svg.window(-wa, wa, -wa, wa))

        svgout.prepend(defs)

        argp = int(arg_peri)
        svgout.save(os.path.join(outdir,
                                 "mpo_orbit_plot_{}_{}.svg".format(ep_name,
                                                                   argp)
                                 )
                    )
Esempio n. 31
0
def test_example_loading():
    currentdir = os.getcwd()
    os.chdir(kernelpath)
    spice.furnsh("ck/moc42_2010100_2010100_v01.bc")
    spice.furnsh("fk/lro_frames_2012255_v02.tf")
    spice.furnsh("fk/lro_dlre_frames_2010132_v04.tf")
    spice.furnsh("ick/lrodv_2010090_2010121_v01.bc")
    spice.furnsh("lsk/naif0010.tls")
    spice.furnsh('sclk/lro_clkcor_2010096_v00.tsc')
    spice.furnsh("spk/fdf29_2010100_2010101_n01.bsp")
    spice.furnsh('./planet_spk/de421.bsp')

    utc = dt.strptime('2010100 05', '%Y%j %H').isoformat()
    et = spice.utc2et(utc)
    t = spice.spkpos('sun', et, 'LRO_DLRE_SCT_REF', 'lt+s', 'lro')
    print(t)
    answer = ((-63972935.85033857, -55036272.7848299, 123524941.9877458),
              499.009424105693)
    for i, j in zip(t[0], answer[0]):
        assert_equals(round(i, 3), round(j, 3))
    os.chdir(currentdir)
Esempio n. 32
0
    def test_horizons(self):
        import horizons

        target = 'C/2013 S1'
        target = 'C/2011 L4'

        spkFilename, spiceId, status = horizons.gomain(target)

        spice.furnsh(spkFilename)
        self.kernels += [spkFilename]

        target_ = '_'.join(target.split())

        et0 = spice.utc2et('2013-01-10T12:00:00')

        ls2au = spice.convrt(spice.clight(), 'KM', 'AU')
        dpr = spice.dpr()
        spd = spice.spd()

        deltatime = None

        while deltatime is None or abs(deltatime) > 5e-7:
            stS2I, lsS2I = spice.spkgeo(spiceId, et0, 'J2000', 10)
            posn, veloc = stS2I[:3], stS2I[3:]
            deltatime = -spice.vdot(posn, veloc) / spice.vdot(veloc, veloc)
            et0 += deltatime

        valarrs = []
        print((
            deltatime,
            spice.et2utc(et0, 'ISOC', 3),
        ))

        deltatime = 1.0
        sixmonths = spice.pi() * 1e7

        while deltatime < sixmonths:
            for pmdet in (-deltatime, deltatime):
                et = et0 + pmdet
                utc = spice.et2utc(et, 'ISOC', 1)

                stD2I, lsD2I = spice.spkgeo(spiceId, et, 'J2000', -140)
                stI2S, lsI2S = spice.spkgeo(10, et, 'J2000', spiceId)
                stD2S, lsD2S = spice.spkgeo(10, et, 'J2000', -140)

                rD2I, rI2S = [ls * ls2au for ls in [lsD2I, lsI2S]]
                aDIS, aSDI = [
                    ang * dpr for ang in [
                        spice.vsep(spice.vminus(stD2I[:3]), stI2S[:-3]),
                        spice.vsep(stD2S[:3], stD2I[:-3])
                    ]
                ]
                valarrs += [(
                    et,
                    pmdet,
                    rD2I,
                    rI2S,
                    aDIS,
                    aSDI,
                    utc,
                )]

            deltatime *= 1.2

        valarrs.sort()
        for valarr in valarrs:
            print('%12.1f %9.3f %9.3f %7.2f %7.2f %s' % valarr[1:])

        days = [i[1] / spd for i in valarrs]

        titles = [
            i % (target_, ) for i in """
    Range, %s-DI, AU
    Range, %s-Sun, AU
    Phase, DI-%s-Sun, deg
    Elongation, Sun-DI-%s, deg
    """.strip().split('\n')
        ]

        try:
            ### Moved matplotlib import to here so test runs to here at least
            from matplotlib import pyplot as plt
            plt.figure(1)
            for idx in range(len(titles)):
                ordinate = [i[idx + 2] for i in valarrs]
                plt.subplot(221 + idx)
                plt.plot(days, ordinate)
                plt.plot(days, ordinate, '.')
                plt.title(titles[idx])
                plt.ylabel(titles[idx])
                if idx > 1: plt.xlabel('T-Tperi, d')

            plt.show()

        except:
            print("Bypassed, or failed, matplotlib tests")
Esempio n. 33
0
ETTOI-108d is TOI(tparse('2005-07-04T05:44:34.2')) + 64.184s - 108d
Alternate DII SCLK kernels:
'$K/dii_sclkscet_00008_science.tsc'
'$K/dii_sclkscet_00008.tsc'
========================================================================
"""

import os
import sys
import spice
import pprint
import timediffs
import matplotlib.pyplot as plt

### Load meta-kernel, get start time ETTOI-108d
spice.furnsh(__file__)

### Override any kernels with sys.argv[1:]
for sclkk in sys.argv[1:]:
    spice.furnsh(sclkk)

### Get TEXT kernel list
ks = '\n'.join([
    os.path.basename(spice.kdata(i, 'text')[0])
    for i in range(spice.ktotal('TEXT'))
])

### Get TOI-108d, set up for one point per day for 108d
et = spice.gdpool('ETTOI-108d', 0, 1)[1]
spanDays = 108
diffs = range(spanDays + 1)