def setup_simulator(path, config='d'): ''' ''' sm.open(path + '.int.ms') u = simutil() configdir = os.getenv('CASAPATH').split()[0] + "/data/alma/simmos/" x, y, z, d, padnames, telescope, posobs = u.readantenna(configdir + 'vla.{}.cfg'.format(config)) sm.setconfig(telescopename=telescope, x=x, y=y, z=z, dishdiameter=d.tolist(), mount=['alt-az'], antname=padnames, coordsystem='global', referencelocation=posobs) sm.setspwindow(spwname='CBand', freq='5GHz', deltafreq='50MHz', freqresolution='50MHz', nchannels=1, stokes='RR') # Initialize the source and calibrater sm.setfield(sourcename='My cal', sourcedirection=['J2000','00h0m0.0','+45.0.0.000'], calcode='A') sm.setfield(sourcename='My source', sourcedirection=['J2000','01h0m0.0','+47.0.0.000']) sm.setlimits(shadowlimit=0.001, elevationlimit='8.0deg') sm.setauto(autocorrwt=0.0) sm.settimes(integrationtime='10s', usehourangle=False, referencetime=me.epoch('utc', 'today')) sm.observe('My cal', 'CBand', starttime='0s', stoptime='300s') sm.observe('My source', 'CBand', starttime='310s', stoptime='610s') sm.setdata(spwid=1, fieldid=1) sm.predict(complist='data/points.cl') sm.close()
def astro_stations2simdata(aststatfn): """ Reads aststatfn and writes it to simdata compatible antennalists pdbi-a.cfg, pdbi-b.cfg, pdbi-c.cfg, and pdbi-d.cfg. aststatfn: gildas-src-mmmxxx/packages/astro/etc/astro_stations.dat 1st line is ignored: 800 / Largest baseline length The rest are: ITRF relative to PdBI center (m) Station X Y Z simdatfn: simdata compatible configuration file, in ITRF. """ mysim = simutil() pdbi['itrf'] = mysim.locxyz2itrf(dms2d(pdbi['lat']), dms2d(pdbi['long']), locz=pdbi['alt']) statdict = {} asf = open(aststatfn, 'r') line = asf.readline() # Skip 1st line. for line in asf: stn, xstr, ystr, zstr = line.strip().split() statdict[stn] = [ float(c) + d for (c, d) in zip((xstr, ystr, zstr), pdbi['itrf']) ] asf.close() for cfg in ('a', 'b', 'c', 'd'): stns = [s.upper() for s in pdbi[cfg].split()] ofile = open('pdbi-' + cfg + '.cfg', 'w') ofile.write('# observatory=IRAM_PDB\n') # Is the _ necessary? ofile.write('# coordsys=XYZ\n') ofile.write('#\n') ofile.write('# Plateau de Bure %s configuration,\n' % cfg.upper()) ofile.write( '# converted to simdata format from\n# %s\n# (%s)\n' % (aststatfn, time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(aststatfn))))) ofile.write('# by recipes.astro_stations2simdata\n') ofile.write('#\n') ofile.write( '# X Y Z Diam Station\n') for stn in stns: ofile.write('% 14.12g % 14.12g % 14.12g %4.1f %s\n' % (statdict[stn][0], statdict[stn][1], statdict[stn][2], pdbi['diam'], stn)) ofile.close()
def astro_stations2simdata(aststatfn): """ Reads aststatfn and writes it to simdata compatible antennalists pdbi-a.cfg, pdbi-b.cfg, pdbi-c.cfg, and pdbi-d.cfg. aststatfn: gildas-src-mmmxxx/packages/astro/etc/astro_stations.dat 1st line is ignored: 800 / Largest baseline length The rest are: ITRF relative to PdBI center (m) Station X Y Z simdatfn: simdata compatible configuration file, in ITRF. """ mysim = simutil() pdbi['itrf'] = mysim.locxyz2itrf(dms2d(pdbi['lat']), dms2d(pdbi['long']), locz=pdbi['alt']) statdict = {} asf = open(aststatfn, 'r') line = asf.readline() # Skip 1st line. for line in asf: stn, xstr, ystr, zstr = line.strip().split() statdict[stn] = [float(c) + d for (c, d) in zip((xstr, ystr, zstr), pdbi['itrf'])] asf.close() for cfg in ('a', 'b', 'c', 'd'): stns = [s.upper() for s in pdbi[cfg].split()] ofile = open('pdbi-' + cfg + '.cfg', 'w') ofile.write('# observatory=IRAM_PDB\n') # Is the _ necessary? ofile.write('# coordsys=XYZ\n') ofile.write('#\n') ofile.write('# Plateau de Bure %s configuration,\n' % cfg.upper()) ofile.write('# converted to simdata format from\n# %s\n# (%s)\n' % (aststatfn, time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(aststatfn))))) ofile.write('# by recipes.astro_stations2simdata\n') ofile.write('#\n') ofile.write('# X Y Z Diam Station\n') for stn in stns: ofile.write('% 14.12g % 14.12g % 14.12g %4.1f %s\n' % (statdict[stn][0], statdict[stn][1], statdict[stn][2], pdbi['diam'], stn)) ofile.close()
def visibility(cfgfile, myvis, imageref, alpha, chan, delta_f, int_time, RT, nscans, ST, dT, sg): col = simutil().readantenna(antab=cfgfile) xx = col[0] # X coordinate of the antenna position yy = col[1] # Y coordinate of the antenna position zz = col[2] # Z coordinate of the antenna position diam = col[3] # diameter of the antenna antnames = col[4] # name of the antenna telescope = col[6] # name of observatory mounttype = 'alt-az' if telescope in ['DRAO', 'WSRT']: # Add ASKAP here if it also has equatorial mount mounttype = 'EQUATORIAL' coordsys = 'global' # CASA suggests taking global for all .cfg files # prerequisite for function sclimg() frequency = imhead(imagename=imageref, mode='get', hdkey='crval4') funit = frequency['unit'] fvalue = frequency['value'] #print 'Reference image is at', frequency['value'], funit if funit == 'Hz': fvalue = fvalue * (10**(-9)) # Hz to GHz print 'fvalue in GHz=', fvalue if funit == 'MHz': fvalue = fvalue * (10**(-3)) # MHz to GHz print 'fvalue in GHz=', fvalue fvalue2 = [] # list of the frquencies corresponding to each channel for i in range(0, chan): fvalue2.append(fvalue + (i) * delta_f) fvalue3 = [fvalue] for i in range(0, chan - 1): fvalue3.append(fvalue + (i) * delta_f) fratio = [ ] # ratio of scaling frequency to original frequency with spectral index as power for i in range(0, chan): fratio.append((fvalue3[i] / fvalue2[i])**alpha) # finding source direction or phasecenter of the image ra = imhead(imagename=imageref, mode='get', hdkey='crval1') ra_value = ra['value'] * 206264.81 # in arcsec dec = imhead(imagename=imageref, mode='get', hdkey='crval2') dec_value = dec['value'] * 206264.81 # in arcsec # ra dec conversion RA = RAs(ra_value) DEC = DECl(dec_value) if telescope == 'SKA_Mid': telescope = telescope.replace( telescope, 'MeerKAT' ) # SKA_Mid is recognized by MeerKAT location (April 2017) # visibility simulation syntax sm.open(myvis) # open a new file posant = me.observatory(telescope) # location of telescope read from CASA sm.setconfig(telescopename=telescope, x=xx, y=yy, z=zz, dishdiameter=diam, mount=mounttype, antname=antnames, coordsystem=coordsys, referencelocation=posant) sm.setspwindow(spwname=telescope, freq=str(fvalue) + 'GHz', deltafreq=str(delta_f) + 'GHz', freqresolution=str(delta_f) + 'GHz', nchannels=chan, stokes='RR LL') # Set autocorrelation weight sm.setauto(0.0) sm.setfield(sourcename='MODEL', sourcedirection=[ 'J2000', RA, DEC ]) # source direction is taken as pointing center from image file # define the feed sm.setfeed(mode='perfect R L', pol=['']) sm.setlimits(shadowlimit=0.001, elevationlimit='17.0deg') sm.settimes( integrationtime=int_time, usehourangle=True, referencetime=me.epoch('UTC', RT) ) # source rise time(in IST) on 2014/07/01 from GMRT location is 04:03:42 which when converted to UTC(IST-5:30:00) becomes 2014/06/30/22:33:42 for i in range(0, nscans): ET = ST + dT - 1 sm.observe(sourcename='MODEL', spwname=telescope, starttime=str(ST) + 's', stoptime=str(ET) + 's') ST = ET + sg + 1 # if you use usehourangle=True, you can't control starttime # On CASA prompt running me.epoch('utc','2014/07/02/00:00:00.1') will give 56840.00000115741d (-> MJD: Mean Julian Day) sm.setdata(fieldid=0) noise = '0.0Jy' # add some noise. Use '0.0Jy' if no noise wanted #sm.setnoise(mode='simplenoise', simplenoise=noise) #sm.corrupt(); for v in range(0, chan): inp_img = sclimg(imageref, fratio[v], fvalue, fvalue2[v]) sm.predict(imagename=inp_img, incremental=True) sm.close()
float(ra_src.split("h")[0]) + (float(ra_src.split("h")[1].split("m")[0]) / 60) + (float(ra_src.split("h")[1].split("m")[1][:-1]) / 3600)) hr_angle_src_end = lst_src_end - ( float(ra_src.split("h")[0]) + (float(ra_src.split("h")[1].split("m")[0]) / 60) + (float(ra_src.split("h")[1].split("m")[1][:-1]) / 3600)) start_time = str(round(hr_angle_src, 2)) + "h" stop_time = str(round(hr_angle_src_end, 2)) + "h" freq_min = str( qa.convert(str(freq_centre_src) + 'MHz', 'MHz')['value'] - (float(nfft_src) / 2) * qa.convert(str(16.0 / nfft_src) + 'MHz', 'MHz')['value']) + 'MHz' conf_file = 'gbd_src.cfg' u = simutil() xx, yy, zz, diam, padnames, telescope, posobs = u.readantenna(conf_file) ms_name = 'gbd_src.ms' sm.open(ms_name) pos_gmrt = me.observatory('GMRT') sm.setconfig(telescopename=telescope, x=xx, y=yy, z=zz, dishdiameter=diam.tolist(), mount='alt-az', antname=padnames, padname=padnames, coordsystem='global', referencelocation=pos_gmrt) sm.setspwindow(spwname='Band',
def plotcomp(compdict, showplot=True, wantdict=False, symb=',', include0amp=False, include0bl=False, blunit='', bl0flux=0.0): """ Given a dict including {'clist': component list, 'objname': objname, 'epoch': epoch, 'shape': component shape dict, including direction. 'freqs (GHz)': pl.array of frequencies, 'antennalist': An array configuration file as used by simdata, 'savedfig': False or, if specified, the filename to save the plot to, 'standard': setjy fluxstandard type}, and symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_ default: ',': The smallest points I could find, make a plot of visibility amplitude vs. baseline length for clist at epoch. If antennalist is not found as is, it will look for antennalist in os.getenv('CASAPATH').split(' ')[0] + '/data/alma/simmos/'. showplot: Whether or not to show the plot on screen. If wantdict is True, it returns a dictionary with the amplitudes and baselines on success. Otherwise, it returns True or False as its estimated success value. include0amp: Force the lower limit of the amplitude axis to 0. include0bl: Force the lower limit of the baseline length axis to 0. blunit: unit of the baseline length (='' used the unit in the data or klambda) bl0flux: Zero baseline flux """ def failval(): """ Returns an appropriate failure value. Note that mydict.update(plotcomp(wantdict=True, ...)) would give a confusing error message if plotcomp returned False. """ retval = False if wantdict: retval = {} return retval retval = failval() # Default try: clist = compdict['clist'] objname = compdict['objname'] epoch = compdict['epoch'] epstr = mepoch_to_str(epoch) antennalist = compdict['antennalist'] # Read the configuration info. if not antennalist: print "compdict['antennalist'] must be set!" print "Try something in", os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/" return failval() # Try repodir if raw antennalist doesn't work. if not os.path.exists(antennalist): repodir = os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/" antennalist = repodir + antennalist su = simutil("") stnx, stny, stnz, diam, padnames, telescopename, obsmeas = su.readantenna(antennalist) #print "telescopename:", telescopename # Check that the source is up. myme = metool() posobs = myme.observatory(telescopename) #print "posobs:", posobs myme.doframe(epoch) myme.doframe(posobs) azel = myme.measure(compdict['shape']['direction'], 'azel') azeldegs = tuple([qa.convert(azel[m], 'deg')['value'] for m in ('m0', 'm1')]) casalog.post("(az, el): (%.2f, %.2f) degrees" % azeldegs) # riseset blabs to the logger, so introduce it now. casalog.post('Rise and set times of ' + objname + " from " + telescopename + ':') approx = '' if 'JPL' in compdict.get('standard', 'JPL'): # The object is in the Solar System or not known to be extragalactic. approx = "APPROXIMATE. The times do not account for the apparent motion of "\ + objname + "." casalog.post(" (" + approx + ")") riset = myme.riseset(compdict['shape']['direction']) msg = '' if riset['rise'] == 'above': msg = objname + " is circumpolar" elif riset['rise'] == 'below': msg = objname + ' is not visible from ' + telescopename if msg: if approx: msg += ' around ' + mepoch_to_str(epoch) casalog.post(msg) else: for t in riset: riset[t]['str'] = mepoch_to_str(riset[t]['utc']) casalog.post(objname + " rises at %s and sets at %s." % (riset['rise']['str'], riset['set']['str'])) tmeridian=(riset['rise']['utc']['m0']['value']+riset['set']['utc']['m0']['value'])/2. casalog.post(objname + ': meridian passage at ' + qa.time(str(tmeridian)+'d')[0]) if approx: riset['NOTE'] = approx if not azel['m1']['value'] > 0.0: casalog.post(objname + " is not visible from " + telescopename + " at " + epstr, 'SEVERE') if wantdict: return riset else: return False # Start a temp MS. workingdir = os.path.abspath(os.path.dirname(clist.rstrip('/'))) tempms = tempfile.mkdtemp(prefix=objname, dir=workingdir) mysm = smtool() mysm.open(tempms) su.setcfg(mysm, telescopename, stnx, stny, stnz, diam, padnames, posobs) #print "cfg set" # Only 1 polarization is wanted for now. stokes, feeds = su.polsettings(telescopename, 'RR') casalog.post("stokes, feeds: %s, %s" % (stokes, feeds)) fband = su.bandname(compdict['freqs (GHz)'][0]) chaninc = 1.0 nchan = len(compdict['freqs (GHz)']) if nchan > 1: chaninc = (compdict['freqs (GHz)'][-1] - compdict['freqs (GHz)'][0]) / (nchan - 1) mysm.setspwindow(spwname=fband, freq=str(compdict['freqs (GHz)'][0]) + 'GHz', deltafreq=str(chaninc) + 'GHz', freqresolution='1Hz', nchannels=nchan, refcode="LSRK", stokes=stokes) mysm.setfeed(mode=feeds, pol=['']) mysm.setlimits(shadowlimit=0.01, elevationlimit='10deg') mysm.setauto(0.0) mysm.setfield(sourcename=objname, sourcedirection=compdict['shape']['direction'], calcode="OBJ", distance='0m') mysm.settimes(integrationtime="1s", usehourangle=False, referencetime=epoch) # this only creates blank uv entries mysm.observe(sourcename=objname, spwname=fband, starttime="-0.5s", stoptime="0.5s", project=objname) mysm.setdata(fieldid=[0]) mysm.setvp() casalog.post("done setting up simulation parameters") mysm.predict(complist=clist) # do actual calculation of visibilities: mysm.close() casalog.post("Simulation finished.") mytb = tbtool() mytb.open(tempms) data = mytb.getcol('DATA')[0] # Again, only 1 polarization for now. data = abs(data) baselines = mytb.getcol('UVW')[:2,:] # Drop w. datablunit = mytb.getcolkeywords('UVW')['QuantumUnits'] mytb.close() #print "Got the data and baselines" shutil.rmtree(tempms) if datablunit[1] != datablunit[0]: casalog.post('The baseline units are mismatched!: %s' % datablunit, 'SEVERE') return failval() datablunit = datablunit[0] # uv dist unit in klambda or m if datablunit == 'm' and blunit=='klambda': kl = qa.constants('C')['value']/(compdict['freqs (GHz)'][0]*1e6) blunit = 'k$\lambda$' else: blunit = datablunit kl = 1.0 pl.ioff() #baselines = pl.hypot(baselines[0]/kl, baselines[1]/kl) baselines = pl.hypot(baselines[0], baselines[1]) #if not showplot: # casalog.post('Sorry, not showing the plot is not yet implemented', # 'WARN') if showplot: pl.ion() pl.clf() pl.ioff() nfreqs = len(compdict['freqs (GHz)']) for freqnum in xrange(nfreqs): freq = compdict['freqs (GHz)'][freqnum] casalog.post("Plotting " + str(freq) + " GHz.") pl.plot(baselines/kl, data[freqnum], symb, label="%.3g GHz" % freq) #pl.plot(baselines, data[freqnum], symb, label="%.3g GHz" % freq) pl.xlabel("Baseline length (" + blunit + ")") pl.ylabel("Visibility amplitude (Jy)") if include0amp: pl.ylim(ymin=0.0) if include0bl: pl.xlim(xmin=0.0) pl.suptitle(objname + " (predicted by %s)" % compdict['standard'], fontsize=14) #pl.suptitle(objname + " (predicted)", fontsize=14) # Unlike compdict['antennalist'], antennalist might have had repodir # prefixed to it. pl.title('at ' + epstr + ' for ' + os.path.basename(compdict['antennalist']), fontsize=10) titletxt='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs # for comparison of old and new models - omit azeldegs as all in az~0 if bl0flux > 0.0: if len(compdict['freqs (GHz)']) == 1: titletxt+='\n bl0 flux:%.3f Jy' % bl0flux else: titletxt+='\n bl0 flux:%.3f Jy @ %s GHz' % (bl0flux, compdict['freqs (GHz)'][0]) pl.legend(loc='best', title=titletxt) #pl.legend(loc='best', title='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs) y_formatter=matplotlib.ticker.ScalarFormatter(useOffset=False) pl.axes().yaxis.set_major_formatter(y_formatter) if showplot: pl.ion() pl.draw() if compdict.get('savedfig'): pl.savefig(compdict.get('savedfig')) casalog.post("Saved plot to " + str(compdict.get('savedfig'))) if wantdict: retval = {'amps': data, 'antennalist': antennalist, # Absolute path, now. 'azel': azel, 'baselines': baselines, 'blunit': blunit, 'riseset': riset, 'savedfig': compdict.get('savedfig')} else: retval = True except Exception, instance: casalog.post(str(instance), 'SEVERE') if os.path.isdir(tempms): shutil.rmtree(tempms)
def plotcomp(compdict, showplot=True, wantdict=False, symb=',', include0amp=False, include0bl=False, blunit='', bl0flux=0.0): """ Given a dict including {'clist': component list, 'objname': objname, 'epoch': epoch, 'shape': component shape dict, including direction. 'freqs (GHz)': pl.array of frequencies, 'antennalist': An array configuration file as used by simdata, 'savedfig': False or, if specified, the filename to save the plot to, 'standard': setjy fluxstandard type}, and symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_ default: ',': The smallest points I could find, make a plot of visibility amplitude vs. baseline length for clist at epoch. If antennalist is not found as is, it will look for antennalist in os.getenv('CASAPATH').split(' ')[0] + '/data/alma/simmos/'. showplot: Whether or not to show the plot on screen. If wantdict is True, it returns a dictionary with the amplitudes and baselines on success. Otherwise, it returns True or False as its estimated success value. include0amp: Force the lower limit of the amplitude axis to 0. include0bl: Force the lower limit of the baseline length axis to 0. blunit: unit of the baseline length (='' used the unit in the data or klambda) bl0flux: Zero baseline flux """ def failval(): """ Returns an appropriate failure value. Note that mydict.update(plotcomp(wantdict=True, ...)) would give a confusing error message if plotcomp returned False. """ retval = False if wantdict: retval = {} return retval retval = failval() # Default try: clist = compdict['clist'] objname = compdict['objname'] epoch = compdict['epoch'] epstr = mepoch_to_str(epoch) antennalist = compdict['antennalist'] # Read the configuration info. if not antennalist: print "compdict['antennalist'] must be set!" print "Try something in", os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/" return failval() # Try repodir if raw antennalist doesn't work. if not os.path.exists(antennalist): repodir = os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/" antennalist = repodir + antennalist su = simutil("") stnx, stny, stnz, diam, padnames, nant, telescopename = su.readantenna(antennalist) #print "telescopename:", telescopename # Check that the source is up. myme = metool() posobs = myme.observatory(telescopename) #print "posobs:", posobs myme.doframe(epoch) myme.doframe(posobs) azel = myme.measure(compdict['shape']['direction'], 'azel') azeldegs = tuple([qa.convert(azel[m], 'deg')['value'] for m in ('m0', 'm1')]) casalog.post("(az, el): (%.2f, %.2f) degrees" % azeldegs) # riseset blabs to the logger, so introduce it now. casalog.post('Rise and set times of ' + objname + " from " + telescopename + ':') approx = '' if 'JPL' in compdict.get('standard', 'JPL'): # The object is in the Solar System or not known to be extragalactic. approx = "APPROXIMATE. The times do not account for the apparent motion of "\ + objname + "." casalog.post(" (" + approx + ")") riset = myme.riseset(compdict['shape']['direction']) msg = '' if riset['rise'] == 'above': msg = objname + " is circumpolar" elif riset['rise'] == 'below': msg = objname + ' is not visible from ' + telescopename if msg: if approx: msg += ' around ' + mepoch_to_str(epoch) casalog.post(msg) else: for t in riset: riset[t]['str'] = mepoch_to_str(riset[t]['utc']) casalog.post(objname + " rises at %s and sets at %s." % (riset['rise']['str'], riset['set']['str'])) tmeridian=(riset['rise']['utc']['m0']['value']+riset['set']['utc']['m0']['value'])/2. casalog.post(objname + ': meridian passage at ' + qa.time(str(tmeridian)+'d')[0]) if approx: riset['NOTE'] = approx if not azel['m1']['value'] > 0.0: casalog.post(objname + " is not visible from " + telescopename + " at " + epstr, 'SEVERE') if wantdict: return riset else: return False # Start a temp MS. workingdir = os.path.abspath(os.path.dirname(clist.rstrip('/'))) tempms = tempfile.mkdtemp(prefix=objname, dir=workingdir) mysm = smtool() mysm.open(tempms) su.setcfg(mysm, telescopename, stnx, stny, stnz, diam, padnames, posobs) #print "cfg set" # Only 1 polarization is wanted for now. stokes, feeds = su.polsettings(telescopename, 'RR') casalog.post("stokes, feeds: %s, %s" % (stokes, feeds)) fband = su.bandname(compdict['freqs (GHz)'][0]) chaninc = 1.0 nchan = len(compdict['freqs (GHz)']) if nchan > 1: chaninc = (compdict['freqs (GHz)'][-1] - compdict['freqs (GHz)'][0]) / (nchan - 1) mysm.setspwindow(spwname=fband, freq=str(compdict['freqs (GHz)'][0]) + 'GHz', deltafreq=str(chaninc) + 'GHz', freqresolution='1Hz', nchannels=nchan, refcode="LSRK", stokes=stokes) mysm.setfeed(mode=feeds, pol=['']) mysm.setlimits(shadowlimit=0.01, elevationlimit='10deg') mysm.setauto(0.0) mysm.setfield(sourcename=objname, sourcedirection=compdict['shape']['direction'], calcode="OBJ", distance='0m') mysm.settimes(integrationtime="1s", usehourangle=False, referencetime=epoch) # this only creates blank uv entries mysm.observe(sourcename=objname, spwname=fband, starttime="-0.5s", stoptime="0.5s", project=objname) mysm.setdata(fieldid=[0]) mysm.setvp() casalog.post("done setting up simulation parameters") mysm.predict(complist=clist) # do actual calculation of visibilities: mysm.close() casalog.post("Simulation finished.") mytb = tbtool() mytb.open(tempms) data = mytb.getcol('DATA')[0] # Again, only 1 polarization for now. data = abs(data) baselines = mytb.getcol('UVW')[:2,:] # Drop w. datablunit = mytb.getcolkeywords('UVW')['QuantumUnits'] mytb.close() #print "Got the data and baselines" shutil.rmtree(tempms) if datablunit[1] != datablunit[0]: casalog.post('The baseline units are mismatched!: %s' % datablunit, 'SEVERE') return failval() datablunit = datablunit[0] # uv dist unit in klambda or m if datablunit == 'm' and blunit=='klambda': kl = qa.constants('C')['value']/(compdict['freqs (GHz)'][0]*1e6) blunit = 'k$\lambda$' else: blunit = datablunit kl = 1.0 pl.ioff() #baselines = pl.hypot(baselines[0]/kl, baselines[1]/kl) baselines = pl.hypot(baselines[0], baselines[1]) #if not showplot: # casalog.post('Sorry, not showing the plot is not yet implemented', # 'WARN') if showplot: pl.ion() pl.clf() pl.ioff() nfreqs = len(compdict['freqs (GHz)']) for freqnum in xrange(nfreqs): freq = compdict['freqs (GHz)'][freqnum] casalog.post("Plotting " + str(freq) + " GHz.") pl.plot(baselines/kl, data[freqnum], symb, label="%.3g GHz" % freq) #pl.plot(baselines, data[freqnum], symb, label="%.3g GHz" % freq) pl.xlabel("Baseline length (" + blunit + ")") pl.ylabel("Visibility amplitude (Jy)") if include0amp: pl.ylim(ymin=0.0) if include0bl: pl.xlim(xmin=0.0) pl.suptitle(objname + " (predicted by %s)" % compdict['standard'], fontsize=14) #pl.suptitle(objname + " (predicted)", fontsize=14) # Unlike compdict['antennalist'], antennalist might have had repodir # prefixed to it. pl.title('at ' + epstr + ' for ' + os.path.basename(compdict['antennalist']), fontsize=10) titletxt='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs # for comparison of old and new models - omit azeldegs as all in az~0 if bl0flux > 0.0: if len(compdict['freqs (GHz)']) == 1: titletxt+='\n bl0 flux:%.3f Jy' % bl0flux else: titletxt+='\n bl0 flux:%.3f Jy @ %s GHz' % (bl0flux, compdict['freqs (GHz)'][0]) pl.legend(loc='best', title=titletxt) #pl.legend(loc='best', title='($%.0f^\circ$ az, $%.0f^\circ$ el)' % azeldegs) y_formatter=matplotlib.ticker.ScalarFormatter(useOffset=False) pl.axes().yaxis.set_major_formatter(y_formatter) if showplot: pl.ion() pl.draw() if compdict.get('savedfig'): pl.savefig(compdict.get('savedfig')) casalog.post("Saved plot to " + str(compdict.get('savedfig'))) if wantdict: retval = {'amps': data, 'antennalist': antennalist, # Absolute path, now. 'azel': azel, 'baselines': baselines, 'blunit': blunit, 'riseset': riset, 'savedfig': compdict.get('savedfig')} else: retval = True except Exception, instance: casalog.post(str(instance), 'SEVERE') if os.path.isdir(tempms): shutil.rmtree(tempms)
# this script tests the table persistence error and multiple applications of noise CAS-2258 name="tmp" oldnoise=False sm.open(name+".ms") from simutil import simutil u=simutil() x,y,z,d,padnames,nant,telescope = u.readantenna("ES.250m.20100902.cfg") sm.setconfig(telescopename=telescope,x=x,y=y,z=z, dishdiameter=d.tolist(), mount=['alt-az'], antname=padnames, padname=padnames, coordsystem='global', referencelocation=me.observatory(telescope)) sm.setspwindow(spwname="band1", freq="230GHz", deltafreq="1GHz",freqresolution="1GHz",nchannels=1,stokes='XX YY') sm.setfeed(mode='perfect X Y',pol=['']) sm.setlimits(shadowlimit=0.01, elevationlimit='10deg') sm.setauto(0.0) sm.setfield(sourcename="src1", sourcedirection="J2000 00:00:00.00 00.00.00", calcode="OBJ", distance='0m') sm.settimes(integrationtime="10s", usehourangle=True, referencetime=me.epoch('TAI', "2012/01/01/00:00:00")) sm.observe(sourcename="src1", spwname="band1", starttime=qa.quantity("0s"), stoptime=qa.quantity("30s")); sm.done()