def imgseq (inna,incl,indisk,inseq): uvdata = AIPSUVData (inna,incl,indisk,inseq) for i in AIPSCat()[1]: if i['name']==inna and i['klass']=='IMGSEQ': AIPSImage(inna,'IMGSEQ',indisk,i['seq']).zap() if i['name']==inna and i['klass']=='ICL001': AIPSImage(inna,'ICL001',indisk,i['seq']).zap() imagr=AIPSTask('imagr') imagr.indata = uvdata imagr.cellsize[1:] = [0.2,0.2] imagr.imsize[1:] = [1024,1024] imagr.uvwtfn = 'NA' imagr.uvrange[1:] = [5.0,100000.0] imagr.source[1] = 'BEAM_1' imagr.outname = inna imagr.niter = 200 imagr.nchav = 54 uvtap = [400.0,200.0,100.0,50.0] beam = [0.5,0.9,1.8,5.0] for i in range(4): imagr.uvtaper[1:] = [uvtap[i],uvtap[i]] imagr.bmaj,imagr.bmin = beam[i],beam[i] imagr.go() AIPSImage(inna,'IBM001',indisk,1).zap() AIPSImage(inna,'ICL001',indisk,1).rename(inna,'IMGSEQ',indisk,0)
def aipszap(aipsname, aipsclass, indisk=1): pca = AIPSCat() for j in pca[indisk]: if j['name'] == aipsname and j['klass'] == aipsclass: if j['type'] == 'UV': data = AIPSUVData(aipsname, aipsclass, indisk, j['seq']) else: data = AIPSImage(aipsname, aipsclass, indisk, j['seq']) data.zap()
def zapexisting(inna, incl, indisk=1): for i in AIPSCat()[indisk]: if i['name'] == inna and i['klass'] == incl: if i['type'] == 'MA': AIPSImage(inna, incl, indisk, i['seq']).clrstat() AIPSImage(inna, incl, indisk, i['seq']).zap() else: AIPSUVData(inna, incl, indisk, i['seq']).clrstat() AIPSUVData(inna, incl, indisk, i['seq']).zap()
def get_entry(self, n): """Return an AIPS catalog entry. Args: n(int): Catalog entry number. Returns: AIPS catalog entry. """ return AIPSCat()[self.DISK_ID][n]
def empty(self, do_empty): """Empty the AIPS catalog. Args: do_empty(bool): If set, do not prompt user for confirmation. """ if not do_empty: choice = raw_input('Is it OK to clear your AIPS ' 'catalog (id={0})? [y/n] '.format(AIPS.userno)) if choice.lower() == 'n': print "Can not continue without an empty catalog. Exiting." sys.exit() elif choice.lower() == 'y': AIPSCat().zap() # empty the catalog else: self.empty( do_empty) # if they didn't type 'y' or 'n', ask again. else: AIPSCat().zap()
def show(self, ): """Print to screen the contents of the AIPS catalog. """ msg = "AIPS Catalog" print "" print "-" * len(msg) print msg print "-" * len(msg) print "" print AIPSCat(self.DISK_ID)
def datatype(data): """ return the datatype of the file """ # datatype = 'None' catalog_in = AIPSCat(int(data[2])) catalog = str(catalog_in).split() # matchfname = [] for i in range(len(catalog)): if catalog[i].find(data[0]) == 0: matchfname.append(i) matchfname.append(len(catalog)) classindex = -1 isname = -1 isclass = -1 isdisk = -1 isseq = -1 i = 0 while (isname != 1 or isclass != 1 or isdisk != 1 or isseq != 1 or classindex != -1) and i < len(matchfname) - 1: isname = -1 isclass = -1 isdisk = -1 isseq = -1 #print matchfname[i],matchfname[i+1] #print catalog[matchfname[i]:matchfname[i+1]] for j in range(matchfname[i], matchfname[i + 1]): if catalog[j].replace('.', '') == data[0].replace('.', ''): isname = 1 if catalog[j].replace('.', '') == data[1]: isclass = 1 if catalog[j].replace('.', '') == str(int(data[2])): isdisk = 1 if catalog[j].replace('.', '') == str(int(data[3])): isseq = 1 if catalog[ j] == 'UV' and isname == 1 and isclass == 1 and isdisk == 1 and isseq == 1 and classindex == -1: classindex = j if catalog[ j] == 'MA' and isname == 1 and isclass == 1 and isdisk == 1 and isseq == 1 and classindex == -1: classindex = j i += 1 if classindex != -1: datatype = catalog[classindex] return (datatype)
def pcat(output=False, doprint=True, disk=1): ''' set AIPS USER NO Args: output (bool, default=False): if True, return a list of AIPS data in the specified disk doprint (bool, default=True): print list of AIPS data in the specified disk disk (int, default=1): Number of AIPS Disk Returns: catalogue (list, if output=True): A list of dictionary for uvdata in specified disk ''' if AIPS.userno == 0: raise ValueError( "Please set AIPS USER NO with setuser(XX) or AIPS.userno=XX") try: catlist = AIPSCat()[disk] except KeyError: raise ValueError("disk=%d does not exist." % (disk)) return catlist if doprint: if len(catlist) == 0: if doprint: print("pcat: disk=%d is empty." % (disk)) else: for catdata in catlist: print("%3d: %12s.%6s.%3d.%3d %s %s %s" % (catdata["cno"], catdata["name"], catdata["klass"], catdata["seq"], disk, catdata["type"], catdata["time"], catdata["date"])) if output: return catlist
def __len__(self, ): """Get the number of catalog entries.""" return len(AIPSCat()[self.DISK_ID])
imsize = int(inputs['imsize']) #Image size in pixels. print imsize niter = int(inputs['niter']) #Clean iterations itercal = int(inputs['self_cal_iter']) soli = float(inputs['solution_interval']) combinIFLLRR = int(inputs['combineIFLLRR']) APhas = str(inputs['amplitude_or_phase']) pointcenRA, pointcenDEC = str(inputs['pointing_centre']).split(',') pointcenRA = float(pointcenRA) pointcenDEC = float(pointcenDEC) if do_load == 'True': AIPSCat().zap() logging.info('Loading data into AIPS') print('Loading data into AIPS') if len(UV_files) !=0: UV_files = UV_files.split(',') else: UV_files = [] for file in os.listdir(UV_path): if file.endswith(UV_suffix): UV_files = UV_files + [file] uvname = [] #HDF names of files for i in range(len(UV_files)): total_progress = len(UV_files) + 5 total = i
def dbcon_combine(indisk): tasav = AIPSTask('TASAV') uvavg = AIPSTask('UVAVG') avspc = AIPSTask('AVSPC') dbcon = AIPSTask('DBCON') msort = AIPSTask('MSORT') indxr = AIPSTask('INDXR') split = AIPSTask('SPLIT') splat = AIPSTask('SPLAT') uvcop = AIPSTask('UVCOP') pca = AIPSCat(indisk) print "Your AIPS catalog looks like this:" print AIPSCat(indisk) print ".... DBCONing....." pca = AIPSCat(indisk) i = 0 queueNAME = deque([]) queueKLAS = deque([]) queueSEQ = deque([]) for fitsfil in pca[indisk]: if pca[indisk][i]["klass"] == 'UV' : queueNAME.append(pca[indisk][i]["name"]) queueKLAS.append(pca[indisk][i]["klass"]) queueSEQ.append(pca[indisk][i]["seq"]) i = i + 1 i = 0 while len(queueNAME)>1 : print "Combining " + queueNAME[0] + '.' + queueKLAS[0] + '.' + format(queueSEQ[0]) + " and " + queueNAME[1] + '.' + queueKLAS[1] + '.' + format(queueSEQ[1]) uvdata1 = AIPSUVData(queueNAME.popleft(), queueKLAS.popleft(), indisk, queueSEQ.popleft()) uvdata2 = AIPSUVData(queueNAME.popleft(), queueKLAS.popleft(), indisk, queueSEQ.popleft()) dbcon.indata = uvdata1 dbcon.in2data = uvdata2 dbcon.outname = format(i) dbcon.outclass = 'DBCON' dbcon.outdisk = indisk dbcon.doarray = 1 dbcon.fqcenter = -1 dbcon.go() indxr.indata = AIPSUVData(dbcon.outname, dbcon.outclass, indisk, dbcon.outseq) indxr.go() queueNAME.append(format(i)) queueKLAS.append('DBCON') queueSEQ.append(1) i = i + 1 print "Final sort and index...." data = AIPSUVData(queueNAME[0], queueKLAS[0], indisk, queueSEQ[0]) msort.indata = data msort.outdata = data msort.go() indxr.indata = data indxr.go() data.rename('COMBO','DBCON',0) print "Tidying up your AIPS catalogue." pca = AIPSCat(indisk) j = 0 for fitsfil in pca[indisk]: if pca[indisk][j]["klass"] == 'FGED' : print "Zapping: " + pca[indisk][j]["name"] + '.' + pca[indisk][j]["klass"] + '.' + format(pca[indisk][j]["seq"]) uvdata1 = AIPSUVData(pca[indisk][j]["name"], pca[indisk][j]["klass"], indisk, pca[indisk][j]["seq"]) uvdata1.zap() if pca[indisk][j]["klass"] == 'DBCON' : if pca[indisk][j]["name"].isdigit() : print "Zapping: " + pca[indisk][j]["name"] + '.' + pca[indisk][j]["klass"] + '.' + format(pca[indisk][j]["seq"]) uvdata1 = AIPSUVData(pca[indisk][j]["name"], pca[indisk][j]["klass"], indisk, pca[indisk][j]["seq"]) uvdata1.zap() j = j + 1
from eMERLIN_tasks.eMERLIN_tasks import * aips_no = config.getint('pipeline', 'aips_number') print aips_no AIPS.userno = aips_no indisk = config.getint('pipeline', 'aips_indisk') thisdir = 0 data_path = config.get('pipeline', 'data_path') data_file = data_path + config.get('pipeline', 'project_name') + '.uvfits' outfilename = config.get('pipeline', 'project_name') + '.fits' fovradius = config.getfloat('configuration', 'fov_radius') noiter = config.getint('configuration', 'number_of_iterations') target = config.get('field', 'name') #'obsfield' option = config.getboolean('pipeline', 'clear_aips') print AIPSCat(indisk) print config.get('pipeline', 'project_name') + '.uvfits' #remove all files previously in aips catalogue removeall(option, target, indisk) # fitld runfitld2(data_file, indisk, thisdir, target) pca = AIPSCat(indisk) fitsfil = pca[indisk][-1] data = AIPSUVData(fitsfil.name, fitsfil.klass, indisk, fitsfil.seq) print 'fix antenna' # fix the antenna table and run indxr data.zap_table('AN', 1)
from Wizardry.AIPSData import AIPSUVData as WizAIPSUVData from AIPSTV import AIPSTV ############################################### # Starting up AIPS ############################ ############################################### # aips_out = OP.aips_out + '/' sys.stdout.write( 'Will write AIPS messages to file \n{0} \n and task inputs to file \n{1}\n' .format(OP.aipslog, OP.tasklog)) AIPS.log = open(OP.aipslog, 'a') # AIPS.userno = OP.aipsid sys.stdout.write('Printing AIPSCat.\n') print AIPSCat(OP.outdisk) #list the catalogs on the desired disk #raw_input('Press Enter to continue if you are happy with what you see ...') # #logfile.close() ############################################### # Calibration start ########################### ############################################### if OP.load_data: if len(OP.uvrawdatafile) > 1: for files in OP.uvrawdatafile: uvdata_catalog = AT.loadata(files, OP.outname, OP.outclass, OP.outdisk, OP.outseq, clint=OP.cl_table_interval,
def findexisting(inna, incl, indisk=1): isseq = 0 for i in AIPSCat()[indisk]: if i['name'] == inna and i['klass'] == incl: isseq = max(isseq, i['seq']) return isseq
from AIPS import AIPS from AIPSTask import AIPSTask from AIPSData import AIPSCat, AIPSImage AIPS.userno = 1999 print(AIPSCat(1)) image = AIPSImage('MANDELBROT', 'MANDL', 1, 1) if image.exists(): image.zap() pass try: mandl = AIPSTask('mandl') mandl.outdata = image mandl.imsize[1:] = [512, 512] mandl.go() mandl.outclass = 'TEMP' mandl.go() print(AIPSCat(1)) try: AIPSCat(1).zap(klaas='TEMP') except TypeError: pass else: raise AssertionError
# delete FR606 if we are between L264200 and L266700 fring_antennas = list(all_antennas) # copy list try: intaipsname = int(aipsname[1:]) if 264200 < intaipsname < 266700: fring_antennas.remove('FR606') except: pass ########################################################### obs = dict() obs['obsnum'] = aipsname if os.path.isfile(logdir + aipsname + '.log'): os.system('rm ' + logdir + aipsname + '.log') print time.ctime( ), ':Processing ', fi, ' with AIPS catalogue name', aipsname pca = AIPSCat() try: for j in pca[indisk]: if j['name'] == aipsname and j['klass'] == 'FITS': uvdata = AIPSUVData(aipsname, 'FITS', indisk, j['seq']) uvdata.zap() if j['klass'] == 'SPLIT': uvdata = AIPSUVData(j['name'], 'SPLIT', indisk, j['seq']) uvdata.zap() except: pass #print ('***',fi,aipsname,indisk,logdir) pload(fi, aipsname, indisk, 'FITS', logdir) uvdata = AIPSUVData(aipsname, 'FITS', indisk, 1)
# Check for an inputs file if len(sys.argv) == 2: print "Using inputs specified in", sys.argv[1] afile = sys.argv[1] if os.path.isfile(afile): control = parse_inp(afile) else: print "Error:" + afile + "does not exist, quitting." sys.exit() else: print "Error: no parameter file specified, quitting." print "Usage: parseltongue pipeline.py inputs.txt" sys.exit() checkin(control) pca = AIPSCat(indisk) AIPSTask.msgkill = msgkill def findmaxb(uvdata): maxbaseline = 0 antab = uvdata.table('AN', 1) for row in antab: for row2 in antab: xsep = row.stabxyz[0] - row2.stabxyz[0] ysep = row.stabxyz[1] - row2.stabxyz[1] zsep = row.stabxyz[2] - row2.stabxyz[2] hypxy = math.sqrt((xsep * xsep) + (ysep * ysep)) hypxyz = math.sqrt((zsep * zsep) + (hypxy * hypxy)) if hypxyz > maxbaseline: maxbaseline = hypxyz
def plot_sn(user='', entry='', disk=1, chosen_station=[''], FQ=1, AN=1, SN=[0], keep=False): # exit if some conditions are not adhered to ----------------------------------- if entry == '': print('The catalogue entry of the data is required.') return if user == '': print('The AIPS number of the user is required.') return if len(SN) > 7: print('Too many SN were specified.') return # retrieve the data ------------------------------------------------------------ AIPS.userno = user name = AIPSCat()[disk][entry]['name'] klass = AIPSCat()[disk][entry]['klass'] seq = AIPSCat()[disk][entry]['seq'] indata = AIPSUVData(name, klass, disk, seq) # pull the frequencies of the subbands from the frequency extension table ------ fq = indata.table('FQ', FQ) crval = indata.header['crval'][2] nif = len(np.atleast_1d(fq[0]['if_freq'])) frequencies = np.atleast_1d(fq[0]['if_freq']) + crval # pull the list of stations from the antenna extension ------------------------- an = indata.table('AN', AN) antennas = [] stations = [] for antenna in an: antennas.append(antenna['nosta']) stations.append(antenna['anname'].strip('HBA').strip('LBA')) if chosen_station != ['']: print('This feature does not work yet.') # stations = chosen_station # chosen_joined = ', '.join(chosen_station) # if len(chosen_station) == 1: # print('The selected stations is ' + chosen_joined + '.') # else: # print('The selected stations are ' + chosen_joined + '.') else: print('Data for all stations are being plotted.') # pull information from the solution table and save to a text a file ----------- sn_string = '' sn_data = name + '_SN.txt' if os.path.exists(sn_data): os.remove(sn_data) print('The old ' + sn_data + ' file was deleted.') print('The data are being written to ' + sn_data + '.') for k in SN: sn = indata.table('SN', k) sn_string += '-' + str(k) # lines 87 to 93 were taken from a script by L Morabito ------------------------ with open(sn_data, 'a+') as f: for i in sn: if nif == 1: f.write( '%s\t%.2f\t%.16f\t%i\t%s\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\n' % (k, frequencies[0], i['time'], i['antenna_no'], stations[i['antenna_no'] - 1], i['delay_1'], i['delay_2'], i['weight_1'], i['weight_2'], i['rate_1'], i['rate_2'], np.arctan2(i['imag1'], i['real1']), np.arctan2(i['imag2'], i['real2']))) else: for j in range(nif): f.write( '%s\t%.2f\t%.16f\t%i\t%s\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\t%.16f\n' % (k, frequencies[j], i['time'], i['antenna_no'], stations[i['antenna_no'] - 1], i['delay_1'][j], i['delay_2'][j], i['weight_1'][j], i['weight_2'][j], i['rate_1'][j], i['rate_2'][j], np.arctan2(i['imag1'][j], i['real1'][j]), np.arctan2(i['imag2'][j], i['real2'][j]))) # load in the solution table data from the text file --------------------------- solution, f, t, antenna, p0, p1 = np.genfromtxt(sn_data, usecols=(0, 1, 2, 4, 5, 6), dtype=str, unpack=True) frequency, time, pol0, pol1, pdfs = [], [], [], [], [] colors = ['r', 'b', 'g', 'c', 'm', 'y', 'k'] total_clipped = 0 for i in range(len(t)): frequency.append(float(f[i])) time.append(float(t[i])) pol0.append(float(p0[i])) pol1.append(float(p1[i])) # loop through the stations with a new plot for each one ----------------------- for s in stations: station = s.strip(' ') plt.figure(figsize=(10, 8)) plt.title('Polarisation 0 at ' + str(int(frequency[1] * 1e-6)) + ' MHz for ' + station) plt.xticks([]) plt.xlabel('Time') plt.ylabel('Delay (ns)') q = -1 clipped = 0 # plot the data for each solution table ---------------------------------------- for k in SN: station_time, station_pol0, station_pol1 = [], [], [] q += 1 # data clipped in AIPS appears on my plot with value of 3140.892822265625 ------ for i in range(len(time)): if solution[i] == str(k) and frequency[i] == frequency[ 1] and antenna[i] == station: station_time.append(time[i]) if pol0[i] == 3140.892822265625 and i > 0: station_pol0.append(station_pol0[len(station_pol0) - 1]) total_clipped += 1 clipped += 1 elif pol0[i] == 3140.892822265625 and i == 0: station_pol0.append(0) total_clipped += 1 clipped += 1 else: station_pol0.append(pol0[i] * 1e9) # actually do the plotting and save the plots when they are all done ----------- plt.plot(station_time, station_pol0, linewidth=1, marker=None, color=colors[q], label='SN ' + str(k)) print( str(clipped) + ' points were clipped from SN ' + str(k) + ' for station ' + station + '.') plt.legend(loc=1) plt.savefig(station + '-SN.pdf', bbox_inches='tight', format='pdf') pdfs.append(station + '-SN.pdf') plt.close() print(str(total_clipped) + ' points were clipped in total.\n') # join the saved plots into one PDF -------------------------------------------- inputs = ' '.join(pdfs) output = name + '-SN' + sn_string + '.pdf' print('The transfer is being commenced.') make = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dQUIET -dBATCH -dDetectDuplicateImages -dCompressFonts=true -r150 -sOutputFile=" + output + ' ' + inputs os.system(make) # upload the PDF to transfer.sh ------------------------------------------------ upload = name + '-SN' + sn_string + '-upload.txt' transfer = 'curl --upload-file ' + output + ' https://transfer.sh/' + output + ' > ' + upload os.system(transfer) line = linecache.getline(upload, 1).rstrip('\n') print('\nPaste this into the terminal to retrieve the file:\n') print('curl ' + line + ' -o ' + output + '; xdg-open ' + output + '\n') # delete the working files ----------------------------------------------------- if keep == False: for pdf in pdfs: os.remove(pdf) os.remove(sn_data) os.remove(upload) print('The working files were deleted.') else: print('The working files were not deleted.')
from AIPS import AIPS #, AIPSDisk # I am not sure if I need AIPSDisk from AIPSTask import AIPSTask #, AIPSList from AIPSData import AIPSUVData, AIPSImage, AIPSCat from Wizardry.AIPSData import AIPSUVData as WizAIPSUVData from AIPSTV import AIPSTV logger.info('Will use local AIPS installation') aips_out = local_dir + 'aips_out/' #All outputs from AIPS (Plots, text-files) will be saved there if not os.path.isdir(aips_out): os.makedirs(aips_out) AIPS.log = open(aipslog, 'a') # AIPS.userno = aipsid sys.stdout.write('Printing AIPSCat.\n') print AIPSCat(outdisk) #list the catalogs on the desired disk ############################################### # SLICE analysis start ########################### ############################################### for ff in glob('*.txt'): os.remove(ff) for ff in glob('*.dat'): os.remove(ff) jj = 0 for ii in angles: if jj == 0: angstep = True else: angstep = False
def cal_aips2casa(userno, disk, cno, inver, ms_name, cal_base, caltype="CL", antfile=None): AIPS.userno = userno ant_aips2ms = AntMapping(antfile) do_band = caltype == 'BP' do_calib = not do_band # Select dataset and table ds = [i for i in AIPSCat()[disk] if i['cno'] == cno][0] uv = wiz.AIPSUVData(ds['name'], ds['klass'], disk, ds['seq']) obs_date = datetime.datetime( *[int(i) for i in uv.header.date_obs.split('-')]) print AIPSUVData(uv), '%s%d' % (caltype, inver), '->', ms_name, cal_base cal_aips = uv.table(caltype, inver) pols = cal_aips.keywords['NO_POL'] ifs = cal_aips.keywords['NO_IF'] # AIPS IF / Casa SPW if do_band: chans = cal_aips.keywords['NO_CHAN'] else: chans = 1 prgs = Progress(len(cal_aips)) sys.stdout.write('Reading %s table\n' % caltype) sys.stdout.flush() # Holds all table data as a multi-level dict indexed by time, antenna, # IF, mode. Where mode is one of 'common', 'sbdelay', 'mbdelay'. Format # is the same as in the final Table. Casa requires a fairly regular # table with rows present for all antennas, and IFs. cals = {} for i in range(len(cal_aips)): prgs.update(i) # Progress bar sol_time = obs_date + datetime.timedelta(float(cal_aips[i]['time'])) time_unix = calendar.timegm(sol_time.timetuple()) time_casa = time_unix + mod_jul_day if time_casa not in cals: cals[time_casa] = {} if do_band: time_interval = cal_aips[i]['interval'] else: time_interval = cal_aips[i]['time_interval'] time_interval *= 24 * 60 * 60 # Convert days to seconds field_id = cal_aips[i]['source_id'] - 1 try: if do_band: antenna1 = ant_aips2ms(cal_aips[i]['antenna']) else: antenna1 = ant_aips2ms(cal_aips[i]['antenna_no']) except KeyError: # Ignore antennas not present in MS continue if antenna1 not in cals[time_casa]: cals[time_casa][antenna1] = {} for iif in range(ifs): if not iif in cals[time_casa][antenna1]: cals[time_casa][antenna1][iif] = {} row = iif * len(cal_aips) + i gain = numpy.ones(shape=(chans, pols), dtype='complex64') mbdelay = numpy.ones(shape=(chans, pols), dtype='complex64') sbdelay = numpy.ones(shape=(chans, pols), dtype='complex64') snr = numpy.ones(shape=(chans, pols), dtype='float32') for p in range(pols): if do_band: gain[:, p].real = cal_aips[i]['real_%d' % (p + 1)][iif * chans:(iif + 1) * chans] gain[:, p].imag = cal_aips[i]['imag_%d' % (p + 1)][iif * chans:(iif + 1) * chans] if ifs == 1: if do_calib: gain[:, p] = cal_aips[i][ 'real%d' % (p + 1)] + 1j * cal_aips[i]['imag%d' % (p + 1)] sbdelay[:, p] = cal_aips[i][ 'delay_%d' % (p + 1)] * 1e9 # convert to nano-seconds snr[:, p] = cal_aips[i]['weight_%d' % (p + 1)] else: if do_calib: gain[:, p] = cal_aips[i][ 'real%d' % (p + 1)][iif] + 1j * cal_aips[i]['imag%d' % (p + 1)][iif] sbdelay[:, p] = cal_aips[i][ 'delay_%d' % (p + 1)][iif] * 1e9 # convert to nano-seconds snr[:, p] = cal_aips[i]['weight_%d' % (p + 1)][iif] if do_calib: mbdelay[:, p] = cal_aips[i][ 'mbdelay%d' % (p + 1)] * 1e9 # convert to nano-seconds zero_wt = numpy.logical_not(numpy.array(snr, dtype='bool')) # AIPS seems to use 3140 to indicate a bad solution flag_val = numpy.logical_and( numpy.array(gain.real, dtype='int') == 3140, numpy.array(gain.imag, dtype='int') == 3140) flag = numpy.logical_or(zero_wt, flag_val) soln_ok = numpy.logical_not(flag) cals[time_casa][antenna1][iif]['common'] = { 'TIME': time_casa, 'INTERVAL': time_interval, 'SNR': snr, 'ANTENNA1': antenna1, 'CAL_DESC_ID': iif, 'FIELD_ID': field_id, 'SOLUTION_OK': soln_ok, 'FLAG': flag } cals[time_casa][antenna1][iif]['gain'] = {'GAIN': gain} cals[time_casa][antenna1][iif]['mbdelay'] = {'GAIN': mbdelay} cals[time_casa][antenna1][iif]['sbdelay'] = {'GAIN': sbdelay} prgs.done() if do_band: cal_type_list = ['bcal'] else: cal_type_list = ['gcal', 'mbdcal', 'sbdcal'] for cal_type in cal_type_list: cal_table = cal_base + '.' + cal_type shutil.copytree('empty.' + cal_type, cal_table) # Copy empty template table # Make an CAL_DESC entry for each AIPS IF cal_desc_defs = { 'NUM_SPW': 1, 'NUM_CHAN': numpy.ones(shape=(chans, ), dtype='int32'), 'NUM_RECEPTORS': pols, 'N_JONES': 2, 'CHAN_FREQ': numpy.zeros(shape=(chans, 1), dtype='float64'), 'MEAS_FREQ_REF': 0, 'CHAN_WIDTH': numpy.zeros(shape=(chans, 1), dtype='float64'), 'CHAN_RANGE': numpy.zeros(shape=(chans, 1, 2), dtype='int32'), 'POLARIZATION_TYPE': { 'shape': [chans, 1], 'array': chans * [''] }, 'JONES_TYPE': 'full', 'MS_NAME': os.path.basename(ms_name) } cal_desc = table(cal_table + '/CAL_DESC', ack=False, readonly=False) cal_desc.addrows(ifs) for i in range(ifs): cal_desc[i] = cal_desc_defs cal_desc[i] = { 'SPECTRAL_WINDOW_ID': numpy.array((i, ), dtype='int32') } cal_desc[i].update() cal_desc.close() # Make the CAL_MAIN table defs = { 'TOTAL_SOLUTION_OK': True, 'TOTAL_FIT_WEIGHT': 1.0, 'TOTAL_FIT': 1.0, 'FIT': numpy.ones(shape=(chans, 1), dtype='float32'), 'FIT_WEIGHT': numpy.ones(shape=(chans, 1), dtype='float32') } defs_bad = { 'SOLUTION_OK': numpy.zeros(shape=(chans, pols), dtype='bool'), 'FLAG': numpy.ones(shape=(chans, pols), dtype='bool'), 'GAIN': numpy.ones(shape=(chans, pols), dtype='complex64'), 'SNR': numpy.zeros(shape=(chans, pols), dtype='float32') } ms_ant = table(ms_name + '/ANTENNA', ack=False) ms_num_ants = len(ms_ant) ms_ant.close() # Open table and create required number of rows if do_band: bcal = table(cal_base + '.bcal', ack=False, readonly=False) bcal.addrows(ms_num_ants * len(cals) * ifs) tb_cals = [bcal] else: gcal = table(cal_base + '.gcal', ack=False, readonly=False) gcal.addrows(ms_num_ants * len(cals) * ifs) mbdcal = table(cal_base + '.mbdcal', ack=False, readonly=False) mbdcal.addrows(ms_num_ants * len(cals) * ifs) sbdcal = table(cal_base + '.sbdcal', ack=False, readonly=False) sbdcal.addrows(ms_num_ants * len(cals) * ifs) tb_cals = [gcal, mbdcal, sbdcal] def update_row(tb, row, *vals): for val in vals: tb[row] = val tb[row].update() timestamps = cals.keys() timestamps.sort() i = 0 prgs = Progress(len(tb_cals[0])) print 'Writing cal tables' for iif in range(ifs): for ts in timestamps: for ant in range(ms_num_ants): try: c_common = cals[ts][ant][iif]['common'] c_gain = cals[ts][ant][iif]['gain'] if do_calib: c_mbdelay = cals[ts][ant][iif]['mbdelay'] c_sbdelay = cals[ts][ant][iif]['sbdelay'] defs2 = {} except KeyError: # If a solution does not exist for this ant/IF # create an standard one and mark it as bad. # Use another solution as a base. dummy_ant = cals[ts].keys()[0] dummy_if = cals[ts][dummy_ant].keys()[0] c_common = cals[ts][dummy_ant][dummy_if]['common'] c_gain = cals[ts][dummy_ant][dummy_if]['gain'] if do_calib: c_mbdelay = cals[ts][dummy_ant][dummy_if]['mbdelay'] c_sbdelay = cals[ts][dummy_ant][dummy_if]['sbdelay'] c_common['ANTENNA1'] = ant c_common['CAL_DESC_ID'] = iif defs2 = defs_bad if do_band: update_row(tb_cals[0], i, c_common, c_gain, defs, defs2) else: update_row(tb_cals[0], i, c_common, c_gain, defs, defs2) update_row(tb_cals[1], i, c_common, c_mbdelay, defs, defs2) update_row(tb_cals[2], i, c_common, c_sbdelay, defs, defs2) i += 1 prgs.update(i) prgs.done()
from AIPS import AIPS from AIPSTask import AIPSTask from AIPSData import AIPSCat, AIPSImage AIPS.userno = 1999 print AIPSCat(1) image = AIPSImage('MANDELBROT', 'MANDL', 1, 1) if image.exists(): image.zap() pass try: mandl = AIPSTask('mandl') mandl.outdata = image mandl.imsize[1:] = [512, 512] mandl.go() mandl.outclass = 'TEMP' mandl.go() print AIPSCat(1) try: AIPSCat(1).zap(klaas='TEMP') except TypeError: pass else: raise AssertionError