Ejemplo n.º 1
0
 def __init__(self, skymap_object, lat, lon, utc_jd):
     """
     Initialize the skymap at input lat,lon (decimal degrees) and time (in 
     UTC julian day).
     """
     
     self.skymap_object = skymap_object
     
     assert  -90 <= lat <=  90, ValueError('lat = %g not in [-90,90]' % lat)
     assert -360 <= lon <= 360, ValueError('lon = %g not in [-360,360]' % lon)
     self.lat  = lat
     self.lon  = lon
     self.time = utc_jd
     
     # Compute the ra and dec locations to a altitude and azimuth. This requires a lat/lon and a time (UTC).
     # Alt and Az are compressed to show only the visible source.
     ## Extract the RA/dec values
     ra = self.skymap_object.ra
     dec = self.skymap_object.dec
     
     ## Compute the LST at the lat/lon (hours)
     lst = astro.get_local_sidereal_time(self.lon, self.time)
     
     ## RA -> HA (deg)
     ha = lst*15.0 - ra
     
     ## HA, dec, and lat in degrees to alt and az in radians
     sinAlt = sin(dec*pi/180)*sin(self.lat*pi/180) + cos(dec*pi/180)*cos(lat*pi/180)*cos(ha*pi/180)
     sinAlt = clip(sinAlt, -1.0, 1.0)
     alt = arcsin(sinAlt)
     cosAz = (sin(dec*pi/180)-sinAlt*sin(self.lat*pi/180))/(cos(alt)*cos(lat*pi/180))
     cosAz = clip(cosAz, -1.0, 1.0)
     az = arccos(cosAz)
     swap = where(sin(ha*pi/180) > 0)
     az[swap] = 2*pi-az[swap]
     
     ## Convert to alt and az to degrees
     self.alt = alt*180/pi
     self.az  = az*180/pi
     
     # Compress the az/alt so that only the visible sources are available. "
     visibleMask = self.alt > 0.0
     
     #Compress arrays to hide non-visible sources
     self.visibleAlt = compress(visibleMask, self.alt)
     self.visibleAz = compress(visibleMask, self.az)
     self.visiblePower = compress(visibleMask, self.skymap_object._power)
     try:
         pixelSolidAngle = (2.0 * pi)**2/(self.skymap_object.numPixelsX*self.skymap_object.numPixelsY)
     except AttributeError:
         pixelSolidAngle = 2.5566346e-4
     fractionSolidAngle = (1.0/4.0*pi) * pixelSolidAngle
     
     # The cosine term is the projection of the receiving area onto the direction 
     # of the source
     normalizedPower = self.skymap_object.normalize_power() * fractionSolidAngle  
     self.visibleNormalizedPower = compress(visibleMask, normalizedPower)
     #self.visibleNormalizedPower = self.visiblePower*cos(self.visibleAlt * self.skymap_object.degToRad)
     self.visibleRa = compress(visibleMask, self.skymap_object.ra)
     self.visibleDec = compress(visibleMask, self.skymap_object.dec)
Ejemplo n.º 2
0
    def sidereal(self, time_):
        """
        Return the apparent sidereal time for this location.
        The 'time_' parameter should be set to a Time instance providing
        the time of interest.
        Returns sidereal time as a float in range [0.0, 24.0).
        """

        if not isinstance(time_, Time):
            raise TypeError("time_ must be type transform.Time")

        return astro.get_local_sidereal_time(self._posn.lng, time_.utc_jd)
