Exemple #1
0
 def test_iers_a_now():
     # FIXME: might use cached IERS_A_URL?
     # FIXME: what would this actually be testing?
     # astropy has auto-updating IERS data now
     iers_a = IERS_A.open(IERS_A_URL)
     t2 = astropy.time.Time.now()
     t2.delta_ut1_utc = t2.get_delta_ut1_utc(iers_a)
     print(t2.tdb.iso)
Exemple #2
0
    def test_iers_a_now():
        # FIXME: might use cached IERS_A_URL?
        # FIXME: what would this actually be testing?
        # astropy has auto-updating IERS data now
        # Tries the main URL first, then falls back to MIRROR
        try:
            from urllib.error import HTTPError

            iers_a = IERS_A.open(IERS_A_URL)
        except HTTPError:
            try:
                from astropy.utils.iers import IERS_A_URL_MIRROR

                iers_a = IERS_A.open(IERS_A_URL_MIRROR)
            except ImportError:
                raise
        t2 = astropy.time.Time.now()
        t2.delta_ut1_utc = t2.get_delta_ut1_utc(iers_a)
        print(t2.tdb.iso)
Exemple #3
0
def get_updated_iers_table(cache=True, raise_=True):  # TODO: rename
    """Get updated IERS data"""
    from astropy.utils.iers import IERS_A, IERS_A_URL  # import IERS data class
    from astropy.utils.data import download_file

    logging.info('Updating IERS table.')

    # get IERS data tables from cache / download
    try:
        iers_a_file = download_file(IERS_A_URL, cache=cache)
        iers_a = IERS_A.open(iers_a_file)  # load data tables
        logging.info('Done')
        return iers_a
    except URLError as err:
        if raise_:
            raise err
        warn('Unable to update IERS table due to the following exception:\n%s'
             '\nAre you connected to the internet? If not, try re-run with'
             ' cache=True'
             % err)  # TODO with traceback?
        return None
Exemple #4
0
def examine_exposure(info, cframe, cframe_keys):
    # Process CFrame header keywords
    for keyword in cframe_keys:
        info[keyword] = cframe.header[keyword]

    obs_ra = cframe.header['RADEG']
    obs_dec = cframe.header['DECDEG']
    taibeg = cframe.header['TAI-BEG']
    taiend = cframe.header['TAI-END']

    taimid = 0.5*(taibeg+taiend)
    dec = Angle(obs_dec, u.degree)
    ra = Angle(obs_ra, u.degree)



    time = Time(taimid/86400.0, format='mjd', scale='tai', location=apo)
    try:
        lst = time.sidereal_time('apparent')
    except IndexError:
        ## workaround for problem with recent observations relative to astropy release
        ## http://astropy.readthedocs.org/en/v0.4.2/time/index.html#transformation-offsets
        from astropy.utils.iers import IERS_A, IERS_A_URL
        from astropy.utils.data import download_file 
        iers_a_file = download_file(IERS_A_URL, cache=True)  
        iers_a = IERS_A.open(iers_a_file)                     
        time.delta_ut1_utc = time.get_delta_ut1_utc(iers_a)

        lst = time.sidereal_time('apparent')

    ha = (lst - ra)

    if ha > np.pi*u.radian:
        ha -= 2*np.pi*u.radian
    elif ha < -np.pi*u.radian:
        ha += 2*np.pi*u.radian
    info['mean_ha'] = ha.to(u.degree).value

    alt, az = equatorial_to_horizontal(ra, dec, apolat, ha)
    info['mean_alt'] = alt.to(u.degree).value
Exemple #5
0
def examine_exposure(info, cframe, cframe_keys):
    # Process CFrame header keywords
    for keyword in cframe_keys:
        info[keyword] = cframe.header[keyword]

    obs_ra = cframe.header['RADEG']
    obs_dec = cframe.header['DECDEG']
    taibeg = cframe.header['TAI-BEG']
    taiend = cframe.header['TAI-END']

    taimid = 0.5 * (taibeg + taiend)
    dec = Angle(obs_dec, u.degree)
    ra = Angle(obs_ra, u.degree)

    time = Time(taimid / 86400.0, format='mjd', scale='tai', location=apo)
    try:
        lst = time.sidereal_time('apparent')
    except IndexError:
        ## workaround for problem with recent observations relative to astropy release
        ## http://astropy.readthedocs.org/en/v0.4.2/time/index.html#transformation-offsets
        from astropy.utils.iers import IERS_A, IERS_A_URL
        from astropy.utils.data import download_file
        iers_a_file = download_file(IERS_A_URL, cache=True)
        iers_a = IERS_A.open(iers_a_file)
        time.delta_ut1_utc = time.get_delta_ut1_utc(iers_a)

        lst = time.sidereal_time('apparent')

    ha = (lst - ra)

    if ha > np.pi * u.radian:
        ha -= 2 * np.pi * u.radian
    elif ha < -np.pi * u.radian:
        ha += 2 * np.pi * u.radian
    info['mean_ha'] = ha.to(u.degree).value

    alt, az = equatorial_to_horizontal(ra, dec, apolat, ha)
    info['mean_alt'] = alt.to(u.degree).value
