def losotolofarbeam(parmdb, soltabname, ms, inverse=False, useElementResponse=True, useArrayFactor=True, useChanFreq=True): """ Do the beam correction via this imported losoto operation Args: parmdb (str): name of the h5parm to work on. soltabname (str): name of the soltab to operate on. inverse (bool): apply the inverse beam correction. useElementResponse (bool): apply the element beam correction. useArrayFactor (bool): apply the array factor correction. useChanFreq (bool): operate per channel. """ H5 = h5parm.h5parm(parmdb, readonly=False) soltab = H5.getSolset('sol000').getSoltab(soltabname) sr = stationresponse(ms, inverse, useElementResponse, useArrayFactor, useChanFreq) numants = pt.taql('select gcount(*) as numants from ' + ms + '::ANTENNA').getcol('numants')[0] times = soltab.getAxisValues('time') for vals, coord, selection in soltab.getValuesIter( returnAxes=['ant', 'time', 'pol', 'freq'], weight=False): vals = losoto.lib_operations.reorderAxes( vals, soltab.getAxesNames(), ['ant', 'time', 'freq', 'pol']) for stationnum in range(numants): logging.debug('Working on station number %i' % stationnum) for itime, time in enumerate(times): beam = sr.evaluateStation(time=time, station=stationnum) # Reshape from [nfreq, 2, 2] to [nfreq, 4] beam = beam.reshape(beam.shape[0], 4) if soltab.getAxisLen('pol') == 2: beam = beam[:, [0, 3]] # get only XX and YY if soltab.getType() == 'amplitude': vals[stationnum, itime, :, :] = np.abs(beam) elif soltab.getType() == 'phase': vals[stationnum, itime, :, :] = np.angle(beam) else: logging.error( 'Beam prediction works only for amplitude/phase solution tables.' ) return 1 vals = losoto.lib_operations.reorderAxes( vals, ['ant', 'time', 'freq', 'pol'], [ ax for ax in soltab.getAxesNames() if ax in ['ant', 'time', 'freq', 'pol'] ]) soltab.setValues(vals, selection) H5.close()
def beam_me_up(inputs_dir, ms1): """Load the LOFAR station responses. Args: inputs_dir (str): location of input directory. ms1 (str): name of measurement set. Returns: beams: array of station responses. """ #`msname` #Name of the Measurement Set. #`inverse` #Compute the inverse of the LOFAR beam (default False). #`useElementResponse` #Include the effect of the dual dipole (element) beam (default True). #`useArrayFactor` #Include the effect of the station and tile array factor (default #True). #`useChanFreq` #Compute the phase shift for the station beamformer using the channel #frequency instead of the subband reference frequency. This option #should be enabled for Measurement Sets that contain multiple subbands #compressed to single channels inside a single spectral window #(default: False). import lofar.stationresponse as st beams = st.stationresponse(msname='%s/%s' % (inputs_dir, ms1), inverse=False, useElementResponse=True, useArrayFactor=True, useChanFreq=False) return beams
def run(soltab, ms, inverse=False, useElementResponse=True, useArrayFactor=True, useChanFreq=True): """ Generic unspecified step for easy expansion. Parameters ---------- opt1 : float Is a mandatory parameter. """ # load specific libs import numpy as np import casacore.tables as pt from lofar.stationresponse import stationresponse sr = stationresponse(ms, inverse, useElementResponse, useArrayFactor, useChanFreq) numants = pt.taql('select gcount(*) as numants from ' + ms + '::ANTENNA').getcol('numants')[0] times = soltab.getAxisValues('time') for vals, coord, selection in soltab.getValuesIter( returnAxes=['ant', 'time', 'pol', 'freq'], weight=False): vals = reorderAxes(vals, soltab.getAxesNames(), ['ant', 'time', 'freq', 'pol']) for stationnum in range(numants): logging.debug('Working on station number %i' % stationnum) for itime, time in enumerate(times): beam = sr.evaluateStation(time=time, station=stationnum) # Reshape from [nfreq, 2, 2] to [nfreq, 4] beam = beam.reshape(beam.shape[0], 4) if soltab.getAxisLen('pol') == 2: beam = beam[:, [0, 3]] # get only XX and YY if soltab.getType() == 'amplitude': vals[stationnum, itime, :, :] = np.abs(beam) elif soltab.getType() == 'phase': vals[stationnum, itime, :, :] = np.angle(beam) else: logging.error( 'Beam prediction work only for amplitude/phase solution tables.' ) return 1 vals = reorderAxes(vals, ['ant', 'time', 'freq', 'pol'], [ ax for ax in soltab.getAxesNames() if ax in ['ant', 'time', 'freq', 'pol'] ]) soltab.setValues(vals, selection) return 0
def LoadSR(self): if self.SR != None: return import lofar.stationresponse as lsr f = self.ChanFreq.flatten() if f.shape[0] > 1: t = table(self.MSName + "/SPECTRAL_WINDOW/", readonly=False) c = t.getcol("CHAN_WIDTH") c.fill(np.abs((f[0:-1] - f[1::])[0])) t.putcol("CHAN_WIDTH", c) t.close() self.SR = lsr.stationresponse(self.MSName) self.SR.setDirection(self.rarad, self.decrad)
def LoadSR(self): if self.SR!=None: return import lofar.stationresponse as lsr f=self.ChanFreq.flatten() if f.shape[0]>1: t=table(self.MSName+"/SPECTRAL_WINDOW/",readonly=False) c=t.getcol("CHAN_WIDTH") c.fill(np.abs((f[0:-1]-f[1::])[0])) t.putcol("CHAN_WIDTH",c) t.close() self.SR = lsr.stationresponse(self.MSName) self.SR.setDirection(self.rarad,self.decrad)
def InitLOFARBeam(self): GD=self.GD LOFARBeamMode=GD["Beam"]["LOFARBeamMode"] print>>log, " LOFAR beam model in %s mode"%(LOFARBeamMode) useArrayFactor=("A" in LOFARBeamMode) useElementBeam=("E" in LOFARBeamMode) if self.SR is not None: return import lofar.stationresponse as lsr self.SR = lsr.stationresponse(self.MS.MSName, useElementResponse=useElementBeam, #useElementBeam=useElementBeam, useArrayFactor=useArrayFactor)#,useChanFreq=True) self.SR.setDirection(self.MS.rarad,self.MS.decrad)
def run( soltab, ms, inverse=False, useElementResponse=True, useArrayFactor=True, useChanFreq=True ): """ Generic unspecified step for easy expansion. Parameters ---------- opt1 : float Is a mandatory parameter. """ # load specific libs import numpy as np import casacore.tables as pt from lofar.stationresponse import stationresponse sr = stationresponse(ms, inverse, useElementResponse, useArrayFactor, useChanFreq) numants = pt.taql('select gcount(*) as numants from '+ms+'::ANTENNA').getcol('numants')[0] times = soltab.getAxisValues('time') for vals, coord, selection in soltab.getValuesIter(returnAxes=['ant','time','pol','freq'], weight=False): vals = reorderAxes( vals, soltab.getAxesNames(), ['ant','time','freq','pol'] ) for stationnum in range(numants): logging.debug('Working on station number %i' % stationnum) for itime, time in enumerate(times): beam = sr.evaluateStation(time=time, station=stationnum) # Reshape from [nfreq, 2, 2] to [nfreq, 4] beam = beam.reshape(beam.shape[0], 4) if soltab.getAxisLen('pol') == 2: beam = beam[:,[0,3]] # get only XX and YY if soltab.getType() == 'amplitude': vals[stationnum, itime, :, :] = np.abs(beam) elif soltab.getType() == 'phase': vals[stationnum, itime, :, :] = np.angle(beam) else: logging.error('Beam prediction work only for amplitude/phase solution tables.') return 1 vals = reorderAxes( vals, ['ant','time','freq','pol'], [ax for ax in soltab.getAxesNames() if ax in ['ant','time','freq','pol']] ) soltab.setValues(vals, selection) return 0
def apply_beam(RA, Dec, spectralIndex, flux, referenceFrequency, beamMS, time, ant1, numchannels, startfreq, channelwidth, invert): import numpy as np import lofar.stationresponse as lsr # Use ant1, times, and n channel to compute the beam, where n is determined by # the order of the spectral index polynomial sr = lsr.stationresponse(beamMS, inverse=invert, useElementResponse=False, useArrayFactor=True, useChanFreq=False) sr.setDirection(RA * np.pi / 180., Dec * np.pi / 180.) beam = sr.evaluateStation(time, ant1) # Correct the source spectrum if needed if spectralIndex is not None: nspec = len(spectralIndex) s = max(1, int(numchannels / nspec)) ch_indices = list(range(0, numchannels, s)) ch_indices.append(numchannels) else: ch_indices = [int(numchannels / 2)] freqs_new = [] fluxes_new = [] for ind in ch_indices: beam = abs(sr.evaluateChannel(time, ant1, ind)) beam = beam[0][0] # take XX only (XX and YY should be equal) if spectralIndex is not None: nu = (startfreq + ind * channelwidth) / referenceFrequency - 1 freqs_new.append(nu) fluxes_new.append(polynomial(flux, spectralIndex, nu) * beam) else: fluxes_new.append(flux * beam) if spectralIndex is not None: fit = np.polyfit(freqs_new, fluxes_new, len(spectralIndex - 1)).tolist() fit.reverse() return fit[0], fit[1:] else: return fluxes_new[0], None
def LoadSR(self,useElementBeam=True,useArrayFactor=True): if self.SR!=None: return # t=table(self.MSName,ack=False,readonly=False) # if not("LOFAR_ANTENNA_FIELD" in t.getkeywords().keys()): # self.PutLOFARKeys() # t.close() import lofar.stationresponse as lsr f=self.ChanFreq.flatten() if f.shape[0]>1: t=table(self.MSName+"/SPECTRAL_WINDOW/",readonly=False) c=t.getcol("CHAN_WIDTH") c.fill(np.abs((f[0:-1]-f[1::])[0])) t.putcol("CHAN_WIDTH",c) t.close() self.SR = lsr.stationresponse(self.MSName, useElementResponse=useElementBeam, #useElementBeam=useElementBeam, useArrayFactor=useArrayFactor)#,useChanFreq=True) self.SR.setDirection(self.rarad,self.decrad)
def LoadSR(self, useElementBeam=True, useArrayFactor=True): if self.SR != None: return # t=table(self.MSName,ack=False,readonly=False) # if not("LOFAR_ANTENNA_FIELD" in t.getkeywords().keys()): # self.PutLOFARKeys() # t.close() from lofar.stationresponse import stationresponse # f=self.ChanFreq.flatten() # if f.shape[0]>1: # t=table(self.MSName+"/SPECTRAL_WINDOW/",ack=False) # c=t.getcol("CHAN_WIDTH") # c.fill(np.abs((f[0:-1]-f[1::])[0])) # t.putcol("CHAN_WIDTH",c) # t.close() self.SR = stationresponse( self.MSName, useElementResponse=useElementBeam, #useElementBeam=useElementBeam, useArrayFactor=useArrayFactor, useChanFreq=True) self.SR.setDirection(self.rarad, self.decrad)
def main((frequency, msname, minst, maxst, refms)): # Arguments as a tuple to make threading easier assert maxst + 1 > minst # Set frequency of the MS to the specified frequency freqmhz = int(frequency / 1.e6) print frequency, freqmhz t = pt.table(msname + '/SPECTRAL_WINDOW', readonly=False, ack=False) t.putcol('REF_FREQUENCY', np.array([frequency])) t.putcol('CHAN_FREQ', np.array([[frequency]])) t.close() t = pt.table(msname, ack=False) timecol = t.getcol('TIME') msreftime = min(timecol) print 'time reference', msreftime JD = msreftime / 3600. / 24. + 2400000.5 print 'MS JD', JD # makeresponseimage abs=true frames=1 ms=freq00.MS size=350 cellsize=1200arcsec stations=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 hs = 100. ds = 1 # downsample, ** was 2 ** xvals = np.arange(-hs, hs + 1.) X, Y = np.meshgrid(xvals, xvals) R = np.hypot(X, Y) #w = wcs.WCS(naxes=2) #w.wcs.crpix=[151,151] #w.wcs.cdelt=array([165./301.,165./301.]) #w.wcs.crval=[0.,90.] #w.wcs.ctype=['RA---ZEA','DEC--ZEA'] h = pyfits.open('wcs_azimuth_201.fits') w = pywcs.WCS(h[0].header) els = np.zeros(R.shape) azs = np.zeros(R.shape) for i in range(R.shape[0]): for j in range(R.shape[1]): azel = w.wcs_pix2sky([[i, j]], 0) if azel[0][1] < 0.: els[i, j] = np.nan azs[i, j] = np.nan elif ((i - hs)**2 + (j - hs)**2)**0.5 > 1.2 * hs: els[i, j] = np.nan azs[i, j] = np.nan else: els[i, j] = azel[0][1] * np.pi / 180. azs[i, j] = azel[0][0] * np.pi / 180. ra = np.zeros(R.shape) dec = np.zeros(R.shape) t = pt.table(msname + '/ANTENNA', ack=False) stcol = t.getcol('NAME') poscol = t.getcol('POSITION') #stations = range(len(stcol)) stations = range(minst, maxst + 1) print len(stations), 'stations' beamintmap = np.zeros( (2, len(stations), len(range(0, len(xvals), ds)), len(range(0, len(xvals), ds)))) beamtmpmap = np.zeros((2, len(stations), len(xvals), len(xvals))) azmap = np.zeros((len(range(0, len(xvals), ds)), len(range(0, len(xvals), ds)))) elmap = np.zeros((len(range(0, len(xvals), ds)), len(range(0, len(xvals), ds)))) sr = lsr.stationresponse(msname, useElementResponse=True) stll = {} for line in open('stations_positions.txt'): sline = line.split() stll[sline[0]] = [ float(sline[2]) * np.pi / 180., float(sline[3]) * np.pi / 180. ] # lon, lat t = time.time() # directionmap contains itrf directions for every x,y point directionmap = np.zeros((len(xvals), len(xvals), 3)) evals = 0 for ss in range(len(stations)): # Convert azel to RA/DEC for this station meas = pm.measures() # Set station position meas.do_frame( meas.position('ITRF', *(str(coord) + "m" for coord in poscol[ss]))) # Set reference time meas.do_frame(meas.epoch('utc', pyrap.quanta.quantity(msreftime, 's'))) for i in range(0, len(xvals), ds): for j in range(0, len(xvals), ds): if not np.isnan(els[i, j]): radecmeas = meas.measure( meas.direction('AZEL', str(azs[i, j]) + ' rad', str(els[i, j]) + ' rad'), 'J2000') ra[i, j] = radecmeas['m0']['value'] dec[i, j] = radecmeas['m1']['value'] directionmap *= 0. for i in range(0, len(xvals), ds): for j in range(0, len(xvals), ds): if not np.isnan(dec[i, j]): sr.setDirection(ra[i, j], dec[i, j]) tmpdirection = sr.getDirection(msreftime) directionmap[i, j, :] = tmpdirection if refms is None: print "Using all points" pointsgenerator = allpointsgenerator() else: print "Using points in", refms pointsgenerator = mypointsgenerator(refms, stcol[ss]) for i, j in pointsgenerator: azmap[i / ds, j / ds] = azs[i, j] elmap[i / ds, j / ds] = els[i, j] #print dec[i,j] #exit() lenxvals = len(xvals) tmpra = 0. tmpdec = 0. if not np.isnan(dec[i, j]): thisra = ra[i, j] thisdec = dec[i, j] sr.setRefDelay(thisra, thisdec) sr.setRefTile(thisra, thisdec) refdelay = sr.getRefDelay(msreftime) reftile = sr.getRefTile(msreftime) beamtmpmap *= 0. for x in xrange(lenxvals): for y in xrange(lenxvals): if not np.isnan(dec[x, y]): #tmpra = ra[x,y] #tmpdec = dec[x,y] #sr.setDirection(tmpra,tmpdec) #mydirection=sr.getDirection(msreftime) mydirection = directionmap[x, y] bmj = sr.evaluateFreqITRF(msreftime, stations[ss], frequency, mydirection, refdelay, reftile) #bmj1=sr.evaluateFreq(msreftime,stations[ss],frequency) evals += 1 #beamtmpmap[ss,x,y]=np.sum(np.abs(bmj)) beamtmpmap[0, ss, x, y] = np.sqrt( np.abs(bmj[0, 0])**2 + np.abs(bmj[0, 1])**2) beamtmpmap[1, ss, x, y] = np.sqrt( np.abs(bmj[1, 1])**2 + np.abs(bmj[1, 0])**2) beamintmap[0, ss, j / ds, i / ds] = np.sum(beamtmpmap[0, ss, :, :]) #*cosel) beamintmap[1, ss, j / ds, i / ds] = np.sum(beamtmpmap[1, ss, :, :]) #*cosel) print ss, '/', len(stations), '-', i / ds, '/', len( range(0, len(xvals), ds)), ':', int( time.time() - t), 'sec elapsed so far,', evals, 'beam evaluations' header = h[0].header #header['CRPIX1']=51. #header['CRPIX2']=51. #pixsize = header['CDELT1'] #pixsize *= 2. #header['CDELT1']=pixsize #header['CDELT2']=pixsize for stationnr in range(minst, maxst + 1): stationname = stcol[stationnr] hdu = pyfits.PrimaryHDU(header=header, data=beamintmap[0, stationnr - minst, ]) hdu.writeto('beamcubexx-%s-%dMHz.fits' % (stationname, freqmhz), clobber=True) hdu = pyfits.PrimaryHDU(header=header, data=beamintmap[1, stationnr - minst, ]) hdu.writeto('beamcubeyy-%s-%dMHz.fits' % (stationname, freqmhz), clobber=True)
# get direction t = pt.table(msname + '/FIELD') direction = t.getcol('PHASE_DIR')[0][0] print "Direction:", direction t.close() # get stations t = pt.table(msname + '/ANTENNA') stations = t.getcol('NAME') t.close() print "Stations:", stations import lofar.stationresponse as st s = st.stationresponse(msname=msname, inverse=True, useElementResponse=True, useArrayFactor=False, useChanFreq=False) s.setDirection(direction[0], direction[1]) Nc = int(np.ceil(np.sqrt(len(stations)))) Nr = int(np.ceil(np.float(len(stations)) / Nc)) f_a, axa_a = plt.subplots(Nc, Nr, sharey=True, sharex=True, figsize=(15, 12)) f_p, axa_p = plt.subplots(Nc, Nr, sharey=True, sharex=True, figsize=(15, 12)) axa_a = axa_a.flatten() axa_p = axa_p.flatten() for idx_station in xrange(len(stations)): print "Working on station: %s", stations[idx_station] beam_matrix = [] for time in times: beam_matrix_ch0 = s.evaluateStation(
t.close() # get direction t = pt.table(msname+'/FIELD') direction = t.getcol('PHASE_DIR')[0][0] print("Direction:", direction) t.close() # get stations t = pt.table(msname+'/ANTENNA') stations = t.getcol('NAME') t.close() print("Stations:", stations) import lofar.stationresponse as st s = st.stationresponse( msname=msname, inverse=True, useElementResponse=True, useArrayFactor=False, useChanFreq=False ) s.setDirection(direction[0],direction[1]) Nc = int(np.ceil(np.sqrt(len(stations)))) Nr = int(np.ceil(np.float(len(stations))/Nc)) f_a, axa_a = plt.subplots(Nc, Nr, sharey=True, sharex=True, figsize=(15,12)) f_p, axa_p = plt.subplots(Nc, Nr, sharey=True, sharex=True, figsize=(15,12)) axa_a = axa_a.flatten() axa_p = axa_p.flatten() for idx_station in range(len(stations)): print("Working on station: %s", stations[idx_station]) beam_matrix = [] for time in times: beam_matrix_ch0 = s.evaluateStation(time=time,station=idx_station)[0,:,:] # only first chan beam_matrix.append(beam_matrix_ch0)
def attenuate(beamMS, fluxes, RADeg, DecDeg, timeIndx=0.5): """ Returns flux attenuated by primary beam. Parameters ---------- beamMS : str Measurement set for which the beam model is made fluxes : list List of fluxes to attenuate RADeg : list List of RA values in degrees DecDeg : list List of Dec values in degrees timeIndx : float (between 0 and 1), optional Time as fraction of that covered by the beamMS for which the beam is calculated Returns ------- attFluxes : numpy array """ import numpy as np import pyrap.tables as pt import lofar.stationresponse as lsr log = logging.getLogger('LSMTool') t = pt.table(beamMS, ack=False) time = None ant1 = -1 ant2 = 1 while time is None: ant1 += 1 ant2 += 1 tt = t.query('ANTENNA1=={0} AND ANTENNA2=={1}'.format(ant1, ant2), columns='TIME') time = tt.getcol("TIME") t.close() if timeIndx < 0.0: timeIndx = 0.0 if timeIndx > 1.0: timeIndx = 1.0 time = min(time) + ( max(time) - min(time) ) * timeIndx log.debug('Applying beam attenuation using beam at time of {0}% point of ' 'observation.'.format(int(timeIndx*100.0))) attFluxes = [] sr = lsr.stationresponse(beamMS, inverse=False, useElementResponse=False, useArrayFactor=True, useChanFreq=False) if type(fluxes) is not list: fluxes = list(fluxes) if type(RADeg) is not list: RADeg= list(RADeg) if type(DecDeg) is not list: DecDeg = list(DecDeg) for flux, RA, Dec in zip(fluxes, RADeg, DecDeg): # Use ant1, mid time, and mid channel to compute the beam sr.setDirection(RA*np.pi/180., Dec*np.pi/180.) beam = sr.evaluateStation(time, ant1) r = abs(beam[int(len(beam)/2.)]) beam = ( r[0][0] + r[1][1] ) / 2. attFluxes.append(flux * beam) return np.array(attFluxes)
def attenuate(beamMS, fluxes, RADeg, DecDeg, timeIndx=0.5): """ Returns flux attenuated by primary beam. Parameters ---------- beamMS : str Measurement set for which the beam model is made fluxes : list List of fluxes to attenuate RADeg : list List of RA values in degrees DecDeg : list List of Dec values in degrees timeIndx : float (between 0 and 1), optional Time as fraction of that covered by the beamMS for which the beam is calculated Returns ------- attFluxes : numpy array """ import numpy as np import pyrap.tables as pt import lofar.stationresponse as lsr log = logging.getLogger('LSMTool') t = pt.table(beamMS, ack=False) time = None ant1 = -1 ant2 = 1 while time is None: ant1 += 1 ant2 += 1 tt = t.query('ANTENNA1=={0} AND ANTENNA2=={1}'.format(ant1, ant2), columns='TIME') time = tt.getcol("TIME") t.close() if timeIndx < 0.0: timeIndx = 0.0 if timeIndx > 1.0: timeIndx = 1.0 time = min(time) + (max(time) - min(time)) * timeIndx log.debug('Applying beam attenuation using beam at time of {0}% point of ' 'observation.'.format(int(timeIndx * 100.0))) attFluxes = [] sr = lsr.stationresponse(beamMS, inverse=False, useElementResponse=False, useArrayFactor=True, useChanFreq=False) if type(fluxes) is not list: fluxes = list(fluxes) if type(RADeg) is not list: RADeg = list(RADeg) if type(DecDeg) is not list: DecDeg = list(DecDeg) for flux, RA, Dec in zip(fluxes, RADeg, DecDeg): # Use ant1, mid time, and mid channel to compute the beam sr.setDirection(RA * np.pi / 180., Dec * np.pi / 180.) beam = sr.evaluateStation(time, ant1) r = abs(beam[int(len(beam) / 2.)]) beam = (r[0][0] + r[1][1]) / 2. attFluxes.append(flux * beam) return np.array(attFluxes)
def main((frequency, msname, minst, maxst, refms)): # Arguments as a tuple to make threading easier assert maxst+1 > minst # Set frequency of the MS to the specified frequency freqmhz = int(frequency/1.e6) print frequency,freqmhz t = pt.table(msname+'/SPECTRAL_WINDOW',readonly=False,ack=False) t.putcol('REF_FREQUENCY',np.array([frequency])) t.putcol('CHAN_FREQ',np.array([[frequency]])) t.close() t = pt.table(msname,ack=False) timecol = t.getcol('TIME') msreftime = min(timecol) print 'time reference', msreftime JD = msreftime/3600./24. + 2400000.5 print 'MS JD', JD # makeresponseimage abs=true frames=1 ms=freq00.MS size=350 cellsize=1200arcsec stations=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 hs = 100. ds = 1 # downsample, ** was 2 ** xvals = np.arange(-hs,hs+1.) X,Y = np.meshgrid(xvals,xvals) R=np.hypot(X,Y) #w = wcs.WCS(naxes=2) #w.wcs.crpix=[151,151] #w.wcs.cdelt=array([165./301.,165./301.]) #w.wcs.crval=[0.,90.] #w.wcs.ctype=['RA---ZEA','DEC--ZEA'] h = pyfits.open('wcs_azimuth_201.fits') w = pywcs.WCS(h[0].header) els = np.zeros(R.shape) azs = np.zeros(R.shape) for i in range(R.shape[0]): for j in range(R.shape[1]): azel = w.wcs_pix2sky([[i,j]],0) if azel[0][1]<0.: els[i,j]=np.nan azs[i,j]=np.nan elif ((i-hs)**2+(j-hs)**2)**0.5 > 1.2*hs: els[i,j]=np.nan azs[i,j]=np.nan else: els[i,j]=azel[0][1]*np.pi/180. azs[i,j]=azel[0][0]*np.pi/180. ra = np.zeros(R.shape) dec = np.zeros(R.shape) t = pt.table(msname+'/ANTENNA',ack=False) stcol = t.getcol('NAME') poscol = t.getcol('POSITION') #stations = range(len(stcol)) stations = range(minst,maxst+1) print len(stations), 'stations' beamintmap = np.zeros((2,len(stations),len(range(0,len(xvals),ds)),len(range(0,len(xvals),ds)))) beamtmpmap = np.zeros((2,len(stations),len(xvals),len(xvals))) azmap = np.zeros((len(range(0,len(xvals),ds)),len(range(0,len(xvals),ds)))) elmap = np.zeros((len(range(0,len(xvals),ds)),len(range(0,len(xvals),ds)))) sr = lsr.stationresponse(msname, useElementResponse=True) stll = {} for line in open('stations_positions.txt'): sline = line.split() stll[sline[0]]=[float(sline[2])*np.pi/180.,float(sline[3])*np.pi/180.] # lon, lat t = time.time() # directionmap contains itrf directions for every x,y point directionmap=np.zeros((len(xvals),len(xvals),3)) evals=0 for ss in range(len(stations)): # Convert azel to RA/DEC for this station meas=pm.measures() # Set station position meas.do_frame(meas.position('ITRF',*(str(coord)+"m" for coord in poscol[ss]))) # Set reference time meas.do_frame(meas.epoch('utc',pyrap.quanta.quantity(msreftime,'s'))) for i in range(0,len(xvals),ds): for j in range(0,len(xvals),ds): if not np.isnan(els[i,j]): radecmeas=meas.measure(meas.direction('AZEL', str(azs[i,j])+' rad', str(els[i,j])+' rad'),'J2000') ra[i,j]=radecmeas['m0']['value'] dec[i,j]=radecmeas['m1']['value'] directionmap*=0.; for i in range(0,len(xvals),ds): for j in range(0,len(xvals),ds): if not np.isnan(dec[i,j]): sr.setDirection(ra[i,j],dec[i,j]) tmpdirection=sr.getDirection(msreftime) directionmap[i,j,:]=tmpdirection if refms is None: print "Using all points" pointsgenerator=allpointsgenerator(); else: print "Using points in",refms pointsgenerator=mypointsgenerator(refms,stcol[ss]) for i,j in pointsgenerator: azmap[i/ds,j/ds]=azs[i,j] elmap[i/ds,j/ds]=els[i,j] #print dec[i,j] #exit() lenxvals=len(xvals) tmpra=0. tmpdec=0. if not np.isnan(dec[i,j]): thisra=ra[i,j] thisdec=dec[i,j] sr.setRefDelay(thisra,thisdec) sr.setRefTile(thisra,thisdec) refdelay=sr.getRefDelay(msreftime) reftile=sr.getRefTile(msreftime) beamtmpmap*=0. for x in xrange(lenxvals): for y in xrange(lenxvals): if not np.isnan(dec[x,y]): #tmpra = ra[x,y] #tmpdec = dec[x,y] #sr.setDirection(tmpra,tmpdec) #mydirection=sr.getDirection(msreftime) mydirection=directionmap[x,y] bmj=sr.evaluateFreqITRF(msreftime,stations[ss],frequency,mydirection,refdelay,reftile) #bmj1=sr.evaluateFreq(msreftime,stations[ss],frequency) evals+=1 #beamtmpmap[ss,x,y]=np.sum(np.abs(bmj)) beamtmpmap[0,ss,x,y]=np.sqrt(np.abs(bmj[0,0])**2+np.abs(bmj[0,1])**2) beamtmpmap[1,ss,x,y]=np.sqrt(np.abs(bmj[1,1])**2+np.abs(bmj[1,0])**2) beamintmap[0,ss,j/ds,i/ds]=np.sum(beamtmpmap[0,ss,:,:])#*cosel) beamintmap[1,ss,j/ds,i/ds]=np.sum(beamtmpmap[1,ss,:,:])#*cosel) print ss,'/',len(stations),'-',i/ds,'/',len(range(0,len(xvals),ds)),':',int(time.time()-t),'sec elapsed so far,',evals,'beam evaluations' header = h[0].header #header['CRPIX1']=51. #header['CRPIX2']=51. #pixsize = header['CDELT1'] #pixsize *= 2. #header['CDELT1']=pixsize #header['CDELT2']=pixsize for stationnr in range(minst, maxst+1): stationname=stcol[stationnr] hdu = pyfits.PrimaryHDU(header=header,data=beamintmap[0,stationnr-minst,]) hdu.writeto('beamcubexx-%s-%dMHz.fits'%(stationname,freqmhz),clobber=True) hdu = pyfits.PrimaryHDU(header=header,data=beamintmap[1,stationnr-minst,]) hdu.writeto('beamcubeyy-%s-%dMHz.fits'%(stationname,freqmhz),clobber=True)