def CompareFITS(fitsFile1, fitsFile2, err): """ Compare 2 fits files. * fitsFile1 = path to first FITS file * fitsFile2 = path to second FITS file """ image1 = Image.newPFImage('image1', fitsFile1, 0, True, err, True) image2 = Image.newPFImage('image2', fitsFile2, 0, True, err, True) compList = Image.PCompare(image1, image2, err) return compList
def crop_pb(image, outimage, err, minlevel=0.15, scratch_dir='/tmp/'): #Crop the image at the 15% level of the primary beam wtim = Image.newPFImage("weight", scratch_dir + '/crop_pb.fits', 0, False, err) im = Image.newPFImage("orig", image, 0, False, err) im.Clone(wtim, err) ImageUtil.PPBImage(im, wtim, err, minGain=minlevel) #Crop using pyfits output = pyfits.open(image) wtim = pyfits.open(scratch_dir + '/crop_pb.fits') output[0].data[ 0, 0] = output[0].data[0, 0] * wtim[0].data[0, 0] / wtim[0].data[0, 0] output.writeto(outimage, clobber=True) #cleanup os.remove(scratch_dir + '/crop_pb.fits')
def pbcorr_multiplane(image_filename, output_image, err, scratch_dir='/tmp/'): nplanes = Extract(image_filename, scratch_dir + "/TEMP", err) basename = os.path.splitext(os.path.basename(image_filename))[0] #Got number of planes, now split them out and primary beam correct them. imArr = [] for plane in range(nplanes - 1): imArr.append( pbcorr_obit(scratch_dir + "/TEMP.plane%2.2d.fits" % (plane + 1), scratch_dir + "/PBCORR.plane%2.2d.fits" % (plane + 1), err, scratch_dir=scratch_dir)) #Delete the image os.remove(scratch_dir + "/TEMP.plane%2.2d.fits" % (plane + 1)) #imArr.append(Image.newPFImage("P%2.2d"%(plane+1),"TEMP.plane%2.2d.fits"%(plane+1),0,True,err)) output = Image.newPFImage("out", scratch_dir + '/pbcor_' + basename + '.fits', 0, False, err) import SpectrumFit sf = SpectrumFit.PCreate("Fitter", 2) #Form final image by fitting the spectrum in the pb corrected planes at each pixel. sf.ImArr(imArr, output, err) #Crop the image at the 15% level of the primary beam crop_pb(scratch_dir + '/pbcor_' + basename + '.fits', output_image, err, minlevel=0.05, scratch_dir=scratch_dir) #cleanup for plane in range(nplanes - 1): os.remove(scratch_dir + "/PBCORR.plane%2.2d.fits" % (plane + 1)) os.remove(scratch_dir + '/pbcor_' + basename + '.fits')
def PNVSSFetch (RA, Dec, outfile, err, \ Type = 'image/xfits', Equinox = '2000', \ ObjName='unnamed', Size = '0.50 0.50', \ Poltype = 'I', MAPROJ = 'SIN', rotate = 0.0, Cells=[15.,15.]): """ Postage Stamp server for the NRAO/VLA Sky Survey (1.4 GHz) Fetch a postage stamp (AKA cutout) FITS image, jpeg or contour from the NVSS If a FITS file, returns an ObitImage object pointing to the result, otherwise the output file name If something goes wrong with the request or download, the output file will likely contain an HTML file explaining the results. Throws exception on error * RA = Right Ascension as 'hh mm ss.sss' * Dec = Declination as 'sdd mm ss.ss' * outfile = Name of the output file, absolute path or relative to CWD None => use name from server * err = Python Obit Error/message stack * Type = Type = "type" of result; 'image/jpeg' = jpeg image, 'application/octet-stream' = fits file 'application/postscript' = contour plot (postscript) 'image/x-fits' = fits image (default = /image/jpeg) * Equinox = coordinate equinox ('2000' or '1950') * ObjName = object name - used for labeling only (optional) * Size = field size (RA,dec) in deg. (default 0.50 0.50) * Poltype = total intensity 'I' or 'IQU' (default 'I') * MAPROJ = Map projection type: 'SIN', 'TAN', 'ARC', 'NCP', 'GLS', 'MER', 'AIT','STG' * rotate = Rotation on sky in deg in sense of from North to East * Cells = pixel spacing in aseconds (default 15. 15.) """ ################################################################ # Package parameters query_args = { 'Type': Type, 'Equinox': Equinox, 'ObjName': ObjName, 'RA': RA, 'Dec': Dec, 'Size': Size, 'Poltype': Poltype, 'MAPROJ': MAPROJ, 'rotate': str(rotate), 'Cells': str(Cells[0]) + ' ' + str(Cells[1]) } NVSSURL = "https://www.cv.nrao.edu/cgi-bin/postage.pl" # fetch PWebFetch(NVSSURL, query_args, outfile, err) # Get fits image if requested if (Type == 'image/x-fits') or (Type == 'application/octet-stream'): #print "Get FITS" outfits = Image.newPFImage(ObjName, outfile, 0, True, err) OErr.printErrMsg(err, "Problem with FITS image, see contents of outfile") else: return outfile return outfits
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 window(image): """ Make a window object for an image Returns OWindow object * image = Obit image object """ ################################################################ if Image.IsA(image): # Obit/Image naxis = image.Desc.Dict["inaxes"][0:2] elif image.__class__ == AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",image.name, image.klass, image.disk, \ image.seq, True, err) naxis = tmp.Desc.Dict["inaxes"][0:2] del tmp elif image.__class__ == FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image", image.filename, image.disk, True, err) naxis = tmp.Desc.Dict["inaxes"][0:2] del tmp return OWindow.PCreate1("Window", naxis, 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 ImageSpectrum(path, pixel, err, chOff=-9999, bchan=1, echan=0): """ Obtain a spectrum from a given pixel in an FITS image returns a dictionary with entries ch = channel numbers vel = velocity (km/s) coordinate (first col) freq = frequency (Hz) flux = spectral values path = FITS file path, assume FITS disk 0 pixel = array of integers giving 1-rel pixel chOff = offset to add to channel number in computing Vel if not given is determined from image header bchan = first 1-rel plane number echan = highest plane number 0->all """ ################################################################ inImage = Image.newPFImage("Input image", path, 0, True, err) OErr.printErrMsg(err, "Error making image") imDict = inImage.Desc.Dict #print imDict nplane = imDict["inaxes"][2] blc = [pixel[0], pixel[1], 1] trc = [pixel[0], imDict["inaxes"][1], 1] nchan = echan if echan <= 0: echan = imDict["inaxes"][2] inImage.Open(1, err) OErr.printErrMsg(err, "Error making image") if chOff < -9000: d = inImage.Desc.Dict chOff = 1 - d["crpix"][d["jlocf"]] # Loop over planes ch = [] vel = [] freq = [] flux = [] for i in range(bchan, echan + 1): # Read plane blc[2] = i trc[2] = i data = inImage.ReadPlane(err, blc=blc, trc=trc) OErr.printErrMsg(err, "Error reading plane") s = data.get(0, 0) # save ch.append(i) v = 0.001 * (imDict['crval'][2] + imDict['cdelt'][2] * (i + chOff - imDict['crpix'][2])) vel.append(v) freq.append(v) flux.append(s) #print "debug", i, s, v inImage.Close(err) OErr.printErrMsg(err, "Error closinging image") return {'ch': ch, 'vel': vel, 'freq': freq, 'flux': flux}
def writefits(self, disk, output, tables_to_copy=['AIPS CC', 'AIPS SN']): """ Write the image to a FITS file """ err_msg = "Unable to write image to %s" % output outImage = Image.newPFImage("FITS Image DATA", output, disk, False, self._err) Image.PCopy(self._img, outImage, self._err) Image.PCopyTables(self._img, outImage, ['AIPS HI'], tables_to_copy, self._err) handle_obit_err(err_msg, self._err)
def _init(self, desc, verbose=True): # Open with full path in disk 0 disk = 0 path = desc['dirname']+"/"+desc['filename'] image = Image.newPFImage(desc['filename'], path, disk, True, self.err, verbose = verbose) if not image.isOK: # Exception if something went wrong raise OErr.OErr OErr.printErrMsg(self.err, "Error with FITSImage") return image
def AppendVLTable(infile, outfile=outfile, err=err): """ Copy VL table ver 1 from infile to outfile infile = name of input FITS image file with VL table outfile = name of output FITS image file with extant VL table err = Python Obit Error/message stack """ ################################################################ # Get images inImage = Image.newPFImage("Input image", infile, indisk, 1, err) outImage = Image.newPFImage("Output image", outfile, outdisk, 1, err) OErr.printErrMsg(err, "Error creating image objects") # # obtain "AIPS VL" tables from each inTable = Image.PImageNewImageTable(inImage, 1, "AIPS VL", 1, err) outTable = Image.PImageNewImageTable(outImage, 3, "AIPS VL", 1, err) OErr.printErrMsg(err, "Error extracting AIPS VL table objects") # Concatenate Table.PConcat(inTable, outTable, err) OErr.printErrMsg(err, "Error concatenatinfg tables") print "Appended", infile, "to", outfile
def SumCCSpectrum(path, err, chOff=-9999): """ Obtain a spectrum from the CC tables in an FITS image Sum all the clean components in each table (one per channel) returns a dictionary with entries ch = channel numbers vel = velocity (km/s) coordinate (first col) flux = spectral values path = FITS file path, assume FITS disk 0 chOff = offset to add to channel number in computing Vel if not given is determined from image header """ ################################################################ inImage = Image.newPFImage("Input image", path, 0, True, err) OErr.printErrMsg(err, "Error making image") imDict = inImage.Desc.Dict ntable = inImage.GetHighVer("AIPS CC") inImage.Open(Image.READONLY, err) OErr.printErrMsg(err, "Error making image") if chOff < -9000: d = inImage.Desc.Dict chOff = 1 - d["crpix"][d["jlocf"]] # Loop over tables ch = [] vel = [] flux = [] for i in range(1, ntable + 1): # Make Table inTable = inImage.NewTable(Table.READONLY, "AIPS CC", i, err) OErr.printErrMsg(err, "Eror making table") inTable.Open(Table.READONLY, err) OErr.printErrMsg(err, "Error with table") nrow = inTable.Desc.Dict["nrow"] sum = 0.0 for irow in range(1, nrow + 1): row = inTable.ReadRow(irow, err) OErr.printErrMsg(err, "Error with table") sum = sum + row['FLUX'][0] inTable.Close(err) OErr.printErrMsg(err, "Error with table") #print "debug", i, nrow, sum # save ch.append(i) v = 0.001 * (imDict['crval'][2] + imDict['cdelt'][2] * (i + chOff - imDict['crpix'][2])) vel.append(v) flux.append(sum) inImage.Close(err) OErr.printErrMsg(err, "Error closinging image") return {'ch': ch, 'vel': vel, 'flux': flux}
def SumImageSpectrum(path, err, chOff=-9999): """ Obtain a spectrum from integral of image planes in an FITS image Sum all pixel values and divides by the beam area returns a dictionary with entries ch = channel numbers vel = velocity (km/s) coordinate (first col) flux = spectral values path = FITS file path, assume FITS disk 0 chOff = offset to add to channel number in computing Vel if not given is determined from image header """ ################################################################ inImage = Image.newPFImage("Input image", path, 0, True, err) OErr.printErrMsg(err, "Error making image") imDict = inImage.Desc.Dict nplane = imDict["inaxes"][2] blc = [1, 1, 1] trc = [imDict["inaxes"][0], imDict["inaxes"][1], 1] beamMaj = imDict["beamMaj"] / abs(imDict["cdelt"][0]) beamMin = imDict["beamMin"] / abs(imDict["cdelt"][1]) barea = 1.1331 * beamMaj * beamMin inImage.Open(1, err) OErr.printErrMsg(err, "Error making image") if chOff < -9000: d = inImage.Desc.Dict chOff = 1 - d["crpix"][d["jlocf"]] # Loop over planes ch = [] vel = [] flux = [] for i in range(1, nplane + 1): # Read plane blc[2] = i trc[2] = i data = inImage.ReadPlane(err, blc=blc, trc=trc) OErr.printErrMsg(err, "Error reading plane") s = data.Sum #print "debug", i, s/barea # save ch.append(i) v = 0.001 * (imDict['crval'][2] + imDict['cdelt'][2] * (i + chOff - imDict['crpix'][2])) vel.append(v) flux.append(s / barea) inImage.Close(err) OErr.printErrMsg(err, "Error closinging image") return {'ch': ch, 'vel': vel, 'flux': flux}
def NVSSPtFlux(RA, Dec, equinox, err, stokes='I',dir="/home/ftp/nvss/MAPS"): """ Determine the NVSS Flux density Returns flux density, None on failure RA = Right ascension as string ("HH MM SS.SS") Dec = Declonation as string ("sDD MM SS.SS") equinox = equinox of RA,Dec, 1950 or 2000 err = Python Obit Error/message stack stokes = Stokes desired, 'I', 'Q' or 'U' dir = directory or url of directory """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" if err.isErr: # existing error? return None # file = NVSSFindFile(RA, Dec, equinox, err, stokes=stokes) if err.isErr: OErr.printErr(err) return None path = dir+"/"+file #print "Image ",path img = Image.newPFImage("Image", path, 0, True, err, verbose=False) if err.isErr: OErr.printErr(err) return None interp = ImageInterp.PCreate("Interpolator", img, err) if err.isErr: OErr.printErr(err) return None ra = ImageDesc.PHMS2RA(RA, sep=' ') dec = ImageDesc.PDMS2Dec(Dec, sep=' ') # Precess 1950 to 2000? if equinox==1950: (ra,dec) = SkyGeom.PBtoJ(ra,dec) # Plane plane = 1 if stokes=='Q': plane = 2 if stokes=='U': plane = 3 # Interpolate value = interp.Value(ra, dec, err, plane=plane) if err.isErr: OErr.printErr(err) return None return value;
def pbcorr_obit(image_filename, output_image, err, mingain=0.05, scratch_dir='/tmp'): #Load the original image into Obit im = Image.newPFImage("in", image_filename, 0, True, err) #Construct an output Obit Image im_pbcorr = Image.newPFImage("wt", scratch_dir + '/crop_pb.fits', 0, False, err) im.Clone(im_pbcorr, err) #PBCOrrect #ImageUtil.PPBCorr(im, im, im_pbcorr, err, antSize=12.0, PBmin=0.1) ImageUtil.PPBImage(im, im_pbcorr, err, minGain=mingain, antSize=13.5) inimage = pyfits.open(image_filename) beam = pyfits.open(scratch_dir + '/crop_pb.fits') pbcorrdata = inimage[0].data / beam[0].data new_hdu = pyfits.PrimaryHDU(data=pbcorrdata, header=inimage[0].header) pyfits.HDUList([new_hdu]).writeto(output_image, clobber=True) im_pbcorr = Image.newPFImage("wt", output_image, 0, False, err) #cleanup os.remove(scratch_dir + '/crop_pb.fits') return im_pbcorr
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 tvlod(image, window=None): """ display image image = Obit Image, created with getname, getFITS window = Optional window for image to edit """ ################################################################ if Image.PIsA(image): # Obit/Image ODisplay.PImage(disp, image, err, window=window) elif image.__class__==AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",image.name, image.klass, image.disk, \ image.seq, True, err) ODisplay.PImage(disp, tmp, err, window=window) del tmp elif image.__class__==FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image",image.filename, image.disk, True, err) ODisplay.PImage(disp, tmp, err, window=window) del tmp
def tvlod(image, window=None): """ display image * image = Obit Image, created with getname, getFITS * window = Optional window for image to edit """ ################################################################ if Image.PIsA(image): # Obit/Image ODisplay.PImage(disp, image, err, window=window) elif image.__class__==AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",image.name, image.klass, image.disk, \ image.seq, True, err) ODisplay.PImage(disp, tmp, err, window=window) del tmp elif image.__class__==FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image",image.filename, image.disk, True, err) ODisplay.PImage(disp, tmp, err, window=window) del tmp
def window (image): """ Make a window object for an image Returns OWindow object image = Obit image object """ ################################################################ if Image.IsA(image): # Obit/Image naxis = image.Desc.Dict["inaxes"][0:2] elif image.__class__==AIPSData.AIPSImage: # AIPS Image tmp = Image.newPAImage("AIPS Image",image.name, image.klass, image.disk, \ image.seq, True, err) naxis = tmp.Desc.Dict["inaxes"][0:2] del tmp elif image.__class__==FITSData.FITSImage: # FITS Image tmp = Image.newPFImage("FITS Image",image.filename, image.disk, True, err) naxis = tmp.Desc.Dict["inaxes"][0:2] del tmp return OWindow.PCreate1("Window", naxis, err)
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
def VLAImFITS(inImage, filename, outDisk, err, fract=None, quant=None, \ exclude=["AIPS HI","AIPS PL","AIPS SL"], include=["AIPS CC"], headHi=False): """ Write AIPS image as FITS Write a Image data set as a FITAB format file History also copied inImage = Image data to copy filename = name of FITS file outDisk = FITS directory number err = Python Obit Error/message stack fract = Fraction of RMS to quantize quant = quantization level in image units, has precedence over fract None or <= 0 => use fract. 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 headHi = if True move history to header, else leave in History table """ ################################################################ # # Checks if not Image.PIsA(inImage): raise TypeError, "inImage MUST be a Python Obit Image" if not OErr.OErrIsA(err): raise TypeError, "err MUST be an OErr" # # Set output outImage = Image.newPFImage("FITS Image DATA", filename, outDisk, False, err) if err.isErr: OErr.printErrMsg(err, "Error creating FITS data") # Check for valid pixels if inImage.Desc.Dict["maxval"] <= inImage.Desc.Dict["minval"]: fract = None quant = None # Copy if fract or quant: Image.PCopyQuantizeFITS(inImage, outImage, err, fract=fract, quant=quant) else: Image.PCopy(inImage, outImage, err) if err.isErr: OErr.printErrMsg(err, "Error copying Image data to FITS") # Copy History inHistory = History.History("inhistory", inImage.List, err) outHistory = History.History("outhistory", outImage.List, err) History.PCopy(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit imtab", err) if fract: outHistory.WriteRec(-1, "imtab / Quantized at " + str(fract) + " RMS", err) outHistory.WriteRec( -1, "imtab / FITS file " + filename + ", disk " + str(outDisk), err) outHistory.Close(err) # History in header? if headHi: # Copy back to header inHistory = History.History("inhistory", outImage.List, err) History.PCopy2Header(inHistory, outHistory, err) # zap table outHistory.Zap(err) OErr.printErrMsg(err, "Error with history") # Copy Tables Image.PCopyTables(inImage, outImage, exclude, include, err)
list = InfoList.InfoList() dim = [1, 0, 0, 0, 0] InfoList.PPutLong(list, "longItem", dim, [321], err) x = InfoList.PGet(list, "longItem") x = FArray.FArray("MyFArray", [30, 50]) FArray.PSetVal(x, [25, 25], 3.1415926) pos = [-1, -1] result = FArray.PMax(x, pos) print "FArray max is", result, "should be 3.1415926" result = FArray.PMin(x, pos) print "FArray min is", result, "should be 0" file = "testPcube.fits" disk = 1 image = Image.newPFImage("myImage", file, disk, True, err) OErr.printErr(err) Image.POpen(image, 1, err) OErr.printErr(err) Image.PRead(image, err) OErr.printErr(err) Image.PClose(image, err) data = Image.PGetFArray(image) pos = [-1, -1] result = FArray.PMax(data, pos) print "Max in", file, "is", result result = FArray.PRMS(data) print "RMS in", file, "is", result OErr.printErr(err) del err
# Init Obit err = OErr.OErr() ObitSys = OSystem.OSystem("Image", 1, 100, 1, ["None"], 1, ["."], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Bomb if needed for debugging #Bomb() # Get file names outFile = sys.argv[1] inFile = sys.argv[2:] inDisk = 1 outDisk = 1 # Convert files into Images inImage = [Image.newPFImage(inFile[0], inFile[0], inDisk, True, err)] for x in inFile[1:]: inImage.append(Image.newPFImage("Input image", x, inDisk, True, err)) OErr.printErrMsg(err, "Error initializing images") # output image outImage = Image.newPFImage(outFile, outFile, outDisk, False, err) OErr.printErrMsg(err, "Error initializing output image") # Add number of planes id = inImage[0].Desc od = outImage.Desc ImageDesc.PCopyDesc(id, od, err) dict = od.Dict inaxes = id.Dict["inaxes"] inaxes[2] = len(inImage)
#print sys.argv #Bomb() # Get Filenames (FITS) inDisk = 1 outDisk = 1 inFile = sys.argv[1] outFile = sys.argv[2] # Fraction of RMS if given if (len(sys.argv) >= 4): fract = float(sys.argv[3]) else: fract = 0.25 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, True, err) outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) #Image.PClone(inImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # Copy to quantized integer image with history print "Write quantized output image" Image.PCopyQuantizeFITS(inImage, outImage, err, fract=fract) # Copy History inHistory = History.History("inhistory", inImage.List, err) outHistory = History.History("outhistory", outImage.List, err) History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit " + ObitSys.pgmName, err)
ObitSys=OSystem.OSystem ("Feather", 1, 100, 1, ["../AIPSdata/"], 1, ["../testIt/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # For debugging #Bomb() # Get file names outFile = 'FeatherTestOut.fits' inFile = ['FeatherTestIn1.fits','FeatherTestIn2.fits'] inDisk = 1 outDisk = 1 masterDisk = 1 masterFile = 'FeatherTestMaster.fits' # Convert files into Images inImage = [Image.newPFImage(inFile[0], inFile[0], inDisk, 1, err)] for x in inFile[1:]: inImage.append(Image.newPFImage("Input image", x, inDisk, 1, err)) OErr.printErrMsg(err, "Error initializing images") # Create FFTs FFTfor = FeatherUtil.PCreateFFT(inImage[0], 1) FFTrev = FeatherUtil.PCreateFFT(inImage[0], 2) # Create padded images for FFT size print "Pad/interpolate Images to same grid" padImage = [] i = 0; # First image sets the grid for the following print "Pad Loop",i,inFile[i] name = "Pad"+inFile[i]
def UpdateOTF (OTFTask, Rcvr, outFile, outDisk, DataRoot, err, \ scanList=None, offTime=None, avgTime=None, config=None, \ scanNo=None, doBS=None, dataNorm=None): """ Update OTF and return object return Python OTF object Update an OTF object with scans not yet in the file. Read DataRoot/scanLog.fits and determine which scans are available and are not already in the output OTF. These scans are appended and the output OTF returned. Does some data validity checks. OTFTask = Name of Obit task to read GBT archive and write to OTF format DCR = "DCROTF" PAR = "PAROTF" (Mustang) CCB = "CCBOTF" VEGAS = "VEGASOTF" Rcvr = directory name with data for receiver. DCR = "DCR" PAR = "Rcvr_PAR" (Mustang) CCB = "CCB26_40" VEGAS = GBT VEGAS spectrometer outFile = Name of output OTF FITS file outDisk = disk number for outFile, 0=> current working directory DataRoot = Root of GBT archive for current project If None, don't attempt err = Python Obit Error/message stack Optional, backend specific values scanList = All, list of scan numbers, None=>all offTime = PAR, CCB, VEGAS Offset in sec to be added to time avgTime = PAR Data averaging time in seconds config = PAR path of configuration file scanNo = PAR, CCB, VEGAS, replace GBT scan number with this value doBS = CCB, output beamswitched data dataNorm = CCB normalization factors for beamswitched data """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError, "err MUST be an OErr" # Anything to do? if not DataRoot: outOTF = OTF.newPOTF("output", outFile, outDisk, True, err, nrec=1000) return outOTF # Scan list if scanList: sList = scanList else: sList = range(1, 1000000) # How much data is already there? maxscan = 0 # max scan number found so far outOTF = None if FITSDir.PExist(outFile, outDisk, err): outOTF = OTF.newPOTF("output", outFile, outDisk, True, err) indx = outOTF.NewTable(Table.READONLY, "OTFIndex", 1, err) indx.Open(Table.READONLY, err) norow = indx.Desc.Dict["nrow"] indxRow = indx.ReadRow(norow, err) maxscan = indxRow["SCAN_ID"][0] indx.Close(err) OErr.printErrMsg(err, "Error with Output OTF file") print "Highest previous scan is", maxscan # Task to read/append otf = ObitTask.ObitTask(OTFTask) otf.DataRoot = DataRoot otf.outOTF = outFile otf.outDisk = outDisk # Optional parameters if offTime: otf.offTime = offTime if avgTime: otf.avgTime = avgTime if config: otf.config = config if scanNo: otf.scanNo = scanNo if doBS: otf.doBS = doBS if dataNorm: otf.dataNorm = dataNorm img = Image.newPFImage("Scan log", DataRoot + "ScanLog.fits", 0, True, err) scanLog = img.NewTable(Table.READONLY, "ScanLog", 1, err) scanLog.Open(Table.READONLY, err) OErr.printErrMsg(err, "Error with ScanLog") norow = scanLog.Desc.Dict["nrow"] scnstr = [] # list of scan numbers for irow in range(1, norow + 1): scan = scanLog.ReadRow(irow, err) scanno = scan["SCAN"][0] if (scanno > maxscan) and (scanno in sList): # Take this one maxscan = scanno datetime = scan["DATE-OBS"][0] # Table ScanLog, multiple entries per scan, need to translate # timestring to scan, "-" => "_", "T" => "_" scanstr = datetime.replace("-", "_").replace("T", "_").rstrip() # Make sure there is actual data test = DataRoot + Rcvr + "/" + scanstr + ".fits" OK = FITSDir.PExist(test, 0, err) or FITSDir.PExist( test + ".gz", 0, err) test = DataRoot + "GO/" + scanstr + ".fits" OK = OK and FITSDir.PExist(test, 0, err) or FITSDir.PExist( test + ".gz", 0, err) test = DataRoot + "Antenna/" + scanstr + ".fits" #print "antenna",test OK = OK and FITSDir.PExist(test, 0, err) or FITSDir.PExist( test + ".gz", 0, err) #print "DEBUG scan",scanstr, Rcvr, OK if OK: scnstr.append(scanstr) # Run selected translator to append this scan otf.Scan = scanstr try: otf.debug = True # DEBUG otf.g except: print "failed on scan", scanstr else: pass # Now have list of scans>maxscan in scnstr scanLog.Close(err) OErr.printErrMsg(err, "Error with ScanLog") print "Added Scans", scnstr # Output if just created if not outOTF: outOTF = OTF.newPOTF("output", outFile, outDisk, True, err) OErr.printErrMsg(err, "Error with Output OTF file") return outOTF
OErr.printErrMsg(err, "Error with Obit startup") # For debugging #print sys.argv #Obit.Bomb() # Get file names tmplFile = "C0000P00.gz" # Template tmpFile1 = "testSum1.fits" # work accumulation tmpFile2 = "testSum2.fits" # work accumulation outFile = "Comb0000P00.fits" # output inDisk = 1 outDisk = 1 # Convert files into Images tmplImage = Image.newPFImage("Template image", tmplFile, inDisk, True, err) SumWtImage = Image.newPFImage("Accum image 1", tmpFile1, outDisk, False, err) SumWt2 = Image.newPFImage("Accum image 2", tmpFile2, outDisk, False, err) OErr.printErrMsg(err, "Error initializing images") # Do it MosaicUtil.PMakeMaster(tmplImage, [1000,1000], SumWtImage, SumWt2, err) OErr.printErrMsg(err, "Error initializing images") print "Made accumulation images " print "Made master images ",tmpFile1,tmpFile2 del tmplImage # cleanup # Weight them together inFile=["00000+00000.PCUBE.gz","00000-00260.PCUBE.gz","00000+00260.PCUBE.gz"]
#print sys.argv #Bomb() # Get Filenames (FITS) inDisk = 1 outDisk = 1 inFile = sys.argv[1] outFile = sys.argv[2] # Fraction of RMS if given if (len(sys.argv)>=4): fract = float(sys.argv[3]) else: fract = 0.25 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, True, err) outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) #Image.PClone(inImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # Copy to quantized integer image with history print "Write quantized output image" Image.PCopyQuantizeFITS (inImage, outImage, err, fract=fract) # Copy History inHistory = History.History("inhistory", inImage.List, err) outHistory = History.History("outhistory", outImage.List, err) History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit "+ObitSys.pgmName,err)
list = InfoList.InfoList(); dim = [1,0,0,0,0] InfoList.PPutLong (list, "longItem", dim, [321], err) x=InfoList.PGet (list, "longItem") x=FArray.FArray("MyFArray",[30,50]) FArray.PSetVal(x,[25,25],3.1415926) pos=[-1,-1] result = FArray.PMax(x,pos) print "FArray max is",result, "should be 3.1415926" result = FArray.PMin(x,pos) print "FArray min is",result, "should be 0" file = "testPcube.fits" disk = 1 image = Image.newPFImage("myImage", file, disk, True, err); OErr.printErr(err) Image.POpen(image,1,err) OErr.printErr(err) Image.PRead(image,err) OErr.printErr(err) Image.PClose(image,err) data = Image.PGetFArray(image); pos=[-1,-1] result = FArray.PMax(data,pos) print "Max in",file,"is",result result = FArray.PRMS(data) print "RMS in",file,"is",result OErr.printErr(err) del err
OErr.printErrMsg(err, "Error with Obit startup") # For debugging #print sys.argv #Bomb() # Get Filenames (FITS) inDisk = 1 tmplDisk = 1 outDisk = 1 scale = float(sys.argv[1]) inFile = sys.argv[2] outFile = sys.argv[3] # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, 1, err) outImage = Image.newPFImage("Output image", outFile, outDisk, 0, err) OErr.printErrMsg(err, "Error initializing") # Update header scale times bigger image with scale times smaller increment inHead = inImage.Desc.Dict inHead["cdelt"][0] /= scale inHead["cdelt"][1] /= scale inHead["crpix"][0] = (scale * (inHead["crpix"][0] - 1.0)) + 1.0 inHead["crpix"][1] = (scale * (inHead["crpix"][1] - 1.0)) + 1.0 inHead["inaxes"][0] = int(scale * (inHead["inaxes"][0])) inHead["inaxes"][1] = int(scale * (inHead["inaxes"][1])) outImage.Desc.Dict = inHead outImage.UpdateDesc(err) OErr.printErrMsg(err, "Error setting output header")
# 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")
# test Contour plot import Obit, OTObit, Image, ImageUtil, OSystem, OErr, OPlot, math # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Plot", 1, 100, 0, ["None"], 1, ["../testIt/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Contour plot file = "AGNVLA.fits" plotfile = "testCont.ps" lev=0.1 cntfac = 2.0**0.5 blc =[ 230,119] trc = [285,178] img = Image.newPFImage("in image",file, 1, True, err) info=img.List info.set("BLC",blc) info.set("TRC",trc) cont = OPlot.newOPlot("cont", err, output=plotfile+"/ps") OPlot.PContour(cont, "Some AGN", img, lev, cntfac, err) # Text txt=[(265.0,155.0,"A"), \ (258.0,155.0,"B"), \ (251.0,152.0,"C"), \ (247.0,149.0,"D"), \ (241.0,146.0,"E"), \ (244.0,141.0,"F")] OPlot.PSetCharSize(cont, 1 ,err) for ss in txt: x=-(ss[0]-1.-250.9)*2.0/60.0; y=(ss[1]-1.-150.1)*2.0/60.0;
OErr.printErrMsg(err, "Error with Obit startup") # For debugging #print sys.argv #Bomb() # Get Filenames (FITS) inDisk = 1 tmplDisk = 1 outDisk = 1 inFile = sys.argv[1] tmplFile = sys.argv[2] outFile = sys.argv[3] # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, 1, err) tmplImage = Image.newPFImage("Template image", tmplFile, tmplDisk, 1, err) outImage = Image.newPFImage("Output image", outFile, outDisk, 0, err) Image.PClone(tmplImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # Interpolate ImageUtil.PInterpolateImage(inImage, outImage, err) OErr.printErrMsg(err, "Error interpolating") # copy history inHistory = History.History("history", inImage.List, err) outHistory = History.History("history", outImage.List, err) History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err)
import OErr, OSystem adirs = [] fdirs = ['./'] # Init Obit err = OErr.OErr() user = 100 ObitSys=OSystem.OSystem ("plotSpectrum", 1, user, len(adirs), adirs, \ len(fdirs), fdirs, True, False, err) OErr.printErrMsg(err, "Error with Obit startup") fblank = FArray.fblank # In image icube = Image.newPFImage('In', inFile, fdisk, True, err) # Image info nterm = icube.Desc.List.Dict['NTERM'][2][0] nspec = icube.Desc.List.Dict['NSPEC'][2][0] freqs = [] for i in range(1, nspec + 1): key = 'FREQ%4.4d' % i freqs.append(1.0e-9 * icube.Desc.List.Dict[key][2][0]) # GHz # end loop # Interpolator fi = FInterpolate.FInterpolate('FI', icube.FArray, icube.Desc, 2) # Get pixel locations pixels = [] vals = [] for s in srcpos:
# end image to uv plane inIm.Desc.Dict = header inIm.UpdateDesc(err) # end FFTHeaderUpdate # Get file names inFile = sys.argv[1] outAFile = sys.argv[2] outPFile = sys.argv[3] inDisk = 1 outADisk = 1 outPDisk = 1 # Convert files into Images inImage = Image.newPFImage(inFile, inFile, inDisk, True, err) outAImage = Image.newPFImage(outAFile, outAFile, outADisk, False, err) inImage.Clone(outAImage,err) outPImage = Image.newPFImage(outPFile, outPFile, outPDisk, False, err) inImage.Clone(outPImage,err) OErr.printErrMsg(err, "Error initializing images") # Size of FFT inImage.Open(Image.READONLY, err) inImage.Read(err) OErr.printErrMsg(err, "Error reading input") inHead = inImage.Desc.Dict FFTdim = [FFT.PSuggestSize(inHead["inaxes"][0]), FFT.PSuggestSize(inHead["inaxes"][1])] # Create float arrays for FFT size inFArray = FArray.FArray("inF", naxis=FFTdim)
err = OErr.OErr() ObitSys = OSystem.OSystem("TestSort", 1, 100, 1, ["../AIPSdata/"], 1, ["../PythonData/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files (FITS) inDisk = 1 inFile = 'GaussTest.fits' #outFile = 'GaussTest.fits' # AIPS test AIPS image user 100 C346R422 .POLI . 2,, disk 8/142 #aname = "C346R422" #aclass = "POLI" #aseq = 2 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, 1, err) #outImage = Image.newPAImage("Output image", aname, aclass, inDisk, aseq, 1, err) OErr.printErrMsg(err, "Error initializing") # For debugging #Obit.Bomb() # Make Table inTable = Image.PImageGetTable(inImage, 3, "AIPS VL", 1, err) OErr.printErrMsg(err, "Eror making table") #Sort Table.PSort(inTable, "DEC(2000)", 0, err) OErr.printErrMsg(err, "Error sorting") # Say something
def VLAImFITS(inImage, filename, outDisk, err, fract=None, quant=None, \ exclude=["AIPS HI","AIPS PL","AIPS SL"], include=["AIPS CC"], headHi=False): """ Write AIPS image as FITS Write a Image data set as a FITAB format file History also copied inImage = Image data to copy filename = name of FITS file outDisk = FITS directory number err = Python Obit Error/message stack fract = Fraction of RMS to quantize quant = quantization level in image units, has precedence over fract None or <= 0 => use fract. 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 headHi = if True move history to header, else leave in History table """ ################################################################ # # Checks if not Image.PIsA(inImage): raise TypeError,"inImage MUST be a Python Obit Image" if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # # Set output outImage = Image.newPFImage("FITS Image DATA", filename, outDisk, False, err) if err.isErr: OErr.printErrMsg(err, "Error creating FITS data") # Check for valid pixels if inImage.Desc.Dict["maxval"]<=inImage.Desc.Dict["minval"]: fract=None; quant=None # Copy if fract or quant: Image.PCopyQuantizeFITS (inImage, outImage, err, fract=fract, quant=quant) else: Image.PCopy (inImage, outImage, err) if err.isErr: OErr.printErrMsg(err, "Error copying Image data to FITS") # Copy History inHistory = History.History("inhistory", inImage.List, err) outHistory = History.History("outhistory", outImage.List, err) History.PCopy(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit imtab",err) if fract: outHistory.WriteRec(-1,"imtab / Quantized at "+str(fract)+" RMS",err) outHistory.WriteRec(-1,"imtab / FITS file "+filename+", disk "+str(outDisk),err) outHistory.Close(err) # History in header? if headHi: # Copy back to header inHistory = History.History("inhistory", outImage.List, err) History.PCopy2Header (inHistory, outHistory, err) # zap table outHistory.Zap(err) OErr.printErrMsg(err, "Error with history") # Copy Tables Image.PCopyTables (inImage, outImage, exclude, include, err)
# 4) #---------------------------------------------------------------- # Set data inOTF =OTF.newPOTF("Input data", inFile, inDisk, 1, err) OErr.printErrMsg(err, "Error creating input data object") inInfo = inOTF.List ################################## Set parameters ##################################### # Get position from OTF pos = GBTUtil.GetTargetPos(inOTF, target[0], err) ra = pos[0] # ra of center dec = pos[1] # dec of center # dirty beam dirtyBeam = Image.newPFImage("dirty beam", BeamFile, inDisk, True, err) OErr.printErrMsg(err, "Error initializing dirty beam") # Image display disp = ODisplay.ODisplay("ObitView", "ObitView", err) # Imaging parameters OTF.ImageInput["InData"] = inOTF OTF.ImageInput["disk"] = inDisk OTF.ImageInput["OutName"] = dirtFile OTF.ImageInput["Beam"] = dirtyBeam OTF.ImageInput["ra"] = ra # Center RA OTF.ImageInput["dec"] = dec # Center Dec OTF.ImageInput["xCells"] = cells # "X" cell spacing OTF.ImageInput["yCells"] = cells # "Y" cell spacing OTF.ImageInput["nx"] = nx # number of cells in X
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
# Program to generate a dirty beam import Image, ImageDesc, OSystem, OErr, FArray # Init Obit err = OErr.OErr() ObitSys = OSystem.OSystem("MakeDBeam", 1, 103, 1, ["None"], 1, ["./FITSdata/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files disk = 1 outFile = "!PARDBeam1.5.fits" # output image # Create image object outImage = Image.newPFImage("Output image", outFile, disk, 0, err) OErr.printErrMsg(err, "Error initializing") # define image RA = 0.0 Dec = 0.0 nx = 51 ny = 51 xCells = 2.0 / 3600.0 yCells = 2.0 / 3600.0 beamsize = 8.0 / 3600.0 # beamsize in deg. # Set image parameters in descriptor imagDesc = outImage.Desc imagDict = imagDesc.Dict imagDict["ctype"][0] = "RA---SIN" imagDict["ctype"][1] = "DEC--SIN"
import sys, Obit, Image, FArray, CArray, FFT, ImageUtil, OSystem, OErr, InfoList, History # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("AvgImage", 1, 100, 1, ["None"], 1, ["./"], True, False, err) OErr.printErrMsg(err, "Error with Obit startup") # Get file names outFile = sys.argv[1] inFile = sys.argv[2:] inDisk = 1 outDisk = 1 # Convert files into Images inImage = [Image.newPFImage(inFile[0], inFile[0], inDisk, 1, err)] for x in inFile[1:]: inImage.append(Image.newPFImage("Input image", x, inDisk, 1, err)) OErr.printErrMsg(err, "Error initializing images") # Read accumulate images accumArray = None countArray = None for x in inImage: x.Open(Image.READONLY,err) x.Read(err) fa = x.FArray if not accumArray: accumArray = FArray.PCopy(fa,err) countArray = FArray.PClone(fa,err) # Count of elements FArray.PFill(countArray, 1.0)
History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit "+ObitSys.pgmName,err) outHistory.WriteRec(-1,ObitSys.pgmName+" inFile = "+inFile,err) outHistory.WriteRec(-1,ObitSys.pgmName+" FOV = "+str(FOV),err) outHistory.WriteRec(-1,ObitSys.pgmName+" Stokes = "+Stokes,err) outHistory.WriteRec(-1,ObitSys.pgmName+" TimeRange = "+str(TimeRange),err) outHistory.WriteRec(-1,ObitSys.pgmName+" UVRange = "+str(UVRange),err) outHistory.WriteRec(-1,ObitSys.pgmName+" Robust = "+str(Robust),err) outHistory.WriteRec(-1,ObitSys.pgmName+" UVTaper = "+str(UVTaper),err) outHistory.Close(err) OErr.printErrMsg(err, "Error with history") # output image outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) Image.PClone(tmpImage, outImage, err) # Same structure etc. # Copy to quantized integer image with history print "Write output image" inHistory = History.History("history", tmpImage.List, err) Image.PCopyQuantizeFITS (tmpImage, outImage, err, inHistory=inHistory) # Compare with master lie [rms diff, max abs diff, max. master] masterImage = Image.newPFImage("Master image", masterFile, masterDisk, True, err) diff = Image.PCompare(outImage, masterImage, err); print "Comparison, rel. max. residual",diff[1]/diff[0], " rel RMS residual",diff[2]/diff[0] # Say something print "CLEAN: Dirty Image ",inFile,"Clean",outFile
err=OErr.OErr() ObitSys=OSystem.OSystem ("Feather", 1, 100, 1, ["../AIPSdata/"], 1, ["../PythonData/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # For debugging #print sys.argv #Bomb() # Get file names outFile = sys.argv[1] inFile = sys.argv[2:] inDisk = 1 outDisk = 1 # Convert files into Images inImage = [Image.newPFImage(inFile[0], inFile[0], inDisk, 1, err)] for x in inFile[1:]: inImage.append(Image.newPFImage("Input image", x, inDisk, 1, err)) OErr.printErrMsg(err, "Error initializing images") # Create FFTs FFTfor = FeatherUtil.PCreateFFT(inImage[0], 1) FFTrev = FeatherUtil.PCreateFFT(inImage[0], 2) # Create padded images for FFT size print "********** Pad/interpolate Images to same grid *******" padImage = [] i = 0; # First image sets the grid for the following print "Pad Loop",i,inFile[i] name = "Pad"+inFile[i]
History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit "+ObitSys.pgmName,err) outHistory.WriteRec(-1,ObitSys.pgmName+" inFile = "+inFile,err) outHistory.WriteRec(-1,ObitSys.pgmName+" FOV = "+str(FOV),err) outHistory.WriteRec(-1,ObitSys.pgmName+" Stokes = "+Stokes,err) outHistory.WriteRec(-1,ObitSys.pgmName+" TimeRange = "+str(TimeRange),err) outHistory.WriteRec(-1,ObitSys.pgmName+" UVRange = "+str(UVRange),err) outHistory.WriteRec(-1,ObitSys.pgmName+" Robust = "+str(Robust),err) outHistory.WriteRec(-1,ObitSys.pgmName+" UVTaper = "+str(UVTaper),err) outHistory.Close(err) OErr.printErrMsg(err, "Error with history") # output image outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) Image.PClone(tmpImage, outImage, err) # Same structure etc. # Copy to quantized integer image with history print "Write output image" inHistory = History.History("history", tmpImage.List, err) Image.PCopyQuantizeFITS (tmpImage, outImage, err, inHistory=inHistory) # Compare with master lie [rms diff, max abs diff, max. master] masterImage = Image.newPFImage("Master image", masterFile, masterDisk, True, err) diff = Image.PCompare(outImage, masterImage, err); print "Comparison, rel. max. residual",diff[1]/diff[0], " rel RMS residual",diff[2]/diff[0] # Cleanup ImageMosaic.PZapImage(outMosaic, -1, err) # delete mosaic images tmpImage.Zap(err) # Full field too
# Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("TestSort", 1, 100, 1, ["../AIPSdata/"], 1, ["../PythonData/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files (FITS) inDisk = 1 inFile = 'GaussTest.fits' #outFile = 'GaussTest.fits' # AIPS test AIPS image user 100 C346R422 .POLI . 2,, disk 8/142 #aname = "C346R422" #aclass = "POLI" #aseq = 2 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, 1, err) #outImage = Image.newPAImage("Output image", aname, aclass, inDisk, aseq, 1, err) OErr.printErrMsg(err, "Error initializing") # For debugging #Obit.Bomb() # Make Table inTable = Image.PImageGetTable (inImage, 3, "AIPS VL", 1, err) OErr.printErrMsg(err, "Eror making table") #Sort Table.PSort (inTable, "DEC(2000)", 0, err) OErr.printErrMsg(err, "Error sorting") # Say something
def open_img(aips_path, mode=None, MF=False): """ Opens an AIPS/FITS Image file and returns a wrapped :class:`ImageFacade` object. Parameters ---------- aips_path: :class:`AIPSPath` Obit file object. mode(optional): str "r" to read, "w" to write, "rw" to read and write. Defaults to "r" MF(optional): boolean Open as an ImageMF? Returns ------- :class:`Image` An Obit Image object """ err = obit_err() if mode is None: mode = "r" img_mode = img_file_mode(mode) exists = False # Test if the file exists if aips_path.dtype == "AIPS": if MF: img_open = ImageMF.newPAImage else: img_open = Image.newPAImage try: img = img_open(aips_path.label, aips_path.name, aips_path.aclass, aips_path.disk, aips_path.seq, exists, err) except Exception: raise ValueError("Error calling newPAImage on '%s'" % aips_path) elif aips_path.dtype == "FITS": raise NotImplementedError("newPFImage calls do not currently work") try: img = Image.newPFImage(aips_path.label, aips_path.name, aips_path.disk, exists, err) except Exception: raise ValueError("Error calling newPFImage on '%s'" % aips_path) else: raise ValueError("Invalid dtype '{}'".format(aips_path.dtype)) handle_obit_err("Error opening '%s'" % aips_path, err) err_msg = "Error opening '%s'" % aips_path try: img.Open(img_mode, err) except Exception: raise ValueError(err_msg) handle_obit_err(err_msg, err) return img
err=OErr.OErr() ObitSys=OSystem.OSystem ("HGeom", 1, 100, 1, ["../AIPSdata/"], 1, ["../testIt/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files (FITS) inDisk = 1 inFile = 'HGeomTestIn.fits' tmplDisk = 1 tmplFile = 'HGeomTestTmpl.fits' masterDisk = 1 masterFile = 'HGeomTestMaster.fits' outDisk = 1 outFile = '!HGeomTestOut.fits' # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, True, err) tmplImage = Image.newPFImage("Template image", tmplFile, tmplDisk, True, err) outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) Image.PClone(tmplImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # For debugging #Obit.Bomb() # Generate scratch file from tmplFile tmpImage = Image.PScratch(tmplImage, err) Image.POpen(tmpImage, Image.WRITEONLY, err) # Open OErr.printErrMsg(err, "Error cloning template") # Interpolate ImageUtil.PInterpolateImage(inImage, tmpImage, err)