Exemple #6
0
    def _pvobs(self):
        '''calculates position and velocity of the observatory
           returns position/velocity in AU and AU/d in GCRS reference frame
        '''

        # convert obs position from WGS84 (lat long) to ITRF geocentric coords in AU
        xyz = self.location.to(u.AU).value

        # now we need to convert this position to Celestial Coords
        # specifically, the GCRS coords.
        # conversion from celestial to terrestrial coords given by
        # [TRS] = RPOM * R_3(ERA) * RC2I * [CRS]
        # where:
        # [CRS] is vector in GCRS (geocentric celestial system)
        # [TRS] is vector in ITRS (International Terrestrial Ref System)
        # ERA is earth rotation angle
        # RPOM = polar motion matrix

        tt = self.tt
        mjd = self.utc.mjd

        # we need the IERS values to correct for the precession/nutation of the Earth
        iers_tab = IERS.open()

        # Find UT1, which is needed to calculate ERA
        # uses IERS_B by default , for more recent times use IERS_A download
        try:
            ut1 = self.ut1
        except:
            try:
                iers_a_file = download_file(IERS_A_URL, cache=True)
                iers_a = IERS_A.open(iers_a_file)
                self.delta_ut1_utc = self.get_delta_ut1_utc(iers_a)
                ut1 = self.ut1
            except:
                # fall back to UTC with degraded accuracy
                warnings.warn(
                    'Cannot calculate UT1: using UTC with degraded accuracy')
                ut1 = self.utc

        # Gets x,y coords of Celestial Intermediate Pole (CIP) and CIO locator s
        # CIO = Celestial Intermediate Origin
        # Both in GCRS
        X, Y, S = erfa.xys00a(tt.jd1, tt.jd2)

        # Get dX and dY from IERS B
        dX = np.interp(mjd, iers_tab['MJD'], iers_tab['dX_2000A']) * u.arcsec
        dY = np.interp(mjd, iers_tab['MJD'], iers_tab['dY_2000A']) * u.arcsec

        # Get GCRS to CIRS matrix
        # can be used to convert to Celestial Intermediate Ref Sys
        # from GCRS.
        rc2i = erfa.c2ixys(X + dX.to(u.rad).value, Y + dY.to(u.rad).value, S)

        # Gets the Terrestrial Intermediate Origin (TIO) locator s'
        # Terrestrial Intermediate Ref Sys (TIRS) defined by TIO and CIP.
        # TIRS related to to CIRS by Earth Rotation Angle
        sp = erfa.sp00(tt.jd1, tt.jd2)

        # Get X and Y from IERS B
        # X and Y are
        xp = np.interp(mjd, iers_tab['MJD'], iers_tab['PM_x']) * u.arcsec
        yp = np.interp(mjd, iers_tab['MJD'], iers_tab['PM_y']) * u.arcsec

        # Get the polar motion matrix. Relates ITRF to TIRS.
        rpm = erfa.pom00(xp.to(u.rad).value, yp.to(u.rad).value, sp)

        # multiply ITRF position of obs by transpose of polar motion matrix
        # Gives Intermediate Ref Frame position of obs
        x, y, z = np.array([rpmMat.T.dot(xyz) for rpmMat in rpm]).T

        # Functions of Earth Rotation Angle, theta
        # Theta is angle bewtween TIO and CIO (along CIP)
        # USE UT1 here.
        theta = erfa.era00(ut1.jd1, ut1.jd2)
        S, C = np.sin(theta), np.cos(theta)

        # Position #GOT HERE
        pos = np.asarray([C * x - S * y, S * x + C * y, z]).T

        # multiply by inverse of GCRS to CIRS matrix
        # different methods for scalar times vs arrays
        if pos.ndim > 1:
            pos = np.array(
                [np.dot(rc2i[j].T, pos[j]) for j in range(len(pos))])
        else:
            pos = np.dot(rc2i.T, pos)

        # Velocity
        vel = np.asarray(
            [SR * (-S * x - C * y), SR * (C * x - S * y),
             np.zeros_like(x)]).T
        # multiply by inverse of GCRS to CIRS matrix
        if vel.ndim > 1:
            vel = np.array(
                [np.dot(rc2i[j].T, vel[j]) for j in range(len(pos))])
        else:
            vel = np.dot(rc2i.T, vel)

        #return position and velocity
        return pos, vel
