def UVAddSource(inUV, outUV, err): """ Add a Source table to a UV data Source information is derived from the UV descriptor and a Source random parameter added if needed. * inUV = input Obit UV object * outUV = output Obit UV object, defined but not instantiated Onlyt really works for AIPS * err = Obit error/message stack """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError, "inUV MUST be a Python Obit UV" if not UV.PIsA(outUV): raise TypeError, "outUV MUST be a defined Python Obit UV" # Patch UV Descriptor DescAddSource(inUV, outUV, err) OErr.printErrMsg(err, "Error updating Descriptor") CreateSU(inUV, outUV, err) OErr.printErrMsg(err, "Error creating SU Table") # Copy data CopyData(inUV, outUV, err) # Update # outUV.UpdateDesc(err) outUV.Header(err) # show results OErr.printErrMsg(err, "Error copying")
def PCVel (inUV, outUV, RestFreq, err, scratch=False, \ VLSR=0.0, refDate="0000-00-00", refChan=-9999.): """ Doppler correct a UV data set inUV = Input UV data, any calibration/editing/selection parameters should be entered on the List member. outUV = Output UV data, should be defined but not instantiated if not scratch RestFreq = Rest Frequency (GHz) err = Obit error/message object scratch = True if output a scratch file (destroyed on object deletion) VLSR = desired center LSR velocity (km/s) refDate = reference date for reference channel as 'yyyy-mm-dd' defaults to observation date. refChan = reference channel (-9999=> compute) """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError, "inUV MUST be a Python ObitUV" if not UV.PIsA(outUV): raise TypeError, "outUV MUST be a Python ObitUV" # if scratch: lscratch = 1 else: lscratch = 0 # set parameters info = inUV.List info.set("RestFreq", RestFreq * 1.0e9, ttype="double") info.set("VelLSR", VLSR * 1000) info.set("JDref", UVDesc.PDate2JD(refDate), ttype="double") info.set("refChan", refChan) # Correct data Obit.DopplerCVel(inUV.me, lscratch, outUV.me, err.me)
def imhead (ObitObj): """ List header ObitObj = Obit or ParselTongue data object """ ################################################################ if ObitObj.__class__==AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",ObitObj.name, ObitObj.klass, ObitObj.disk, \ ObitObj.seq, True, err) tmp.Header(err) del tmp elif ObitObj.__class__==FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image",ObitObj.filename, ObitObj.disk, True, err) tmp.Header(err) del tmp elif ObitObj.__class__==AIPSData.AIPSUVData: # AIPS UVData tmp = UV.newPAImage("AIPS UVData",ObitObj.name, ObitObj.klass, ObitObj.disk, \ ObitObj.seq, True, err) tmp.Header(err) del tmp elif ObitObj.__class__==FITSData.FITSUVData: # FITS UVData tmp = UV.newPFImage("FITS UVData",ObitObj.filename, ObitObj.disk, True, err) tmp.Header(err) del tmp else: # Presume it's an Obit object ObitObj.Header(err)
def imhead(ObitObj): """ List header * ObitObj = Obit or ParselTongue data object """ ################################################################ if ObitObj.__class__ == AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",ObitObj.name, ObitObj.klass, ObitObj.disk, \ ObitObj.seq, True, err) tmp.Header(err) del tmp elif ObitObj.__class__ == FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image", ObitObj.filename, ObitObj.disk, True, err) tmp.Header(err) del tmp elif ObitObj.__class__ == AIPSData.AIPSUVData: # AIPS UVData tmp = UV.newPAImage("AIPS UVData",ObitObj.name, ObitObj.klass, ObitObj.disk, \ ObitObj.seq, True, err) tmp.Header(err) del tmp elif ObitObj.__class__ == FITSData.FITSUVData: # FITS UVData tmp = UV.newPFImage("FITS UVData", ObitObj.filename, ObitObj.disk, True, err) tmp.Header(err) del tmp else: # Presume it's an Obit object ObitObj.Header(err)
def VLAUVLoad(filename, inDisk, Aname, Aclass, Adisk, Aseq, err, logfile=''): """ Read FITS uvtab file into AIPS Read a UVTAB FITS UV data file and write an AIPS data set filename = name of FITS file inDisk = FITS directory number Aname = AIPS name of file Aclass = AIPS class of file Aseq = AIPS sequence number of file, 0=> create new Adisk = FITS directory number err = Python Obit Error/message stack logfile = logfile for messages returns AIPS UV data object """ ################################################################ # # Checks if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # # Get input inUV = UV.newPFUV("FITS UV DATA", filename, inDisk, True, err) if err.isErr: OErr.printErrMsg(err, "Error with FITS data") # Get output, create new if seq=0 if Aseq<1: OErr.printErr(err) # Print any outstanding messages user = OSystem.PGetAIPSuser() Aseq=AIPSDir.PHiSeq(Adisk,user,Aname,Aclass,"MA",err) # If it already exists, increment seq if AIPSDir.PTestCNO(Adisk,user,Aname,Aclass,"MA",Aseq,err)>0: Aseq = Aseq+1 OErr.PClear(err) # Clear any message/error mess = "Creating AIPS UV file "+Aname+"."+Aclass+"."+str(Aseq)+" on disk "+str(Adisk) printMess(mess, logfile) outUV = UV.newPAUV("AIPS UV DATA", Aname, Aclass, Adisk, Aseq, False, err) if err.isErr: OErr.printErrMsg(err, "Error creating AIPS data") # Copy UV.PCopy (inUV, outUV, err) if err.isErr: OErr.printErrMsg(err, "Error copying UV data to AIPS") # Copy History inHistory = History.History("inhistory", inUV.List, err) outHistory = History.History("outhistory", outUV.List, err) History.PCopyHeader(inHistory, outHistory, err) # Add history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit uvlod",err) outHistory.WriteRec(-1,"uvlod / FITS file "+filename+" disk "+str(inDisk),err) outHistory.Close(err) # # Copy Tables exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL", "History"] include=[] UV.PCopyTables (inUV, outUV, exclude, include, err) return outUV # return new object
def VLAUVFITS(inUV, filename, outDisk, err, compress=False, \ exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \ include=[], headHi=False): """ Write UV data as FITS file Write a UV data set as a FITAB format file History written to header inUV = UV data to copy filename = name of FITS file inDisk = FITS directory number err = Python Obit Error/message stack exclude = List of table types NOT to copy NB: "AIPS HI" isn't really a table and gets copied anyway include = List of table types to copy (FQ, AN always done ) Exclude has presidence over include headHi = if True move history to header, else leave in History table returns FITS UV data object """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError, "inUV MUST be a Python Obit UV" if not OErr.OErrIsA(err): raise TypeError, "err MUST be an OErr" # # Set output outUV = UV.newPFUV("FITS UV DATA", filename, outDisk, False, err) if err.isErr: OErr.printErrMsg(err, "Error creating FITS data") #Compressed? if compress: inInfo = UV.PGetList(outUV) # dim = [1, 1, 1, 1, 1] InfoList.PAlwaysPutBoolean(inInfo, "Compress", dim, [True]) # Copy UV.PCopy(inUV, outUV, err) if err.isErr: OErr.printErrMsg(err, "Error copying UV data to FITS") # History inHistory = History.History("inhistory", outUV.List, err) outHistory = History.History("outhistory", outUV.List, err) # Add history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit uvtab", err) outHistory.WriteRec( -1, "uvtab / FITS file " + filename + " disk " + str(outDisk), err) outHistory.Close(err) # History in header? if headHi: History.PCopy2Header(inHistory, outHistory, err) OErr.printErrMsg(err, "Error with history") # zap table outHistory.Zap(err) # Copy Tables UV.PCopyTables(inUV, outUV, exclude, include, err) return outUV # return new object
def UVMakeIF(outUV, nIF, err, solInt=10.): """ Change number of IFs from 1 to nIF Operation done in place * outUV = output Obit UV object Only really works for AIPS * nIF = number of desired output IFs MUST be the same number of channels per IF * err = Obit error/message stack * solInt = Solution interval for remade CL table. """ ################################################################ # Checks if not UV.PIsA(outUV): raise TypeError("outUV MUST be a defined Python Obit UV") # Input can have 1 or no IFs defined jlocif = outUV.Desc.Dict["jlocif"] if jlocif >= 0 and outUV.Desc.Dict["inaxes"][jlocif] > 1: raise RuntimeError("Input UV has excessive IFs already:" \ +str(outUV.Desc.Dict["inaxes"][jlocif])) # Check number of requested IFs if nIF < 2: raise RuntimeError("Too few output IFs requested: " + str(nIF)) # Must be an even number of channels per output IF jlocf = outUV.Desc.Dict["jlocf"] nchan = outUV.Desc.Dict["inaxes"][jlocf] if (nchan % nIF) != 0: raise RuntimeError("Unequal numbers of channels per " + str(nIF) + " IFs") # Patch UV Descriptor DescMakeIF(outUV, nIF, err) # Convert FQ Table UpdateFQ2(outUV, nIF, err) # Convert AN Table maxant = UpdateAN2(outUV, nIF, err) # Convert SU Table UpdateSU2(outUV, nIF, err) # Regenerate CL table 1 - delete any old outUV.ZapTable("AIPS CL", -1, err) print('(Re) generate CL table') UV.PTableCLfromNX(outUV, maxant, err, calInt=solInt) # dummy FG 1 print('Dummy entry in Flag table 1') UV.PFlag(outUV, err, timeRange=[-10., -9.], Ants=[200, 200], Stokes='0000', Reason='Dummy') # Update outUV.UpdateDesc(err) OErr.printErrMsg(err, "Error updating output")
def CompareUV(uvFile1, uvFile2, err, verbose=True): """ Compare UV FITS files *uvFile1* and *uvFile2*. * uvFile1, uvFile2 = UV FITS files to be compared * err = OErr object """ uv1 = UV.newPFUV('uv1', uvFile1, 0, True, err) uv2 = UV.newPFUV('uv2', uvFile2, 0, True, err) rms = UV.PUtilVisCompare(uv1, uv2, err) if verbose: print("UV data set 1: " + uvFile1) print("UV data set 2: " + uvFile2) print("RMS of real, imag differences / amplitude of data set 2 =\n%6i" % (rms))
def PCreate(name, inUV, residUV, outUV, input=RFIXizeInput): """ Create the parameters and underlying structures of a UVRFIXize. Returns UVRFIXize created. name = Name to be given to object Most control parameters are in InfoList member inUV = Input Python uv data to be corrected residUV = Input Python residual uv data outUV = Output Python uv data to be written err = Python Obit Error/message stack input = control parameters: solInt = Counter rotated SN table interval [def 1 min] doInvert = If True invert solution [def False] timeInt = Data integration time in sec [def 10 sec] timeAvg = Time interval (min) over which to average residual. minRot = Min. fringe rotation (turns) in an integration, data with smaller values flagged if > minRFI Only reduce this if a very good model has been subtracted to make the residual data. maxRot = Max. fringe rotation (turns) in an integration to estimate RFI minRFI = Minimum RFI amplitude to subtract """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError("inUV MUST be a Python Obit UV") if not UV.PIsA(residUV): raise TypeError("residUV MUST be a Python Obit UV") if not UV.PIsA(outUV): raise TypeError("outUV MUST be a Python Obit UV") # # Create out = UVRFIXize(name) out.me = Obit.UVRFIXizeCreate(name, inUV.me, residUV.me, outUV.me) # Set RFIXize control values on out inInfo = PGetList(out) # dim = [1, 1, 1, 1, 1] # Set control values on RFIXize InfoList.PAlwaysPutFloat(inInfo, "solInt", dim, [input["solInt"]]) InfoList.PAlwaysPutBoolean(inInfo, "doInvert", dim, [input["doInvert"]]) InfoList.PAlwaysPutFloat(inInfo, "timeInt", dim, [input["timeInt"]]) InfoList.PAlwaysPutFloat(inInfo, "timeAvg", dim, [input["timeAvg"]]) InfoList.PAlwaysPutFloat(inInfo, "minRFI", dim, [input["minRFI"]]) InfoList.PAlwaysPutFloat(inInfo, "minRot", dim, [input["minRot"]]) InfoList.PAlwaysPutFloat(inInfo, "maxRot", dim, [input["maxRot"]]) # return out
def PMakeImage(inUV, outImage, channel, doBeam, doWeight, err): """ Grids UV, FFTs and makes corrections for the gridding convolution. * inUV = Input Python uv data. Should be in form of Stokes to be imaged will all calibration and selection applied. * outImage = Python Image to be written. Must be previously instantiated. Beam normalization factor is written to output Beam infoList as SUMWTS * channel = Which frequency channel to image, 0->all. * doBeam = if TRUE also make beam. Will make the myBeam member of outImage. If FALSE, and myGrid->BeamNorm 0.0 then reads SUMWTS value from beam infolist * doWeigh = if TRUE Apply uniform weighting corrections to uvdata before imaging * err = Python Obit Error/message stack """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError("inUV MUST be a Python Obit UV") if not Image.PIsA(outImage): print("Actually ", outImage.__class__) raise TypeError("outImage MUST be a Python Obit Image") if not err.IsA(): raise TypeError("err MUST be an OErr") # Obit.ImageUtilMakeImage(inUV.me, outImage.me, channel, doBeam, doWeight, err.me) if err.isErr: OErr.printErrMsg(err, "Error creating Image from UV data")
def getname(cno, disk=Adisk): """ Return Obit object for AIPS file in cno on disk cno = AIPS catalog slot number disk = AIPS disk number """ ################################################################ Adisk = disk user = AIPS.AIPS.userno s = AIPSDir.PInfo(disk, user, cno, err) OErr.printErrMsg(err, "Error with AIPS catalog") # parse returned string Aname = s[0:12] Aclass = s[13:19] Aseq = int(s[20:25]) Atype = s[26:28] if Atype == 'MA': out = Image.newPAImage("AIPS image", Aname, Aclass, disk, Aseq, True, err) print "AIPS Image",Aname, Aclass, disk, Aseq elif Atype == 'UV': out = UV.newPAUV("AIPS UV data", Aname, Aclass, disk, Aseq, True, err) print "AIPS UV",Aname, Aclass, disk, Aseq out.Aname = Aname out.Aclass = Aclass out.Aseq = Aseq out.Atype = Atype out.Disk = disk out.Acno = cno return out
def getname(cno, disk=Adisk): """ Return Obit object for AIPS file in cno on disk * cno = AIPS catalog slot number * disk = AIPS disk number """ ################################################################ Adisk = disk user = AIPS.AIPS.userno s = AIPSDir.PInfo(disk, user, cno, err) OErr.printErrMsg(err, "Error with AIPS catalog") # parse returned string Aname = s[0:12] Aclass = s[13:19] Aseq = int(s[20:25]) Atype = s[26:28] if Atype == 'MA': out = Image.newPAImage("AIPS image", Aname, Aclass, disk, Aseq, True, err) print("AIPS Image", Aname, Aclass, disk, Aseq) elif Atype == 'UV': out = UV.newPAUV("AIPS UV data", Aname, Aclass, disk, Aseq, True, err) print("AIPS UV", Aname, Aclass, disk, Aseq) out.Aname = Aname out.Aclass = Aclass out.Aseq = Aseq out.Atype = Atype out.Disk = disk out.Acno = cno return out
def PReimage (inCleanVis, uvdata, err): """ See if an image needs to be remade See if an image needs to be remade because a source which exceeds the flux threshold is not centered (as determined by moments) on the reference pixel (within toler pixel). A new (96x96) field is added centered on the offending source and a negative clean window added to the position of the source in its original window. Avoid duplicates of the same source and ensure that all occurances of this source in any exant field has a negative clean window added. Multiple centering sources per facet are allowed A boolean entry "autoCenField" with value True is added to the info member of any image members added to the mosaic member. * inCleanVis = Python CleanVis object * uvdata = Python uv data from which image is made * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inCleanVis): raise TypeError,"inCleanVis MUST be a Python ObitCleanVis" if not UV.PIsA(uvdata): raise TypeError,"uvData MUST be a Python Obit UV" # out = Obit.CleanVisReimage(inCleanVis.me, uvdata.me, err.me) if err.isErr: OErr.printErrMsg(err, "Error in Reimage") return out
def PIoN2SolNTableConvert(inUV, outSNVer, NITable, pos, err): """ Evaluate Ionospheric model table at pos and convert to SN table Returns resultant SN table * inUV = UV data for output SN table. Control parameters on inUV info member: ========== ================ ================================ "doAntOff" OBIT_bool scalar True if correctionss for antenna offset from array center wanted [def False] ========== ================ ================================ * outSNVer = Desired output SN table version, 0=> new * NITable = Ionospheric model table to evaluate * pos = [RA, Dec] shift (deg) in which NITable to be evaluated. * err = Obit Error stack, returns if not empty. """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError('PIoN2SolNTableConvert: Bad input UV data') if not Table.PIsA(NITable): raise TypeError('PIoN2SolNTableConvert: Bad NI input table') # Create output SN table object outSNTable = Table.Table("None") # Evaluate outSNTable.me = Obit.IoN2SolNTableConvert (inUV.me, outSNVer, \ NITable.me, pos, err.me) if err.isErr: OErr.printErrMsg(err, "Error Converting NI to SN table") return outSNTable
def VLAUVLoadT(filename, disk, Aname, Aclass, Adisk, Aseq, err, \ Compress=False): """ Read FITS file into AIPS Read input uvtab FITS file, write AIPS Returns Obit uv object Filename = input FITS uvtab format file disk = input FITS file disk number Aname = output AIPS file name Aclass = output AIPS file class Adisk = output AIPS file disk Aseq = output AIPS file sequence err = Obit error/message stack Compress = Write AIPS data in compressed form? """ ################################################################ # uvc = ObitTask.ObitTask("UVCopy") uvc.DataType = "FITS" uvc.inFile = filename uvc.inDisk = disk uvc.outDType = "AIPS" uvc.outName = Aname uvc.outClass = Aclass uvc.outSeq = Aseq uvc.outDisk = Adisk uvc.Compress = Compress uvc.g # Get output outuv = UV.newPAUV("UVdata", Aname, Aclass, Adisk, Aseq, True, err) return outuv
def DescMakeIF(outUV, nIF, err): """ Convert outUV descriptor divided into nIF IFs * outUV = output Obit UV object * nIF = number of desired output IFs MUST be the same number of channels per IF * err = Obit error/message stack """ ################################################################ d = outUV.Desc.Dict # Have IF axis? if d["jlocif"] >= 0: jlocif = d["jlocif"] else: # create one jlocif = d['naxis'] d['naxis'] += 1 d['ctype'][jlocif] = "IF" d['crval'][jlocif] = 1.0 d['crpix'][jlocif] = 1.0 d['cdelt'][jlocif] = 1.0 d['crota'][jlocif] = 0.0 jlocf = d["jlocf"] nchan = d["inaxes"][jlocf] / nIF d["inaxes"][jlocif] = nIF d["inaxes"][jlocf] = nchan outUV.Desc.Dict = d UV.PGetIODesc(outUV).Dict = d # And your little dog too # Update outUV.UpdateDesc(err) outUV.Open(UV.WRITEONLY, err) outUV.Close(err) #outUV.Header(err) OErr.printErrMsg(err, "Error converting Descriptor")
def __init__(self, name, klass, disk, seq): self._err = OErr.OErr() OSystem.PSetAIPSuser(AIPS.userno) self._data = UV.newPAUV(name, name, klass, disk, seq, True, self._err) if self._err.isErr: raise RuntimeError return
def IDIFix(uv, err): """ Fix VLBA data loaded from IDI files. * uv = UV data set to be sorted * err = OErr object Returns the corrected UV data object. """ # Sort data uvsrt = AIPSTask.AIPSTask('uvsrt') OTObit.setname(uv, uvsrt) uvsrt.outname = uvsrt.inname uvsrt.outclass = uvsrt.inclass uvsrt.outseq = uvsrt.inseq + 1 uvsrt.outdisk = uvsrt.indisk uvsrt.sort = 'TB' uvsrt.go() # Get output UV data object uvFixed = UV.newPAUV("uvFixed", uvsrt.outname, uvsrt.outclass, int(uvsrt.outdisk), int(uvsrt.outseq), True, err) # Fix tables MergeCal.MergeCal(uvFixed, err) # Create NX table indxr = AIPSTask.AIPSTask('indxr') OTObit.setname(uvFixed, indxr) indxr.go() return uvFixed
def PAllDest(disk, err, Atype=" ", Aname=None, Aclass=None, Aseq=0): """ Delete selected AIPS catalog entries Entries can be selected using Atype, Aname, Aclass, Aseq, using AIPS wildcards A "?" matches one of any character, "*" matches any string all blanks matches anything * disk = AIPS disk number, 0=>all * err = Python Obit Error/message stack * type = optional file type * Aname = desired name, using AIPS wildcards, None -> don't check * Aclass = desired class, using AIPS wildcards, None -> don't check * Aseq = desired sequence, 0=> any * first = optional first slot number (1-rel) * last = optional last slot number * giveList = If true, return list of CNOs matching """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError, "err MUST be an OErr" # if (disk < 0) or (disk > (len(AIPS.AIPS.disks) + 1)): raise RuntimeError, "Disk " + str(disk) + " out of range" # disks if disk > 0: disks = [disk] else: disks = range(1, len(AIPS.AIPS.disks)) user = OSystem.PGetAIPSuser() # loop over disks for dsk in disks: ncno = PNumber(dsk, user, err) OErr.printErrMsg(err, "Error getting number of cnos") for cno in range(1, ncno): line = PInfo(dsk, user, cno, err) OErr.printErrMsg(err, "Error reading entry") if WantDir(line, type=Atype, Aname=Aname, Aclass=Aclass, Aseq=Aseq): # parse directory string Tname = line[0:12] Tclass = line[13:19] Tseq = int(line[20:25]) Ttype = line[26:28] z = None if Ttype == 'MA': z = Image.newPAImage("Zap image", Tname, Tclass, dsk, Tseq, True, err, \ verbose=False) print "Zap AIPS Image", Tname, Tclass, dsk, Tseq elif Ttype == 'UV': z = UV.newPAUV("Zap UV data", Tname, Tclass, dsk, Tseq, True, err, \ verbose=False) print "Zap AIPS UV", Tname, Tclass, dsk, Tseq # Delete entry if z: z.Zap(err) del z
def VLAUVLoadT(filename, disk, Aname, Aclass, Adisk, Aseq, err, \ Compress=False): """ Read FITS file into AIPS Read input uvtab FITS file, write AIPS Returns Obit uv object Filename = input FITS uvtab format file disk = input FITS file disk number Aname = output AIPS file name Aclass = output AIPS file class Adisk = output AIPS file disk Aseq = output AIPS file sequence err = Obit error/message stack Compress = Write AIPS data in compressed form? """ ################################################################ # uvc = ObitTask.ObitTask("UVCopy") uvc.DataType = "FITS" uvc.inFile = filename uvc.inDisk = disk uvc.outDType = "AIPS" uvc.outName = Aname uvc.outClass = Aclass uvc.outSeq = Aseq uvc.outDisk = Adisk uvc.Compress = Compress uvc.g # Get output outuv = UV.newPAUV("UVdata", Aname, Aclass, Adisk, Aseq, True, err) return outuv
def GetFreqArr(inUV, err, inc = 1): """ Get Array of channel frequencies in data Return list of channel Frequencies (Hz) * inUV = Obit UV data with tables * err = Python Obit Error/message stack * inc = increment in channel """ ################################################################ # Checks if not UV.PIsA(inUV): print("Actually ",inUV.__class__) raise TypeError("inUV MUST be a Python Obit UV") d = inUV.Desc.Dict # UV data descriptor dictionary refFreq = d["crval"][ d["jlocf"]] # reference frequency nchan = d["inaxes"][ d["jlocf"]] # Number of channels per IF nif = d["inaxes"][ d["jlocif"]] # Number of IFs chwid = abs(d["cdelt"][ d["jlocf"]]) # channel width from header fqtab = inUV.NewTable(Table.READONLY,"AIPS FQ",1,err) fqtab.Open(Table.READONLY,err) fqrow = fqtab.ReadRow(1, err) # Only bother with first OErr.printErrMsg(err) # catch table errors IFfreq = fqrow['IF FREQ'] # IF offset ChWidth = fqrow['CH WIDTH'] # IF channel width sideband = fqrow['SIDEBAND'] # IF sizeband, 1=USB, -1=LSB freqs = [] for iif in range(0,nif): for ifq in range(0,nchan,inc): frq = refFreq + IFfreq[iif] + sideband[iif] * ifq * min (chwid, ChWidth[iif]) freqs.append(frq) # End loops return freqs
def PInvertSN (SNTab, outUV, outVer, doRepl, err): """ Invert the calibration in an SN table Routine to reverse the effects of the calibration in the input SN table and create a new SN table on outUV Returns new SN table SNTab = Input Python AIPS SN Table to invert outUV = output UV data to which to attach the new SN table outVer = Output SN table version number, 0=> create new doRepl = If True, replace failed solutions with (1,0) err = Python Obit Error/message stack """ ################################################################ # Checks if not Table.PIsA(SNTab): raise TypeError("SNTab MUST be a Python Obit Table") if not UV.PIsA(outUV): raise TypeError('outUV Must be UV data ') if not OErr.OErrIsA(err): raise TypeError("err MUST be an OErr") # # Create output outSN = Table.Table("None") # invert table outSN.me = Obit.SNInvert (SNTab.me, outUV.me, outVer, doRepl, err.me) if err.isErr: printErrMsg(err, "Error inverting solutions") return outSN
def UVAddIF(inUV, outUV, nIF, err): """ Create outUV like inUV but divided into nIF IFs * inUV = input Obit UV object * outUV = output Obit UV object, defined but not instantiated Onlyt really works for AIPS * nIF = number of desired output IFs MUST be the same number of channels per IF * err = Obit error/message stack """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError("inUV MUST be a Python Obit UV") if not UV.PIsA(outUV): raise TypeError("outUV MUST be a defined Python Obit UV") # Input can have 1 or no IFs defined jlocif = inUV.Desc.Dict["jlocif"] if jlocif >= 0 and inUV.Desc.Dict["inaxes"][jlocif] > 1: raise RuntimeError("Input UV has excessive IFs already:" \ +str(inUV.Desc.Dict["inaxes"][jlocif])) # Check number of requested IFs if nIF < 2: raise RuntimeError("Too few output IFs requested: " + str(nIF)) # Must be an even number of channels per output IF jlocf = inUV.Desc.Dict["jlocf"] nchan = inUV.Desc.Dict["inaxes"][jlocf] if (nchan % nIF) != 0: raise RuntimeError("Unequal numbers of channels per " + str(nIF) + " IFs") # Patch UV Descriptor DescAddIF(inUV, outUV, nIF, err) # Convert FG Table UpdateFQ(inUV, outUV, nIF, err) # Convert AN Table UpdateAN(inUV, outUV, nIF, err) # Convert SU Table UpdateSU(inUV, outUV, nIF, err) # Copy data CopyData(inUV, outUV, err) # Update outUV.UpdateDesc(err) OErr.printErrMsg(err, "Error updating output") print("Any CL tables need to be regenerated")
def PGetRFI (inRFI): """ Return the data set containing estimated RFI returns Residual dataset, this is only valid after calling PRemove or PCounterRot. If PFilter (or PRemove) has beed called the residual will have been filtered to give the estimate of the RFI. inRFI = Python UVRFIXize object """ ################################################################ # Checks if not PIsA(inRFI): raise TypeError,"inRFI MUST be a Python Obit UVRFIXize" # RFIUV = UV("RFI") RFIUV.me = Obit.UVRFIXizeGetRFI (inRFI.me); return RFIUV
def PGetRFI(inRFI): """ Return the data set containing estimated RFI returns Residual dataset, this is only valid after calling PRemove or PCounterRot. If PFilter (or PRemove) has beed called the residual will have been filtered to give the estimate of the RFI. inRFI = Python UVRFIXize object """ ################################################################ # Checks if not PIsA(inRFI): raise TypeError("inRFI MUST be a Python Obit UVRFIXize") # RFIUV = UV("RFI") RFIUV.me = Obit.UVRFIXizeGetRFI(inRFI.me) return RFIUV
def PCreate(name, err, input=GSolveInput): """ Create the parameters and underlying structures of a UVGSolve. Returns UVGSolve created. name = Name to be given to object Most control parameters are in InfoList member err = Python Obit Error/message stack input = control parameters: subA = Selected subarray (default 1) solInt = Solution interval (min). (default 1 sec) refAnt = Ref ant to use. (default 1) avgPol = True if RR and LL to be averaged (false) avgIF = True if all IFs to be averaged (false) minSNR = Minimum acceptable SNR (5) doMGM = True then find the mean gain modulus (true) solType = Solution type ' ', 'L1', (' ') solMode = Solution mode: 'A&P', 'P', 'P!A', 'GCON' ('P') minNo = Min. no. antennas. (default 4) WtUV = Weight outside of UV_Full. (default 1.0) antWt = Weight per antenna, def all 1 prtLv = Print level (default no print) """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError("err MUST be an OErr") # # Create out = UVGSolve(name) out.me = Obit.UVGSolveCreate(name, skyModel.me) # Set SelfCal control values on out inInfo = PGetList(out) # dim = [1, 1, 1, 1, 1] # Set control values on SelfCal dim[0] = 1 inInfo = UV.PGetList(skyModel) # InfoList.PPutInt(inInfo, "subA", dim, [input["subA"]], err) InfoList.PPutInt(inInfo, "refAnt", dim, [input["refAnt"]], err) InfoList.PPutInt(inInfo, "minNo", dim, [input["minNo"]], err) InfoList.PPutInt(inInfo, "prtLv", dim, [input["prtLv"]], err) InfoList.PPutBoolean(inInfo, "avgPol", dim, [input["avgPol"]], err) InfoList.PPutBoolean(inInfo, "avgIF", dim, [input["avgIF"]], err) InfoList.PPutBoolean(inInfo, "doMGM", dim, [input["doMGM"]], err) InfoList.PPutFloat(inInfo, "solInt", dim, [input["solInt"]], err) InfoList.PPutFloat(inInfo, "minSNR", dim, [input["minSNR"]], err) InfoList.PPutFloat(inInfo, "WtUV", dim, [input["WtUV"]], err) dim[0] = len(input["solType"]) InfoList.PAlwaysPutString(inInfo, "solType", dim, [input["solType"]]) dim[0] = len(input["solMode"]) InfoList.PAlwaysPutString(inInfo, "solMode", dim, [input["solMode"]]) # antWt if given if input["antWt"].__class__ != None.__class__: dim[0] = len(input["antWt"]) InfoList.PAlwaysPutFloat(inInfo, "antWt", dim, input["antWt"]) # show any errors #OErr.printErrMsg(err, "UVGSolveCreate: Error setting parameters") # return out
def PAllDest(disk, err, Atype = " ", Aname=None, Aclass=None, Aseq=0): """ Delete selected AIPS catalog entries Entries can be selected using Atype, Aname, Aclass, Aseq, using AIPS wildcards A "?" matches one of any character, "*" matches any string all blanks matches anything disk = AIPS disk number, 0=>all err = Python Obit Error/message stack type = optional file type Aname = desired name, using AIPS wildcards, None -> don't check Aclass = desired class, using AIPS wildcards, None -> don't check Aseq = desired sequence, 0=> any first = optional first slot number (1-rel) last = optional last slot number giveList = If true, return list of CNOs matching """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # if (disk<0) or (disk>(len(AIPS.AIPS.disks)+1)): raise RuntimeError,"Disk "+str(disk)+" out of range" # disks if disk>0: disks=[disk] else: disks= range(1,len(AIPS.AIPS.disks)) user = OSystem.PGetAIPSuser() # loop over disks for dsk in disks: ncno = PNumber (dsk, user, err) OErr.printErrMsg(err, "Error getting number of cnos") for cno in range(1, ncno): line=PInfo(dsk, user, cno, err); OErr.printErrMsg(err, "Error reading entry") if WantDir(line, type=Atype, Aname=Aname, Aclass=Aclass, Aseq=Aseq): # parse directory string Tname = line[0:12] Tclass = line[13:19] Tseq = int(line[20:25]) Ttype = line[26:28] z = None if Ttype == 'MA': z = Image.newPAImage("Zap image", Tname, Tclass, dsk, Tseq, True, err, \ verbose=False) print "Zap AIPS Image",Tname, Tclass, dsk, Tseq elif Ttype == 'UV': z = UV.newPAUV("Zap UV data", Tname, Tclass, dsk, Tseq, True, err, \ verbose=False) print "Zap AIPS UV",Tname, Tclass, dsk, Tseq # Delete entry if z: z.Zap(err) del z
def VLAUVFITS(inUV, filename, outDisk, err, compress=False, \ exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \ include=[], headHi=False): """ Write UV data as FITS file Write a UV data set as a FITAB format file History written to header inUV = UV data to copy filename = name of FITS file inDisk = FITS directory number err = Python Obit Error/message stack exclude = List of table types NOT to copy NB: "AIPS HI" isn't really a table and gets copied anyway include = List of table types to copy (FQ, AN always done ) Exclude has presidence over include headHi = if True move history to header, else leave in History table returns FITS UV data object """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError,"inUV MUST be a Python Obit UV" if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # # Set output outUV = UV.newPFUV("FITS UV DATA", filename, outDisk, False, err) if err.isErr: OErr.printErrMsg(err, "Error creating FITS data") #Compressed? if compress: inInfo = UV.PGetList(outUV) # dim = [1,1,1,1,1] InfoList.PAlwaysPutBoolean (inInfo, "Compress", dim, [True]) # Copy UV.PCopy (inUV, outUV, err) if err.isErr: OErr.printErrMsg(err, "Error copying UV data to FITS") # History inHistory = History.History("inhistory", outUV.List, err) outHistory = History.History("outhistory", outUV.List, err) # Add history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit uvtab",err) outHistory.WriteRec(-1,"uvtab / FITS file "+filename+" disk "+str(outDisk),err) outHistory.Close(err) # History in header? if headHi: History.PCopy2Header (inHistory, outHistory, err) OErr.printErrMsg(err, "Error with history") # zap table outHistory.Zap(err) # Copy Tables UV.PCopyTables (inUV, outUV, exclude, include, err) return outUV # return new object
def PUVWeight(InImager, err, input=UVWeightInput): """ Apply any calibration/editing/selection and do UV weighting UV Data is calibrated and weighted, values in input override those given when the UVImage was created. This operation is optionally done in PUVImage. err = Python Obit Error/message stack input = input parameter dictionary Input dictionary entries: InImager = Input Python UVImager to image Robust = Briggs robust parameter. (AIPS definition) UVTaper = UV plane taper, sigma in klambda,deg as [maj, min, pa] WtSize = Size of weighting grid in cells [same as image nx] WtBox = Size of weighting box in cells [def 1] WtFunc = Weighting convolution function [def. 1] 1=Pill box, 2=linear, 3=exponential, 4=Gaussian if positive, function is of radius, negative in u and v. WtPower = Power to raise weights to. [def = 1.0] Note: a power of 0.0 sets all the output weights to 1 as modified by uniform/Tapering weighting. Applied in determinng weights as well as after. Channel = Channel (1-rel) number to image, 0-> all. """ ################################################################ # Get input parameters Channel = input["Channel"] WtSize = input["WtSize"] # # Checks if not PIsA(InImager): raise TypeError, 'PUVWeight: Bad input UVImager' # Set control values on UV dim[0] = 1 dim[1] = 1 dim[2] = 1 dim[3] = 1 dim[4] = 1 inInfo = UV.PGetList(PGetUV(InImager)) InfoList.PAlwaysPutFloat(inInfo, "Robust", dim, [input["Robust"]]) InfoList.PAlwaysPutInt(inInfo, "WtBox", dim, [input["WtBox"]]) InfoList.PAlwaysPutInt(inInfo, "WtFunc", dim, [input["WtFunc"]]) InfoList.PAlwaysPutFloat(inInfo, "WtPower", dim, [input["WtPower"]]) dim[1] = len(input["UVTaper"]) InfoList.PAlwaysPutFloat(inInfo, "Taper", dim, input["UVTaper"]) if (WtSize > 0): print "WtSize", WtSize # Change name for C routine. dim[0] = 1 InfoList.PAlwaysPutInt(inInfo, "nuGrid", dim, [WtSize]) InfoList.PAlwaysPutInt(inInfo, "nvGrid", dim, [WtSize]) # Obit.UVImagerWeight(InImager.me, err.me) if err.isErr: OErr.printErrMsg(err, "Error weighting UV data")
def _init(self, desc, verbose=True): userno = OSystem.PGetAIPSuser() OSystem.PSetAIPSuser(desc['userno']) uvdata = UV.newPAUV(desc['name'], desc['name'], desc['klass'], desc['disk'], desc['seq'], True, self.err, verbose = verbose) OSystem.PSetAIPSuser(userno) if not uvdata.isOK: # Exception if something went wrong raise OErr.OErr OErr.printErrMsg(self.err, "Error with AIPSUVdata") return uvdata
def WriteFGTable(outUV, katdata, meta, err): """ Get the flags from the h5 file and convert to FG table format. UNUSED- This implimentation is too slow! outUV = Obit UV object meta = dict with data meta data err = Python Obit Error/message stack to init """ ############################################################### # work out Start time in unix sec tm = katdata.timestamps[1:2] tx = time.gmtime(tm[0]) time0 = tm[0] - tx[3] * 3600.0 - tx[4] * 60.0 - tx[5] int_time = katdata.dump_period #Loop through scans in h5 file row = 0 for scan, state, target in katdata.scans(): name = target.name.replace(' ', '_') if state != 'track': continue tm = katdata.timestamps[:] nint = len(tm) el = target.azel(tm[int(nint / 2)])[1] * 180. / math.pi if el < 15.0: continue row += 1 flags = katdata.flags()[:] numflag = 0 for t, chan_corr in enumerate(flags): for c, chan in enumerate(chan_corr): cpflagged = [] for p, cp in enumerate(chan): #for cpaverage in meta['pairLookup']: flag = cp #numpy.any(chan[meta['pairLookup'][cpaverage]]) product = meta['products'][p] if product[0] == product[1]: continue if flag and (not product[0:2] in cpflagged): cpflagged.append(product[0:2]) numflag += 1 starttime = float( (tm[t] - time0 - (int_time / 2)) / 86400.0) endtime = float( (tm[t] - time0 + (int_time / 2)) / 86400.0) UV.PFlag(outUV,err,timeRange=[starttime,endtime], flagVer=1, \ Ants=[product[0],product[1]], \ Chans=[c+1,c+1], IFs=[1,1], Stokes='1111', Reason='Online flag') numvis = t * c * (p / meta["nstokes"]) msg = "Scan %4d %16s Online flags: %7s of %8s vis" % ( row, name, numflag, numvis) OErr.PLog(err, OErr.Info, msg) OErr.printErr(err)
def _init(self, desc, verbose=True): # Open with full path in disk 0 disk = 0 path = desc['dirname']+"/"+desc['filename'] uvdata = UV.newPFUV(desc['filename'], path, disk, True, self.err, verbose = verbose) if not uvdata.isOK: # Exception if something went wrong raise OErr.OErr OErr.printErrMsg(self.err, "Error with FITSUVdata") return uvdata
def PGenPrint(printer, data, err, VLVer=1, first=True, last=True): """ Print selected contents of a generic VL format catalog Returns logical quit to indicate user wants to quit * printer = Printer for output * data = OData to to which VL table is attached will cast from Image or UV types with control parameters on the info: Object string Name of object equinCode long Epoch code for output, 1=>B1950, 2=>J2000, 3=>Galactic [def 2] Fitted bool If True give fitted values [def F] doraw bool If True give raw values from table, else corrected/deconvolved.[def F] RA double RA center of search, degrees in equinCode [def 0] Dec double Dec center of search, degrees in equinCode [def 0] Search double Search radius in arcsec, <= 0 => all selected. [def 15] Box double[2] RA and Dec halfwidth of search rectangle in hr,deg [0,0] Silent double Half width asec of silent search box. [def 720] minFlux float Minimum peak flux density. [def 0] maxFlux float Maximum peak flux density. [def LARGE] minGlat float Minimum abs galactic latitude [def any] maxGlat float Minimum abs galactic latitude [def any] Calibration Parameters fluxScale float Flux density scaling factor, def 1.0 biasRA float RA position bias in deg, def 0.0 biasDec float Dec position bias in deg, def 0.0 calRAEr float Cal component of RA position error (squared), def 0.0 calDecEr float Cal component of Dec position error (squared), def 0.0 ClnBiasAv float Mean CLEAN bias in Jy, def 0.0 ClnBiasEr float Uncertainty in CLEAN bias in Jy, def 0.0 calAmpEr float Cal component of amplitude error as fraction, def 0.03 calSizeEr float Cal component of amplitude error as fraction, def 0.02 calPolEr float Cal component of polarization error, def 0.003 * err = Python Obit Error/message stack * VLVer = VL table version * first = True if this first write to printer * last = True if this is the last write to printer """ ################################################################ # Checks if not OPrinter.PIsA(printer): raise TypeError("printer MUST be a Python Obit printer") # cast data if necessary if Image.PIsA(data) or UV.PIsA(data): ldata = data.cast("ObitData") else: ldata = data ret = Obit.OSurveyGenPrint(printer.me, ldata.me, VLVer, first, last, err.me) return ret != 0
def PSNSmo (inSC, err, input=UVSelfSNSmoInput): """ Smooth SN table possibly replacing blanked soln. inSC = Selfcal object err = Python Obit Error/message stack input = input parameter dictionary Input dictionary entries: InData = Input Python UV data InTable = Input SN table isuba = Desired subarray, 0=> 1 smoType = Smoothing type MWF, GAUS or BOX, def BOX smoAmp = Amplitude smoothing time in min smpPhase = Phase smoothing time in min. (0 => fix failed only') """ ################################################################ # Get input parameters InData = input["InData"] InTable = input["InTable"] isuba = input["isuba"] # # Checks if not UV.PIsA(InData): raise TypeError('PCal: Bad input UV data') if not Table.PIsA(InTable): raise TypeError('PCal: Bad input table') # Set control values on UV dim[0] = 1; inInfo = UV.PGetList(InData) # Add control to UV data dim[0] = len(input["smoType"]); InfoList.PAlwaysPutString (inInfo, "smoType", dim, [input["smoType"]]) dim[0] = 1; InfoList.PPutFloat (inInfo, "smoAmp", dim, [input["smoAmp"]], err) InfoList.PPutFloat (inInfo, "smoPhase",dim, [input["smoPhase"]],err) # Smooth Obit.UVSolnSNSmo(InTable.me, isuba, err.me) if err.isErr: printErrMsg(err, "Error smoothing SN table")
def PGetUV(InImager): """ Return the member uvdata returns uv data (as UV) InImager = Python ImageMosaic object """ ################################################################ # Checks if not PIsA(InImager): raise TypeError, "InImager MUST be a Python Obit UVImager" # out = UV.UV("None") out.me = Obit.UVImagerGetUV(InImager.me) return out
def getFITS(file, disk=Adisk, Ftype='Image'): """ Return Obit object for FITS file in file on disk file = FITS file name disk = FITS disk number Ftype = FITS data type: 'Image', 'UV' """ ################################################################ if Ftype == 'Image': out = Image.newPFImage("FITS image", file, disk, True, err) elif Ftype == 'UV': out = UV.newPFUV("FITS UV data", file, disk, True, err) out.Fname = file out.Disk = disk out.Otype = Ftype return out
def getFITS(file, disk=Adisk, Ftype='Image'): """ Return Obit object for FITS file in file on disk * file = FITS file name * disk = FITS disk number * Ftype = FITS data type: 'Image', 'UV' """ ################################################################ if Ftype == 'Image': out = Image.newPFImage("FITS image", file, disk, True, err) elif Ftype == 'UV': out = UV.newPFUV("FITS UV data", file, disk, True, err) out.Fname = file out.Disk = disk out.Otype = Ftype return out
def PICreateImage(inUV, fieldNo, doBeam, err): """ Create an image from information on an ObitUV returns Python Image * inUV = Python UV object, following read from InfoList member ======== ================== ============================================= "nChAvg" OBIT_int (1,1,1) number of channels to average. This is for spectral line observations and is ignored if the IF axis on the uv data has more than one IF. Default is continuum = average all freq/IFs. 0=> all. "rotate" OBIT_float (?,1,1) Desired rotation on sky (from N thru E) in deg. [0] "nx" OBIT_int (?,1,1) Dimension of image in RA [no default]. This and the following are arrays with one entry per field. "nxBeam" OBIT_int (?,1,1) Dimension of beam in RA, [def. nx] "ny" OBIT_int (?,1,1) Dimension of image in declination[no default] "nyBeam" OBIT_int (?,1,1) Dimension of beam in declination, [def. ny] "xCells" OBIT_float (?,1,1) X (=RA) cell spacing in degrees [no default] "yCells" OBIT_float (?,1,1) Y (=dec) cell spacing in degrees [no default] "xShift" OBIT_float (?,1,1) Desired shift in X (=RA) in degrees. [0] "yShift" OBIT_float (?,1,1) Desired shift in Y (=dec) in degrees. [0] "nuGrid" OBIT_int (1,1,1) Size in pixels of weighting grid for uniform weighting ======== ================== ============================================= * fieldNo = Which field (1-rel) in imaging parameter arrays. * doBeam = if TRUE also create beam as the myBeam member of returned image. * err = Python Obit Error/message stack """ ################################################################ # Checks if not UV.PIsA(inUV): raise TypeError("inUV MUST be a Python Obit UV") if not err.IsA(): raise TypeError("err MUST be an OErr") # out = Image("None") out.me = Obit.ImageUtilCreateImage(inUV.me, fieldNo, doBeam, err.me) if err.isErr: OErr.printErrMsg(err, "Error Creating Image") return out
Stokes = 'I' TimeRange = [0.0,10.0] UVRange = [0.0,0.0] Robust = 0.0 UVTaper = [0.0,0.0] # NVSS catalog Catalog = 'NVSSVZ.FIT' OutlierDist = 1.0 # Maximum distance to add outlyers (deg) OutlierFlux = 0.001 # Minimum estimated outlier flux density (Jy) OutlierSI = -0.7 # Spectral index to estimate flux density OutlierSize = 50 # Size of outlyer field # Convert files into uvdata inUV = UV.newPFUV("input data", inFile, inDisk, 1, err) OErr.printErrMsg(err, "Error initializing uvdata") # Set inputs Input = CleanVis.CleanInput #Input['Sources'] = ["C346R422"] Input['Sources'] = ["C346R424"] Input['doCalSelect'] = True; Input['Niter'] = 1000 Input['minFlux'] = 0.0001 Input['minPatch'] = 200 Input['Gain'] = 0.1 Input['CCVer'] = 1 #Input['BMAJ'] = 4.0/3600.0 #Input['BMIN'] = 4.0/3600.0 #Input['BPA'] = 0.0
# Init Obit err=OErr.OErr() user = 101 ObitSys=OSystem.OSystem ("debug", 1, user, len(adirs), adirs, len(fdirs), fdirs, True, False, err) OErr.printErrMsg(err, "Error with Obit startup") # This shit really bites AIPS.AIPS.userno = user disk = 0 for ad in adirs: disk += 1 AIPS.AIPS.disks.append(AIPS.AIPSDisk(None, disk, ad)) disk = 0 for fd in fdirs: disk += 1 FITS.FITS.disks.append(FITS.FITSDisk(None, disk, ad)) # Set uv data u3=UV.newPAUV("in","20051116", "K BAND", 3,1,True,err) u3.Header(err) VLACal.VLAClearCal(u3,err) calModel="3C286_K.MODEL" target="M87" ACal="1331+305" PCal="1239+075" VLACal.VLACal(u3, target, ACal, err, calModel=calModel,calDisk=1) VLACal.VLASplit(u3, target, err, outClass="IKDarr")
outSeq = 2666 # Single outSeq = 1666 # Single # NVSS catalog Catalog = 'NVSSVZ.FIT' OutlierDist = 1.0 # Maximum distance to add outlyers (deg) OutlierFlux = 0.01 # Minimum estimated outlier flux density (Jy) OutlierSI = -1.0 # Spectral index to estimate flux density OutlierSize = 50 # Size of outlyer field # Bombs away #Bomb() # Set data print "Set data" inData = UV.newPAUV("Input data", inName, inClass, inDisk, inSeq, True, err) OErr.printErrMsg(err, "Error initializing") # Make scratch version print "Make scratch file" scrData = UV.PScratch (inData, err) OErr.printErrMsg(err, "Error making scratch file") # Calibration/selection parameters Input = UVImager.UVCalInput Input['InData'] = inData Input['OutData'] = scrData Input['doCalSelect'] = True Input['Stokes'] = 'I' Input['BChan'] = 0 Input['EChan'] = 0
def VLAPolCal(uv, InsCals, RLCal, RLPhase, err, RM=0.0, \ doCalib=2, gainUse=0, flagVer=-1, \ soltype="APPR", fixPoln=False, avgIF=False, \ solInt=0.0, refAnt=0, \ pmodel=[0.0,0.0,0.0,0.0,0.0,0.0,0.0], \ FOV=0.05, niter = 100, \ nThreads=1, noScrat=[], logfile = ""): """ Polarization calibration, both instrumental and orientation Do Instrumental and R-L calibration Instrumental cal uses PCAL, R-L cal is done by imaging each IF in Q and U and summing the CLEAN components. uv = UV data object to calibrate InsCals = Instrumental poln calibrators, name or list of names If None no instrumental cal RLCal = R-L (polarization angle) calibrator, If None no R-L cal RLPhase = R-L phase of RLCal (deg) at 1 GHz err = Obit error/message stack RM = Rotation measure of RLCal doCalib = Apply prior calibration table, positive=>calibrate gainUse = CL/SN table to apply flagVer = Input Flagging table version soltype = solution type fixPoln = if True, don't solve for source polarization in ins. cal avgIF = if True, average IFs in ins. cal. solInt = instrumental solution interval (min), 0=> scan average refAnt = Reference antenna pmodel = Instrumental poln cal source poln model. pmodel[0] = I flux density (Jy) pmodel[1] = Q flux density (Jy) pmodel[2] = U flux density (Jy) pmodel[3] = V flux density (Jy) pmodel[4] = X offset in sky (arcsec) pmodel[5] = Y offset in sky (arcsec) FOV = field of view radius (deg) needed to image RLCal niter = Number of iterations of CLEAN in R-L cal nThreads = Number of threads to use in imaging noScrat = list of disks to avoid for scratch files logfile = Log file for task """ ################################################################ # Instrumental calibrtation if InsCals!=None: pcal = AIPSTask.AIPSTask("pcal") pcal.logFile = logfile setname(uv,pcal) if type(InsCals)==list: pcal.calsour[1:] = InsCals else: pcal.calsour[1:] = [InsCals] pcal.docalib = doCalib pcal.gainuse = gainUse pcal.flagver = flagVer pcal.soltype = soltype pcal.solint = solInt pcal.refant = refAnt if fixPoln: pcal.bparm[10]=1.0 if avgIF: pcal.cparm[1]=1.0 pcal.pmodel[1:] = pmodel pcal.i pcal.g # end instrumental poln cal # R-L phase cal if RLCal!=None: img = ObitTask.ObitTask("Imager") img.logFile = logfile setname(uv,img) img.doCalib = doCalib img.gainUse = gainUse img.flagVer = flagVer img.doPol = True img.Sources[0] = RLCal img.Stokes = "IQU" img.FOV = FOV img.Niter = niter img.autoWindow = True img.dispURL = "None" img.Catalog = "None" img.nThreads = nThreads img.noScrat = noScrat # Temporary output files if img.DataType=="AIPS": img.outName = "TEMP" img.outClass= "IPOLCL" img.outDisk = img.inDisk img.outSeq = 6666 img.out2Name = "TEMP" img.out2Class= "IPOLCL" img.out2Disk = img.inDisk img.out2Seq = 7777 elif img.DataType=="FITS": img.outFile = "TEMPPOLCAL.fits" img.outDisk = img.inDisk img.out2File = "TEMPPOLCAL2.uvtab" img.out2Disk = img.inDisk # How many IFs? h = uv.Desc.Dict if h["jlocif"]>=0: nif = h["inaxes"][h["jlocif"]] else: nif = 1 # Lists of flux densities and RMSes IFlux = [] IRMS = [] QFlux = [] QRMS = [] UFlux = [] URMS = [] # Loop over IF imaging I,Q, U for iif in range (1, nif+1): img.BIF = iif img.EIF = iif #img.dispURL = "ObitView" # DEBUG #img.debug=True # DEBUG img.g # Get fluxes from inner quarter of images if img.DataType=="AIPS": outName = (img.Sources[0].strip()+"TEMP")[0:12] outDisk = img.outDisk outSeq = 6666 # Stokes I outClass="IPOLCL" x = Image.newPAImage("I",outName, outClass, outDisk,outSeq,True,err) h = x.Desc.Dict blc = [h["inaxes"][0]/4,h["inaxes"][1]/4] trc = [3*h["inaxes"][0]/4,3*h["inaxes"][1]/4] stat = imstat(x, err, blc=blc,trc=trc) IFlux.append(stat["Flux"]) IRMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x # Stokes Q outClass="QPOLCL" x = Image.newPAImage("Q",outName, outClass, outDisk,outSeq,True,err) stat = imstat(x, err, blc=blc,trc=trc) QFlux.append(stat["Flux"]) QRMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x # Stokes U outClass="UPOLCL" x = Image.newPAImage("U",outName, outClass, outDisk,outSeq,True,err) stat = imstat(x, err, blc=blc,trc=trc) UFlux.append(stat["Flux"]) URMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x # Delete UV output out2Name = (img.Sources[0].strip()+"TEMP")[0:12] out2Class="IPOLCL" out2Disk = img.inDisk out2Seq = 7777 u = UV.newPAUV("UV",out2Name,out2Class,out2Disk,out2Seq,True,err) u.Zap(err) del u elif img.DataType=="FITS": # Stokes I outFile = img.Sources[0].strip()+"ITEMPPOLCAL.fits" x = Image.newPFImage("I",outFile,img.outDisk,True,err) h = x.Desc.Dict blc = [h["inaxes"][0]/4,h["inaxes"][1]/4] trc = [3*h["inaxes"][0]/4,3*h["inaxes"][1]/4] stat = imstat(x, err, blc=blc,trc=trc) IFlux.append(stat["Flux"]) IRMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x # Stokes Q outFile = img.Sources[0].strip()+"ITEMPPOLCAL.fits" x = Image.newPFImage("Q",outFile,img.outDisk,True,err) stat = imstat(x, err, blc=blc,trc=trc) IFlux.append(stat["Flux"]) IRMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x # Stokes U outFile = img.Sources[0].strip()+"ITEMPPOLCAL.fits" x = Image.newPFImage("Q",outFile,img.outDisk,True,err) stat = imstat(x, err, blc=blc,trc=trc) IFlux.append(stat["Flux"]) IRMS.append(stat["RMSHist"]) x.Zap(err) # Cleanup del x out2File = img.Sources[0].strip()+"TEMPPOLCAL2.uvtab" u = UV.newPFUV("UV",outFile,img.outDisk,True,err) u.Zap(err) del u # End accumulate statistics by file type # End loop over IF # Give results, compute R-L correction RLCor = [] import math mess = " IF IFlux IRMS QFlux QRMS UFlux URMS R-L Corr" printMess(mess, logfile) for i in range (0,len(IFlux)): # REALLY NEED RM Correction!!!!! cor = RLPhase - 57.296 * math.atan2(UFlux[i],QFlux[i]) RLCor.append(cor) mess = "%3d %8.3f %8.3f %7.3f %7.3f %7.3f %7.3f %7.3f "%\ (i+1, IFlux[i], IRMS[i], QFlux[i], QRMS[i], UFlux[i], URMS[i], cor) printMess(mess, logfile) # Copy highest CL table hiCL = uv.GetHighVer("AIPS CL") # Apply R-L phase corrections clcor = AIPSTask.AIPSTask("clcor") clcor.logFile = logfile setname(uv,clcor) clcor.opcode = "POLR" clcor.gainver = hiCL clcor.gainuse = hiCL+1 clcor.clcorprm[1:] = RLCor clcor.g
UVTaper = [0.0,0.0] # NVSS catalog Catalog = 'NVSSVZ.FIT' OutlierDist = 1.0 # Maximum distance to add outlyers (deg) OutlierFlux = 0.01 # Minimum estimated outlier flux density (Jy) OutlierSI = -1.0 # Spectral index to estimate flux density OutlierSize = 50 # Size of outlyer field # If debugging #Bomb() # Set data print "Set data" inData = UV.newPFUV("Input data", inFile, inDisk, True, err) OErr.printErrMsg(err, "Error initializing") # Calibration/selection parameters Input = UVImager.UVCreateImagerInput # Data selection, cal etc. Input['InData'] = inData Input['doCalSelect'] = True Input['Stokes'] = Stokes Input['BChan'] = 0 Input['EChan'] = 0 Input['BIF'] = 0 Input['EIF'] = 0 Input['doCalib'] = -1 Input['gainUse'] = 1 Input['flagVer'] = 1
# Files (FITS) inDisk = 1 outDisk = 1 inFile = 'UVSubTestIn.uvtab' inModel = 'UVSubTestModIn.fits' outFile = 'UVSubTestOut.uvtab' masterDisk = 1 masterFile = 'UVSubTestMaster.uvtab' # Bombs away #Bomb() # Set data print "Set data" inData = UV.newPFUV("Input uv data", inFile, inDisk, True, err) inImage = Image.newPFImage("Input image",inModel, inDisk, True, err) outData = UV.newPFUV("Output uv data", outFile, outDisk, False, err) OErr.printErrMsg(err, "Error initializing") # Make Mosaic mosaic = ImageMosaic.newObit("Mosaic", 2, err) #mosaic = ImageMosaic.newObit("Mosaic", 1, err) OErr.printErrMsg(err, "Error making mosaic") # Add image ImageMosaic.PSetImage(mosaic, 0, inImage) ImageMosaic.PSetImage(mosaic, 1, inImage) # Make SkyModel model model = SkyModel.PCreate("SkyModel", mosaic) OErr.printErrMsg(err, "Error making SkyModel")
import UV, UVImager, Image, ImageMosaic, SkyModel from Obit import Bomb # Files (FITS) inDisk = 1 outDisk = 1 inFile = 'PModel.uvtab' inModel = 'PModelQ.fits' outFile = 'UVSubTestOut.uvtab' # Bombs away #Bomb() # Set data print "Set data" inData = UV.newPFUV("Input uv data", inFile, inDisk, True, err) inImage = Image.newPFImage("Input image",inModel, inDisk, True, err) outData = UV.newPFUV("Output uv data", outFile, outDisk, True, err) OErr.printErrMsg(err, "Error initializing") # Make Mosaic mosaic = ImageMosaic.newObit("Mosaic", 1, err) OErr.printErrMsg(err, "Error making mosaic") # Add image ImageMosaic.PSetImage(mosaic, 0, inImage) # Make SkyModel model = SkyModel.newObit("SkyModel", err) OErr.printErrMsg(err, "Error making SkyModel") SkyModel.PSetMosaic(model, mosaic)