Ejemplo n.º 3
0
def main(args):
    # Beam
    beamFilename = args.filename
    beamDict = numpy.load(beamFilename)
    beam = beamDict['beam']
    beam /= beam.max()
    
    # Station, polarization, frequency, and beam simulation resolution
    name = beamDict['station'].item()
    pol = beamDict['pol'].item()
    freq = beamDict['freq'].item()
    try:
        res = beamDict['res'].item()
    except KeyError:
        res = 1.0
    ires = 1.0 / (min([1.0, res]))
        
    # Get the site information
    if name == 'lwa1':
        sta = stations.lwa1
    elif name == 'lwasv':
        sta = stations.lwasv
    else:
        raise RuntimeError("Unknown site: %s" % name)
        
    # Read in the skymap (GSM or LF map @ 74 MHz)
    if not args.lfsm:
        smap = skymap.SkyMapGSM(freq_MHz=freq/1e6)
        if args.verbose:
            print("Read in GSM map at %.2f MHz of %s pixels; min=%f, max=%f" % (freq/1e6, len(smap.ra), smap._power.min(), smap._power.max()))
    else:
        smap = skymap.SkyMapLFSM(freq_MHz=freq/1e6)
        if args.verbose:
            print("Read in LFSM map at %.2f MHz of %s pixels; min=%f, max=%f" % (freq/1e6, len(smap.ra), smap._power.min(), smap._power.max()))
            
    def BeamPattern(az, alt, beam=beam, ires=ires):
        iAz = (numpy.round(az*ires)).astype(numpy.int32)
        iAlt = (numpy.round(alt*ires)).astype(numpy.int32) 
        
        return beam[iAz,iAlt]
        
    if args.do_plot:
        az = numpy.arange(0,360*ires+1,1) / float(ires)
        alt = numpy.arange(0,90*ires+1,1) / float(ires)
        alt, az = numpy.meshgrid(alt, az)
        pylab.figure(1)
        pylab.title("Beam Response: %s pol. @ %0.2f MHz" % (pol, freq/1e6))
        pylab.imshow(BeamPattern(az, alt), interpolation='nearest', extent=(0,359, 0,89), origin='lower')
        pylab.xlabel("Azimuth [deg]")
        pylab.ylabel("Altitude [deg]")
        pylab.grid(1)
        pylab.draw()
        
    # Calculate times in both site LST and UTC
    t0 = astro.get_julian_from_sys()
    lst = astro.get_local_sidereal_time(sta.long*180.0/math.pi, t0) / 24.0
    t0 -= lst*(23.933/24.0) # Compensate for shorter sidereal days
    times = numpy.arange(0.0, 1.0, args.time_step/1440.0) + t0
    
    lstList = []
    powListAnt = [] 
    
    for t in times:
        # Project skymap to site location and observation time
        pmap = skymap.ProjectedSkyMap(smap, sta.lat*180.0/math.pi, sta.long*180.0/math.pi, t)
        lst = astro.get_local_sidereal_time(sta.long*180.0/math.pi, t)
        lstList.append(lst)
        
        # Convolution of user antenna pattern with visible skymap
        gain = BeamPattern(pmap.visibleAz, pmap.visibleAlt)
        powerAnt = (pmap.visiblePower * gain).sum() / gain.sum()
        powListAnt.append(powerAnt)

        if args.verbose:
            lstH = int(lst)
            lstM = int((lst - lstH)*60.0)
            lstS = ((lst - lstH)*60.0 - lstM)*60.0
            sys.stdout.write("LST: %02i:%02i:%04.1f, Power_ant: %.1f K \r" % (lstH, lstM, lstS, powerAnt))
            sys.stdout.flush()
    sys.stdout.write("\n")
    
    # Plot results
    if args.do_plot:
        pylab.figure(2)
        pylab.title("Driftcurve: %s pol. @ %0.2f MHz - %s" % \
            (pol, freq/1e6, name.upper()))
        pylab.plot(lstList, powListAnt, "ro",label="Antenna Pattern")
        pylab.xlabel("LST [hours]")
        pylab.ylabel("Temp. [K]")
        pylab.grid(2)
        pylab.draw()
        pylab.show()
        
    outputFile = "driftcurve_%s_%s_%.2f.txt" % (name, pol, freq/1e6)
    print("Writing driftcurve to file '%s'" % outputFile)
    mf = open(outputFile, "w")
    for lst,pow in zip(lstList, powListAnt):
        mf.write("%f  %f\n" % (lst,pow))
    mf.close()