TEL_LONGITUDE = 74*u.deg+02*u.arcmin+59.07*u.arcsec
TEL_LATITUDE = 19*u.deg+05*u.arcmin+47.46*u.arcsec

NPOD = 30  # Number of baselines (only used as sanity check)

ANTENNA_FILE = '/Users/Natalie/scintellometry/scintellometry/phasing/' \
               'antsys.hdr'
OUR_ANTENNA_ORDER = 'CWES'   # and by number inside each group
NON_EXISTING_ANTENNAS = ('C07', 'S05')  # to remove from antenna file


USE_UT1 = False
if USE_UT1:
    IERS_A_FILE = '/home/mhvk/packages/astropy/finals2000A.all'
    from astropy.utils.iers import IERS_A
    iers_a = IERS_A.open(IERS_A_FILE)

IST_UTC = TimeDelta(0., 5.5/24., format='jd')


def timestamp_to_Time(line):
    """Convert a timestamp item to a astropy Time instance.
    Store telescope lon, lat as well for full precision in possible
    TDB conversion (not used so far)
    """
    tl = line.split()
    seconds = float(tl[5])+float(tl[6])
    return Time(tl[0] + '-' + tl[1] + '-' + tl[2] + ' ' +
                tl[3] + ':' + tl[4] + ':{}'.format(seconds), scale='utc',
                lat=TEL_LATITUDE, lon=TEL_LONGITUDE)
def test_iers_a_now():
    iers_a_file = download_file(IERS_A_URL, cache=True)
    iers_a = IERS_A.open(iers_a_file)
    t2 = astropy.time.Time.now()
    t2.delta_ut1_utc = t2.get_delta_ut1_utc(iers_a)
    print t2.tdb.iso
from numpy.linalg import norm
import matplotlib.pyplot as plt

from astropy import units as u
from astropy.time import Time
from astropy.coordinates import HCRS, ITRS, GCRS
from astropy.utils.iers import IERS_A, IERS_A_URL, IERS
from astropy.utils.data import download_file

from trajectory_utilities import ECEF2LLH, \
     EarthPosition, HCRS2HCI, HCI2ECI_pos, \
     OrbitalElements2PosVel, ECI2ECEF_pos

try:
    iers_a_file = download_file(IERS_A_URL, cache=True)
    iers_a = IERS_A.open(iers_a_file)
    IERS.iers_table = iers_a
except:
    print('IERS_A_URL is temporarily unavailable')
    pass

AU = 1 * u.au.to(u.m)
SMA_JUPITER = 5.20336301 * u.au


def tisserand_wrt_jupiter(a, e, i):
    '''
    Calculate the Tisserrand criterion with respect to Jupiter
    '''
    T_j = (SMA_JUPITER / a + 2 * np.cos(i) * np.sqrt(a / SMA_JUPITER *
                                                     (1 - e**2)))
Exemple #10
0
import astropy.units as u
from astropy.utils.iers import IERS_A, IERS_A_URL
from astropy.utils.data import download_file
from .spiceutils import objPosVel, load_kernels
from pint import pintdir
from astropy import log


toa_commands = ("DITHER", "EFAC", "EMAX", "EMAP", "EMIN", "EQUAD", "FMAX",
                "FMIN", "INCLUDE", "INFO", "JUMP", "MODE", "NOSKIP", "PHA1",
                "PHA2", "PHASE", "SEARCH", "SIGMA", "SIM", "SKIP", "TIME",
                "TRACK", "ZAWGT", "FORMAT", "END")

observatories = observatories_module.read_observatories()
iers_a_file = download_file(IERS_A_URL, cache=True)
iers_a = IERS_A.open(iers_a_file)

