def drawmaskinimage(image='', maskname='maskoo', makedefault=True): """ Till casa think graphical interaction is important. Ugly Function that uses interactive clean image mask to allow users to draw a mask and store it as a bit mask in the image so it can be used by imageanalysis methods or to mask an image Parameters image: is the image to put a bit mask in maskname: name of bit mask makedefault: if True will make new bit mask drawn be the default mask """ if (not os.path.exists(image)): return tmpmaskimage = '__muluktani' if (os.path.exists(tmpmaskimage)): shutil.rmtree(tmpmaskimage, True) im.drawmask(image=image, mask=tmpmaskimage) ia.open(image) ia.calcmask(mask='__muluktani < 0.5', name=maskname, asdefault=makedefault) ia.done() print 'regions/mask in ', image, rg.namesintable(image) shutil.rmtree(tmpmaskimage, True)
def radialMaxLevel(self, rmin, rmax, Nbin): "Compute the maximum (absolute) level for the image and return the array of radius (arcsec) and values" dr = (rmax - rmin) / Nbin radius = np.arange(Nbin) * dr + rmin radMaxLevel = np.zeros(Nbin) ## loop over the pixels ia.open(self.beamImage) for i in range(self.Nx): for j in range(self.Ny): xx = (i - self.refx) * self.dx yy = (j - self.refy) * self.dy rr = sqrt(xx * xx + yy * yy) indexR = floor((rr - rmin) / dr) if indexR >= 0 and indexR < Nbin: val = ia.pixelvalue([i, j])['value']['value'] if abs(val) > abs(radMaxLevel[indexR]): radMaxLevel[indexR] = val ia.close() return (radius, radMaxLevel)
def drawmaskinimage(image='', maskname='maskoo', makedefault=True): """ Till casa think graphical interaction is important. Ugly Function that uses interactive clean image mask to allow users to draw a mask and store it as a bit mask in the image so it can be used by imageanalysis methods or to mask an image Parameters image: is the image to put a bit mask in maskname: name of bit mask makedefault: if True will make new bit mask drawn be the default mask """ if(not os.path.exists(image)): return tmpmaskimage='__muluktani' if(os.path.exists(tmpmaskimage)): shutil.rmtree(tmpmaskimage, True) im.drawmask(image=image, mask=tmpmaskimage) ia.open(image) ia.calcmask(mask='__muluktani < 0.5', name=maskname, asdefault=makedefault) ia.done() print 'regions/mask in ', image, rg.namesintable(image) shutil.rmtree(tmpmaskimage, True)
def printProperties(filenames): from casa import imstat from casa import image as ia from casa import imager as im imageDir = './' for i, image in enumerate(filenames): flux = imstat(imageDir + image + '.mom0.blk.image')['flux'][0] ia.open(imageDir + image + '.mom0.blk.image') beammaj = ia.restoringbeam(channel=0)['major']['value'] beammin = ia.restoringbeam(channel=0)['minor']['value'] beamsizeUnit = ia.restoringbeam(channel=0)['major']['unit'] ia.close() ia.open(imageDir + image + '.image') noise = ia.statistics()['sigma'][0] ia.close() if True: mosaic, res = 'Multiscale clean', i #else: mosaic,res = 'Mosaic', i*3 -3 print '\nImage: '+mosaic+' resolution #' + str(res) + \ '\nBeamsize: ' + str(beammaj) + '" X ' + str(beammin) + '"' + \ '\nStd: ' + str(noise) + ' Jy/Bm' + \ '\nFlux: ' + str(flux) + ' Jy km/s'
def printProperties(filenames): from casa import imstat from casa import image as ia from casa import imager as im imageDir = './' for i, image in enumerate(filenames): flux = imstat(imageDir + image+ '.mom0.blk.image')['flux'][0] ia.open(imageDir + image + '.mom0.blk.image') beammaj = ia.restoringbeam(channel=0)['major']['value'] beammin = ia.restoringbeam(channel=0)['minor']['value'] beamsizeUnit = ia.restoringbeam(channel=0)['major']['unit'] ia.close() ia.open(imageDir + image + '.image') noise = ia.statistics()['sigma'][0] ia.close() if True: mosaic,res = 'Multiscale clean', i #else: mosaic,res = 'Mosaic', i*3 -3 print '\nImage: '+mosaic+' resolution #' + str(res) + \ '\nBeamsize: ' + str(beammaj) + '" X ' + str(beammin) + '"' + \ '\nStd: ' + str(noise) + ' Jy/Bm' + \ '\nFlux: ' + str(flux) + ' Jy km/s'
def radialMaxLevel(self,rmin,rmax,Nbin): "Compute the maximum (absolute) level for the image and return the array of radius (arcsec) and values" dr=(rmax-rmin)/Nbin radius=np.arange(Nbin)*dr+rmin radMaxLevel=np.zeros(Nbin) ## loop over the pixels ia.open(self.beamImage) for i in range(self.Nx): for j in range(self.Ny): xx=(i-self.refx)*self.dx yy=(j-self.refy)*self.dy rr=sqrt(xx*xx+yy*yy) indexR=floor((rr-rmin)/dr) if indexR >=0 and indexR < Nbin: val=ia.pixelvalue([i,j])['value']['value'] if abs(val) > abs(radMaxLevel[indexR]): radMaxLevel[indexR]=val ia.close() return(radius,radMaxLevel)
def pixelmask2cleanmask(imagename='', maskname='mask0', maskimage='', usemasked=False): """ convert pixel(T/F) mask (in a CASA image) to a mask image (1/0) used for clean imagename - input imagename that contain a mask to be used maskname - mask name in the image (default: mask0) maskimage - output mask image name usemasked - if True use masked region as a valid region """ ia.open(imagename) masks = ia.maskhandler('get') ia.close() inmaskname = '' if type(masks) != list: masks = [masks] for msk in masks: if maskname == msk: inmaskname = msk break if inmaskname == '': raise Exception, "mask %s does not exist. Available masks are: %s" % ( maskname, masks) tb.open(imagename + '/' + maskname) dat0 = tb.getcol('PagedArray') tb.close() #os.system('cp -r %s %s' % (imagename, maskimage)) shutil.copytree(imagename, maskimage) ia.open(maskimage) # to unset mask ia.maskhandler('set', ['']) # make all valid if (usemasked): ia.set(1) else: ia.set(0) ia.close() # tb.open(maskimage, nomodify=False) imd = tb.getcol('map') # maybe shape check here #by default use True part of bool mask masked = 1 if (usemasked): masked = 0 imd[dat0] = masked tb.putcol('map', imd) tb.close()
def pixelmask2cleanmask(imagename='',maskname='mask0',maskimage='',usemasked=False): """ convert pixel(T/F) mask (in a CASA image) to a mask image (1/0) used for clean imagename - input imagename that contain a mask to be used maskname - mask name in the image (default: mask0) maskimage - output mask image name usemasked - if True use masked region as a valid region """ ia.open(imagename) masks=ia.maskhandler('get') ia.close() inmaskname='' if type(masks)!=list: masks=[masks] for msk in masks: if maskname == msk: inmaskname=msk break if inmaskname=='': raise Exception, "mask %s does not exist. Available masks are: %s" % (maskname,masks) tb.open(imagename+'/'+maskname) dat0=tb.getcol('PagedArray') tb.close() #os.system('cp -r %s %s' % (imagename, maskimage)) shutil.copytree(imagename,maskimage) ia.open(maskimage) # to unset mask ia.maskhandler('set',['']) # make all valid if (usemasked): ia.set(1) else: ia.set(0) ia.close() # tb.open(maskimage,nomodify=False) imd=tb.getcol('map') # maybe shape check here #by default use True part of bool mask masked=1 if (usemasked): masked=0 imd[dat0]=masked tb.putcol('map',imd) tb.close()
def __setImage(self): "Set the parameters of the image" ia.open(self.beamImage) hdr = ia.summary() print hdr ## Image Size self.Nx = hdr['shape'][0] self.Ny = hdr['shape'][1] ## Pixel reference self.refx = hdr['refpix'][0] self.refy = hdr['refpix'][0] ##Increment (radians) self.dx = hdr['incr'][0] self.dy = hdr['incr'][1] self.dx *= RAD2ARCSEC self.dy *= RAD2ARCSEC ia.close()
def __setImage(self): "Set the parameters of the image" ia.open(self.beamImage) hdr = ia.summary() print hdr ## Image Size self.Nx=hdr['shape'][0] self.Ny=hdr['shape'][1] ## Pixel reference self.refx=hdr['refpix'][0] self.refy=hdr['refpix'][0] ##Increment (radians) self.dx=hdr['incr'][0] self.dy=hdr['incr'][1] self.dx*=RAD2ARCSEC self.dy*=RAD2ARCSEC ia.close()
def curveFluxDiskSize(self, antennaCfg, trackDuration, sizeMin, sizeMax, sizeStep, declination, cellsize='0.2arcsec', hourAngle='transit', shapeCL='Gaussian', threshClean='0mJy'): """ Compute the flux of disk with different size antennaCfg: antenna configuration trackDuration: time duration, e.g. "6h" sizeMin,sizeMax: range of the disk size in arcsec. The total flux is 1 Jy sizeStep: step for the disk size declination: disk declination cellsize : size of the cell Output: array [sizeDisk, flux] """ ## setting simobserve projectName = "tempDiskFlux" nStep = int((sizeMax - sizeMin) / sizeStep) sizeArr = np.arange(nStep) * sizeStep + sizeMin flux = np.zeros(nStep) size = np.zeros(nStep) las100 = np.zeros(nStep) totalSize = 120. mapSize = "%3.1farcsec" % (totalSize) cellF = float(cellsize[:-6]) ## to be improved .... imagesize = int(totalSize / cellF) index = 0 print "image size: %d " % (imagesize) print "mapsize :%s" % (mapSize) # simulation with one arcsec component. We clean the old files. os.system("rm -Rf *%s*" % (projectName)) if declination <= -10: decString = "J2000 0h00m00s %3dd00m00s" % (declination) raDisk = "0h00m00s" decDisk = "%3dd00m00s" % (declination) elif declination < 0 and dec > -10: decString = "J2000 0h00m00s -0%1dd00m00s" % (-declination) raDisk = "0h00m00s" decDisk = "-0%1d00m00s" % (declination) elif declination >= 0 and dec < 10: decString = "J2000 0h00m00s +0%1dd00m00s" % (declination) raDisk = "0h00m00s" decDisk = "+0%1d00m00s" % (declination) elif declination >= 10: decString = "J2000 0h00m00s +%2dd00m00s" % (declination) raDisk = "0h00m00s" decDisk = "+0%2d00m00s" % (declination) ## Estimation of the spatial resolution at 100 GHz for the mask arrCfg = aT.ArrayInfo(antennaCfg) arrCfg.stats() maxBL = arrCfg.maxBl resEstimated = 61800. / (maxBL * 100.) print("Estimated RES: %3.2f" % (resEstimated)) for disksize in sizeArr: #cl.done() cl.addcomponent(dir=decString, flux=1., freq='100GHz', shape=shapeCL, majoraxis="%2.2farcsec" % (disksize), minoraxis="%2.2farcsec" % (disksize), positionangle="0deg") cl.rename(projectName + "%d.cl" % (index)) cl.done() print projectName + "%d.cl" % (index) so.simobserve( project=projectName + "%d" % (index), complist=projectName + "%d.cl" % (index), compwidth='8GHz', antennalist=antennaCfg, totaltime=trackDuration, integration='10s', mapsize=mapSize, user_pwv=0., ) maxDisk = max(disksize, resEstimated) regDiskClean = 'circle[[%s , %s], %3.1farcsec ]' % ( raDisk, decDisk, maxDisk * 1.5) regDiskFlux = 'circle[[%s , %s], %3.1farcsec ]' % (raDisk, decDisk, maxDisk * 1.5) sa.simanalyze( project=projectName + "%d" % (index), image=True, weighting='briggs', imsize=imagesize, cell=cellsize, mask=regDiskClean, niter=2000, threshold=threshClean, imdirection=decString, # graphics = 'file' ) msName = projectName + "%d/" % ( index) + projectName + "%d.%s.ms" % (index, antennaCfg.split('.')[0]) imageName = projectName + "%d/" % ( index) + projectName + "%d.%s.noisy.image" % ( index, antennaCfg.split('.')[0]) print(" ") print("## analysis ...") print "Mask Clean :: %s" % (regDiskClean) print "Mask Flux :: %s" % (regDiskFlux) print "Component Size :: %2.2f" % (disksize) ia.open(imageName) data = ia.restoringbeam() bmaj = data['major']['value'] stat = ia.statistics(region=regDiskFlux) flux[index] = stat['flux'] ia.close() print data ms = uvw.UVW(msName) dUV = ms.distUV(noShadow=True) duvMin = min(dUV) las100[ index] = RAD2ARCSEC * 0.0017987547479999 / duvMin ## 0.6 * Lambda / BL_min print "mininum BL:", duvMin print "LAS (100 GHz & min BL):", las100[index] print "Flux: %2.3f" % (flux[index]) print "--" index += 1 return ([sizeArr, flux])
def curveBeamResolutiongDeclination(self, antennaCfg, trackDuration, declinationMin, declinationMax, decStep, ha='transit'): """ Compute the minor,Major axis vs. Declination for a given configuration antennaCfg: antenna configuration trackDuration: time duration, e.g. "6h" declinationMin,declinationMax: range of declination decStep: step for the declination, needs to be an integer... Output : arrays [declination] [minor] [major] """ projectName = "tempCurveBeamDeclination" nStep = math.floor((declinationMax - declinationMin) / decStep) decArr = np.arange(nStep) * decStep + declinationMin minorAxis = np.zeros(nStep) majorAxis = np.zeros(nStep) las100 = np.zeros(nStep) index = 0 # simulation with one arcsec component. We clean the old files. os.system("rm -Rf *%s*" % (projectName)) for dec in decArr: if dec <= -10: decString = "J2000 0h00m00s %3dd00m00s" % (dec) elif dec < 0 and dec > -10: decString = "J2000 0h00m00s -0%1dd00m00s" % (-dec) elif dec >= 0 and dec < 10: decString = "J2000 0h00m00s +0%1dd00m00s" % (dec) elif dec >= 10: decString = "J2000 0h00m00s +%2dd00m00s" % (dec) # simulayion with one arcsec component #os.system("rm -Rf *%s*"%(projectName)) print decString #cl.done() cl.addcomponent(dir=decString, flux=1, freq='100GHz', shape="Gaussian", majoraxis="0.1arcsec", minoraxis="0.1arcsec", positionangle="0deg") cl.rename(projectName + "%d.cl" % (index)) cl.done() print projectName + "%d.cl" % (index) so.simobserve(project=projectName + "%d" % (index), complist=projectName + "%d.cl" % (index), compwidth='8GHz', antennalist=antennaCfg, totaltime=trackDuration, integration='10s', hourangle='ha') sa.simanalyze( project=projectName + "%d" % (index), image=True, weighting='briggs', # imsize = 256, # cell = cellsize, # mask = maskClean, niter=100, # threshold = '0.1mJy', # graphics = 'file' ) psfName = projectName + "%d/" % ( index) + projectName + "%d.%s.psf" % (index, antennaCfg.split('.')[0]) psfQuickName = projectName + "%d/" % ( index) + projectName + "%d.%s.quick.psf" % ( index, antennaCfg.split('.')[0]) msName = projectName + "%d/" % ( index) + projectName + "%d.%s.ms" % (index, antennaCfg.split('.')[0]) imageName = projectName + "%d/" % ( index) + projectName + "%d.%s.noisy.image" % ( index, antennaCfg.split('.')[0]) # if os.path.exists(psfName): # psfRes = psf.psf_calc(psfName) # else: # psfRes = psf.psf_calc(psfQuickName) ia.open(imageName) data = ia.restoringbeam() ia.close() print data minorAxis[index] = data['minor']['value'] majorAxis[index] = data['major']['value'] print "minor Axis:", minorAxis[index] print "major Axis:", majorAxis[index] ms = uvw.UVW(msName) dUV = ms.distUV(noShadow=True) duvMin = min(dUV) rds = np.sort(dUV) nuv = len(rds) i05 = (int)(0.05 * nuv) L05 = rds[i05] las = RAD2ARCSEC * 0.0017987547479999 / duvMin ## 0.6 * Lambda / BL_min ## Definition of LAS from SCIREQ-328 las100[index] = RAD2ARCSEC * 0.983296 * 0.0029979245799998332 / L05 # if las100[index] > las : # las100[index] = las # las100[index] = las print "mininum BL:", duvMin print "L05:", L05 print "LAS (old definition)", las print "LAS (100 GHz):", las100[index] index += 1 # fout=open("curveBeamDec.last","wb") # data={'Dec':decArr,'Shadow':fractionShadowing} # pickle.dump(data,fout) # fout.close() return (decArr, minorAxis, majorAxis, las100)
def runFiltering(self, antennaCfg, trackDuration, frequency, dec, imageTotalSize, resolutionStart, resolutionEnd, resolutionStep): """ use the disk100.fits image of a uniform disk of 100 pixel size (diameter) Run a set of simulations to account for the filtering at different scales. antennaCfg: antenna configuration file trackDuration : trackDuration resolutionStart,resolutionEnd,resolutionStep: range for the resolution to simulate dec: declination OUTPUT: resolution, flux: resolution and flux output (1 Jy in entry) """ maskClean = [70, 70, 180, 180] projectName = "tempCurveFiltering" nStep = math.floor((resolutionEnd - resolutionStart) / resolutionStep) resolutionArr = np.arange(nStep) * resolutionStep + resolutionStart flux = np.zeros(nStep) boxStat = '%d,%d,%d,%d' % (maskClean[0], maskClean[1], maskClean[2], maskClean[3]) os.system("rm -Rf *%s*" % (projectName)) if dec <= -10: decString = "J2000 10h00m00s %3dd00m00s" % (dec) elif dec < 0 and dec > -10: decString = "J2000 10h00m00s -0%1dd00m00s" % (-dec) elif dec >= 0 and dec < 10: decString = "J2000 10h00m00s +0%1dd00m00s" % (dec) elif dec >= 10: decString = "J2000 10h00m00s +%2dd00m00s" % (dec) # simulayion with one arcsec component ##os.system("rm -Rf *%s*"%(projectName)) print decString index = 0 print resolutionArr for res in resolutionArr: resolutionDisk = "%4.2farcsec" % (res / 100.) print resolutionDisk print antennaCfg so.sim_observe( project=projectName + "%d" % (index), skymodel='disk100.fits', inbright='1Jy/pixel', indirection=decString, incell=resolutionDisk, incenter=frequency, inwidth='8GHz', antennalist=antennaCfg, totaltime=trackDuration, integration='10s', direction=decString, maptype='ALMA', # mapsize = ['2arcmin','2arcmin'], # pointingspacing = "2arcmin" ) sa.sim_analyze( project=projectName + "%d" % (index), image=True, imsize=imageTotalSize, # cell = cellsize, mask=maskClean, niter=2000, threshold='0.1mJy', graphics='file') imageName = projectName + "%d/" % ( index) + projectName + "%d.%s.image" % ( index, antennaCfg.split('.')[0]) # imageName=projectName+"%d/"%(index)+projectName+"%d.image"%(index) print "Read %s" % (imageName) ia.open(imageName) # flux0=ia.statistics()['flux'][0] stat = ims.imstat( imagename=imageName, box=boxStat, ) flux0 = stat['flux'][0] print flux0 if res == resolutionArr[0]: fluxNormalization = flux0 fluxRes = flux0 / fluxNormalization print "Flux: %4.3f" % (fluxRes) flux[index] = fluxRes ia.close() index += 1 return (resolutionArr, flux)
def curveBeamResolutiongDeclination(self, trackDuration, declinationMin, declinationMax, decStep): """ Compute the minor,Major axis vs. Declination for a given configuration trackDuration: time duration, e.g. "6h" declinationMin,declinationMax: range of declination decStep: step for the declination, needs to be an integer... Output : arrays [declination] [minor] [major] """ antennaCfg = self.fileCfg print antennaCfg projectName = "tempCurveBeamDeclination" nStep = floor((declinationMax - declinationMin) / decStep) decArr = np.arange(nStep) * decStep + declinationMin minorAxis = np.zeros(nStep) majorAxis = np.zeros(nStep) las100 = np.zeros(nStep) index = 0 # simulation with one arcsec component. We clean the old files. os.system("rm -Rf *%s*" % (projectName)) for dec in decArr: if dec <= -10: decString = "J2000 0h00m00s %3dd00m00s" % (dec) elif dec < 0 and dec > -10: decString = "J2000 0h00m00s -0%1dd00m00s" % (-dec) elif dec >= 0 and dec < 10: decString = "J2000 0h00m00s +0%1dd00m00s" % (dec) elif dec >= 10: decString = "J2000 0h00m00s +%2dd00m00s" % (dec) # simulayion with one arcsec component #os.system("rm -Rf *%s*"%(projectName)) print decString #cl.done() cl.addcomponent(dir=decString, flux=1, freq='100GHz', shape="Gaussian", majoraxis="0.1arcsec", minoraxis="0.1arcsec", positionangle="0deg") cl.rename(projectName + "%d.cl" % (index)) cl.done() print projectName + "%d.cl" % (index) sim = inspect.getargspec(casa.simobserve) ind = 0 for arg in sim.args: casa.simobserve.__setattr__(arg, sim.defaults[ind]) ind += 1 casa.simobserve.__setattr__('project', projectName + "%d" % (index)) casa.simobserve.__setattr__('complist', projectName + "%d.cl" % (index)) casa.simobserve.__setattr__('compwidth', '8GHz') casa.simobserve.__setattr__('antennalist', antennaCfg) casa.simobserve.__setattr__('totaltime', trackDuration) casa.simobserve.__setattr__('integration', '10s') casa.simobserve(antennalist='best-O-1_step2_88.cfg', complist='tempCurveBeamDeclination0.cl') simanalyze( project=projectName + "%d" % (index), image=True, weighting='briggs', # imsize = 256, # cell = cellsize, # mask = maskClean, niter=100, # threshold = '0.1mJy', # graphics = 'file' ) psfName = projectName + "%d/" % ( index) + projectName + "%d.%s.psf" % (index, antennaCfg.split('.')[0]) psfQuickName = projectName + "%d/" % ( index) + projectName + "%d.%s.quick.psf" % ( index, antennaCfg.split('.')[0]) msName = projectName + "%d/" % ( index) + projectName + "%d.%s.ms" % (index, antennaCfg.split('.')[0]) imageName = projectName + "%d/" % ( index) + projectName + "%d.%s.image" % ( index, antennaCfg.split('.')[0]) # if os.path.exists(psfName): # psfRes = psf.psf_calc(psfName) # else: # psfRes = psf.psf_calc(psfQuickName) ia.open(imageName) data = ia.restoringbeam() ia.close() print data minorAxis[index] = data['minor']['value'] majorAxis[index] = data['major']['value'] print "minor Axis:", minorAxis[index] print "major Axis:", majorAxis[index] ms = uvw.UVW(msName) dUV = ms.distUV(noShadow=True) duvMin = min(dUV) las100[ index] = RAD2ARCSEC * 0.0017987547479999 / duvMin ## 0.6 * Lambda / BL_min print "mininum BL:", duvMin print "LAS (100 GHz):", las100[index] index += 1 # fout=open("curveBeamDec.last","wb") # data={'Dec':decArr,'Shadow':fractionShadowing} # pickle.dump(data,fout) # fout.close() return (decArr, minorAxis, majorAxis, las100)
def blankcube(image, dummyMS, smooth=True, verbose=True, region='centerbox[[10h21m45s,18.05.14.9],[15arcmin,15arcmin]]', ruthless=False, extension='.image', beamround='int', blankThreshold=2.5, moments=[0]): ''' Parameters ---------- image : string Base name of image. If target image has extension other than '.image', change the extension keyword. dummyMS : string MS file required for blanking process in CASA smooth : bool, optional Smooth the image to a circular beam before blanking? Default True verbose : bool, optional region : string, optional region parameter featured in CASA ruthless : bool, optional Delete previous outputs from blankcube extension : string, optional Extension of the target image. Must include the '.', e.g., '.restored' Default '.image' beamround : string,float P blankThreshold : float, optional Initial blanking threshold of all pixels scaled by the standard deviation times the blankingthreshold Default = 2.5 (Walter et al. 2008) moments : list, optional Moments to calculate from cube. Options are 0,1,2. Example: [0,1,2] Default: [0] Returns ------- out : null Examples -------- ''' from casa import immath, imsmooth, immoments from casa import image as ia from casa import imager as im from casa import quanta as qa import os import numpy as np # Delete files associated with previous runs if ruthless: os.system('rm -rf ' + image + '.smooth.blk.image') os.system('rm -rf ' + image + '.smooth.image') os.system('rm -rf ' + image + '.blk.image') os.system('rm -rf ' + image + '.mask') imageDir = './' # Create moment maps mom0, mom1, mom2 = False, False, False if len(moments) > 0: for i, moment in enumerate(moments): if moment == 0: mom0 = True if moment == 1: mom1 = True if moment == 2: mom2 = True if mom1 == True or mom2 == True: beamScale = 1.01 elif mom0 == True: beamScale = 2. # determine beamsize of cube ia.open(imageDir + image + extension) beamsizes = np.zeros(ia.shape()[2]) for i in range(ia.shape()[2]): beamsizes[i] = ia.restoringbeam(channel=i)['major']['value'] beamsizeUnit = ia.restoringbeam(channel=i)['major']['unit'] beamsize = qa.convert(str(beamsizes.max()) + beamsizeUnit, 'arcsec')['value'] if type(beamround) == float: beamsize_smooth = beamround * beamsize else: beamsize_smooth = np.ceil(beamsize) #beamsize_smooth = 1.01 * beamsize ia.close() if verbose: print 'Max beamsize is ' + str(beamsize) + '"' if not os.path.exists(image + '.blk.image'): # create cube for blanking if smooth: # smooth to a larger beam if the user desires if verbose: print 'Convolving to ' + str(beamsize_smooth) + '"' imsmooth(imagename=image + extension, outfile=image + '.blk.image', major=str(beamsize_smooth) + 'arcsec', minor=str(beamsize_smooth) + 'arcsec', region=region, pa='0deg', targetres=True) else: # do no smooth immath(imagename=image + extension, outfile=image + '.blk.image', mode='evalexpr', region=region, expr='IM0') if not os.path.exists(image + '.smooth.image'): # convolve cube to 2X beam for blanking imsmooth(imagename=image + extension, outfile=image + '.smooth.image', major=str(beamsize * beamScale) + 'arcsec', minor=str(beamsize * beamScale) + 'arcsec', pa='0deg', region=region, targetres=True) # determine threshold of cube ia.open(image + '.smooth.image') threshold = ia.statistics()['sigma'][0] * blankThreshold ia.close() # blank the cube at threshold*sigma ia.open(image + '.smooth.image') ia.calcmask(mask=image + '.smooth.image > ' + str(threshold), name='mask1') wait = 'waits for calcmask to close' ia.close() # hand blank the cube im.open(dummyMS) pause = None while pause is None: im.drawmask(image=image + '.smooth.image', mask=image + '.mask') pause = 0 im.close # mask contains values of 0 and 1, change to a mask with only values of 1 ia.open(image + '.mask') ia.calcmask(image + '.mask' + '>0.5') ia.close() # apply mask on smoothed image immath(imagename=image + '.smooth.image', outfile=image + '.smooth.blk.image', mode='evalexpr', mask='mask(' + image + '.mask)', expr='IM0') # apply mask on image ia.open(imageDir + image + '.blk.image') ia.maskhandler('copy', [image + '.smooth.blk.image:mask0', 'newmask']) ia.maskhandler('set', 'newmask') ia.done() cube = '.blk.image' # specify name of cube for moment calculation # create moment 0 map if mom0: if ruthless: os.system('rm -rf ' + image + '.mom0.image') immoments(imagename=image + cube, moments=[0], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom0.image') # create moment 1 map if mom1: if ruthless: os.system('rm -rf ' + image + '.mom1.image') immoments(imagename=image + cube, moments=[1], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom1.image') # create moment 2 map if mom2: if ruthless: os.system('rm -rf ' + image + '.mom2.image') immoments(imagename=image + cube, moments=[2], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom2.image') if verbose and mom0: from casa import imstat flux = imstat(image + '.mom0.image')['flux'][0] ia.open(image + '.mom0.image') beammaj = ia.restoringbeam(channel=0)['major']['value'] beammin = ia.restoringbeam(channel=0)['minor']['value'] beamsizeUnit = ia.restoringbeam(channel=0)['major']['unit'] ia.close() print 'Moment Image: ' + str(image) + '.mom0.image' print 'Beamsize: ' + str(beammaj) + '" X ' + str(beammin) + '"' print 'Flux: ' + str(flux) + ' Jy km/s'
def blankcube(image, dummyMS, smooth=True, verbose=True, region='centerbox[[10h21m45s,18.05.14.9],[15arcmin,15arcmin]]', ruthless=False, extension='.image', beamround='int', blankThreshold=2.5, moments=[0]): ''' Parameters ---------- image : string Base name of image. If target image has extension other than '.image', change the extension keyword. dummyMS : string MS file required for blanking process in CASA smooth : bool, optional Smooth the image to a circular beam before blanking? Default True verbose : bool, optional region : string, optional region parameter featured in CASA ruthless : bool, optional Delete previous outputs from blankcube extension : string, optional Extension of the target image. Must include the '.', e.g., '.restored' Default '.image' beamround : string,float P blankThreshold : float, optional Initial blanking threshold of all pixels scaled by the standard deviation times the blankingthreshold Default = 2.5 (Walter et al. 2008) moments : list, optional Moments to calculate from cube. Options are 0,1,2. Example: [0,1,2] Default: [0] Returns ------- out : null Examples -------- ''' from casa import immath,imsmooth,immoments from casa import image as ia from casa import imager as im from casa import quanta as qa import os import numpy as np # Delete files associated with previous runs if ruthless: os.system('rm -rf ' + image + '.smooth.blk.image') os.system('rm -rf ' + image + '.smooth.image') os.system('rm -rf ' + image + '.blk.image') os.system('rm -rf ' + image + '.mask') imageDir = './' # Create moment maps mom0,mom1,mom2 = False,False,False if len(moments) > 0: for i, moment in enumerate(moments): if moment == 0: mom0 = True if moment == 1: mom1 = True if moment == 2: mom2 = True if mom1 == True or mom2 == True: beamScale = 1.01 elif mom0 == True: beamScale = 2. # determine beamsize of cube ia.open(imageDir + image + extension) beamsizes = np.zeros(ia.shape()[2]) for i in range(ia.shape()[2]): beamsizes[i] = ia.restoringbeam(channel=i)['major']['value'] beamsizeUnit = ia.restoringbeam(channel=i)['major']['unit'] beamsize = qa.convert(str(beamsizes.max()) + beamsizeUnit,'arcsec')['value'] if type(beamround) == float: beamsize_smooth = beamround*beamsize else: beamsize_smooth = np.ceil(beamsize) #beamsize_smooth = 1.01 * beamsize ia.close() if verbose: print 'Max beamsize is ' + str(beamsize) + '"' if not os.path.exists(image + '.blk.image'): # create cube for blanking if smooth: # smooth to a larger beam if the user desires if verbose: print 'Convolving to ' + str(beamsize_smooth) + '"' imsmooth(imagename=image + extension, outfile=image + '.blk.image', major=str(beamsize_smooth) + 'arcsec', minor=str(beamsize_smooth) + 'arcsec', region=region, pa='0deg', targetres=True) else: # do no smooth immath(imagename=image + extension, outfile=image + '.blk.image', mode='evalexpr', region=region, expr='IM0') if not os.path.exists(image + '.smooth.image'): # convolve cube to 2X beam for blanking imsmooth(imagename=image + extension, outfile=image + '.smooth.image', major=str(beamsize*beamScale) + 'arcsec', minor=str(beamsize*beamScale) + 'arcsec', pa='0deg', region=region, targetres=True) # determine threshold of cube ia.open(image + '.smooth.image') threshold = ia.statistics()['sigma'][0] * blankThreshold ia.close() # blank the cube at threshold*sigma ia.open(image + '.smooth.image') ia.calcmask(mask=image + '.smooth.image > ' + str(threshold), name='mask1') wait = 'waits for calcmask to close' ia.close() # hand blank the cube im.open(dummyMS) pause = None while pause is None: im.drawmask(image=image + '.smooth.image', mask=image + '.mask') pause = 0 im.close # mask contains values of 0 and 1, change to a mask with only values of 1 ia.open(image + '.mask') ia.calcmask(image + '.mask' + '>0.5') ia.close() # apply mask on smoothed image immath(imagename=image + '.smooth.image', outfile=image + '.smooth.blk.image', mode='evalexpr', mask='mask(' + image + '.mask)', expr='IM0') # apply mask on image ia.open(imageDir + image + '.blk.image') ia.maskhandler('copy',[image + '.smooth.blk.image:mask0', 'newmask']) ia.maskhandler('set','newmask') ia.done() cube = '.blk.image' # specify name of cube for moment calculation # create moment 0 map if mom0: if ruthless: os.system('rm -rf ' + image + '.mom0.image') immoments(imagename=image + cube, moments=[0], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom0.image') # create moment 1 map if mom1: if ruthless: os.system('rm -rf ' + image + '.mom1.image') immoments(imagename=image + cube, moments=[1], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom1.image') # create moment 2 map if mom2: if ruthless: os.system('rm -rf ' + image + '.mom2.image') immoments(imagename=image + cube, moments=[2], axis='spectra', chans='', mask='mask(' + image + cube + ')', outfile=image + '.mom2.image') if verbose and mom0: from casa import imstat flux = imstat(image + '.mom0.image')['flux'][0] ia.open(image + '.mom0.image') beammaj = ia.restoringbeam(channel=0)['major']['value'] beammin = ia.restoringbeam(channel=0)['minor']['value'] beamsizeUnit = ia.restoringbeam(channel=0)['major']['unit'] ia.close() print 'Moment Image: ' + str(image) + '.mom0.image' print 'Beamsize: ' + str(beammaj) + '" X ' + str(beammin) + '"' print 'Flux: ' + str(flux) + ' Jy km/s'