Ejemplo n.º 4
0
def main(args):
    # Parse command line
    config = parseOptions(args)
    
    # Get the site information
    if config['site'] == 'lwa1':
        sta = stations.lwa1
    elif config['site'] == 'lwasv':
        sta = stations.lwasv
    elif config['site'] == 'ovro':
        sta = stations.lwa1
        sta.lat, sta.lon, sta.elev = ('37.2397808', '-118.2816819', 1183.4839)
    else:
        raise RuntimeError("Unknown site: %s" % config['site'])
        
    # Read in the skymap (GSM or LF map @ 74 MHz)
    if config['GSM']:
        smap = skymap.SkyMapGSM(freqMHz=config['freq']/1e6)
        if config['verbose']:
            print "Read in GSM map at %.2f MHz of %s pixels; min=%f, max=%f" % (config['freq']/1e6, len(smap.ra), smap._power.min(), smap._power.max())
    else:
        smap = skymap.SkyMapLFSM(freqMHz=config['freq']/1e6)
        if config['verbose']:
            print "Read in LFSM map at %.2f MHz of %s pixels; min=%f, max=%f" % (config['freq']/1e6, len(smap.ra), smap._power.min(), smap._power.max())
    
    # Get the emperical model of the beam and compute it for the correct frequencies
    beamDict = numpy.load(os.path.join(dataPath, 'lwa1-dipole-emp.npz'))
    if config['pol'] == 'EW':
        beamCoeff = beamDict['fitX']
    else:
        beamCoeff = beamDict['fitY']
    try:
        beamDict.close()
    except AttributeError:
        pass
    alphaE = numpy.polyval(beamCoeff[0,0,:], config['freq'])
    betaE =  numpy.polyval(beamCoeff[0,1,:], config['freq'])
    gammaE = numpy.polyval(beamCoeff[0,2,:], config['freq'])
    deltaE = numpy.polyval(beamCoeff[0,3,:], config['freq'])
    alphaH = numpy.polyval(beamCoeff[1,0,:], config['freq'])
    betaH =  numpy.polyval(beamCoeff[1,1,:], config['freq'])
    gammaH = numpy.polyval(beamCoeff[1,2,:], config['freq'])
    deltaH = numpy.polyval(beamCoeff[1,3,:], config['freq'])
    if config['verbose']:
        print "Beam Coeffs. X: a=%.2f, b=%.2f, g=%.2f, d=%.2f" % (alphaH, betaH, gammaH, deltaH)
        print "Beam Coeffs. Y: a=%.2f, b=%.2f, g=%.2f, d=%.2f" % (alphaE, betaE, gammaE, deltaE)
        
    if config['corr']:
        corrDict = numpy.load(os.path.join(dataPath, 'lwa1-dipole-cor.npz'))
        cFreqs = corrDict['freqs']
        cAlts  = corrDict['alts']
        if corrDict['degrees'].item():
            cAlts *= numpy.pi / 180.0
        cCorrs = corrDict['corrs']
        corrDict.close()
        
        if config['freq']/1e6 < cFreqs.min()-11 or config['freq']/1e6 > cFreqs.max()+11:
            print "WARNING: Input frequency of %.3f MHz is out of range, skipping correction"
            corrFnc = None
        else:
            fCors = cAlts*0.0
            for i in xrange(fCors.size):
                ffnc = interpextrap1d(cFreqs, cCorrs[:,i])
                fCors[i] = ffnc(config['freq']/1e6)
            corrFnc = interp1d(cAlts, fCors, bounds_error=False)
            
    else:
        corrFnc = None
        
    def BeamPattern(az, alt, corr=corrFnc):
        zaR = numpy.pi/2 - alt*numpy.pi / 180.0 
        azR = az*numpy.pi / 180.0
        
        c = 1.0
        if corrFnc is not None:
            c = corrFnc(alt*numpy.pi / 180.0)
            c = numpy.where(numpy.isfinite(c), c, 1.0)
            
        pE = (1-(2*zaR/numpy.pi)**alphaE)*numpy.cos(zaR)**betaE + gammaE*(2*zaR/numpy.pi)*numpy.cos(zaR)**deltaE
        pH = (1-(2*zaR/numpy.pi)**alphaH)*numpy.cos(zaR)**betaH + gammaH*(2*zaR/numpy.pi)*numpy.cos(zaR)**deltaH

        return c*numpy.sqrt((pE*numpy.cos(azR))**2 + (pH*numpy.sin(azR))**2)

    if config['enableDisplay']:
        az = numpy.zeros((90,360))
        alt = numpy.zeros((90,360))
        for i in range(360):
            az[:,i] = i
        for i in range(90):
            alt[i,:] = i
        pylab.figure(1)
        pylab.title("Beam Response: %s pol. @ %0.2f MHz" % (config['pol'], config['freq']/1e6))
        pylab.imshow(BeamPattern(az, alt), extent=(0,359, 0,89), origin='lower')
        pylab.xlabel("Azimuth [deg]")
        pylab.ylabel("Altitude [deg]")
        pylab.grid(1)
        pylab.draw()
    
    # Calculate times in both site LST and UTC
    t0 = astro.get_julian_from_sys()
    lst = astro.get_local_sidereal_time(sta.long*180.0/math.pi, t0) / 24.0
    t0 -= lst*(23.933/24.0) # Compensate for shorter sidereal days
    times = numpy.arange(0.0, 1.0, config['tStep']/1440.0) + t0
    
    lstList = []
    powListAnt = [] 
    
    for t in times:
        # Project skymap to site location and observation time
        pmap = skymap.ProjectedSkyMap(smap, sta.lat*180.0/math.pi, sta.long*180.0/math.pi, t)
        lst = astro.get_local_sidereal_time(sta.long*180.0/math.pi, t)
        lstList.append(lst)
        
        # Convolution of user antenna pattern with visible skymap
        gain = BeamPattern(pmap.visibleAz, pmap.visibleAlt)
        powerAnt = (pmap.visiblePower * gain).sum() / gain.sum()
        powListAnt.append(powerAnt)

        if config['verbose']:
            lstH = int(lst)
            lstM = int((lst - lstH)*60.0)
            lstS = ((lst - lstH)*60.0 - lstM)*60.0
            sys.stdout.write("LST: %02i:%02i:%04.1f, Power_ant: %.1f K\r" % (lstH, lstM, lstS, powerAnt))
            sys.stdout.flush()
    sys.stdout.write("\n")
            
    # plot results
    if config['enableDisplay']:
        pylab.figure(2)
        pylab.title("Driftcurve: %s pol. @ %0.2f MHz - %s" % \
            (config['pol'], config['freq']/1e6, config['site'].upper()))
        pylab.plot(lstList, powListAnt, "ro", label="Antenna Pattern")
        pylab.xlabel("LST [hours]")
        pylab.ylabel("Temp. [K]")
        pylab.grid(2)
        pylab.draw()
        pylab.show()
    
    outputFile = "driftcurve_%s_%s_%.2f.txt" % (config['site'], config['pol'], config['freq']/1e6)
    if config['tag'] is not None:
        base, ext = os.path.splitext(outputFile)
        outputFile = "%s_%s%s" % (base, config['tag'], ext)
    print "Writing driftcurve to file '%s'" % outputFile
    mf = file(outputFile, "w")
    for lst,pow in zip(lstList, powListAnt):
        mf.write("%f  %f\n" % (lst, pow))
    mf.close()