def toa_format(line, fmt="Unknown"):
    """Determine the type of a TOA line.

    Identifies a TOA line as one of the following types:  Comment, Command,
    Blank, Tempo2, Princeton, ITOA, Parkes, Unknown."""
    if line[0] == 'C' or line[0] == '#':
        return "Comment"
    elif line.startswith(toa_commands):
        return "Command"
    elif re.match(r"^\s+$", line):
        return "Blank"
    elif re.match(r"[0-9a-z@] ", line):
        return "Princeton"
    elif re.match(r"  ", line) and len(line) > 41 and line[41] == '.':
Exemple #11
0
def baryvel_los(obstime, coords, observatory_loc, sun=False,
                heliocentric=False, aORg='g'):
    """
    vvec (output vector(4))
    Various projections of the barycentric velocity
	correction, expressed in km/sec. The four elements in the vector are radial,
 	tangential, right ascension, and declination projections respectively.
 	Add vvec(0) to the observed velocity scale to shift it to the barycenter.
    
    sun=True to get shift of scattered light from sun. Coords don't matter
    """
    from PyAstronomy.pyasl import baryvel
    from astropy.coordinates import Longitude, ICRS
    import astropy.units as u
    import os
    
    OBSERVATORY_COORD={
     'lick3':{
        'lat':0.651734547,   #+37 20 29.9
        'lon':2.123019229,	  # 121 38 24.15
        'ht':1283.},
     'cfht': {
        'lat':0.346030917,  #+19 49 34
        'lon':2.713492477, #155 28 18
        'ht':4198.},
     'kp':{
        'lat':0.557865407,	#+31 57.8 (1991 Almanac)
        'lon': 1.947787445,  #111 36.0
        'ht':2120.},
     'mcd':{ #McDonald (Fort Davis)
	    'lat':0.5353215959, # +30 40.3 (1995 Almanac)
	    'lon':1.815520621, #104 01.3
        'ht':2075.},
     'keck':{ #Keck (Mauna Kea)
	    'lat':0.346040613,  #+19 49.6 (Keck website)
	    'lon': 2.71352157,  #155 28.4
        'ht':4159.58122},
     'keck2':{
         #http://irtfweb.ifa.hawaii.edu/IRrefdata/telescope_ref_data.html
         'lat':0.34603876045870413, #19 49 35.61788
        'lon':2.7135372866735916,   #155 28 27.24268
        'ht':4159.58122},
     'irtf':{
         #http://irtfweb.ifa.hawaii.edu/IRrefdata/telescope_ref_data.html
	    'lat':0.34603278784504105, #19 49 34.38594
	    'lon':2.7134982735227475,  #155 28 19.19564
        'ht':4168.06685},
     'clay':{
    	  'lat':-0.5063938434309143,
    	  'lon':-1.2338154852026897,
          'ht':2450.0},
     'clay_jb':{
          'lat':-0.506392081, #  .364" diff ~22 meters different
          'lon':1.23381854, # .63" diff
          'ht':2406.1}
    }
    if type(observatory_loc)!=str:
        lat, lon, ht =observatory_loc
    else:
        lat=OBSERVATORY_COORD[observatory_loc]['lat']
        lon=OBSERVATORY_COORD[observatory_loc]['lon']
        ht=OBSERVATORY_COORD[observatory_loc]['ht']

    #Make sure we've got the longitude in the time object to compute lmst
    time=obstime.copy()
    if time.lon==None or type(observatory_loc)!=str:
        time.lon=Longitude(lon, unit=u.radian)

    from astropy.utils.iers import IERS_A,IERS_A_URL
    from astropy.utils.data import download_file
    try:
        this_dir, _ = os.path.split(__file__)
        IERS_A_PATH = os.path.join(this_dir, "data", 'finals2000A.all')
        iers_a = IERS_A.open(IERS_A_PATH)
    except IOError:
        iers_a_file = download_file(IERS_A_URL, cache=True)
        iers_a = IERS_A.open(iers_a_file)

    time.delta_ut1_utc = iers_a.ut1_utc(time)

    #Local rotaion rate
    vrot = 465.102 * ((1.0 + 1.57e-7 * ht) /
                     np.sqrt(1.0 + 0.993305 * np.tan(lat)**2))

    #Calculate barycentric velocity of earth.
    velh, velb= baryvel(time.jd,0.0)

    #Find lmst of observation
    lmst=time.sidereal_time('mean')

    #Calculation of geocentric velocity of observatory.
    velt = vrot * np.array([-np.sin(lmst.radian), np.cos(lmst.radian), 0.0])

    #Calculate dv (what is dv?)
    dv = velb + velt * 1e-3

    if sun or heliocentric:
        dv = velh + velt * 1e-3

    if sun:
        import ephem
        eo = ephem.Observer()
        eo.lon = lon
        eo.lat = lat
        eo.elevation = 2450.0
        eo.date = time.datetime
        sunephem=ephem.Sun(eo)
        
        #Calculation of barycentric velocity components.
        if aORg=='a':
            sra = np.sin(sunephem.a_ra)
            sdec = np.sin(sunephem.a_dec)
            cra = np.cos(sunephem.a_ra)
            cdec = np.cos(sunephem.a_dec)
        else:
            sra = np.sin(sunephem.g_ra)
            sdec = np.sin(sunephem.g_dec)
            cra = np.cos(sunephem.g_ra)
            cdec = np.cos(sunephem.g_dec)
    else:
        #Make sure coords is an ICRS object
        if type(coords) != ICRS:
            if coords[3]!=2000:
                raise ValueError('Provide IRCS to handle equniox other than 2000')
            coords=ICRS(coords[0], coords[1],
                        unit=(u.degree, u.degree),
                        equinox=Time('J2000', scale='utc'))

        #Precess coordinates to j
        pcoords=coords.fk5.precess_to(time)

        #Calculation of barycentric velocity components.
        sra = np.sin(pcoords.ra.radian)
        sdec = np.sin(pcoords.dec.radian)
        cra = np.cos(pcoords.ra.radian)
        cdec = np.cos(pcoords.dec.radian)


    dvr = dv[0]*cra*cdec + dv[1]*sra*cdec + dv[2]*sdec
    dva = -dv[0]*sra + dv[1]*cra
    dvd = -dv[0]*cra*sdec - dv[1]*sra*sdec + dv[2]*cdec
    dvt = np.sqrt(dva*dva + dvd*dvd)

    #Return
    return [dvr, dvt, dva, dvd]
