def cal2et(date): """Convert calendar date to SPICE ephemeris time. Ephemeris time is seconds past 2000.0. UTC is assumed. Parameters ---------- date : string or array The date. Returns ------- et : float or array Ephemeris time. """ from ..util import cal2iso global _spice_setup if not _spice_setup: _setup_spice() if isinstance(date, (list, tuple, np.ndarray)): return [cal2et(x) for x in t] return spice.utc2et(cal2iso(date))
def jd2et(jd): """Convert Julian date to SPICE ephemeris time. Ephemeris time is seconds past 2000.0. UTC is assumed. Parameters ---------- jd : string, float, or array The Julian date. Strings will have higher precisions than floats. Returns ------- et : float or array Ephemeris time. """ global _spice_setup if not _spice_setup: _setup_spice() if isinstance(jd, (list, tuple, np.ndarray)): return [jd2et(x) for x in jd] if isinstance(jd, float): jd = "{:17.9f} JD".format(jd) return spice.utc2et(jd)
def time2et(t): """Convert astropy `Time` to SPICE ephemeris time. Ephemeris time is seconds past 2000.0. Parameters ---------- t : astropy Time The time. Must be convertable to the UTC scale. Returns ------- et : float or array Ephemeris time. """ global _spice_setup from .. import util if not _spice_setup: _setup_spice() if util.date_len(t) > 0: return [time2et(x) for x in t] return spice.utc2et(t.utc.iso)
def readone(lin): ### Exception for lines that do not match try: ### Parse (split on whitespace) three items from line tims, tems, scids = lin.split()[:3] ### Parse strings: Temp, degC; S/C SPICE ID; ERT UTC to ET(s past J2k) tem = float(tems) scid = int(scids) ert = spice.utc2et(tims) if spice.failed(): spice.reset() assert False ### Discard invalid data ### - temperature < 10degC; typically -61.0 = null return ### - SCID neither DII nor DIF if tem < 10: assert False if scid != -140 and scid != -70: assert False ### Calculate light time to Earth from S/C to get time at S/C stateVector, lighttime = spice.spkez(scid, ert, "j2000", "LT", 399) return ert - lighttime, tem, scid ### success except: return [0.0, 0.0, 0] ### failure (SCID==0)
def test_smap(self): target = 'SMAP' et0 = spice.utc2et( '2016-06-01T12:00:00' ) dpr = spice.dpr() a,b,c = [spice.gdpool('BODY399_RADII',i,1)[1] for i in range(3)] ods = [] for deltatime in [0.1 * i for i in range(1080)]: et = et0 + deltatime stSmap,lsSmap = spice.spkezr( target, et, 'IAU_EARTH', 'NONE', 'EARTH' ) posn, veloc = stSmap[:3], stSmap[3:] stSun,lsSun = spice.spkezr( 'SUN', et0, 'IAU_EARTH', 'LT', 'EARTH' ) mtx = spice.pxform( 'SMAP_REFLECTOR', 'IAU_EARTH', et) boreEbf = spice.mxv( mtx, [1.0,0,0] ) point = spice.surfpt( posn, boreEbf, a, b, c) rsurfpt,lon,lat = spice.reclat( point ) utc = spice.et2utc( et, 'ISOC', 3 ) ods += [ OD(deltatime=deltatime,posn=posn,veloc=veloc,boreEbf=boreEbf ,utc=utc,point=point,rsurfpt=rsurfpt ,rsmap=spice.vnorm(posn),lat=lat,lon=lon ,raynge=spice.vnorm(spice.vsub(point,posn)) ,sunsep=spice.vsep( spice.ucrss(posn,veloc), stSun[:3] ) ) ] try: ### Moved matplotlib import to here so test runs to here at least from matplotlib import pyplot as plt plt.figure(1) keys = 'lat lon raynge'.split() secs = [od['deltatime'] for od in ods] for idx in range(len(keys)): scal = 1.0 if keys[idx] in 'rsurfpt rsmap raynge sunsep rp ecc t0 mu a P eccmean amean Pmean'.split() else dpr ordinate = [od[keys[idx]]*scal for od in ods] plt.subplot( 221+idx ) plt.plot( secs, ordinate ) plt.plot( secs, ordinate, '.') plt.title( keys[idx] ) plt.ylabel( '%s%s' % (keys[idx],'' if scal==1.0 else ', deg') ) if idx>1: plt.xlabel( 'T-T0, s' ) abscissa = [od['lon']*dpr for od in ods] ordinate = [od['lat']*dpr for od in ods] plt.subplot( 221+idx+1 ) plt.title( 'lon vs. lat' ) plt.plot( abscissa, ordinate ) plt.xlabel( 'lon, deg' ) plt.ylabel( 'lat, deg' ) plt.show() except: print( "Bypassed, or failed, matplotlib tests" )
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' )
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)
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 print( __doc__.replace('\b','\\b') ) ### Output differences and UTC TOI ET converted to SCLKs pprint.pprint( ( 'ET differences:' , ( ('%s(DII)-%s'%(diitoi,utctoi,)) ,diiet-toiet,) , ( ('%s(DIF)-%s'%(diftoi,utctoi,)) ,difet-toiet,) , ( ('%s(DIF)-%s(DII)'%(diftoi,diitoi,)),difet-diiet,) , '' , 'UTC TOI converted to DII and DIF SCLK:' , (utctoi+'=>DII', spice.sce2s(-70,toiet),) , (utctoi+'=>DIF', spice.sce2s(-140,toiet),)
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" )
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")
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)) t = spice.spkpos('sun', et, 'LRO_DLRE_SCT_REF', 'lt+s', 'lro') unitv = spice.vhat(t[0]) print(t[0], "Zenith angle:", degrees(arccos(unitv[2]))) spice.unload('ck/'+ck)
pdsi = PDSImage.PDSImage() ### dcmd ocontains recursive dictionaries dcmd = pdsi._downone(faux) ### Extract start time from dcmd (CoreMetadata) as ISO UTC string firstTomsUTC = '%sT%s' % ( dcmd['INVENTORYMETADATA']['RANGEDATETIME']['RANGEBEGINNINGDATE'] ['VALUE'], dcmd['INVENTORYMETADATA']['RANGEDATETIME']['RANGEBEGINNINGTIME'] ['VALUE'], ) ### Combine start time and /Time offset to get the TOMS data zero epoch as seconds past J2000 epoch ### N.B. is typically (always?) equivalent to 1993-01-01T00:00:00 UTC tomsZeroEpoch = spice.utc2et(firstTomsUTC) - tomsOffsetTimes[0] print('%s(Epoch) %s(Start) %s' % ( spice.et2utc(tomsZeroEpoch, 'ISOC', 1), firstTomsUTC, fnInput, )) ### Iterators twoDshape = surfLonDegs.shape rowIter, pixelIter = map(xrange, twoDshape) glintAngles = numpy.zeros(twoDshape, dtype=numpy.float32) for row in rowIter:
def test_smap(self): target = 'SMAP' et0 = spice.utc2et('2016-06-01T12:00:00') dpr = spice.dpr() a, b, c = [spice.gdpool('BODY399_RADII', i, 1)[1] for i in range(3)] ods = [] for deltatime in [0.1 * i for i in range(1080)]: et = et0 + deltatime stSmap, lsSmap = spice.spkezr(target, et, 'IAU_EARTH', 'NONE', 'EARTH') posn, veloc = stSmap[:3], stSmap[3:] stSun, lsSun = spice.spkezr('SUN', et0, 'IAU_EARTH', 'LT', 'EARTH') mtx = spice.pxform('SMAP_REFLECTOR', 'IAU_EARTH', et) boreEbf = spice.mxv(mtx, [1.0, 0, 0]) point = spice.surfpt(posn, boreEbf, a, b, c) rsurfpt, lon, lat = spice.reclat(point) utc = spice.et2utc(et, 'ISOC', 3) ods += [ OD(deltatime=deltatime, posn=posn, veloc=veloc, boreEbf=boreEbf, utc=utc, point=point, rsurfpt=rsurfpt, rsmap=spice.vnorm(posn), lat=lat, lon=lon, raynge=spice.vnorm(spice.vsub(point, posn)), sunsep=spice.vsep(spice.ucrss(posn, veloc), stSun[:3])) ] try: ### Moved matplotlib import to here so test runs to here at least from matplotlib import pyplot as plt plt.figure(1) keys = 'lat lon raynge'.split() secs = [od['deltatime'] for od in ods] for idx in range(len(keys)): scal = 1.0 if keys[ idx] in 'rsurfpt rsmap raynge sunsep rp ecc t0 mu a P eccmean amean Pmean'.split( ) else dpr ordinate = [od[keys[idx]] * scal for od in ods] plt.subplot(221 + idx) plt.plot(secs, ordinate) plt.plot(secs, ordinate, '.') plt.title(keys[idx]) plt.ylabel('%s%s' % (keys[idx], '' if scal == 1.0 else ', deg')) if idx > 1: plt.xlabel('T-T0, s') abscissa = [od['lon'] * dpr for od in ods] ordinate = [od['lat'] * dpr for od in ods] plt.subplot(221 + idx + 1) plt.title('lon vs. lat') plt.plot(abscissa, ordinate) plt.xlabel('lon, deg') plt.ylabel('lat, deg') plt.show() except: print("Bypassed, or failed, matplotlib tests")
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 print(__doc__.replace('\b', '\\b')) ### Output differences and UTC TOI ET converted to SCLKs pprint.pprint(( 'ET differences:', ( ('%s(DII)-%s' % ( diitoi, utctoi, )), diiet - toiet,