def MFPBCor(inIm, err, antSize=24.5, minGain=0.05): """ Apply primary beam corrections to an ImageMF WARNING: This routine modifies the input image; ONLY RUN IT ONCE. * inIm = Image to be modified * err = Python Obit Error/message stack * antSize = Antenna diameter in m. * minGain = Minimum antenna gain """ # Check if not inIm.ImageIsA(): raise TypeError("input MUST be a Python Obit Image") # Image info nterm = inIm.Desc.List.Dict['NTERM'][2][0] nspec = inIm.Desc.List.Dict['NSPEC'][2][0] freqs = [] for i in range(1, nspec + 1): key = 'FREQ%4.4d' % i freqs.append(inIm.Desc.List.Dict[key][2][0]) # end loop # Make scratch image for beam beam = Image.Image("PBeam") Image.PCloneMem(inIm, beam, err) OErr.printErrMsg(err, "Error with scratch beam image") # Loop over planes for i in range(1, nspec + 1): # Read plane plane = [i + nterm, 1, 1, 1, 1] Image.PGetPlane(inIm, None, plane, err) OErr.printErrMsg(err, "Error reading image") # Set frequency for PBCor d = inIm.Desc.Dict d['crval'][2] = freqs[i - 1] inIm.Desc.Dict = d # Make PB Image ImageUtil.PPBImage(beam, beam, err, minGain=minGain, antSize=antSize, outPlane=plane) OErr.printErrMsg(err, "Error making PB image") # Divide FArray.PDivClip(inIm.FArray, beam.FArray, minGain, inIm.FArray) # Rewrite plane Image.PPutPlane(inIm, None, plane, err) OErr.printErrMsg(err, "Error writing image") # end loop # Add history outHistory = History.History("history", inIm.List, err) outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit MFPBCor", err) outHistory.WriteRec(-1, "MFPBCor" + " antSize = " + str(antSize), err) outHistory.WriteRec(-1, "MFPBCor" + " minGain = " + str(minGain), err) outHistory.Close(err)
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_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 PWeightImageEq(inImage, factor, SumWtImage, SumWt2, err, minGain=0.1, iblc=[1,1,1], itrc=[0,0,1], restart=0, hwidth=2, doGPU=False, planeWt=False, OTFRA=None, OTFDec=None, inWtImage=None, maxRMS=None, minAccWt=0.15): """ Sum an image onto Weighting accumulators using PB corrections Version for equatorial in/output and no relative rotation Calculate the weights for an image from the primary beam pattern And accumulate into the correct locations in the accumulation images. * inImage = Image to be accumulated * factor = Additional multiplication factor, normally 1.0 >0 => use the factor/RMS of each image plane * SumWtImage = First output image, must be defined (i.e. files named) but not fully created. * SumWt2 = Second output image, like SumWtImage * err = Python Obit Error/message stack * minGain = minimum allowed gain (lower values blanked). * iblc = BLC in plane to start selection * itrc = TRC in plane to end selection * restart = restart channel no. 0-rel * hwidth = half width of interpolation kernal [1-4] default 2 * doGPU = If true and GPU enables, use a GPU for the interpolation. * NB: routine will fail if GPU is not enabled. * planeWt = if True generate weight image per input plane * OTFoffsets = if >1 then make beam using multiple pointing offsets "Aussie mode" OTF. must also go=ive OTFRA, OTFDec * OTFRA = Array of RA offsets in deg not corrected for Declination * OTFDec = Array of Declinations offsets in deg, same size as OTFRA * inWtImage = Beam (weight) image to use if not None MUST have the same size as inImage * maxRMS = if given, the maximum RMS allowed * minAccWt = min. acceptable max. weight, otherwise ignore """ ################################################################ # Checks if not Image.PIsA(inImage): print "Actually ",inImage.__class__ raise TypeError,"inImage MUST be a Python Obit Image" if not Image.PIsA(SumWtImage): print "Actually ",SumWtImage.__class__ raise TypeError,"SumWtImage MUST be a Python Obit Image" if not Image.PIsA(SumWt2): print "Actually ",SumWt2.__class__ raise TypeError,"SumWt2 MUST be a Python Obit Image" if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # t0 = os.times()[4] # Initial time haveWtImage = inWtImage != None # Weight image given # Set BLC,TRC inImage.List.set("BLC",[iblc[0], iblc[1],1,1,1,1,1]) inImage.List.set("TRC",[itrc[0], itrc[1],0,0,0,0,0]) # Open accumulation files Image.POpen(inImage, Image.READONLY, err) # pythpn gets confused Image.POpen(SumWtImage, Image.READWRITE, err) Image.POpen(SumWt2, Image.READWRITE, err) # Get output descriptor to see how many planes outDesc = Image.PGetDesc(SumWtImage) outDescDict = ImageDesc.PGetDict(outDesc) outNaxis = outDescDict["inaxes"] print "Accumulation naxis",outNaxis # Get input descriptor to see how many planes inDesc = Image.PGetDesc(inImage) inDescDict = ImageDesc.PGetDict(inDesc) ndim = inDescDict["naxis"] inNaxis = inDescDict["inaxes"] finterp = None # GPU not yet enabled # Range of planes bpln = max (1,iblc[2]); epln = min (inNaxis[2], itrc[2]) if epln<bpln: epln = inNaxis[2] npln = epln-bpln+1 # Test if compatible if npln < outNaxis[2]: print "input has",npln,"planes selected and output has",outNaxis[2] raise RuntimeError,"input image has too few planes " if (ndim>0) and (inNaxis[2]>1): # list of 0-rel planes to loop over planes = range(bpln+restart-1,bpln+npln-1) else: planes = [0] # if inWtImage: inWtImage.List.set("BLC",[iblc[0], iblc[1],1,1,1,1,1]) inWtImage.List.set("TRC",[itrc[0], itrc[1],0,0,0,0,0]) inWtImage.Open(Image.READONLY,err) # Open/close to update inWtImage.Close(err) XPixelImage = None; YPixelImage = None; InterpWtImage = None;InterpWt = None InterpWtWt = None; WtImage = None # Loop over planes for iPlane in planes: doPlane = [iPlane+1,1,1,1,1] # Input plane outPlane = [iPlane+2-bpln,1,1,1,1] # output plane if not (iPlane%20): print "At plane", iPlane+1,'t=%6.1f sec'%(os.times()[4]-t0) # Get image inImage.List.set("BLC",[iblc[0], iblc[1],1,1,1,1,1]) inImage.List.set("TRC",[itrc[0], itrc[1],0,0,0,0,0]) Image.PGetPlane (inImage, None, doPlane, err) OErr.printErrMsg(err, "Error reading image "+str(iPlane)+" for "+Image.PGetName(inImage)) # # Make weight image if needed, first pass or planeWt if WtImage == None: WtImage = Image.Image("WeightImage") Image.PCloneMem(inImage, WtImage, err) # The interpolated versions if not InterpWtImage: InterpWtImage = Image.Image("InterpWtImage") Image.PClone2(inImage, SumWtImage, InterpWtImage, err) # input x, y pixels for output if (not XPixelImage) or (not YPixelImage): XPixelImage = Image.Image("XPixelImage") YPixelImage = Image.Image("YPixelImage") Image.PClone2(inImage, SumWtImage, XPixelImage, err) Image.PClone2(inImage, SumWtImage, YPixelImage, err) ImageUtil.PGetXYPixels(WtImage, InterpWtImage, XPixelImage, YPixelImage, err) # Special weighting? if factor<0.0: RMS = inImage.FArray.RMS fact = abs(factor)/RMS else: fact = factor if planeWt: pln = [iPlane+1,1,1,1,1] else: pln = [max(1,inNaxis[2]/2),1,1,1,1] if haveWtImage: # Beam provided, extract relevant plane to a memory resident WtImage OErr.printErrMsg(err, "Error reading wt image "+str(iPlane)+" for "+ Image.PGetName(inWtImage)) # Interpolate to WtImage ImageUtil.PInterpolateImage(inWtImage, WtImage, err, \ inPlane=doPlane, hwidth=hwidth, finterp=finterp) OErr.printErrMsg(err, "Error interpolating wt plane "+str(doPlane)) elif planeWt or (iPlane==0): # Normal or OTF Beam? if (OTFRA==None): ImageUtil.PPBImage(inImage, WtImage, err, minGain, outPlane=pln) pass else: ImageUtil.POTFBeam (inImage, WtImage, OTFRA, OTFDec, err, minGain, outPlane=pln) OErr.printErrMsg(err, "Error making weight image for "+Image.PGetName(inImage)) # Check maximum weight for first plane if iPlane==0: pos = [0,0] maxWt = FArray.PMax(WtImage.FArray,pos) print "Maximum weight",maxWt if maxWt<minAccWt: print "Less than minAccWt",minAccWt,"skipping" break # Interpolated weight image if not InterpWt: InterpWt = Image.Image("InterpWt") Image.PClone2(inImage, SumWtImage, InterpWt, err) # Is GPU interpolation requested? if doGPU: finterp = GPUFInterpolate.PCreate("GPUinterp", WtImage.FArray, XPixelImage.FArray, YPixelImage.FArray, hwidth, err) OErr.printErrMsg(err, "Creating GPU FInterpolator") InterpWt.Desc.Dict['inaxes'], WtImage.Desc.Dict['inaxes'] ImageUtil.PInterpolateImage(WtImage, InterpWt, err, \ XPix=XPixelImage, YPix=YPixelImage, hwidth=hwidth, finterp=finterp) OErr.printErrMsg(err, "Error interpolating wt*wt "+Image.PGetName(inImage)) # Interpolated weight image Squared if not InterpWtWt: InterpWtWt = Image.Image("InterpWtWt") Image.PClone2(inImage, SumWtImage, InterpWtWt, err) # Determine alignment inDesc = Image.PGetDesc(InterpWtImage) # get descriptors inDescDict = ImageDesc.PGetDict(inDesc) outDesc = Image.PGetDesc(SumWtImage) outDescDict = ImageDesc.PGetDict(outDesc) naxis = inDescDict["inaxes"] # find input center pixel in output pos1 = [int(naxis[0]*0.5+0.5), int(naxis[1]*0.5+0.5)] xpos1 = [float(pos1[0]),float(pos1[1])] xpos2 = ImageDesc.PCvtPixel (inDesc, xpos1, outDesc, err) pos2 = [int(xpos2[0]+0.5), int(xpos2[1]+0.5)] # Is GPU interpolation requested? if doGPU: del finterp finterp = GPUFInterpolate.PCreate("GPUinterp", inImage.FArray, XPixelImage.FArray, YPixelImage.FArray, hwidth, err) OErr.printErrMsg(err, "Creating GPU FInterpolator") # End init wt image # Special weighting or editing? if (factor<0.0) or maxRMS: # Get image Image.PGetPlane (inImage, None, doPlane, err) OErr.printErrMsg(err, "Error reading image "+str(iPlane)+" for "+Image.PGetName(inImage)) RMS = inImage.FArray.RMS # This plane acceptable? if maxRMS and ((RMS>maxRMS) or (RMS<=0.0)): #print 'drop plane',doPlane[0],'RMS',RMS continue if (factor<0.0): fact = abs(factor)/RMS else: fact = factor if not (iPlane%20): print "Factor",fact, "plane",iPlane,"RMS",RMS else: fact = factor # Interpolate image plane ImageUtil.PInterpolateImage(inImage, InterpWtImage, err, \ inPlane=doPlane, XPix=XPixelImage, YPix=YPixelImage, hwidth=hwidth, finterp=finterp) OErr.printErrMsg(err, "Error interpolating plane "+str(doPlane)) # Interpolated image times beam FArray.PMul(InterpWtImage.FArray, InterpWt.FArray, InterpWtImage.FArray) # # Read accumulation image planes Image.PGetPlane(SumWtImage, None, outPlane, err) OErr.printErrMsg(err, "Error reading accumulation image ") # # Accumulate FArray.PShiftAdd (SumWtImage.FArray, pos2, InterpWtImage.FArray, pos1, fact, SumWtImage.FArray) Image.PPutPlane(SumWtImage, None, outPlane, err) OErr.printErrMsg(err, "Error writing accumulation image ") # Square weight image Image.PGetPlane(SumWt2, None, outPlane, err) FArray.PMul(InterpWt.FArray, InterpWt.FArray, InterpWtWt.FArray) # Blank weight whereever image is blank or zero FArray.PInClip(InterpWt.FArray, -1.0e-20, 1.0e-20, FArray.PGetBlank()) # Blank weight squared where image * Wt is blanked FArray.PBlank (InterpWtWt.FArray, InterpWt.FArray, InterpWtWt.FArray); # Accumulate Wt*Wt FArray.PShiftAdd (SumWt2.FArray, pos2, InterpWtWt.FArray,pos1, fact, SumWt2.FArray) # # Write output Image.PPutPlane(SumWt2, None, outPlane, err) OErr.printErrMsg(err, "Error writing accumulation image ") # Cleanup if doing a weight image per plane (continuum) if planeWt: del WtImage, XPixelImage, YPixelImage; WtImage = None;XPixelImage=None; YPixelImage=None; # end loop over planes # close output Image.PClose(inImage, err) Image.PClose(SumWtImage, err) Image.PClose(SumWt2, err) del XPixelImage, YPixelImage, InterpWtImage, InterpWtWt, if WtImage: del WtImage; WtImage = None if finterp!=None: del finterp
inFile = sys.argv[1] pntFile = sys.argv[2] outFile = sys.argv[3] inDisk = 1 outDisk = 1 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, 1, err) pntImage = Image.newPFImage("Pointing image", pntFile, inDisk, 1, err) outImage = Image.newPFImage("Output image", outFile, outDisk, 0, err) Image.PClone(inImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # Make scratchfile for beam beam = inImage.Scratch(err) ImageUtil.PPBImage(pntImage, beam, err,antSize=25.,minGain=0.05) plane = [1,1,1,1,1] beam.GetPlane(None,plane,err) # Multiply nplane = inImage.Desc.Dict['inaxes'][2] for iplane in range(0,nplane): plane = [iplane+1,1,1,1,1] inImage.GetPlane(None, plane, err) FArray.PMul(inImage.FArray, beam.FArray, inImage.FArray) outImage.PutPlane(inImage.FArray, plane, err) beam.Zap(err) OErr.printErrMsg(err, "Error correcting image") # Copy History