Exemple #12
0
    def compute_TDBs(self):
        """Compute and add TDB and TDB long double columns to the TOA table.

        This routine creates new columns 'tdb' and 'tdbld' in a TOA table
        for TDB times, using the Observatory locations and IERS A Earth
        rotation corrections for UT1.
        """
        from astropy.utils.iers import IERS_A, IERS_A_URL
        from astropy.utils.data import download_file, clear_download_cache
        global iers_a_file, iers_a
        # If previous columns exist, delete them
        if 'tdb' in self.table.colnames:
            log.info('tdb column already exists. Deleting...')
            self.table.remove_column('tdb')
        if 'tdbld' in self.table.colnames:
            log.info('tdbld column already exists. Deleting...')
            self.table.remove_column('tdbld')

        # First make sure that we have already applied clock corrections
        ccs = False
        for tfs in self.table['flags']:
            if 'clkcorr' in tfs: ccs = True
        if ccs is False:
            log.warn("No TOAs have clock corrections.  Use .apply_clock_corrections() first.")
        # These will be the new table columns
        col_tdb = numpy.zeros_like(self.table['mjd'])
        col_tdbld = numpy.zeros(self.ntoas, dtype=numpy.longdouble)
        # Read the IERS for ut1_utc corrections, if needed
        iers_a_file = download_file(IERS_A_URL, cache=True)
        # Check to see if the cached file is older than any of the TOAs
        iers_file_time = time.Time(os.path.getctime(iers_a_file), format="unix")
        if (iers_file_time.mjd < self.last_MJD.mjd):
            clear_download_cache(iers_a_file)
            try:
                log.warn("Cached IERS A file is out-of-date.  Re-downloading.")
                iers_a_file = download_file(IERS_A_URL, cache=True)
            except:
                pass
        iers_a = IERS_A.open(iers_a_file)
        # Now step through in observatory groups to compute TDBs
        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]
            # Make sure the string precisions are all set to 9 for all TOAs
            for t in grp['mjd']:
                t.precision = 9
            if key['obs'] in ["Barycenter", "Geocenter", "Spacecraft"]:
                # For these special cases, convert the times to TDB.
                # For Barycenter this will be
                # a null conversion, but for Geocenter the scale will Likely
                # be TT (if they came from a spacecraft like Fermi, RXTE or NICER)
                tdbs = [t.tdb for t in grp['mjd']]
            elif key['obs'] in observatories:
                # For a normal observatory, convert to Time in UTC
                # with location specified as observatory,
                # and then convert to TDB
                utcs = time.Time([t.isot for t in grp['mjd']],
                                format='isot', scale='utc', precision=9,
                                location=observatories[obs].loc)
                utcs.delta_ut1_utc = utcs.get_delta_ut1_utc(iers_a)
                # Also save delta_ut1_utc for these TOAs for later use
                for toa, dut1 in zip(grp['mjd'], utcs.delta_ut1_utc):
                    toa.delta_ut1_utc = dut1
                # The actual conversion from UTC to TDB is done by astropy.Time
                # as described here <http://docs.astropy.org/en/stable/time/>,
                # with the real work done by the IAU SOFA library
                tdbs = utcs.tdb
            else:
                log.error("Unknown observatory ({0})".format(key['obs']))

            col_tdb[loind:hiind] = numpy.asarray([t for t in tdbs])
            col_tdbld[loind:hiind] = numpy.asarray([utils.time_to_longdouble(t) for t in tdbs])
        # Now add the new columns to the table
        col_tdb = table.Column(name='tdb', data=col_tdb)
        col_tdbld = table.Column(name='tdbld', data=col_tdbld)
        self.table.add_columns([col_tdb, col_tdbld])
