Ejemplo n.º 1
0
    def _settimes_fromgps(self):
        """
        _settimes_fromgps(self)
        if the observation number (starttime) is set, determine the rest of the times (MJD, UTC)
        also figure out LST, Sun altitude
        """

        if (self.observation_number is None):
            logger.error('Cannot set times without an observation_number')
        else:
            self.mwatime = ephem_utils.MWATime(gpstime=self.observation_number)
            self.MJD = int(self.mwatime.MJD)
            self.UT = self.mwatime.UT
            self.year = self.mwatime.year
            self.month = self.mwatime.month
            self.day = self.mwatime.day
            self.hour = self.mwatime.hour
            self.minute = self.mwatime.minute
            self.second = self.mwatime.second
            self.LST = float(self.mwatime.LST)
            self.epoch = self.mwatime.epoch

            mwa = ephem_utils.Obs[ephem_utils.obscode['MWA']]
            observer = ephem.Observer()
            # make sure no refraction is included
            observer.pressure = 0
            observer.long = mwa.long / ephem_utils.DEG_IN_RADIAN
            observer.lat = mwa.lat / ephem_utils.DEG_IN_RADIAN
            observer.elevation = mwa.elev
            observer.date = '%d/%d/%d %s' % (self.year, self.month, self.day,
                                             self.mwatime.strftime("%H:%M:%S"))

            body = ephem.__dict__['Sun']()
            body.compute(observer)
            self.sun_elevation = body.alt * ephem_utils.DEG_IN_RADIAN
Ejemplo n.º 2
0
def find_observation_num(filename, maxdiff=10, suffix='_das1.LACSPC', db=db):
    """
    observation_num=find_observation_num(filename, maxdiff=10, suffix='_das1.LACSPC', db=db)
    finds a scheduled MWA_Setting object at the time nearest the UT date/time
    in filename (YYYYMMDDhhmmss)
    that has a valid stoptime
    will search up to +/-maxdiff seconds
    """

    observation_num = return_observation_num(filename, suffix=suffix, db=db)
    if (observation_num is not None):
        # we found it exactly in the database
        logger.info(
            'Found a match to %s%s in the data_files database at time=%d\n' %
            (filename, suffix, observation_num))
        return observation_num

    # otherwise, try to parse
    d = filename.split('_')
    datetimestring = None
    for x in d:
        if (len(x) == 14):
            datetimestring = x
            try:
                yr = int(datetimestring[0:4])
                mn = int(datetimestring[4:6])
                dy = int(datetimestring[6:8])
                h = int(datetimestring[8:10])
                m = int(datetimestring[10:12])
                s = int(datetimestring[12:14])
                continue
            except:
                pass
    try:
        mwatime = ephem_utils.MWATime(year=yr,
                                      month=mn,
                                      day=dy,
                                      hour=h,
                                      minute=m,
                                      second=s)
        oid = mwatime.gpstime
    except:
        logger.warning('Cannot determine GPS time for file=%s\n' % (filename))
        return None
    oid = find_closest_observation(int(oid), maxdiff=maxdiff, db=db)
    return oid
Ejemplo n.º 3
0
import astropy.io.fits as pyfits

# open up database connection
try:
    db = schedule.getdb()
except:
    print "Unable to open connection to database"
    sys.exit(1)

RA, Dec = 69.3158945833333, -47.2523944444444
gpstime = 1063400456
filename = '1063400456_corr_phased.fits'

o = get_observation_info.MWA_Observation(gpstime, db=db)

mwatime = ephem_utils.MWATime(gpstime=gpstime + o.duration / 2)
frequency = o.center_channel * 1.28e6
delays = o.delays

RAnow, Decnow = ephem_utils.precess(RA, Dec, 2000, mwatime.epoch)
HA = float(mwatime.LST) - RAnow
mwa = ephem_utils.Obs[ephem_utils.obscode['MWA']]
Az, Alt = ephem_utils.eq2horz(HA, Decnow, mwa.lat)
theta = (90 - Alt) * math.pi / 180
phi = Az * math.pi / 180