Ejemplo n.º 5
0
def main(args):
    # Parse command line
    config = parseOptions(args)

    # Get the site information for LWA-1
    sta = stations.lwa1

    # Read in the skymap (GSM or LF map @ 74 MHz)
    if config['GSM']:
        smap = skymap.SkyMapGSM(freqMHz=config['freq'] / 1e6)
        if config['verbose']:
            print "Read in GSM map at %.2f MHz of %s pixels; min=%f, max=%f" % (
                config['freq'] / 1e6, len(
                    smap.ra), smap._power.min(), smap._power.max())
    else:
        smap = skymap.SkyMap(freqMHz=config['freq'] / 1e6)
        if config['verbose']:
            print "Read in LF map at %.2f MHz of %d x %d pixels; min=%f, max=%f" % (
                config['freq'] / 1e6, smap.numPixelsX, smap.numPixelsY,
                smap._power.min(), smap._power.max())

    # Get the emperical model of the beam and compute it for the correct frequencies
    beamDict = numpy.load(os.path.join(dataPath, 'lwa1-dipole-emp.npz'))
    if config['pol'] == 'EW':
        beamCoeff = beamDict['fitX']
    else:
        beamCoeff = beamDict['fitY']
    try:
        beamDict.close()
    except AttributeError:
        pass
    alphaE = numpy.polyval(beamCoeff[0, 0, :], config['freq'])
    betaE = numpy.polyval(beamCoeff[0, 1, :], config['freq'])
    gammaE = numpy.polyval(beamCoeff[0, 2, :], config['freq'])
    deltaE = numpy.polyval(beamCoeff[0, 3, :], config['freq'])
    alphaH = numpy.polyval(beamCoeff[1, 0, :], config['freq'])
    betaH = numpy.polyval(beamCoeff[1, 1, :], config['freq'])
    gammaH = numpy.polyval(beamCoeff[1, 2, :], config['freq'])
    deltaH = numpy.polyval(beamCoeff[1, 3, :], config['freq'])
    if config['verbose']:
        print "Beam Coeffs. X: a=%.2f, b=%.2f, g=%.2f, d=%.2f" % (
            alphaH, betaH, gammaH, deltaH)
        print "Beam Coeffs. Y: a=%.2f, b=%.2f, g=%.2f, d=%.2f" % (
            alphaE, betaE, gammaE, deltaE)

    def BeamPattern(az, alt):
        zaR = numpy.pi / 2 - alt * numpy.pi / 180.0
        azR = az * numpy.pi / 180.0

        pE = (
            1 -
            (2 * zaR / numpy.pi)**alphaE) * numpy.cos(zaR)**betaE + gammaE * (
                2 * zaR / numpy.pi) * numpy.cos(zaR)**deltaE
        pH = (
            1 -
            (2 * zaR / numpy.pi)**alphaH) * numpy.cos(zaR)**betaH + gammaH * (
                2 * zaR / numpy.pi) * numpy.cos(zaR)**deltaH

        return numpy.sqrt((pE * numpy.cos(azR))**2 + (pH * numpy.sin(azR))**2)

    if config['enableDisplay']:
        az = numpy.zeros((90, 360))
        alt = numpy.zeros((90, 360))
        for i in range(360):
            az[:, i] = i
        for i in range(90):
            alt[i, :] = i
        pylab.figure(1)
        pylab.title("Beam Response: %s pol. @ %0.2f MHz" %
                    (config['pol'], config['freq'] / 1e6))
        pylab.imshow(BeamPattern(az, alt),
                     extent=(0, 359, 0, 89),
                     origin='lower')
        pylab.xlabel("Azimuth [deg]")
        pylab.ylabel("Altitude [deg]")
        pylab.grid(1)
        pylab.draw()

    # Calculate times in both site LST and UTC
    t0 = astro.get_julian_from_sys()
    lst = astro.get_local_sidereal_time(sta.long * 180.0 / math.pi, t0) / 24.0
    t0 -= lst * (23.933 / 24.0)  # Compensate for shorter sidereal days
    times = numpy.arange(0.0, 1.0, config['tStep'] / 1440.0) + t0

    lstList = []
    powListAnt = []

    for t in times:
        # Project skymap to site location and observation time
        pmap = skymap.ProjectedSkyMap(smap, sta.lat * 180.0 / math.pi,
                                      sta.long * 180.0 / math.pi, t)
        lst = astro.get_local_sidereal_time(sta.long * 180.0 / math.pi, t)
        lstList.append(lst)

        if config['GSM']:
            cdec = numpy.ones_like(pmap.visibleDec)
        else:
            cdec = numpy.cos(pmap.visibleDec * smap.degToRad)

        # Convolution of user antenna pattern with visible skymap
        gain = BeamPattern(pmap.visibleAz, pmap.visibleAlt)
        powerAnt = (pmap.visiblePower * gain * cdec).sum() / (gain *
                                                              cdec).sum()
        powListAnt.append(powerAnt)

        if config['verbose']:
            lstH = int(lst)
            lstM = int((lst - lstH) * 60.0)
            lstS = ((lst - lstH) * 60.0 - lstM) * 60.0
            sys.stdout.write("LST: %02i:%02i:%04.1f, Power_ant: %.1f K\r" %
                             (lstH, lstM, lstS, powerAnt))
            sys.stdout.flush()
    sys.stdout.write("\n")

    # plot results
    if config['enableDisplay']:
        pylab.figure(2)
        pylab.title("Driftcurve: %s pol. @ %0.2f MHz - LWA-1" % \
         (config['pol'], config['freq']/1e6))
        pylab.plot(lstList, powListAnt, "ro", label="Antenna Pattern")
        pylab.xlabel("LST [hours]")
        pylab.ylabel("Temp. [K]")
        pylab.grid(2)
        pylab.draw()
        pylab.show()

    outputFile = "driftcurve_%s_%s_%.2f.txt" % ('lwa1', config['pol'],
                                                config['freq'] / 1e6)
    print "Writing driftcurve to file '%s'" % outputFile
    mf = file(outputFile, "w")
    for lst, pow in zip(lstList, powListAnt):
        mf.write("%f  %f\n" % (lst, pow))
    mf.close()