Exemple #13
0
    def compute_TDBs(self):
        """Compute and add TDB and TDB long double columns to the TOA table.

        This routine creates new columns 'tdb' and 'tdbld' in a TOA table
        for TDB times, using the Observatory locations and IERS A Earth
        rotation corrections for UT1.
        """
        from astropy.utils.iers import IERS_A, IERS_A_URL
        from astropy.utils.data import download_file, clear_download_cache
        global iers_a_file, iers_a
        # If previous columns exist, delete them
        if 'tdb' in self.table.colnames:
            log.info('tdb column already exists. Deleting...')
            self.table.remove_column('tdb')
        if 'tdbld' in self.table.colnames:
            log.info('tdbld column already exists. Deleting...')
            self.table.remove_column('tdbld')

        # First make sure that we have already applied clock corrections
        ccs = False
        for tfs in self.table['flags']:
            if 'clkcorr' in tfs: ccs = True
        if ccs is False:
            log.warn(
                "No TOAs have clock corrections.  Use .apply_clock_corrections() first."
            )
        # These will be the new table columns
        col_tdb = numpy.zeros_like(self.table['mjd'])
        col_tdbld = numpy.zeros(self.ntoas, dtype=numpy.longdouble)
        # Read the IERS for ut1_utc corrections, if needed
        iers_a_file = download_file(IERS_A_URL, cache=True)
        # Check to see if the cached file is older than any of the TOAs
        iers_file_time = time.Time(os.path.getctime(iers_a_file),
                                   format="unix")
        if (iers_file_time.mjd < self.last_MJD.mjd):
            clear_download_cache(iers_a_file)
            try:
                log.warn("Cached IERS A file is out-of-date.  Re-downloading.")
                iers_a_file = download_file(IERS_A_URL, cache=True)
            except:
                pass
        iers_a = IERS_A.open(iers_a_file)
        # Now step through in observatory groups to compute TDBs
        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]
            # Make sure the string precisions are all set to 9 for all TOAs
            for t in grp['mjd']:
                t.precision = 9
            if key['obs'] in ["Barycenter", "Geocenter", "Spacecraft"]:
                # For these special cases, convert the times to TDB.
                # For Barycenter this will be
                # a null conversion, but for Geocenter the scale will Likely
                # be TT (if they came from a spacecraft like Fermi, RXTE or NICER)
                tdbs = [t.tdb for t in grp['mjd']]
            elif key['obs'] in observatories:
                # For a normal observatory, convert to Time in UTC
                # with location specified as observatory,
                # and then convert to TDB
                utcs = time.Time([t.isot for t in grp['mjd']],
                                 format='isot',
                                 scale='utc',
                                 precision=9,
                                 location=observatories[obs].loc)
                utcs.delta_ut1_utc = utcs.get_delta_ut1_utc(iers_a)
                # Also save delta_ut1_utc for these TOAs for later use
                for toa, dut1 in zip(grp['mjd'], utcs.delta_ut1_utc):
                    toa.delta_ut1_utc = dut1
                # The actual conversion from UTC to TDB is done by astropy.Time
                # as described here <http://docs.astropy.org/en/stable/time/>,
                # with the real work done by the IAU SOFA library
                tdbs = utcs.tdb
            else:
                log.error("Unknown observatory ({0})".format(key['obs']))

            col_tdb[loind:hiind] = numpy.asarray([t for t in tdbs])
            col_tdbld[loind:hiind] = numpy.asarray(
                [utils.time_to_longdouble(t) for t in tdbs])
        # Now add the new columns to the table
        col_tdb = table.Column(name='tdb', data=col_tdb)
        col_tdbld = table.Column(name='tdbld', data=col_tdbld)
        self.table.add_columns([col_tdb, col_tdbld])