def MWA_Jones_Analytic(theta,
                       phi,
                       ha,
                       dec,
Ejemplo n.º 4
0
def main():

    usage = "Usage: %prog [options] <file1> <file2>\n"
    usage += '\tConverts between GPS seconds, UT time, MJD\n\n'
    usage += """\tExample:
    \tplock[~/mwa]% bin/timeconvert.py --year=2012 --month=9 --day=30
    \tEntered 2012-09-30 00:00:00...
    \t2012-09-30 00:00:00 UTC
    \t20120930000000
    \tGPS 1032998416
    \tMJD 56200.00000
    \tJD 2456200.50000
    """

    parser = OptionParser(usage=usage)
    parser.add_option('--gps', dest='gps', default=None, help='GPS seconds')
    parser.add_option('--datetime',
                      dest='datetime',
                      default=None,
                      help='Datetime string YYYYMMDDhhmmss (UTC)')
    parser.add_option('--mjd', dest='mjd', default=None, help='MJD')
    parser.add_option('--year', dest='year', default=None, help='Year')
    parser.add_option('--month', dest='month', default=None, help='Month')
    parser.add_option('--day', dest='day', default=None, help='Day')
    parser.add_option('--hour', dest='hour', default=None, help='Hour')
    parser.add_option('--minute', dest='minute', default=None, help='Minute')
    parser.add_option('--second', dest='second', default=None, help='Second')

    (options, args) = parser.parse_args()
    t = None
    if options.gps is not None:
        try:
            t = ephem_utils.MWATime(gpstime=float(options.gps))
            print "Entered GPStime=%s..." % options.gps
        except:
            logger.error('Error converting gps time %s\n\t%s' %
                         (options.gps, sys.exc_info()[1]))
            sys.exit(0)
    elif options.datetime is not None:
        try:
            t = ephem_utils.MWATime()
            t.datetimestring = options.datetime
            print "Entered datetime string=%s..." % options.datetime
        except:
            logger.error('Error converting datetime string %s\n\t%s' %
                         (options.datetime, sys.exc_info()[1]))
            sys.exit(0)
    elif options.mjd is not None:
        try:
            t = ephem_utils.MWATime()
            t.MJD = float(options.mjd)
            print "Entered MJD=%s..." % options.mjd
        except:
            logger.error('Error converting MJD %s\n\t%s' %
                         (options.mjd, sys.exc_info()[1]))
            sys.exit(0)
    elif options.year is not None and options.month is not None and options.day is not None:
        if options.hour is None:
            options.hour = 0
        if options.minute is None:
            options.minute = 0
        if options.second is None:
            options.second = 0
        try:
            t = ephem_utils.MWATime(year=int(options.year),
                                    month=int(options.month),
                                    day=int(options.day),
                                    hour=int(options.hour),
                                    minute=int(options.minute),
                                    second=int(options.second))
            print "Entered %s..." % t.strftime('%Y-%m-%d %H:%M:%S')
        except:
            logger.error('Error converting time\n\t%s' % (sys.exc_info()[1]))
            sys.exit(0)
    if t is not None:
        print t.strftime('%Y-%m-%d %H:%M:%S %Z')
        print t.strftime('%Y%m%d%H%M%S')
        print 'GPS %d' % t.gpstime
        print 'MJD %.5f' % (t.MJD)
        print 'JD %.5f' % (t.MJD + 2400000.5)
        print '%s LST' % (t.LST.strftime('%H:%M:%S'))
    sys.exit(0)
Ejemplo n.º 5
0
def main():

    try:
        x = tpipe.miriad
    except AttributeError:
        logging.error('tpipe.miriad is not available')
        sys.exit(0)

    usage = "Usage: %prog [options]\n"
    parser = OptionParser(usage=usage)
    parser.add_option('-f',
                      '--filename',
                      dest="filename",
                      default=None,
                      help="Miriad filename")
    parser.add_option('-o',
                      '--output',
                      dest="output",
                      default=None,
                      help="Output filename")
    parser.add_option('--channels',
                      dest="channels",
                      default=768,
                      type='int',
                      help="Number of channels")
    parser.add_option('-i',
                      '--integrations',
                      dest="integrations",
                      default=0,
                      type='int',
                      help="Number of integrations to process")
    parser.add_option('-s',
                      '--skip',
                      dest="skip",
                      default=0,
                      type='int',
                      help="Number of integrations to skip")
    parser.add_option('--tle',
                      '--satellite',
                      dest="tlefile",
                      default=None,
                      help="Satellite TLE file",
                      metavar="TLEFILE")
    parser.add_option('--dt',
                      dest="dt",
                      default=0,
                      type='float',
                      help="Number of integrations to shift in absolute WCS")
    parser.add_option('--ds',
                      dest="ds",
                      default=0,
                      type='float',
                      help="Distance in degrees to shift in absolute WCS")
    parser.add_option('--dra',
                      dest="dra",
                      default=0,
                      type='float',
                      help="RA distance in degrees to shift")
    parser.add_option('--ddec',
                      dest="ddec",
                      default=0,
                      type='float',
                      help="Dec distance in degrees to shift")
    parser.add_option(
        '--filter',
        action="store_true",
        dest="filter",
        default=False,
        help="Filter the phased-array beam according to the expected shape")
    parser.add_option(
        '--nofilter',
        action="store_false",
        dest="filter",
        default=False,
        help=
        "Do not filter the phased-array beam according to the expected shape")
    parser.add_option('--width',
                      default=3.0,
                      type='float',
                      dest='width',
                      help="Width for filter (arcmin)")
    parser.add_option('--ra',
                      default=None,
                      type='float',
                      dest='ra',
                      help="Right Ascension (deg) for phasing")
    parser.add_option('--dec',
                      default=None,
                      type='float',
                      dest='dec',
                      help="Declination (deg) for phasing")
    parser.add_option('--maxbuf',
                      default=_maxnint,
                      type='int',
                      dest='maxbuf',
                      help="Maximum number of integrations to process at once")
    parser.add_option('--flip',
                      action="store_true",
                      dest="flip",
                      default=False)
    parser.add_option('--flag',
                      dest="flag",
                      default='',
                      type='str',
                      help='List of antennas to flag (1 origin)')
    parser.add_option('--imag',
                      action="store_true",
                      dest="imag",
                      default=False)

    (options, args) = parser.parse_args()

    nchan = options.channels
    nskip = options.skip
    nints = options.integrations
    outputfile = options.output

    if options.filename is None:
        logging.error('Must supply Miriad file')
        sys.exit(0)

    if not os.path.exists(options.filename):
        logging.error('Miriad file %s does not exist' % options.filename)
        sys.exit(1)

    satellite = None
    if options.tlefile is not None:
        if not os.path.exists(options.tlefile):
            logging.error('TLE file %s does not exist' % options.tlefile)
            sys.exit(1)
        f = open(options.tlefile)
        tlelines = f.readlines()
        satellite_label = tlelines[0].replace('_', '\_').replace('\n', '')
        satellite = ephem.readtle(tlelines[0], tlelines[1], tlelines[2])

    toflag = []
    if len(options.flag) > 0:
        toflag = [int(x) for x in options.flag.split(',')]
        print 'Will flag antennas %s' % toflag

    dataph = numpy.zeros((nints, nchan, 4))
    if options.imag:
        dataph_imag = numpy.zeros((nints, nchan, 4))
    MJD = numpy.zeros((nints))
    RA = numpy.zeros_like(MJD)
    Dec = numpy.zeros_like(MJD)
    Altitude = numpy.zeros_like(MJD)
    Angle = numpy.zeros_like(MJD)
    Speed = numpy.zeros_like(MJD)
    DL = numpy.zeros_like(MJD)
    DM = numpy.zeros_like(MJD)
    if nints <= options.maxbuf:
        try:
            pipe = mwa_pipe.pipe_mwa(options.filename,
                                     profile='mwa',
                                     chans=numpy.arange(nchan),
                                     nints=nints,
                                     dmarr=[0.],
                                     nskip=nskip,
                                     selectpol=['XX', 'YY', 'XY', 'YX'])
        except:
            logging.error('Error reading data')
            sys.exit(1)
        print 'Data read'
        if len(toflag) > 0:
            pipe.flag_antennas(numpy.array(toflag) - 1)

        #dataph=pipe.dataph.data
        dataph = (pipe.data.mean(axis=1)).real
        if options.imag:
            dataph_imag = (pipe.data.mean(axis=1)).imag
        MJD = pipe.time - 2400000.5

        if options.ra is not None:
            dl, dm = pipe.get_shift(options.ra, options.dec)
            pipe.phaseshift(dl, dm)
            dataph = (pipe.data.mean(axis=1)).real
            #dataph=pipe.dataph
            if options.imag:
                dataph_imag = (pipe.data.mean(axis=1)).imag

    else:
        nint_remaining = nints
        nstart = 0
        #if isinstance(dataph_out,numpy.ma.core.MaskedArray):
        #    dataph_imag=numpy.ma.zeros((nints,nchan))

        while nint_remaining > 0:
            ntoread = min(options.maxbuf, nint_remaining)
            print 'Reading %d integrations starting with %d' % (ntoread, nskip)
            pipe = mwa_pipe.pipe_mwa(options.filename,
                                     profile='mwa',
                                     chans=numpy.arange(nchan),
                                     nints=ntoread,
                                     dmarr=[0.],
                                     nskip=nskip,
                                     selectpol=['XX', 'YY', 'XY', 'YX'])
            if len(toflag) > 0:
                pipe.flag_antennas(numpy.array(toflag) - 1)

            #dataph_out=pipe.dataph
            dataph_out = (pipe.data.mean(axis=1)).real
            if options.imag:
                dataph_out_imag = (pipe.data.mean(axis=1)).imag

            if options.ra is not None:
                dl, dm = pipe.get_shift(options.ra, options.dec)
                pipe.phaseshift(dl, dm)
                #dataph_out=pipe.dataph
                dataph_out = (pipe.data.mean(axis=1)).real
                if options.imag:
                    dataph_out_imag = (pipe.data.mean(axis=1)).imag

            dataph[nstart:nstart +
                   min(options.maxbuf, nint_remaining)] = dataph_out
            if options.imag:
                dataph_imag[nstart:nstart + min(options.maxbuf, nint_remaining
                                                )] = dataph_out_imag

            MJD[nstart:nstart +
                min(options.maxbuf, nint_remaining)] = pipe.time - 2400000.5
            try:
                RA[nstart:nstart + min(options.maxbuf, nint_remaining)] = ra
                Dec[nstart:nstart + min(options.maxbuf, nint_remaining)] = dec
                Altitude[nstart:nstart +
                         min(options.maxbuf, nint_remaining)] = alt
                Speed[nstart:nstart +
                      min(options.maxbuf, nint_remaining)] = speed
                Angle[nstart:nstart +
                      min(options.maxbuf, nint_remaining)] = angle
                DL[nstart:nstart + min(options.maxbuf, nint_remaining)] = dl
                DM[nstart:nstart + min(options.maxbuf, nint_remaining)] = dm
            except:
                pass

            nint_remaining -= ntoread
            nskip += ntoread
            nstart += ntoread

    tint = numpy.round((MJD[1] - MJD[0]) * 86400, 1)

    wcs = pywcs.WCS(naxis=3)
    # see Greisen & Calabretta 2002, 395, 1061
    # Table 7
    # I=1
    # XX=-5
    # YY=-6
    # XY=-7
    # YX=-8

    wcs.wcs.ctype = ['FREQ-LSR', 'UTC', 'STOKES']
    wcs.wcs.cunit = ['MHz', 's', '']
    wcs.wcs.crval = [numpy.round(pipe.freq[0] * 1e3, 2), 0.0, -5]
    wcs.wcs.crpix = [1.0, 0.5, 1]
    wcs.wcs.cdelt = [
        numpy.round((pipe.freq[1] - pipe.freq[0]) * 1e3, 2), tint, 1
    ]
    f = pyfits.PrimaryHDU(header=wcs.to_header())
    f.header['TIMESYS'] = 'UTC'
    t = ephem_utils.MWATime()
    t.MJD = MJD[0]
    f.header['DATEREF'] = t.datetime.strftime('%Y-%m-%dT%H:%M:%S')
    if isinstance(dataph, numpy.ma.core.MaskedArray):
        dataph.data[dataph.mask] = 0
        f.data = dataph.data
    else:
        f.data = dataph
    if os.path.exists(outputfile):
        os.remove(outputfile)
    f.header['FILENAME'] = (options.filename, 'Input miriad file')
    f.header['NSKIP'] = (options.skip,
                         'Number of integrations that were skipped')
    f.header['NINT'] = (nints, 'Number of integrations that were processed')
    f.header['INTTIME'] = (tint, '[s] Integration time')
    f.header['CHANNEL'] = (int(
        ((pipe.freq[1] - pipe.freq[0]) * 1e6)), '[kHz] Channel width')
    if len(toflag) > 0:
        f.header['FLAGGED'] = (','.join([str(x)
                                         for x in toflag]), 'Flagged antennas')
    else:
        f.header['FLAGGED'] = ('NONE', 'Flagged antennas')
    if satellite is not None:
        f.header['DT'] = (options.dt, '[s] Time offset for absolute WCS')
        f.header['DS'] = (options.ds,
                          '[deg] Perpendicular offset for absolute WCS')
        f.header['DRA'] = (options.dra, '[deg] RA offset')
        f.header['DDEC'] = (options.ddec, '[deg] Dec offset')
        f.header['TLEFILE'] = (options.tlefile, 'Satellite TLE filename')
        if options.filter:
            f.header['FILTER'] = (pyfits.TRUE, 'Filtered phased-array data?')
        else:
            f.header['FILTER'] = (pyfits.FALSE, 'Filtered phased-array data?')
        c1 = pyfits.Column(name='MJD', format='D', unit='day', array=MJD)
        c2 = pyfits.Column(name='RA', format='E', unit='deg', array=RA)
        c3 = pyfits.Column(name='Dec', format='E', unit='deg', array=Dec)
        c4 = pyfits.Column(name='Altitude',
                           format='E',
                           unit='deg',
                           array=Altitude)
        c5 = pyfits.Column(name='Speed',
                           format='E',
                           unit='deg/int',
                           array=Speed)
        c6 = pyfits.Column(name='Angle', format='E', unit='deg', array=Angle)
        c7 = pyfits.Column(name='DL', format='E', unit='deg', array=DL)
        c8 = pyfits.Column(name='DM', format='E', unit='deg', array=DM)
        coldefs = pyfits.ColDefs([c1, c2, c3, c4, c5, c6, c7, c8])
        tbhdu = pyfits.new_table(coldefs)
        ftemp = f
        f = pyfits.HDUList([ftemp, tbhdu])
    if options.ra is not None:
        f.header['RAPHASE'] = (options.ra, '[deg] RA of phase center')
        f.header['DECPHASE'] = (options.dec, '[deg] Dec of phase center')

    if options.imag:
        z = numpy.zeros(dataph_imag.shape)
        if isinstance(dataph_imag, numpy.ma.core.MaskedArray):
            dataph_imag.data[dataph_imag.mask] = 0
            z = dataph_imag.data
        else:
            z = dataph_imag
        if isinstance(f, pyfits.hdu.hdulist.HDUList):
            f.append(pyfits.ImageHDU(data=z))
        else:
            ftemp = f
            f = pyfits.HDUList([ftemp, pyfits.ImageHDU(data=dataph_imag.data)])
            #f.data=dataph_imag.data

    f.writeto(outputfile)

    sys.exit(0)
Ejemplo n.º 6
0
def getpath(satellite, MJD, dt=0, ds=0.0):
    """
    ra,dec,alt,speed,angle=getpath(satellite, MJD, dt=0, ds=0)
    all are returned as degrees
    dt (sec) adjusts the position forward/backward along the path
    ds (deg) adjusts the position perpendicular to the track
    """
    observer = ephem.Observer()
    # make sure no refraction is included
    observer.pressure = 0
    mwa = ephem_utils.Obs[ephem_utils.obscode['MWA']]
    observer.long = mwa.long / ephem_utils.DEG_IN_RADIAN
    observer.lat = mwa.lat / ephem_utils.DEG_IN_RADIAN
    observer.elevation = mwa.elev
    ra = []
    dec = []
    alt = []
    speed = []
    angle = []
    t = ephem_utils.MWATime()
    for mjd in MJD:
        t.MJD = mjd
        tuse = t.datetime + datetime.timedelta(seconds=dt)
        #print tuse
        observer.date = tuse
        #print float(observer.date),observer.date,observer.date.tuple()
        # make it deal with fractional seconds
        observer.date = float(
            observer.date) + tuse.microsecond / 1.0e6 * ephem.second
        date0 = float(observer.date)
        satellite.compute(observer)
        ra.append(satellite.ra)
        dec.append(satellite.dec)
        alt.append(satellite.alt)
        #print '%.7f %s %f %f' % (observer.date,observer.date,numpy.degrees(satellite.ra),numpy.degrees(satellite.dec))
        #print ''
        observer.date = date0 - 0.5 * ephem.second
        satellite.compute(observer)
        ra1 = satellite.ra
        dec1 = satellite.dec
        observer.date = date0 + 0.5 * ephem.second
        satellite.compute(observer)
        ra2 = satellite.ra
        dec2 = satellite.dec
        ddec = dec2 - dec1
        dra = ra2 - ra1
        dracosdec = dra * numpy.cos(dec[-1])
        speed.append(numpy.sqrt(dracosdec**2 + ddec**2))
        angle.append(numpy.arctan2(ddec, dracosdec))

    ra = numpy.degrees(numpy.array(ra))
    dec = numpy.degrees(numpy.array(dec))
    alt = numpy.degrees(numpy.array(alt))
    speed = numpy.degrees(numpy.array(speed))
    angle = numpy.degrees(numpy.array(angle))
    dx = ds * numpy.sin(numpy.radians(angle))
    dy = -ds * numpy.cos(numpy.radians(angle))
    ra += dx / numpy.cos(numpy.radians(dec))
    dec += dy

    return ra, dec, alt, speed, angle
Ejemplo n.º 7
0
    nint_remaining -= ntoread
    nskip += ntoread
    nstart += ntoread

tint = numpy.round((MJD[1] - MJD[0]) * 86400, 1)

wcs = pywcs.WCS(naxis=2)
wcs.wcs.ctype = ['FREQ-LSR', 'UTC']
wcs.wcs.cunit = ['MHz', 's']
wcs.wcs.crval = [numpy.round(pipe.freq[0] * 1e3, 2), 0.0]
wcs.wcs.crpix = [1.0, 0.5]
wcs.wcs.cdelt = [numpy.round((pipe.freq[1] - pipe.freq[0]) * 1e3, 2), tint]
f = pyfits.PrimaryHDU(header=wcs.to_header())

f.header['TIMESYS'] = 'UTC'
t = ephem_utils.MWATime()
t.MJD = MJD[0]
f.header['DATEREF'] = t.datetime.strftime('%Y-%m-%dT%H:%M:%S')
f.header['FILENAME'] = (filename, 'Input file')
f.header['NSKIP'] = (0, 'Number of integrations that were skipped')
f.header['NINT'] = (nints, 'Number of integrations that were processed')
f.header['INTTIME'] = (tint, '[s] Integration time')
f.header['CHANNEL'] = (int(
    ((pipe.freq[1] - pipe.freq[0]) * 1e6)), '[kHz] Channel width')
if ra is not None:
    f.header['RAPHASE'] = (ra, '[deg] RA of new phase center')
    f.header['DECPHASE'] = (dec, '[deg] DEC of new phase center')

XX.data[XX.mask] = 0
YY.data[YY.mask] = 0
XY.data[XY.mask] = 0
Ejemplo n.º 8
0
                self._Schedule_Metadata = schedule.Schedule_Metadata(
                    self.observation_number, db=self.db)
                self.calibration = self._Schedule_Metadata.calibration
                self.calibrators = self._Schedule_Metadata.calibrators
            except (psycopg2.InternalError, psycopg2.ProgrammingError), e:
                logger.warning('Database error=%s' % (e.pgerror))
                db.rollback()

            mwa = ephem_utils.Obs[ephem_utils.obscode['MWA']]

            if (self._RFstream.ra is not None):
                logger.info('Found (RA,Dec) in RFstream (%.5f,%.5f)\n' %
                            (self._RFstream.ra, self._RFstream.dec))
                self.RA = self._RFstream.ra
                self.Dec = self._RFstream.dec
                mwatime = ephem_utils.MWATime(gpstime=self.observation_number)

                self.azimuth, self.elevation = ephem_utils.radec2azel(
                    self.RA, self.Dec, self.observation_number)
                self.HA = ephem_utils.HA(self.LST, self.RA, self.Dec,
                                         self.epoch) / 15.0

            elif (self._RFstream.azimuth is not None):
                logger.info('Found (Az,El) in RFstream (%.5f,%.5f)\n' %
                            (self._RFstream.azimuth, self._RFstream.elevation))
                self.azimuth = self._RFstream.azimuth
                self.elevation = self._RFstream.elevation
                self.RA, self.Dec = ephem_utils.azel2radec(
                    self.azimuth, self.elevation, self.observation_number)
                self.HA = ephem_utils.HA(self.LST, self.RA, self.Dec,
                                         self.epoch) / 15.0
Ejemplo n.º 9
0
def main():

    observation_num=None

    usage="Usage: %prog [options]\n"
    usage+='\tMakes metadata files necessary for corr2uvfits\n'
    usage+='\t128T sampling windows:\n'
    for i in xrange(len(make_metafiles._START)):
        t1=ephem_utils.MWATime(gpstime=make_metafiles._START[i])
        if i<len(make_metafiles._START)-1:
            t2=ephem_utils.MWATime(gpstime=make_metafiles._START[i+1]-1)
        else:
            t2=ephem_utils.MWATime(gpstime=9046304456)
        usage+='\t%s (%10d) - %s (%10d): %.1f s, %d kHz\n' % (t1.datetime.strftime('%y-%m-%dT%H:%M:%S'),
                                                          t1.gpstime,
                                                          t2.datetime.strftime('%y-%m-%dT%H:%M:%S'),
                                                          t2.gpstime,
                                                          make_metafiles._DT[i],
                                                          make_metafiles._DF[i])
    parser = OptionParser(usage=usage)
    parser.add_option('-f','--filename',dest="filename",
                      help="Create metafiles for <FILE>",metavar="FILE")
    parser.add_option('-d','--datetime',dest="datetimestring",
                      help="Create metafiles for <DATETIME> (YYYYMMDDhhmmss)",
                      metavar="DATETIME")
    parser.add_option('-g','--gps',dest="gpstime",
                      help="Create metafiles for <GPS>",type='int',
                      metavar="GPS")
    parser.add_option('--contiguous',dest="contiguous",
                      action="store_true",default=False,
                      help="Output separate files for contiguous channels only")    
    parser.add_option('--minbaddipoles',dest='min_bad_dipoles',default=2,type='int',
                      help='Minimum number of bad dipoles in a single pol required to flag the entire tile [default=%default]')
    parser.add_option('-m','--maxdiff',dest="maxtimediff",type='int',
                      help="Maximum time difference for search (in sec)", default=10)
    parser.add_option('--channels',dest="channels",default=24,type=int,
                      help="Number of coarse channels [default=%default]")
    parser.add_option('--channel',dest="channel",default=None,type=int,
                      help="Coarse channel (implies channels=1) [default=%default]")
    parser.add_option('--dt',dest="dt",default=0,type=float,
                      help="[sec] Integration time [default=%default, select by gpstime]")
    parser.add_option('--df',dest="df",default=0,type=int,
                      help="[kHz] Fine channel width  [default=%default, select by gpstime]")
    parser.add_option('--timeoffset',dest="timeoffset",default=0,type=int,
                      help="[sec] Time offset between filename and start of data [default=%default]")
    parser.add_option('--header',dest='header',default='header_%gpstime%_%channel%.txt',
                      help="Name of header output file [default=%default]")
    parser.add_option('--antenna',dest='antenna',default='antenna_locations_%gpstime%_%channel%.txt',
                      help="Name of antenna_locations output file [default=%default]")
    parser.add_option('--instr',dest='instr',default='instr_config_%gpstime%_%channel%.txt',
                      help="Name of instr_config output file [default=%default]")
    parser.add_option('--rts',dest='rts',default=False,action="store_true",
                      help="Write RTS files (array file and rts_in)?")
    parser.add_option('--array',dest='array',default='array_file.txt',
                      help="Name of RTS array file  output file [default=%default]")
    parser.add_option('-v','--verbose',action="store_true",dest="verbose",default=False,
                      help="Increase verbosity of output")
    parser.add_option('--debug',action="store_true",dest="debug",default=False,
                      help="Display all database commands")
    parser.add_option('-l','--lock',dest='lock',action='store_true',default=False,
                          help='Use \"-l\" option to create header file for locked phase center (RTS input)')
    

    (options, args) = parser.parse_args()

    if (options.verbose):
        logger.setLevel(logging.INFO)

    logger.info('Connecting to database %s@%s' % (mwaconfig.mandc.dbuser,mwaconfig.mandc.dbhost))

    if options.filename is not None:
        observation_num=get_observation_info.find_observation_num(options.filename,
                                                                  maxdiff=options.maxtimediff, db=db)
        if observation_num is None:
            logger.error('No matching observation found for filename=%s\n' % (options.filename))
            sys.exit(1)
    elif options.datetimestring is not None:
        observation_num=get_observation_info.find_observation_num(options.datetimestring,
                                                                  maxdiff=options.maxtimediff, db=db)
        if observation_num is None:
            logger.error('No matching observation found for datetimestring=%s\n' % (options.datetimestring))
            sys.exit(1)

    elif options.gpstime is not None:
        observation_num=get_observation_info.find_closest_observation((options.gpstime),
                                                                      maxdiff=options.maxtimediff,db=db)
        if observation_num is None:
            logger.error('No matching observation found for gpstime=%d\n' % (options.gpstime))
            sys.exit(1)

    else:
        logger.error('Must specify one of filename, datetime, or gpstime')
        sys.exit(1)


    if options.channel is not None:
        options.channels=1
    if observation_num is not None:
        obs=get_observation_info.MWA_Observation(observation_number=observation_num, db=db)        
        # do this first so that the instrument_configuration can know the duration
        h=make_metafiles.Corr2UVFITSHeader(observation_num, coarse_channels=options.channels,
                                           coarse_channel=options.channel,
                                           timeoffset=options.timeoffset,
                                           inttime=options.dt,
                                           fine_channel=options.df,
                                           lock=options.lock,
                                           db=db)
        vars={'gpstime': observation_num,
              'channel': make_metafiles.ternary(options.channel is None,'all',options.channel)}

        if '%' in options.header:
            options.header=make_metafiles.update_filename(options.header,vars)
        if '%' in options.instr:
            options.instr=make_metafiles.update_filename(options.instr,vars)
        if '%' in options.antenna:
            options.antenna=make_metafiles.update_filename(options.antenna,vars)
            
        T=make_metafiles.instrument_configuration(gpstime=observation_num, duration=h.obs.duration, db=db,
                                                  min_bad_dipoles=options.min_bad_dipoles,
                                                  debug=options.debug)
        result=T.make_instr_config()
        if result is None:
            logger.error('Error making instr_config file')
            sys.exit(1)
        try:
            f=open(options.instr,'w')
        except:
            logger.error('Could not open instr_config file %s for writing' % options.instr)
            sys.exit(1)
            
        f.write(str(T))
        f.close()
        logger.info('Wrote instr_config file %s!' % (options.instr))

        try:
            f=open(options.antenna,'w')
        except:
            logger.error('Could not open antenna_locations file %s for writing' % options.antenna)
            sys.exit(1)
        f.write(T.antenna_locations())
        f.close()
        logger.info('Wrote antenna_locations file %s!' % (options.antenna))

        if options.rts:
            try:
                f=open(options.array,'w')
            except:
                logger.error('Could not open RTS array_file  file %s for writing' % options.array)
                sys.exit(1)
            f.write(T.array_file())
            f.close()
            logger.info('Wrote array file %s!' % (options.array))

            try:
                f=open("rts.in",'w')
            except:
                logger.error('Could not open RTS configuration file rts.in for writing' )
                sys.exit(1)
            try:
                f.write(T.rts_in(rtstime=datetime.strptime(options.datetimestring,"%Y%m%d%H%M%S")))
                f.close()
                logger.info('Wrote rts_in file !')
            except:
                logger.error('Unable to write rts_in file')


        if numpy.diff(obs.channels).max()>1 and options.contiguous:
            # the frequencies are not contiguous
            # determine the contiguous ranges
            df=numpy.diff(obs.channels)
            frequency_indices=numpy.where(df>1)[0]
            channel_selections=[]
            istart=0
            for istop in frequency_indices:
                channel_selections.append(numpy.arange(istart,istop+1))
                istart=istop+1
            channel_selections.append(numpy.arange(istart,len(obs.channels)))            
        else:
            channel_selections=[numpy.arange(len(obs.channels))]


        for i,channel_selection in zip(range(len(channel_selections)),channel_selections):
            header_name=options.header
            logger.info('Creating output for channels %s' % channel_selection)
            h.channel_selection=channel_selection

            h.make_header()
            if len(channel_selections)>1:
                header_name=header_name.replace('.txt','.%02d.txt' % i)
            try:
                f=open(header_name,'w')
            except:
                logger.error('Could not open header file %s for writing' % header_name)
                sys.exit(1)
            f.write(str(h))
            f.close()
            logger.info('Wrote header file %s!' % (header_name))
Ejemplo n.º 10
0
        frequencies=numpy.array([freq])

    # and make them back into arrays
    RA=ra.reshape(X.shape)
    Dec=dec.reshape(Y.shape)

    # get the date so we can convert to Az,El
    try:
        d=h['DATE-OBS']
    except:
        logger.error('Unable to read observation date DATE-OBS from %s' % filename)
        return None
    if '.' in d:
        d=d.split('.')[0]
    dt=datetime.datetime.strptime(d,'%Y-%m-%dT%H:%M:%S')
    mwatime=ephem_utils.MWATime(datetime=dt)
    logger.info('Computing for %s' % mwatime)


    if precess:
        RAnow,Decnow=ephem_utils.precess(RA,Dec,2000,mwatime.epoch)
    else:
        RAnow,Decnow=RA,Dec

    HA=float(mwatime.LST)-RAnow
    mwa=ephem_utils.Obs[ephem_utils.obscode['MWA']]
    Az,Alt=ephem_utils.eq2horz(HA,Decnow,mwa.lat)
    # go from altitude to zenith angle
    theta=(90-Alt)*math.pi/180
    phi=Az*math.pi/180