Ejemplo n.º 6
0
 
 lwa_gm_hms = astro.deg_to_hms(-lwa_lnlat.lng)
 lwa_gm_off = lwa_gm_hms.to_sec()
 print('GM Offset:         %s (%0.3f)' % (lwa_gm_hms, lwa_gm_off))
 
 # get current UTC time from system clock
 
 utc = astro.get_julian_from_sys()
 utcd = astro.get_date(utc)
 lcld = utcd.to_zone()
 unixt = astro.get_timet_from_julian(utc)
 
 # caculate sidereal times
 
 gm_sid = astro.get_apparent_sidereal_time(utc)
 lwa_sid = astro.get_local_sidereal_time(lwa_lnlat.lng, utc)
     
 print('---------------------------------------------------------------')
 print('Current time')
 print('---------------------------------------------------------------')
 print('UTC time:             %s (%0.3f)' % (utcd, utc))
 print('%s local time:     %s' % (nam, str(lcld)))
 print('GM sidereal time:     %0.3f' % gm_sid)
 print('%s sidereal time:  %0.3f' % (nam, lwa_sid))
 print('UNIX time:            %d' % unixt)   
 
 # calculate nutation
 
 nut = astro.get_nutation(utc)
 (nut_lng, nut_obl, nut_ecl) = nut.format()