Exemple #14
0
#!/usr/bin/env python
"Download the IERS_A data file so it will be cached."
from __future__ import print_function, division

import sys

from astropy.utils.iers import IERS_A, IERS_A_URL
from astropy.utils.data import download_file

from astropy import log

# Different code required for Python 2, since it has no HTTPError
# Remove this once Python 2 support is ended
if sys.version_info.major < 3:
    try:
        iers_a = IERS_A.open(IERS_A_URL)
        URL = IERS_A_URL
    except:
        URL = "NO_IERS_A_URL_FOUND"
    try:
        download_file(URL, cache=True)
    except:
        log.error("IERS A file download failed. This may cause problems.")
else:
    from urllib.error import HTTPError, URLError
    from http.client import RemoteDisconnected

    try:
        iers_a = IERS_A.open(IERS_A_URL)
        URL = IERS_A_URL
    except (HTTPError, URLError, RemoteDisconnected):
Exemple #15
0
def test_iers_a_now():
    iers_a = IERS_A.open(IERS_A_URL)
    t2 = astropy.time.Time.now()
    t2.delta_ut1_utc = t2.get_delta_ut1_utc(iers_a)
    print(t2.tdb.iso)
from sgp4.io import twoline2rv
from astropy.time import Time
from astropy import units as u
from astropy import coordinates as coord
from datetime import datetime, timedelta
import time
import numpy as np
from calendar import timegm
#import matplotlib.pyplot as plt
from scipy import mat, cos, sin, arctan, sqrt, pi, arctan2
from math import pow, degrees, radians, sqrt
from ROOT import TFile, TTree
from array import array

from astropy.utils.iers import IERS_A
iers_a = IERS_A.open('finals2000A.all')

import rotations as rot


