def MakeMask(im, vlver, maskFile, err, minSNR=5.0): """ Create a CLEAN mask file for Obit Imaging tasks CLEANFile Radius of entries = major axis size. im = Image with VL table vlver = VL Table version, generate with FndSou maskFile = name for output mask file err = Obit error/message stack minSNR = Min. SNR to use """ scale = 1.0 # Open output file fd = open(maskFile, 'w') vltab = im.NewTable(Table.READONLY, 'AIPS VL', vlver, err) maxscale = scale / abs(im.Desc.Dict['cdelt'][0]) nrow = vltab.Desc.Dict['nrow'] vltab.Open(Table.READONLY, err) OErr.printErr(err) for irow in range(1, nrow + 1): row = vltab.ReadRow(irow, err) if row['PEAK INT'][0] / row['I RMS'][0] > minSNR: ra = ImageDesc.PRA2HMS(row['RA(2000)'][0]) dec = ImageDesc.PDec2DMS(row['DEC(2000)'][0]) size = min(50, int(row['MAJOR AX'][0] * maxscale + 0.5)) line = "%s %s %d\n" % (ra, dec, size) fd.write(line) vltab.Close(err) OErr.printErr(err) fd.close()
def PJ20002Gal(RA2000, Dec2000): """ Convert Equatorial (J2000) to Galactic coordinates strings Converts Convert Equatorial (B1950)to Galactic coordinates RA2000 J2000 Right Ascension as "hh:mm:ss.s" Dec2000 J2000 Declination as 'dd:mm:ss.s' Return [glong, glat] Galactic coordinates as 'dd mm ss.s' """ ################################################################ raj = ImageDesc.PHMS2RA(RA2000) decj = ImageDesc.PDMS2Dec(Dec2000) [rab, decb] = PJtoB(raj, decj) [glong, glat] = PEq2Gal(rab, decb) return [ImageDesc.PDec2DMS(glong), ImageDesc.PDec2DMS(glat)]
def PGal2J(Glong, Glat): """ Convert Galactic coordinates to Equatorial (J2000) Converts Galactic coordinates to Convert Equatorial (J2000) glong Galactic longitude as "D:M:S" glat Galactic latitude as "D:M:S Return [ra,dec] Equatorial (J) coordinates as "H M S", "D M S". """ ################################################################ glong = ImageDesc.PDMS2Dec(Glong) glat = ImageDesc.PDMS2Dec(Glat) (raB, decB) = PGal2Eq(glong, glat) # Galactic to equatorial B1950 (ra, dec) = PBtoJ(raB, decB) # to J2000 return [ImageDesc.PRA2HMS(ra), ImageDesc.PDec2DMS(dec)]
def PJ2Gal(RA, Dec): """ Convert Equatorial (J2000) to Galactic coordinates Converts Convert Equatorial (J2000)to Galactic coordinates RALong Right Ascension/longitude as "H:M:S" DecLat Declination/latitude as "D:M:S Return [GLong, GLat] Galactic coordinates as "D M S". """ ################################################################ ra = ImageDesc.PHMS2RA(RA) dec = ImageDesc.PDMS2Dec(Dec) (raB, decB) = PJtoB(ra, dec) # to B1950 (glong, glat) = PEq2Gal(raB, decB) # to Galactic return [ImageDesc.PDec2DMS(glong), ImageDesc.PDec2DMS(glat)]
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 __getattr__(self, name): if not isinstance(self, ImageMF): return "Bogus dude " + str(self.__class__) if name == "me": return Obit.ImageMF_Get_me(self.this) # Functions to return members if name == "List": if not self.ImageMFIsA(): raise TypeError("input MUST be a Python Obit ImageMF") out = InfoList.InfoList() out.me = Obit.ImageMFGetList(self.me) return out if name == "TableList": if not self.ImageMFIsA(): raise TypeError("input MUST be a Python Obit ImageMF") out = TableList.TableList("TL") out.me = Obit.ImageMFGetTableList(self.me) return out if name == "Desc": if not self.ImageMFIsA(): raise TypeError("input MUST be a Python Obit ImageMF") out = ImageDesc.ImageDesc("None") out.me = Obit.ImageMFGetDesc(self.me) return out if name == "FArray": return PGetFArray(self.me) if name == "Beam": return PGetBeam(self.me) if name == "PixBuf": if not self.ImageMFIsA(): raise TypeError("input MUST be a Python Obit ImageMF") fa = self.FArray return Obit.FArrayGetBuf(fa.me) raise AttributeError(str(name)) # Unknown
def PWriteCirc(sttab, im, center, radius, err): """ Write an entry for drawing a circle sttab = Python Table object, must be open with write enabled im = Obit Image on which to attach ST Table center = [x,y] pixels radius = radius in pixels err = Python Obit Error/message stack """ ################################################################ # Check if not OErr.OErrIsA(err): raise TypeError("err MUST be an OErr") if err.isErr: # existing error? return None # Get image descriptor id = im.Desc.Dict # Get row row = newRow(im) # Convert pixels to positions pos = ImageDesc.PGetPos(im.Desc, center, err) if err.isErr: printErrMsg(err, "Error converting pixel location to position") row[id["ctype"][0].strip()] = [pos[0]] row[id["ctype"][1].strip()] = [pos[1]] row['MAJOR AX'] = [radius * abs(id["cdelt"][0])] row['MINOR AX'] = row['MAJOR AX'] row['POSANG'] = [0.0] row['STARTYPE'] = [3.0] row['LABEL'] = [" "] # Write sttab.WriteRow(-1, row, err) if err.isErr: printErrMsg(err, "Error Writing ST table")
def PModelImage(inOTF, outOTF, image, desc, err): """ Replace OTF data with the model in a 2D ObitFArray inOTF = input Python Obit OTF outOTF = output Python Obit OTF, must be previously defined image = Python Obit Image model to use, as FArray desc = Python Obit ImageDesc for image err = Python Obit Error/message stack """ ################################################################ # Checks if not OTF.PIsA(inOTF): raise TypeError, "inOTF MUST be a Python Obit OTF" if not OTF.PIsA(outOTF): raise TypeError, "outOTF MUST be a Python Obit OTF" if not FArray.PIsA(image): raise TypeError, "image MUST be a Python Obit FArray" if not ImageDesc.PIsA(desc): raise TypeError, "desc MUST be a Python Obit ImageDesc" if not OErr.OErrIsA(err): raise TypeError, "err MUST be a Python ObitErr" if err.isErr: # existing error? return # Obit.OTFUtilModelImage(inOTF.me, outOTF.me, image.me, desc.me, err.me)
def PSubImage(inOTF, outOTF, image, desc, err): """ Subtract a 2D ObitFArray from an OTF inOTF = input Python Obit OTF outOTF = output Python Obit OTF, must be previously defined image = Python Obit Image data to subtract, as FArray desc = Python Obit ImageDesc for image err = Python Obit Error/message stack """ ################################################################ # Checks if not OTF.PIsA(inOTF): raise TypeError, "inOTF MUST be a Python Obit OTF" if not OTF.PIsA(outOTF): raise TypeError, "outOTF MUST be a Python Obit OTF" if not FArray.PIsA(image): raise TypeError, "image MUST be a Python Obit FArray" if not ImageDesc.PIsA(desc): raise TypeError, "desc MUST be a Python Obit ImageDesc" if not OErr.OErrIsA(err): raise TypeError, "err MUST be a Python ObitErr" if err.isErr: # existing error? return # Obit.OTFUtilSubImage(inOTF.me, outOTF.me, image.me, desc.me, err.me)
def PSetDesc(inFI, desc): """ Replace Image descriptor * inFI = Python Obit input FInterpolate * desc = Python Obit ImageDesc to use """ ################################################################ # Checks if not PIsA(inFI): raise TypeError("inFI MUST be a Python Obit FInterpolate") if not ImageDesc.PIsA(desc): raise TypeError("desc MUST be a Python Obit ImageDesc") # Obit.FInterpolateSetDesc(inFI.me, desc.me)
def PGetDesc(inFI): """ Get Image descriptor return ImageDesc reference * inFI = Python Obit input FInterpolate """ ################################################################ # Checks if not PIsA(inFI): raise TypeError("inFI MUST be a Python Obit FInterpolate") # out = ImageDesc.ImageDesc("None") out.me = Obit.FInterpolateGetImageDesc(inFI.me) return out
def __getattr__(self, name): if self.__class__ != ImageMF: return if name == "me": return Obit.ImageMF_me_get(self.this) # Functions to return members if name == "List": if not self.ImageMFIsA(): raise TypeError, "input MUST be a Python Obit ImageMF" out = InfoList.InfoList() out.me = Obit.InfoListUnref(out.me) out.me = Obit.ImageGetList(self.cast("ObitImage")) return out if name == "TableList": if not self.ImageMFIsA(): raise TypeError, "input MUST be a Python Obit ImageMF" out = TableList.TableList("TL") out.me = Obit.TableListUnref(out.me) out.me = Obit.ImageGetTableList(self.cast("ObitImage")) return out if name == "Desc": if not self.ImageMFIsA(): raise TypeError, "input MUST be a Python Obit ImageMF" out = ImageDesc.ImageDesc("None") out.me = Obit.ImageGetDesc(self.cast("ObitImage")) return out if name == "FArray": return PGetFArray(self.cast("ObitImage")) if name == "Beam": return PGetBeam(self.cast("ObitImage")) if name == "PixBuf": if not self.ImageMFIsA(): raise TypeError, "input MUST be a Python Obit ImageMF" fa = self.FArray return Obit.FArrayGetBuf(fa.me) raise AttributeError, str(name) # Unknown
def PScaleImage(inImage, scale, err): """ Scale the pixel values in an image Scale image, optionally by plane, scales any CC tables, writes history * inImage = Obit Python Image * scale = Scaling factor, if scalar, multiply all pixels, otherwise one value per image plane. * err = Python Obit Error/message stack """ ################################################################ # Checks if not Image.PIsA(inImage): raise TypeError("inImage MUST be a Python Obit Image") if not err.IsA(): raise TypeError("err MUST be an OErr") # # Open image Image.POpen(inImage, Image.READWRITE, err) # Get input descriptor to see how many planes inDesc = Image.PGetDesc(inImage) inDescDict = ImageDesc.PGetDict(inDesc) ndim = inDescDict["naxis"] inNaxis = inDescDict["inaxes"] # Work buffer inImageArray = Image.PGetFArray(inImage) ImageBuffer = FArray.PCopy(inImageArray, err) # Reset max/min inDescDict["minval"] = 1.0e20 inDescDict["maxval"] = -1.0e20 inImage.Desc.Dict = inDescDict # Update descriptor on image Image.PDirty(inImage) # Force update Image.PClose(inImage, err) # list of planes to loop over (0-rel) if (ndim > 0) and (inNaxis[2] > 0): planes = list(range(inNaxis[2])) else: planes = [0] # Loop over planes for iPlane in planes: doPlane = [iPlane + 1, 1, 1, 1, 1] # Get image plane Image.PGetPlane(inImage, ImageBuffer, doPlane, err) # Scaling factor if type(scale) == list: scl = scale[iPlane] else: scl = scale # Scale FArray.PSMul(ImageBuffer, scl) # Write output Image.PPutPlane(inImage, ImageBuffer, doPlane, err) # Scale any CC table highVer = Image.PGetHighVer(inImage, "AIPS CC") if (iPlane + 1 <= highVer): CCTab = Image.PImageGetTable(inImage, Image.READWRITE, "AIPS CC", iPlane + 1, err) PCCScale(CCTab, 1, 0, scl, err) # end loop over planes # Write history inHistory = History.History("history", inImage.List, err) # Add this programs history inHistory.Open(History.READWRITE, err) inHistory.TimeStamp(" Start Obit ScaleImage", err) if type(scale) == list: i = -1 for iPlane in planes: i = i + 1 scl = scale[i] inHistory.WriteRec( -1, "ScaleImage / scale[" + str(i + 1) + "] = " + str(scl), err) else: inHistory.WriteRec(-1, "ScaleImage / scale = " + str(scale), err) inHistory.Close(err)
def NVSSFindFile(RA, Dec, equinox, err, stokes='I'): """ Determine the NVSS image best suited for a given position Returns name of image 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' """ ################################################################ # Checks if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" if err.isErr: # existing error? return if not type(RA)==str: raise TypeError,"RA must be a string (HH MM SS.S)" if not type(Dec)==str: raise TypeError,"Dec must be a string (HH MM SS.S)" # ra = ImageDesc.PHMS2RA(RA, sep=' ') dec = ImageDesc.PDMS2Dec(Dec, sep=' ') # Precess 1950 to 2000? if equinox==1950: (ra,dec) = SkyGeom.PBtoJ(ra,dec) # Must be north of -41 dec if dec<-41.: OErr.PLog(err, OErr.Error, "Dec MUST be > -41") return "No Image" # Maximum distance to "belong" tolDec = 2.0 idec = -1 adec = abs(dec) for i in range(0,23): if abs(adec-NVSSnumMap[i][0])<=tolDec: dd = int(NVSSnumMap[i][0]+0.01) idec = i break; # Find it? if idec<0: OErr.PLog(err, OErr.Error, "Failed on declination "+Dec) return "No Image" # Width of images in RA deltRa = 360.0 / NVSSnumMap[idec][1] racell = int(0.5 + ra/deltRa) # Cell if racell>=NVSSnumMap[idec][1]: # Wrap? racell = 0 # Derive name raCen = racell*deltRa / 15.0 iRAH = int(raCen + 0.5) iRAM = int(60.0 * (raCen-iRAH) + 0.1) if iRAM<0.0: iRAH -= 1 iRAM += 59 if iRAH == -1: iRAH = 23 # Sign of declination if dec>=-2.0: dsign = 'P' else: dsign = 'M' # Stokes type if stokes in ["Q","U"]: itype = 'C' else: itype = 'I' # put it together file = "%s%2.2i%2.2i%s%2.2i"%(itype,iRAH,iRAM,dsign,dd) return file
def PHeader(inImage, err): """ Print image descriptor * inImage = Python Image object * err = Python Obit Error/message stack """ ################################################################ # ObitTalk or AIPSImage data? if inImage.myClass == 'AIPSImage': # header dict = inImage.header() ImageDesc.PHeaderDict(dict) # tablelist Tlist = inImage.tables() Tdict = {} # Once to find everything for item in Tlist: Tdict[item[1]] = item[0] # Again to get Max for item in Tlist: count = max(Tdict[item[1]], item[0]) Tdict[item[1]] = count for item, count in Tdict.items(): print "Maximum version number of %s tables is %d " % \ (item, count) return # End AIPSImage elif inImage.myClass == 'FITSImage': # header dict = inImage.header() ImageDesc.PHeaderDict(dict) # tablelist Tlist = inImage.tables() Tdict = {} # Once to find everything for item in Tlist: Tdict[item[1]] = item[0] # Again to get Max for item in Tlist: count = max(Tdict[item[1]], item[0]) Tdict[item[1]] = count for item, count in Tdict.items(): print "Maximum version number of %s tables is %d " % \ (item, count) return # End FITSImage # ObitTalk Image Checks if not inImage.ImageIsA(): raise TypeError, "inImage MUST be a Python Obit Image" # # Fully instantiate #DAMN PFullInstantiate (inImage, READONLY, err) # File info if inImage.FileType == "AIPS": print "AIPS Image Name: %12s Class: %6s seq: %8d disk: %4d" % \ (inImage.Aname, inImage.Aclass, inImage.Aseq, inImage.Disk) elif inImage.FileType == "FITS": print "FITS Image Disk: %5d File Name: %s " % \ (inImage.Disk, inImage.FileName) # print in ImageDesc ImageDesc.PHeader(inImage.Desc) # Tables TL = inImage.TableList Tlist = TableList.PGetList(TL, err) Tdict = {} # Once to find everything for item in Tlist: Tdict[item[1]] = item[0] # Again to get Max for item in Tlist: count = max(Tdict[item[1]], item[0]) Tdict[item[1]] = count for item, count in Tdict.items(): print "Maximum version number of %s tables is %d " % \ (item, count)
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) dict["naxis"] = len(inaxes) dict["inaxes"] = inaxes dict["bitpix"] = -32 od.Dict = dict # Glue 'em together i = 1 outImage.Open(2, err) # Loop over input images for x in inImage: x.Open(1, err)
def PImageAdd (in1Image, in2Image, outImage, err, \ chkPos=False, factor1=1.0, factor2=1.0): """ Adds Pixels in in2Image from in1Image and write to outImage Adds scaled pixel values, writes history * in1Image = input Obit Python Image 1 * in2Image = input Obit Python Image 2 * outImage = output Obit Python Image, must be defined but not instantiated * err = Python Obit Error/message stack * chkPos = If true also check the coordinates on each axis Check is if pixels are within 0.01 of a pixel * factor1 = Scaling factor for in1Image * factor2 = Scaling factor for in2Image """ ################################################################ # Checks if not Image.PIsA(in1Image): raise TypeError("in1Image MUST be a Python Obit Image") if not Image.PIsA(in2Image): raise TypeError("in2Image MUST be a Python Obit Image") if not Image.PIsA(outImage): raise TypeError("outImage MUST be a Python Obit Image") if not err.IsA(): raise TypeError("err MUST be an OErr") # # Clone output from input 1 in1Image.Clone(outImage, err) # Open images Image.POpen(in1Image, Image.READONLY, err) Image.POpen(in2Image, Image.READONLY, err) Image.POpen(outImage, Image.WRITEONLY, err) # Get input descriptor to see how many planes in1Desc = in1Image.Desc in2Desc = in2Image.Desc # Check compatibility ImageDesc.PCheckCompat(in1Desc, in2Desc, chkPos=chkPos) inDescDict = in1Desc.Dict ndim = inDescDict["naxis"] inNaxis = inDescDict["inaxes"] # Work buffer inImageArray = Image.PGetFArray(in1Image) ImageBuffer1 = FArray.PCopy(inImageArray, err) ImageBuffer2 = FArray.PCopy(inImageArray, err) # list of planes to loop over (0-rel) if (ndim > 0) and (inNaxis[2] > 0): planes = list(range(inNaxis[2])) else: planes = [0] # Loop over planes for iPlane in planes: doPlane = [iPlane + 1, 1, 1, 1, 1] # Get image planes Image.PGetPlane(in1Image, ImageBuffer1, doPlane, err) Image.PGetPlane(in2Image, ImageBuffer2, doPlane, err) # Scale FArray.PSMul(ImageBuffer1, factor1) FArray.PSMul(ImageBuffer2, factor2) # Add FArray.PAdd(ImageBuffer1, ImageBuffer2, ImageBuffer2) # Write output Image.PPutPlane(outImage, ImageBuffer2, doPlane, err) # end loop over planes # Close in2Image.Close(err) in2Image.Close(err) outImage.Close(err) # Error? if err.isErr: OErr.printErrMsg(err, "Error subtracting Images") # Write history in1History = History.History("history", in1Image.List, err) in2History = History.History("history", in2Image.List, err) outHistory = History.History("history", outImage.List, err) # Copy Histories outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit PImageAdd", err) outHistory.WriteRec(-1, "/ PImageAdd Input 1 History", err) outHistory.Close(err) info = in1Image.List.Dict # FITS? - copy header if ("FileType" in info) and (info["FileType"][2][0] == 0): History.PCopyHeader(in1History, outHistory, err) #Not needed History.PCopy(in1History, outHistory, err) outHistory.Open(History.READWRITE, err) outHistory.WriteRec(-1, "/ ", err) outHistory.WriteRec(-1, "/ ****** PImageAdd Input 2 History", err) outHistory.Close(err) info = in2Image.List.Dict # FITS? - copy header if ("FileType" in info) and (info["FileType"][2][0] == 0): History.PCopyHeader(in2History, outHistory, err) History.PCopy(in2History, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit PImageAdd", err) outHistory.WriteRec(-1, OSystem.PGetPgmName() + " factor1 = " + str(factor1), err) outHistory.WriteRec(-1, OSystem.PGetPgmName() + " factor2 = " + str(factor2), err) outHistory.Close(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: pos = [ImageDesc.PHMS2RA(s[1]), ImageDesc.PDMS2Dec(s[2])] pixel = ImageDesc.PGetPixel(icube.Desc, pos, err) pixels.append(pixel) vals.append(nspec * [fblank]) # end loop OErr.printErrMsg(err, message='Finding positions') # Loop over planes interpolating values rms = [] for i in range(0, nspec): # Read plane plane = [i + nterm + 1, 1, 1, 1, 1] Image.PGetPlane(icube, None, plane, err) rms.append(icube.FArray.RMS) # Plane RMS # Interpolate positions for j in range(0, len(pixels)):
outDisk = 1 equinox = 2000.0 # Debug print "input",inFile # Convert file into Images inImage = Image.newPImage(inFile, inFile, inDisk, 1, err) OErr.printErrMsg(err, "Error initializing image") # Open/get descriptor Image.POpen(inImage, 3, err) desc = Image.PGetDesc(inImage) # update descriptor descDict = ImageDesc.PGetDict(desc) # Get descriptor as Python Dict descDict["epoch"] = equinox # Update "epoch" descDict["equinox"] = equinox # Update equinox descDict["origin"] = "Obit to fix equinox" # Update origin ImageDesc.PSetDict(desc, descDict) # update descriptor Image.PClose(inImage, err) # Close to update disk OErr.printErrMsg(err, "Error writing updated header for "+Image.PGetName(inImage)) # Say something print "Updated Equinox (EPOCH) in",inFile,"to",equinox # Shutdown Obit OErr.printErr(err) del ObitSys
def PGetOverlap(in1Image, in2Image, err): """ Determine the overlap region in in1Image with in2Image Returns (BLC, TRC) in in1Image of overlap, only BLC pixel if no overlap * in1Image = first input image * in2Image = second input image, need not be same grid but should not be rotated wrt in1Image * err = Python Obit Error/message stack """ ################################################################ # Checks if not Image.PIsA(in1Image): print "Actually ",inI1mage.__class__ raise TypeError,"in1Image MUST be a Python Obit Image" if not Image.PIsA(in2Image): print "Actually ",in21mage.__class__ raise TypeError,"in2Image MUST be a Python Obit Image" if not OErr.OErrIsA(err): raise TypeError,"err MUST be an OErr" # # Is there overlap? if ImageDesc.POverlap(in1Image.Desc, in2Image.Desc, err): d1 = in1Image.Desc.Dict nx1 = d1['inaxes'][0] ny1 = d1['inaxes'][1] d2 = in2Image.Desc.Dict nx2 = d2['inaxes'][0] ny2 = d2['inaxes'][1] # DEBUG ALL #return ([1,1,1,1,1,1,1], [nx1,ny1,0,0,0,0,0]) # Determine corners of in1Image in in2Image 1-rel corn1 = [] xpos = [float(0), float(0)] ypos = ImageDesc.PCvtPixel (in1Image.Desc, xpos, in2Image.Desc, err) corn1.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(0), float(ny1)] ypos = ImageDesc.PCvtPixel (in1Image.Desc, xpos, in2Image.Desc, err) corn1.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(nx1), float(ny1)] ypos = ImageDesc.PCvtPixel (in1Image.Desc, xpos, in2Image.Desc, err) corn1.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(nx1), float(0)] ypos = ImageDesc.PCvtPixel (in1Image.Desc, xpos, in2Image.Desc, err) corn1.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) # Determine corners of in2Image in in1Image corn2 = [] xpos = [float(0), float(0)] ypos = ImageDesc.PCvtPixel (in2Image.Desc, xpos, in1Image.Desc, err) corn2.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(0), float(ny2)] ypos = ImageDesc.PCvtPixel (in2Image.Desc, xpos, in1Image.Desc, err) corn2.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(nx2), float(ny2)] ypos = ImageDesc.PCvtPixel (in2Image.Desc, xpos, in1Image.Desc, err) corn2.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) xpos = [float(nx2), float(0)] ypos = ImageDesc.PCvtPixel (in2Image.Desc, xpos, in1Image.Desc, err) corn2.append([int(ypos[0]+0.5), int(ypos[1]+0.5)]) #print "DEBUG" #print corn1,nx1,ny1 #print corn2,nx2,ny2 # 1 entirely inside 2? if ((corn1[0][0]>0) and (corn1[0][1]>0) and (corn1[2][0]<=nx2) and (corn1[2][1]<=ny2)): print "1 entirely inside 2" return ([1,1,1,1,1,1,1], [nx1, ny1, 0,0,0,0,0]) # 2 entirely inside 1? if ((corn2[0][0]>0) and (corn2[0][1]>0) and (corn2[2][0]<=nx1) and (corn2[2][1]<=ny1)): blc = [corn2[0][0],corn2[0][1], 1,1,1,1,1] trc = [corn2[2][0],corn2[2][1], 0,0,0,0,0] print "2 entirely inside 1" return(blc,trc) # Corner 0 in in2? if ((corn1[0][0]>0) and (corn1[0][0]<=nx2) and (corn1[0][1]>0) and (corn1[0][1]<=ny2)): blc = [1, 1, 1, 1, 1, 1, 1] trc = [min(corn2[2][0],nx1), min(corn2[2][1],ny1), 0,0,0,0,0] print "Corner 0 in in2" return (blc, trc) # Corner 1 in in2? if ((corn1[1][0]>0) and (corn1[1][0]<=nx2) and (corn1[1][1]>0) and (corn1[1][1]<=ny2)): blc = [1, min(corn2[3][1], ny1), 1, 1, 1, 1, 1] trc = [min (corn2[3][0], nx1), ny1, 0,0,0,0,0] print "Corner 1 in in2" return (blc, trc) # Corner 2 in in2? if ((corn1[2][0]>0) and (corn1[2][0]<=nx2) and (corn1[2][1]>0) and (corn1[2][1]<=ny2)): blc = [max(1, corn2[0][0]), max(1, corn2[0][1]), 1, 1, 1, 1, 1] trc = [nx1, ny1, 0,0,0,0,0] print "Corner 2 in in2" return (blc, trc) # Corner 3 in in2? if ((corn1[3][0]>0) and (corn1[3][0]<=nx2) and (corn1[3][1]>0) and (corn1[3][1]<=ny2)): blc = [max(1,corn2[1][0]), 1, 1, 1, 1, 1] trc = [nx1, min(corn2[1][1],ny1), 0,0,0,0,0] print "Corner 3 in in2" return (blc, trc) # 2 straddle bottom of 1? if ((corn2[0][1]<0.0) and (corn2[1][1]>0.0) and (corn2[0][0]>0.0) and (corn2[3][0]<=nx1)): blc = [corn2[0][0], 1,1,1,1,1,1] trc = [corn2[2][0], corn2[2][1],0,0,0,0,0] print "2 straddles bottom of 1" return (blc, trc) # 2 straddle top of 1? if ((corn2[0][1]<ny1) and (corn2[1][1]>ny1) and (corn2[0][0]>0.0) and (corn2[3][0]<=nx1)): blc = [corn2[0][0], corn2[0][1], 1,1,1,1,1,1] trc = [corn2[2][0], ny1,0,0,0,0,0] print "2 straddles top of 1" return (blc, trc) # 2 straddle right edge of 1? if ((corn2[0][0]<nx1) and (corn2[3][0]>nx1) and (corn2[0][1]>0.0) and (corn2[1][1]<=ny1)): blc = [corn2[0][0], corn2[0][1], 1,1,1,1,1,1] trc = [nx1, corn2[2][1], 0,0,0,0,0] print "2 straddles right edge of 1" return (blc, trc) # 2 straddle left edge of 1? if ((corn2[0][0]<0) and (corn2[3][0]>0) and (corn2[0][1]>0.0) and (corn2[1][1]<=ny1)): blc = [1, corn2[0][1], 1,1,1,1,1,1] trc = [corn2[2][0], corn2[2][1], 0,0,0,0,0] print "2 straddles left edge of 1" return (blc, trc) # Likely no overlap print "Confused, probably no overlap" print "corn1", corn1, nx1, ny1 print "corn2", corn2, nx2, ny2 return ([1,1,1,1,1,1,1], [1,1,0,0,0,0,0]) else: # Default is no overlap print "no overlap" return ([1,1,1,1,1,1,1], [1,1,0,0,0,0,0])
def PNormalizeImage(SumWtImage, SumWt2, outImage, err, minWt=0.1): """ Sum an image onto Weighting accumulators Normalize SumWtImage by SumWt2 write to outImage Minimum allowed value in SumWt2 is minWt * SumWtImage = First output image, must be defined (i.e. files named) but not fully created. * SumWt2 = Second output image, like SumWtImage * outImage = Output image, must be defined. * err = Python Obit Error/message stack * minWt = minimum summed weight (lower values blanked). """ ################################################################ # Checks if not Image.PIsA(outImage): print "Actually ",outImage.__class__ raise TypeError,"outImage 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" # # Open files Image.POpen(outImage, 2, err) Image.POpen(SumWtImage, 1, err) Image.POpen(SumWt2, 1, err) # Get 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(outImage) inDescDict = ImageDesc.PGetDict(outDesc) ndim = inDescDict["naxis"] inNaxis = inDescDict["inaxes"] #print "debug input naxis is ",inNaxis # Test if compatible if inNaxis[2] < outNaxis[2]: print "input has",inNaxis[2],"planes and output",outNaxis[2] raise RuntimeError,"input image has too few planes " if (ndim>0) and (inNaxis[2]>0): # list of planes to loop over (0-rel) planes = range(inNaxis[2]) else: planes = [0] # # Loop over planes for iPlane in planes: doPlane = [iPlane+1,1,1,1,1] # Get images Image.PGetPlane (SumWtImage, None, doPlane, err) Image.PGetPlane (SumWt2, None, doPlane, err) OErr.printErrMsg(err, "Error reading images") # Clip FArray.PClipBlank (SumWt2.FArray, minWt, 1.0e25) # Divide FArray.PDiv (SumWtImage.FArray, SumWt2.FArray, outImage.FArray) # Write Image.PPutPlane(outImage, None, doPlane, err) OErr.printErrMsg(err, "Error Writing normalized image ") # end loop over planes # close output Image.PClose(outImage, err) Image.PClose(SumWtImage, err) Image.PClose(SumWt2, err) # Write history - sorta inHistory = History.History("history", SumWtImage.List, err) outHistory = History.History("history", outImage.List, err) # Copy History History.PCopy(inHistory, outHistory, err) outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit PNormalize",err) outHistory.Close(err)
def PAccumIxWt(im, wt, factor, accum, accumwt, err): """ Accumulate im * wt into accum Used to accumulate images which don't need PB corrections and have a weight image. * im = image to accumulate * wt = weight image corresponding to accum * factor = Additional multiplication factor, normally 1.0 * accum = image into which to accumulate im*wt * accumwt = image into which to accumulate wt * err = Python Obit Error/message stack """ ################################################################ # Checks if not Image.PIsA(im): print "Actually ",im.__class__ raise TypeError,"im MUST be a Python Obit Image" if not Image.PIsA(wt): print "Actually ",wt.__class__ raise TypeError,"wt MUST be a Python Obit Image" if not Image.PIsA(accum): print "Actually ",accum.__class__ raise TypeError,"accum MUST be a Python Obit Image" # # Open files #Image.POpen(im, 1, err) Image.POpen(accum, Image.READWRITE, err) Image.POpen(accumwt, Image.READWRITE, err) # Get output descriptor to see how many planes outDesc = accum.Desc outDescDict = outDesc.Dict outNaxis = outDescDict["inaxes"] print "Accumulation naxis",outNaxis # Get input descriptor to see how many planes inDesc = im.Desc inDescDict = inDesc.Dict ndim = inDescDict["naxis"] inNaxis = inDescDict["inaxes"] #print "debug input naxis is ",inNaxis # Test if compatible if inNaxis[2] < outNaxis[2]: print "input has",inNaxis[2],"planes and output",outNaxis[2] raise RuntimeError,"input image has too few planes " if (ndim>0) and (inNaxis[2]>0): # list of planes to loop over (0-rel) planes = range(inNaxis[2]) else: planes = [0] # # Loop over planes for iPlane in planes: doPlane = [iPlane+1,1,1,1,1] # Get image Image.PGetPlane (im, None, doPlane, err) #OErr.printErrMsg(err, "Error reading image for "+Image.PGetName(im)) imArray = im.FArray # Get Weight Image.PGetPlane (wt, None, doPlane, err) #OErr.printErrMsg(err, "Error reading image for "+Image.PGetName(wt)) WtArray = wt.FArray # # Make image*Wt memory resident image ImageWt = Image.Image("ImageXwt") Image.PCloneMem(im, ImageWt, err) ImageWtArray = ImageWt.FArray FArray.PMul(imArray, WtArray, ImageWtArray); # # Now the interpolated versions to be summed to the accumulation arrays InterpWtImage = Image.Image("InterpWtImage") Image.PClone2(im, accum, InterpWtImage, err) ImageUtil.PInterpolateImage(ImageWt, InterpWtImage, err) #OErr.printErrMsg(err, "Error interpolating image "+Image.PGetName(im)) InterpWt = Image.Image("InterpWt") Image.PClone2(im, accum, InterpWt, err) ImageUtil.PInterpolateImage(wt, InterpWt, err) #OErr.printErrMsg(err, "Error interpolating wt "+Image.PGetName(im)) # # Read accumulation image plane Image.PGetPlane(accum, None, doPlane, err) Image.PGetPlane(accumwt, None, doPlane, err) #OErr.printErrMsg(err, "Error reading accumulation image ") # # Determine alignment inDesc = InterpWtImage.Desc inDescDict = inDesc.Dict outDesc = accum.Desc outDescDict = outDesc.Dict 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) #OErr.printErrMsg(err, "Error converting pixel locations for "+Image.PGetName(im)) pos2 = [int(xpos2[0]+0.5), int(xpos2[1]+0.5)] # # Accumulate accumArray = accum.FArray InterpWtArray = InterpWtImage.FArray FArray.PShiftAdd (accumArray, pos2, InterpWtArray, pos1, factor, accumArray) accumwtArray = accumwt.FArray InterpWtWtArray = InterpWt.FArray # Blank weight whereever image is blank or zero FArray.PInClip(InterpWtArray, -1.0e-20, 1.0e-20, FArray.PGetBlank()) FArray.PBlank (InterpWtWtArray, InterpWtArray, InterpWtWtArray); FArray.PShiftAdd (accumwtArray, pos2, InterpWtWtArray,pos1, factor, accumwtArray) # # Write output Image.PPutPlane(accum, None, doPlane, err) Image.PPutPlane(accumwt, None, doPlane, err) #OErr.printErrMsg(err, "Error writing accumulation image ") # Cleanup, del accumArray, accumwtArray, InterpWtArray, InterpWtWtArray, ImageWtArray, WtArray, imArray # end loop over planes # close output #Image.PClose(im, err) Image.PClose(accum, err) Image.PClose(accumwt, err)
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
def PMakeMaster(template, size, SumWtImage, SumWt2, err): """ Create a pair of images to accumulation of partial products Create an image to contain the Sum of the input Images times the weights, and another for the sum of the weights squared. The descriptive material is from image template * template = Image with position etc, to be copied * size = output image size in pixels, e.g. [200,200] * 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 """ ################################################################ # Checks if not Image.PIsA(template): print "Actually ",template.__class__ raise TypeError,"template 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" # # Get image info from template Image.POpen (template, 1, err) Image.PRead (template, err) desc = Image.PGetDesc(template) descDict = ImageDesc.PGetDict(desc) # Python dict object listDict = template.Desc.List.Dict Image.PClose (template, err) #OErr.printErrMsg(err, "Error reading input image "+Image.PGetName(template)) # # Create zero filled array for data outArray = FArray.FArray("Initial array", size) # # Modify the descriptor for output. naxis = size[0:3] # Update reference pixel, pixel shift an integral number dim = descDict["inaxes"] pixOff = [naxis[0]/2-dim[0]/2, naxis[1]/2-dim[1]/2] crpix = descDict["crpix"] crpix[0] = crpix[0] + pixOff[0] crpix[1] = crpix[1] + pixOff[1] # Update size dim[0] = naxis[0]; dim[1] = naxis[1] #print "debug dim",dim descDict["inaxes"] = dim descDict["bitpix"] = -32 # output floating # # Do SumWtImage desc = Image.PGetDesc(SumWtImage) InfoList.PSetDict(desc.List, listDict) # Copy list stuff ImageDesc.PSetDict(desc, descDict) # set output descriptor # Write output image Image.POpen(SumWtImage, 2, err) nplane = template.Desc.Dict["inaxes"][2] for iplane in range(1,(nplane+1)): plane = [iplane,1,1,1,1] SumWtImage.PutPlane(outArray, plane, err) Image.PClose(SumWtImage, err) #OErr.printErrMsg(err, "Error writing image for "+Image.PGetName(SumWtImage)) # # Do SumWt2Image desc = Image.PGetDesc(SumWt2) InfoList.PSetDict(desc.List, listDict) # Copy list stuff ImageDesc.PSetDict(desc, descDict) # set output descriptor # Write output image Image.POpen(SumWt2, 2, err) for iplane in range(1,(nplane+1)): plane = [iplane,1,1,1,1] SumWt2.PutPlane(outArray, plane, err) Image.PClose(SumWt2, err) #OErr.printErrMsg(err, "Error writing image for "+Image.PGetName(SumWt2)) # Write history - sorta inHistory = History.History("history", template.List, err) outHistory = History.History("history", SumWtImage.List, err) # Copy History History.PCopy(inHistory, outHistory, err) outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit PMakeMaster",err) outHistory.Close(err)
def Print(self, ImDesc, corner, file=None): """ Prepare human readable contents Returns string with description of model * self = object with Model to display * ImDesc = Image Descriptor with Beam, etc. * corner = bottom left corner in selected region of image (0-rel) """ ################################################################ # Start output string id = ImDesc.Dict modelInfo = "" # Collect info type = self.type parms = self.parms eparms = self.eparms # Gaussian if type == GaussMod: # Get celestial position xpix = corner[0] + self.DeltaX ypix = corner[1] + self.DeltaY pos=SkyGeom.PWorldPos (xpix, ypix, id["crval"][0], id["crval"][1], \ id["crpix"][0], id["crpix"][1], \ id["cdelt"][0], id["cdelt"][1], id["crota"][1], \ id["ctype"][0][4:8], 0.0, 0.0) rast = ImageDesc.PRA2HMS(pos[1]) decst = ImageDesc.PDec2DMS(pos[2]) # Position errors era = self.eDeltaX * abs(id["cdelt"][0]) * 3600.0 edec = self.eDeltaY * abs(id["cdelt"][1]) * 3600.0 modelInfo += "RA " + rast + " (%8.3g asec), pixel %8.3f (%8.3g)\n" % ( era, xpix, self.eDeltaX) modelInfo += "Dec " + decst + " (%8.3g asec), pixel %8.3f (%8.3g)\n" % ( edec, ypix, self.eDeltaY) modelInfo += "Peak Flux density %8.3g (%8.3g) %s\n" % ( self.Peak, self.ePeak, id["bunit"]) # Ratio of Gaussian beams if beam in ImDesc if (id["beamMaj"] > 0.0) and (id["beamMin"] > 0.0): ratio = (parms[0] * abs(id["cdelt"][0])*parms[1] * abs(id["cdelt"][1])) / \ (id["beamMaj"]*id["beamMin"]) modelInfo += "Integrated Flux density %8.3g (%8.3g) %s\n" % \ (self.Peak*ratio, self.ePeak*ratio, "Jy") modelInfo += "Fitted Major axis %8.3f (%8.3g) asec, %8.3f (%8.3g) pixels\n" % \ (parms[0]*abs(id["cdelt"][0])*3600.0, eparms[0]*abs(id["cdelt"][0])*3600.0, \ parms[0], eparms[1]) modelInfo += "Fitted Minor axis %8.3f (%8.3g) asec, %8.3f (%8.3g) pixels\n" % \ (parms[1]*abs(id["cdelt"][1])*3600.0, eparms[1]*abs(id["cdelt"][1])*3600.0, \ parms[1], eparms[1]) modelInfo += "Fitted Position angle %8.5g (%8.3g) deg\n" % \ (parms[2]*57.296, eparms[2]*57.296) if (id["beamMaj"] > 0.0) and (id["beamMin"] > 0.0): # Deconvolve deconMod = self.DeconGau(ImDesc) if PIsA(deconMod) and deconMod.type > 0: modelInfo += "\nDeconvolved model\n" dparms = deconMod.parms deparms = deconMod.eparms modelInfo += "Deconvolved Major axis %8.3g (%8.3g) asec, %8.3f (%8.3g) pixels\n" % \ (dparms[0]*abs(id["cdelt"][0])*3600.0, deparms[0]*abs(id["cdelt"][0])*3600.0, \ dparms[0], deparms[1]) modelInfo += "Deconvolved Minor axis %8.3g (%8.3g) asec, %8.3f (%8.3g) pixels\n" % \ (dparms[1]*abs(id["cdelt"][1])*3600.0, deparms[1]*abs(id["cdelt"][1])*3600.0, \ dparms[1], deparms[1]) modelInfo += "Deconvolved Position angle %8.5g (%8.3g) deg\n" % \ (dparms[2]*57.296, deparms[2]*57.296) else: modelInfo += "\nDeconvolution failed\n" # end deconvolved # end Gaussian # done return modelInfo
def PVLScale(inImage, inVL, outVL, scale, err, exclude=None): """ Scale the flux density values in a VL table Copies beam parameters and indexes when done. * inImage = Input image with VL tables * inVL = Input Obit VL Table * outVL = Output Obit VL Table, new data appended to end of old * scale = scale factor for flux densities * err = Python Obit Error/message stack * exclude = list of tuples with (ra, deg, size) all in deg describing regions not to rescale """ ################################################################ # Checks if not Table.PIsA(inVL): print("Actually ", inVL.__class__) raise TypeError("inVL MUST be a Python Obit Table") if not Table.PIsA(outVL): print("Actually ", outVL.__class__) raise TypeError("VLTable MUST be a Python Obit Table") fblank = Obit.FArrayGetBlank() # Blanked value inVL.Open(Table.READONLY, err) outVL.Open(Table.READWRITE, err) if err.isErr: OErr.printErrMsg(err, "Error Opening tables") # Copy beam info outVL.keys["BeamMajor"] = inVL.keys["BeamMajor"] outVL.keys["BeamMinor"] = inVL.keys["BeamMinor"] outVL.keys["BeamPA"] = inVL.keys["BeamPA"] #print "debug",outVL.keys nrow = inVL.Desc.Dict['nrow'] orow = -1 for irow in range(1, nrow + 1): row = inVL.ReadRow(irow, err) if err.isErr: break doScale = True # Need to scale? if exclude: for pos in exclude: (dra, ddec) = SkyGeom.PShiftXY(row["RA(2000)"][0], row["DEC(2000)"][0], 0.0, pos[0], pos[1]) if (abs(dra) <= pos[2]) and (abs(ddec) <= pos[2]): doScale = False print("exclude", irow, ImageDesc.PRA2HMS(row["RA(2000)"][0]), ImageDesc.PDec2DMS(row["DEC(2000)"][0]), \ row["PEAK INT"][0]) break if doScale: row["PEAK INT"][0] *= scale row["I RMS"][0] *= scale row["RES RMS"][0] *= scale row["RES PEAK"][0] *= scale row["RES FLUX"][0] *= scale # Have poln data? if (row["Q CENTER"][0] != fblank) and (row["U CENTER"][0] != fblank): row["Q CENTER"][0] *= scale row["U CENTER"][0] *= scale row["P Flux"][0] *= scale row["POL RMS"][0] *= scale # write outVL.WriteRow(orow, row, err) if err.isErr: break inVL.Close(err) outVL.Close(err) # History #outVL.Open(Table.READWRITE,err) inHistory = History.History("history", inImage.List, err) inHistory.Open(History.READWRITE, err) inHistory.TimeStamp("Start PVLScale", err) inHistory.WriteRec(-1, "PVLScale / scale = " + str(scale), err) if exclude: i = 0 for pos in exclude: i += 1 hi = "PVLScale exclude[%d] = (%9.5f,%9.5f,%8.6f) \ no Scale" % ( i, pos[0], pos[1], pos[2]) inHistory.WriteRec(-1, hi, err) inHistory.Close(err) #outVL.Close(err) # Index print("Index output") PVLIndex(outVL, err)
# Create image object outImage = Image.newPImage("Output image", outFile, disk, 0, err) OErr.printErrMsg(err, "Error initializing") # define image RA = 0.0 Dec = 0.0 nx = 51 ny = 51 xCells = 20.0 / 3600.0 yCells = 20.0 / 3600.0 beamsize = 2.2266e-2 # beamsize in deg. # Set image parameters in descriptor imagDesc = Image.PImageGetDesc(outImage) imagDict = ImageDesc.PImageDescGetDict(imagDesc) # descriptor as dictionary imagDict["ctype"][0] = "RA---SIN" imagDict["ctype"][1] = "DEC--SIN" imagDict["crval"][0] = RA imagDict["crval"][1] = Dec imagDict["cdelt"][0] = -abs(xCells) # RA goes backwards imagDict["cdelt"][1] = yCells imagDict["naxis"] = 2 imagDict["inaxes"][0] = nx imagDict["inaxes"][1] = ny imagDict["crpix"][0] = nx / 2 + 1 imagDict["crpix"][1] = ny / 2 + 1 imagDict["bitpix"] = -32 imagDict["bunit"] = "JY/BEAM" imagDict["beamMin"] = beamsize imagDict["beamMaj"] = beamsize
def PGetPoln(VLtab, imQ, imU, err, RMSsize=100): """ Get polarization info for VL table VLtab input VL table imQ Q pol Image imU U pol Image, same geometry as Q err Obit Err/message object RMSsize halfwidth in pixels of RMS box """ dQ = imQ.Desc dU = imU.Desc if not ImageDesc.PCheckCompat(dQ, dU): OErr.printErrMsg(err, "Error: Q,U images are incompatible") nx = dQ.Dict['inaxes'][0] ny = dQ.Dict['inaxes'][1] size = min(RMSsize, nx / 2, ny / 2) # Actual RMS box size fblank = FArray.fblank # Get Q, U images pixQ = Image.PReadPlane(imQ, err) pixU = Image.PReadPlane(imU, err) if err.isErr: OErr.printErrMsg(err, "Error Reading Q,U images") # Make interpolators fiQ = FInterpolate.FInterpolate('Q', pixQ, dQ, 2) fiU = FInterpolate.FInterpolate('U', pixU, dU, 2) # Open table VLtab.Open(Table.READWRITE, err) if err.isErr: OErr.printErrMsg(err, "Error Opening table") nrow = VLtab.Desc.Dict['nrow'] for irow in range(1, nrow + 1): row = VLtab.ReadRow(irow, err) pos = [row['RA(2000)'][0], row['DEC(2000)'][0]] # pixel pixel = ImageDesc.PGetPixel(dQ, pos, err) # In image? if (pixel[0] < 2.0) or (pixel[1] < 2.0) or (pixel[0] > nx - 2) or ( pixel[1] > ny - 2): continue # Fluxes qval = FInterpolate.PPosition(fiQ, pos, err) uval = FInterpolate.PPosition(fiU, pos, err) # Valid? if (qval == fblank) or (uval == fblank): continue row['Q CENTER'][0] = qval row['U CENTER'][0] = uval row['P FLUX'][0] = (qval * qval + uval * uval)**0.5 if err.isErr: OErr.printErrMsg(err, "Error Interpolating") # RMS box blc = [int(pixel[0]) - RMSsize, int(pixel[1]) - RMSsize] trc = [int(pixel[0]) + RMSsize, int(pixel[1]) + RMSsize] if blc[0] < 0: blc[0] = 0 trc[0] = min(2 * size, nx - 1) if blc[1] < 0: blc[1] = 0 trc[1] = min(2 * size, ny - 1) if trc[0] > nx - 1: d = trc[0] - nx blc[0] = max(1, blc[0] - d) trc[0] = nx - 1 if trc[1] > ny - 1: d = trc[1] - ny blc[1] = max(1, blc[1] - d) trc[1] = ny - 1 # RMSes box = FArray.PSubArr(pixQ, blc, trc, err) rmsQ = box.RMS del box box = FArray.PSubArr(pixU, blc, trc, err) rmsU = box.RMS del box row['POL RMS'][0] = 0.5 * (rmsQ + rmsU) VLtab.WriteRow(irow, row, err) if err.isErr: OErr.printErrMsg(err, "Error Writing table") # end loop over table VLtab.Close(err) del pixQ, pixU, fiQ, fiU
def SelectCC(im, inCC, outCC, radius, peelPos, err): """ Select/copy CCs more than radius from peelPos This generates a CC table which can be subtracted from the uv data and remove all sources but the peel source area. * im = Python Image with CC Tables * inCC = input CC version * outCC = output CC version * radius = radius (deg) of zone of exclusion * peelPos= [RA, Dec] in deg. * err = Python Obit Error/message stack """ ################################################################ # Checks if not Image.PIsA(im): raise TypeError("im MUST be a Python Obit Image") if not OErr.OErrIsA(err): raise TypeError("err MUST be an OErr") # # Geometry xref = im.Desc.Dict['crval'][0] yref = im.Desc.Dict['crval'][1] xrefpix = im.Desc.Dict['crpix'][0] yrefpix = im.Desc.Dict['crpix'][1] xinc = abs(im.Desc.Dict['cdelt'][0]) yinc = im.Desc.Dict['cdelt'][1] rot = im.Desc.Dict['crota'][1] imtype = im.Desc.Dict['ctype'][0][4:] # Input CC inTab = im.NewTable(Table.READONLY, "AIPS CC", inCC, err) if err.isErr: OErr.printErrMsg(err, "Error finding input CC Table") return # Output CC nrow = inTab.Desc.Dict['nrow'] noParms = inTab.Desc.List.Dict['NO_PARMS'][2][0] outTab = im.NewTable(Table.WRITEONLY, "AIPS CC", outCC, err, \ noParms = noParms) if err.isErr: OErr.printErrMsg(err, "Error creating output CC Table") return # Open inTab.Open(Table.READONLY, err) outTab.Open(Table.WRITEONLY, err) if err.isErr: OErr.printErrMsg(err, "Error opening CC Tables") return orow = 1 count = 0 sumf = 0.0 OErr.PLog(err, OErr.Info, "Excluding:") for irow in range(1, nrow + 1): row = inTab.ReadRow(irow, err) # Want this one? dx = row['DELTAX'][0] dy = row['DELTAY'][0] [ierr, xpos, ypos] = SkyGeom.PWorldPosLM(dx, dy, xref, yref, xinc, yinc, rot, imtype) # Small angle approximation dra = (xpos - peelPos[0]) * cos(radians(xpos)) delta = ((dra)**2 + (ypos - peelPos[1])**2)**0.5 if delta > radius: outTab.WriteRow(orow, row, err) orow += 1 else: #print irow,xpos,ypos count += 1 sumf += row['FLUX'][0] ras = ImageDesc.PRA2HMS(xpos) decs = ImageDesc.PDec2DMS(ypos) OErr.PLog(err, OErr.Info, "%6d %s %s flux= %f" % (irow, ras, decs, row['FLUX'][0])) # End loop OErr.PLog(err, OErr.Info, "Drop %6d CCs, sum flux= %f" % (count, sumf)) OErr.printErr(err) inTab.Close(err) outTab.Close(err) if err.isErr: OErr.printErrMsg(err, "Error copying CC Table") return
numIF = x.Desc.Dict['inaxes'][3] # Read input plane x.GetPlane(None, iplane, err) inArr = x.FArray # Input pixels ImageUtil.PGetXYPixels(x, outIm, XPixIm, YPixIm, err) xpix = XPixIm.FArray ypix = YPixIm.FArray # Set interpolator to input image FInterpolate.PSetDesc(fi, x.Desc) FInterpolate.PReplace(fi, inArr) # Interpolate for ix in range(0, ncell): for iy in range(0, ncell): pos = [space * (ix - half), space * (iy - half)] pix = ImageDesc.PGetPixel(x.Desc, pos, err) val = FInterpolate.PPixel(fi, pix, err) work.set(val, ix, iy) # end interpolation loops # Accumulate weight image, zero where image blanked FArray.PFill(work2, weight[ires]) FArray.PBlank(work2, work, work2) FArray.PDeblank(work2, 0.0) # Replace any blanking with 0.0 FArray.PAdd(accW, work2, accW) # Image * wt FArray.PDeblank(work, 0.0) # Replace any blanking with 0.0 FArray.PSMul(work, weight[ires]) # Accumulate image*wt FArray.PAdd(accWI, work, accWI) ires += 1 # Next resolution