def computation(name, start_year, start_month, start_day, start_hour,
                start_minute, start_second, end_year, end_month, end_day,
                end_hour, end_minute, end_second):

    # set initial and final times
    aepoch = time.strptime('2004 1 1 0 0 0', '%Y %m %d %H %M %S')
    tepoch = timegm(aepoch)

    dini = datetime(start_year, start_month, start_day, start_hour,
                    start_minute, start_second)  # start date for the analysis
    dfin = datetime(end_year, end_month, end_day, end_hour, end_minute,
Exemple #17
0
TEL_LONGITUDE = 74 * u.deg + 02 * u.arcmin + 59.07 * u.arcsec
TEL_LATITUDE = 19 * u.deg + 05 * u.arcmin + 47.46 * u.arcsec

NPOD = 30  # Number of baselines (only used as sanity check)

ANTENNA_FILE = '/home/mhvk/packages/scintellometry/scintellometry/phasing/' \
               'antsys.hdr'
OUR_ANTENNA_ORDER = 'CWES'  # and by number inside each group
NON_EXISTING_ANTENNAS = ('C07', 'S05')  # to remove from antenna file

USE_UT1 = False
if USE_UT1:
    IERS_A_FILE = '/home/mhvk/packages/astropy/finals2000A.all'
    from astropy.utils.iers import IERS_A
    iers_a = IERS_A.open(IERS_A_FILE)

IST_UTC = TimeDelta(0., 5.5 / 24., format='jd')


def timestamp_to_Time(line):
    """Convert a timestamp item to a astropy Time instance.
    Store telescope lon, lat as well for full precision in possible
    TDB conversion (not used so far)
    """
    tl = line.split()
    seconds = float(tl[5]) + float(tl[6])
    return Time(tl[0] + '-' + tl[1] + '-' + tl[2] + ' ' + tl[3] + ':' + tl[4] +
                ':{}'.format(seconds),
                scale='utc',
                lat=TEL_LATITUDE,
    def _pvobs(self):
        '''calculates position and velocity of the observatory
           returns position/velocity in AU and AU/d in GCRS reference frame
        '''

        # convert obs position from WGS84 (lat long) to ITRF geocentric coords in AU
        xyz = self.location.to(u.AU).value

        # now we need to convert this position to Celestial Coords
        # specifically, the GCRS coords.
        # conversion from celestial to terrestrial coords given by
        # [TRS] = RPOM * R_3(ERA) * RC2I * [CRS]
        # where:
        # [CRS] is vector in GCRS (geocentric celestial system)
        # [TRS] is vector in ITRS (International Terrestrial Ref System)
        # ERA is earth rotation angle
        # RPOM = polar motion matrix

        tt = self.tt
        mjd = self.utc.mjd

        # we need the IERS values to correct for the precession/nutation of the Earth
        iers_tab = IERS.open()

        # Find UT1, which is needed to calculate ERA
        # uses IERS_B by default , for more recent times use IERS_A download
        try:      
            ut1 = self.ut1 
        except:
            try:
                iers_a_file = download_file(IERS_A_URL, cache=True)
                iers_a = IERS_A.open(iers_a_file)
                print "Trying to download...", iers_a_file
                self.delta_ut1_utc = self.get_delta_ut1_utc(iers_a)
                ut1 = self.ut1
            except:
                # fall back to UTC with degraded accuracy
                warnings.warn('Cannot calculate UT1: using UTC with degraded accuracy') 
                ut1 = self.utc
                
        # Gets x,y coords of Celestial Intermediate Pole (CIP) and CIO locator s
        # CIO = Celestial Intermediate Origin
        # Both in GCRS
        X,Y,S = erfa.xys00a(tt.jd1,tt.jd2)

        # Get dX and dY from IERS B
        dX = np.interp(mjd, iers_tab['MJD'], iers_tab['dX_2000A']) * u.arcsec 
        dY = np.interp(mjd, iers_tab['MJD'], iers_tab['dY_2000A']) * u.arcsec

        # Get GCRS to CIRS matrix
        # can be used to convert to Celestial Intermediate Ref Sys
        # from GCRS.
        rc2i = erfa.c2ixys(X+dX.to(u.rad).value, Y+dY.to(u.rad).value, S)

        # Gets the Terrestrial Intermediate Origin (TIO) locator s'
        # Terrestrial Intermediate Ref Sys (TIRS) defined by TIO and CIP.
        # TIRS related to to CIRS by Earth Rotation Angle
        sp = erfa.sp00(tt.jd1,tt.jd2)

        # Get X and Y from IERS B
        # X and Y are
        xp = np.interp(mjd, iers_tab['MJD'], iers_tab['PM_x']) * u.arcsec
        yp = np.interp(mjd, iers_tab['MJD'], iers_tab['PM_y']) * u.arcsec 

        # Get the polar motion matrix. Relates ITRF to TIRS.
        rpm = erfa.pom00(xp.to(u.rad).value, yp.to(u.rad).value, sp)

        # multiply ITRF position of obs by transpose of polar motion matrix
        # Gives Intermediate Ref Frame position of obs
        x,y,z = np.array([rpmMat.T.dot(xyz) for rpmMat in rpm]).T

        # Functions of Earth Rotation Angle, theta
        # Theta is angle bewtween TIO and CIO (along CIP)
        # USE UT1 here.
        theta = erfa.era00(ut1.jd1,ut1.jd2)
        S,C = np.sin(theta),np.cos(theta)

        # Position #GOT HERE
        pos = np.asarray([C*x - S*y, S*x + C*y, z]).T

        # multiply by inverse of GCRS to CIRS matrix
        # different methods for scalar times vs arrays
        if pos.ndim > 1:
            pos = np.array([np.dot(rc2i[j].T,pos[j]) for j in range(len(pos))])
        else:   
            pos = np.dot(rc2i.T,pos)

        # Velocity
        vel = np.asarray([SR*(-S*x - C*y), SR*(C*x-S*y), np.zeros_like(x)]).T
        # multiply by inverse of GCRS to CIRS matrix
        if vel.ndim > 1:
            vel = np.array([np.dot(rc2i[j].T,vel[j]) for j in range(len(pos))])
        else:        
            vel = np.dot(rc2i.T,vel)

        #return position and velocity
        return pos,vel
def test_iers_a_now():
    iers_a = IERS_A.open(IERS_A_URL)
    t2 = astropy.time.Time.now()
    t2.delta_ut1_utc = t2.get_delta_ut1_utc(iers_a)
    print(t2.tdb.iso)