You are on page 1of 30

ImageAnalysiswithCASA

SebastienMuller
NordicARC
OnsalaSpaceObservatory,Sweden

Contents

Introduction
Workingonimages:Generaltasks
Workingonspectrallinedatacubes
Advancedusers:theToolkit(verybriefmention)

ImageAnalysis:Introduction
Viewimages
Extractinformationfromimage/cubeatselectedposition/region
>Statistics(noise,peak,dynamicrange,...)
Fittingofsources
Identifyspectrallines
Preparescienceresults
Spectra

Momentsmaps(integratedmaps,velocityfield,velocitydispersion)
Amongmanyothers

AlotcanbedonewithinCASA

Preliminaryremarks
SeveralCLEANparametersareusedtocontrolyourresultingCLEANedimagesetup,
StilltheycanbemodifiedlateronduringImageAnalysis:
restfreq:Settherestfrequencyreferenceofthecube
outframe:Setthevelocityreferenceframe(LSRK,BARY,TOPO,...)
veltype:(radio,optical)
pbcor:primarybeamcorrection(False/True)
impbcor
ALLimageanalysiscanprobablybedoneinyourfavoritesoftware,hereIfocusonCASA
Ihaveselectedstandardparameters/options(heavilybiased!!!)
whenillustratingCASAcommand
PleaseRefertoCASAhelp,asIcouldnotcopy/pasteallparameters/optionshere
REFERENCES:
CASACookbook
CASAGuides(ALMASciencePortal/ALMAdata/ScienceVerification/)

Workingwithimages:Generaltasks
Import/exportimagesimportfits,exportfits
ViewimagestheViewer
Manipulateheaderinformationimhead
Defineabox/region
Extractvaluesimval
Imagestatisticsimstat
Performmathematicaloperationsonorbetweenimagesimmath
Regridanimageontonewcoordinatesystemimregrid
Smoothimagesimsmooth
Sourcecomponentfittingimfit

ImageImport/Export
importfits:ImportaFITSformatimageintoCASAimagetableformat
(TheCASAviewercanreadfitsimages)

exportfits:ExportaCASAimagetoFITSformat

Ex:
CASA>exportfits(imagename='my.image',fitsimage='my_image.fits')

Viewer
CASA>viewer
andthenusetheGUIinterface,or:
CASA>imview(
raster= {

},
contour={

},
zoom= {

'file':'image.mom1',
'range':[2630,2920],
'colorwedge':T,
'colormap':'Rainbow2'
'file':'image.mom0',
'levels':[5,10,20,40,80,160],
'base':0,
'unit':1
'channel':0,
'blc':[78,78],
'trc':[178,178],
'coord':'pixel'

},
)

out=

'NameFigure.png'

Headerinformation
Manipulateheaderinformationwithimhead
imhead( imagename='my.image',mode='summary')
Mode=
summary
list
get
put

printoutasummaryofimagespropertiesandheadertothelogger
printoutalistofheaderkeywordsandvalues
retrievethecurrentvalueforaspecifiedkeywordhdkey
replacethecurrentvaluewithanewhdvalueUSEWITHCAUTION!

Examples:
Retrievethevalueofheaderfield'observer'andwriteitintoavariable'observer_name':
observer_name=imhead( imagename='my.image',mode='get',hdkey='observer')
ChangeittoAlbert:
imhead( imagename='my.image',mode='put',hdkey='observer',hdvalue='Albert')

Headerhdkeyforreference

beammaj
beammin
beampa
bunit
cdeltn

crpixn
crvaln
ctypen
cunitn
datamax
datamin
dateobs
equinox
imtype
minpos
minpixpos
maxpos
maxpixpos
object
observer
projection
reffreqtype
restfreq
shape
telescope

Majoraxisofthecleanbeam
Minoraxisofthecleanbeam
Positionangleofthecleanbeam
Brightnessunit(K,Jy/beam,etc)
Pixelsize,nthaxis(maxnis4)
Pixelcoordinateofreferencepoint,nthaxis
Pixellocationofreferencepoint,nthaxis
Axisname,nthaxis
Pixelunits,nthaxis
Maximumpixelvalueinimage
Minimumpixelvalueinimage
Dateoftheobservation
Referenceframefordirectionalcoordinates
Imagetype:intensity,
Positionoftheminimumvalue(worldunit)
Sameinpixel(array)
Positionofthemaximumvalue(worldunit)
Sameinpixel(array)
Sourcename
Observername
Imageprojection('SIN','TAN',or'ZEA')
Referenceframeforthespectralcoordinates
RestFrequency
Numberofpixelsalongeachaxis

Telescopename

Definingbox/region
intheviewer
Drawapolygon
Closeit
Doubleclickinsidetoconfirm
Tools>Regioninfile>Save
(Show/Hide)

10

Definingbox/regionCommandline
box='blcx,blcy,trcx,trcy'
Aregioncanbedefinedfromafile,e.g.assavedwiththeViewer:
region='definedregion.rgn'
orwithpredefinedshapes:
region=circle[center,radius]
annulus[center,inner&outerradii]
box,centerbox,rotbox[cornerposition;center,sidelengths;
center,sidelengths,positionangle]'
ellipse[center,major&minoraxes,positionangle]
polygon[verticespositions]
Examples:
box='0,0,50,50'
region='circle[[18h12m24s,23d11m00s],2.3arcsec]'
region='rotbox[[18h12m24s,23d11m00s],[10pix,5pix],45deg]'

11

Extractvaluesfromimages
imvalwillextractthevaluesofthedataandmaskfromaspecifiedregion
andreturnvalueasaPythondictionary
CASA>intensity=imval(imagename='my.image',box='128,128')
CheckthecontentsofthenewPythondictionary'intensity':
CASA>intensity
Out[]:
{'axes':[[0,'Longitude'],[1,'Latitude'],[2,'Frequency'],[3,'Stokes']],
'blc':[128,128,0,0],
'coords':array([[3.65796865e+00,3.34128924e01,1.15269264e+11,
1.00000000e+00]]),
'data':array([56.41896057]),
'mask':array([True],dtype=bool),
'trc':[128,128,0,0],
'unit':'K.km/s'}
Accessdatavalue:
CASA>intensity['data']
Out[]:array([56.41896057])

12

ImageStatistics
imstat:calculatesstatisticsonaregionofanimageandreturntheresultsasvaluesin
aPythondictionary
>noiserms,dynamicrange,...

CASA>:inp(imstat)
#imstat::Displaysstatisticalinformationfromanimageorimageregion
imagename='my.image'#Nameoftheinputimage
axes=1#Listofaxestoevaluatestatisticsover.Defaultisallaxes.
region=''#ImageRegionorname.UseViewer
box=''#Selectoneormoreboxregions
chans=''#Selectthechannel(spectral)range
stokes=''#Stokesparamstoimage(I,IV,IQU,IQUV).Default""=>includeall
listit=True#Printstatsandboundingboxtologger?
robust=False#IfTthencomputerobuststatisticsaswell
verbose=True#Printadditionalmessagestologger?
async=False#Iftruethetasknamemustbestartedusingimstat(...)

13

CASA>imgstat=imstat()
imgstatisnowdefinedas
aPythondictionary,
containingallkeyslistedontheright.
Access:imgstat['KEY'][AXIS]
CASA>rms=(imgstat['rms'][0])
print'>>rms:'+str(rms)
peak=(imgstat['max'][0])
print'>>Peak:'+str(peak)
print'>>Dynamicrange:'+str(peak/rms)

KEYS
blcabsolutePIXELcoordinateofthebottomleftcornerof
theboundingboxsurroundingtheselectedregion
blcfSameasblc,butusesWORLDcoordinatesinsteadofpixels
trctheabsolutePIXELcoordinateofthetoprightcorner
oftheboundingboxsurroundingtheselectedregion
trcfSameastrc,butusesWORLDcoordinatesinsteadofpixels
fluxtheintegratedfluxdensityifthebeamisdefinedand
theifbrightnessunitsare$Jy/beam$
nptsthenumberofunmaskedpointsused
maxthemaximumpixelvalue
minminimumpixelvalue
maxposabsolutePIXELcoordinateofmaximumpixelvalue
maxposfSameasmaxpos,butusesWORLDcoordinatesinsteadofpixels
minposabsolutepixelcoordinateofminimumpixelvalue
minposfSameasminpos,butusesWORLDcoordinatesinsteadofpixels
sumthesumofthepixelvalues:$\sumI_i$
sumsqthesumofthesquaresofthepixelvalues:$\sumI_i^2$
meanthemeanofpixelvalues:
$ar{I}=\sumI_i/n$
sigmathestandarddeviationaboutthemean:
$\sigma^2=(\sumI_iar{I})^2/(n1)$
rmstherootmeansquare:
$\sqrt{\sumI_i^2/n}$
medianthemedianpixelvalue(ifrobust=T)
medabsdevmedthemedianoftheabsolutedeviationsfromthe
median(ifrobust=T)
quartiletheinterquartilerange(ifrobust=T).Findthepoints
whichare25%largestand75%largest(themedianis
50%largest),findtheirdifferenceanddividethat
differenceby2.

14

Mathematicaloperationsonimages
immathperformmathematicaloperationsonorbetweenimages
Examples:
Divideanimagebyanother,withathresholdononeimage:
CASA>immath( imagename=['img1.image','img2.image']
exp='IM0/IM1[IM1>0.007]',
outfile='div.image')
Selectasingleplaneofacubeandsubtractandsubtractitfromallplanes:
CASA>immath( imagename='cube.image',
exp='IM0',
chans='77',
outfile='chan77.image')
CASA>immath(

imagename=['cube.image','chan77.image']
exp='IM0IM1',
outfile='cubeminuschan77.image')

15

Changecoordinatessystem
imregridtoregridanimageontoanewcoordinatesystem
Onlyneedtospecifyinputimage,template,andoutputimage
templatecanbe:
atemplateimage
anoutputcoordinatesystem:'J2000','B1950','GALACTIC',...
'get':thisreturnsaPythondictionaryofthecoordinatesystem
aPythondictionary(e.g.obtainedwithpreviousoption'get'onanotherimage)

However,thismightbetterbedoneonvisibilitieswithtaskfixvis,whichwillrecalculatethe
(u,v,w)and/ormodifythephasecenter
Ex:
fixvis( vis='Moon.ms',outputvis='Moonfixed.ms',field='Moon',
refcode='',phasecenter='J20009h25m00s05d12m00s')

willsetthephasecenterforfield'Moon'tothegivendirectionandrecalculatetheuvw
16

Smoothimages
imsmoothImageconvolution(withGaussianorboxcarkernel)
CASA>inpimsmooth
#imsmooth::Smoothanimageorportionofanimage
imagename='my.image'
#Nameoftheinputimage
kernel='gauss'
#Typeofkerneltouse:gaussianorboxcar.
major='2.5arcsec'
#Majoraxisforthekernels,defaultdirectionisalongyaxis.
minor='2.0arcsec'
#Minoraxisingaussianandboxcarkernels
pa='0deg'
#Positionangleforgaussiankernel
targetres=False
#Ifgaussiankernel,specifiedparametersaretobe
#resolutionofoutputimage(True)orparametersof
#gaussiantoconvolvewithinputimage(False).
ConvolutionbyGaussian:img_out2=img_in2+smo2
Ex:SmoothingwithaGaussiankernel20''by10'',withpositionangle45deg:
CASA>imsmooth(
imagename='my.image',
kernel='gauss',
major='20arcsec',minor='10arcsec',pa='45deg')

17

ImageplaneComponentFitting
imfit2DGaussianFitting(oneormoreGaussiancomponent)tosourcesinanimage
seealsouvmodelfitforfitinthevisibilitydomain

CASA<9>:inpimfit
#imfit::FitoneormoreellipticalGaussiancomponentsonanimageregion(s)
imagename=''#Nameoftheinputimage
box=''#Specifyoneormoreboxregionsforthefit
region=''#Regionnameorregionspecifiedusingrgtool
chans=''#Spectralchannelsonwhichtoperformfit
stokes=''#Stokesparametertofit.Ifblank,firststokesplaneisused
mask=''#Masktobeappliedtotheimage
includepix=[]#Rangeofpixelvaluestoincludeforfitting@
excludepix=[]#Rangeofpixelvaluestoexcludeforfitting@
residual=''#Nameofoutputresidualimage@
model=''#Nameofoutputmodelimage@
estimates=''#Nameoffilecontaininginitialestimatesofcomponentparameters@
logfile=''#Nameoffiletowritefitresults
newestimates=''#Filetowritefitresultswhichcanbeusedasinitialestimatesfornextrun
complist=''#Nameofoutputcomponentlisttable
chan=1#DEPRECATED.USEchansINSTEAD

async=False#Iftruethetasknamemustbestartedusingimfit(...)

18

Ifonly1Gaussiancomponent(default),thefitwilldowithoutpriorguess.
Ifmore,estimateshavetobeinputfromafilecontaining(foreachcomponent):
peakintensity,peakxpixvalue,peakypixvalue,majoraxis,minoraxis,positionangle,fixed
fixed=combinationof:fxyabp,fortheparameterstobekeptconstant
Example:Simultaneousfitof2Gaussiancomponents,thefirstonefixedinxyposition
prior_guess=open(inputparameter.estimate,w)
print>>prior_guess,#peak,x,y,bmaj,bmin,pa
print>>prior_guess,0.02,128,128,0.4arcsec,0.2arcsec,120deg,xy'
print>>prior_guess,0.01,113,120,0.4arcsec,0.2arcsec,120deg'
prior_guess.close()
xfit=imfit( imagename=my.image,

estimates=inputparameter.estimate,
logfile='fitresults.log,
box=118,118,138,138,103,110,110,130')
ResultsarereturnedasaPythondictionary(xfit)+canbewritteninalogfile
oracomponentlisttable
Iftheimagehasacleanbeam,thereportwillcontainboththeconvolvedandthedeconvolvedfitresults.

19

OtherIAtasksinCASA

imtransreordertheaxesofanimage
Ex:[RA,Dec,freq]tobecome[freq,RA,Dec]
imcollapsecollapseimagealongoneormoreaxes
byaggregatingpixelvaluesalongthataxis
Fonctiontocomputeaggregationofpixelvalues:mean,median,rms,max,...

20

Workingwithspectraldatacube

Extractspectra
Subtractcontinuumimcontsub
Momentsimagesimmoments
Spectrallinesidentificationslsearch
Spectrallinefittingspecfit

21

ExtractspectrawiththeViewer
SpectralProfile

Thespectrumcanbesavedinascii

22

ExtractaspectrumScriptmode
UsethefollowingsetofCASAcommandstoextractaspectrumandoutputinanasciifile:
CASA> imgname='your_image.image'#specifyinputimagecube
cubestat=imstat(imagename=imgname)
importnumpy#makesurevectorandarrayarithmeticoptionsareloaded
cubeheader=imhead(imagename=imgname,mode="list")#setheadervariables
nspec=cubestat['trc'][3]+1#getthenumberoffrequencychannels.
f0=float(cubeheader['crval4'])#referencefreqinHz
df=float(cubeheader['cdelt4'])#channelwidthinHz
i0=cubeheader['crpix4']#referencepixel
freqspec=((numpy.arange(nspec)i0)*df+f0)
valspec=imval(imagename=imgname,box='128,128')#e.g.extractspec@pixel128,128
outspec='spec.txt'#specifynameofoutputspectrumfile
spectrum=numpy.vstack((freqspec,valspec['data']))
numpy.savetxt(outspec,numpy.transpose(spectrum))#savethespectruminasciifile

Youcansimplycopy/pastetheselinesinyourscript,andadaptthepartsinred
Notetheuseofimhead,imvalwithPythondictionaries

23

Continuumsubtraction
inuvplane:
CASA>

uvcontsub
uvcontsub(

vis=ngc5921.ms,
field=N5921,
spw=0,
fitspw=0:0~10;50~60
solint=int,
fitorder=0)

#line&cont.ms

#channels010and5060usedforcontinuum
#leaveitatthedefault(seehelpfordetails)
#meanonly

ThiswillcreateanewMS:ngc5921.ms.contsub,tobedeconvolvedtoobtainthecontinuumsubtractedcube
ThemainMS(line&cont.ms)canbecleanedwithmode='mfs'andspw=fitspwtocreateacontinuumimage

inimageplane:
CASA>

imcontsub
default(imcontsub)
imagename=ngc5921.image #Inputimage(notalreadycontinuumsubtracted)
linefile=ngc5921.lineimage
#Outputlineimage
contfile=ngc5921.contimage #Outputcontinuumimage
fitorder=1
#Polynomialorderforcontinuumestimation
chans=0~10,50~60
#Linefreechannels
imcontsub()
#Go!

24

MomentsImages
Sometimes,informationisdifficulttoextractfromadatacube.
Easierviewwhencollapsinga3DcubeI(x,y,v)intoa2DmomentimageM(x,y)
Examples:
Integratedintensitymap(moment0) Mom0(i,j)=kI(i,j,k)

Velocityfield(moment1): Mom1(i,j)=kv(k)I(i,j,k)/Mom0(i,j)
Velocitydispersion(moment2):

Mom1(i,j)=k[v(k)Mom1(i,j)]2/Mom0(i,j)

25

Momentsmapsarecalculatedwiththetaskimmoments
CASA>immoments(

imagename='my.image',
moments=[1,2],
#willcalculatethe1stand2ndmoments
chans='15~34',
#channelrange
box='38,38,90,90',
axis='spectral',
includepix=[0.045,10000],#threshold
outfile='moments.mom')

Generaladvices:
Togetanunbiasedmom0image,bettersetnothreshold
Togetameaningfulmom1(orhigher)image,thresholdatfewtimesthenoiselevel
Setanappropriatechannelrange(chans),toavoidaddingunwantednoise
moments=1meanvalueofthespectrum
moments=0integratedvalueofthespectrum
moments=1intensityweightedcoordinate;traditionallyusedtogetvelocityfields
moments=2intensityweighteddispersionofthecoordinate;traditionallyusedtogetvelocitydispersion
moments=3medianofI
moments=4mediancoordinate
moments=5standarddeviationaboutthemeanofthespectrum
moments=6rootmeansquareofthespectrum
moments=7absolutemeandeviationofthespectrum
moments=8maximumvalueofthespectrum
moments=9coordinateofthemaximumvalueofthespectrum
moments=10minimumvalueofthespectrum

moments=11coordinateoftheminimumvalueofthespectrum

26

SpectralLinesSearch
1)UseSPLATALOGhttp://www.cv.nrao.edu/php/splat/
tocreateaspectrallinecatalogwithyourlines/speciesofinterest
orcreateyourowncatalogbyyourself
>seeCASAhelpforcorrectsyntax
2)ImportthiscatalogintoaCASATable:
CASA> mysltable=splattotable("mysplatlist.txt","mynewsl.tbl",true)
3)Querythecatalogwithdesiredfilters,e.g.(seehelpformore):
CASA>slsearch(

tablename='mynewsl.tbl',
freqrange=[100,300],
species='H2CO,CH3NH2'
el=[0,100],
logfile='extractedlist.out')

#inputSLtable
#FrequencyrangeinGHz
#Selectspecies
#ElowrangeinK
#Listresults

(ThedefaultcatalogdistributedwithCASAmightbeverylimitedforyourusage)
Exampleofoutputinthelogfile:
SPECIESRECOMMENDEDCHEMICAL_NAMEFREQUENCYQUANTUM_NUMBERSINTENSITYSMU2LOGAELEULINELIST
H2CO*
Formaldehyde72.837950 1(0,1)0(0,0) 4.178905.43720 5.08874 0.000003.49565 CDMS

H2CO*
Formaldehyde145.602950 2(0,2)1(0,1) 3.2839010.872544.10719 3.4956310.48343 CDMS

27

SpectralLineFitting
specfittoperformspectrallinefitsindatacubes
dataaveragedacrossaregion(multifit=False)oronpixelbypixelbasis(multifit=True)
fitaGaussian(poly=1,default)orpolynomials(e.g.poly=6)
canfitmultiGaussian(e.g.ngauss=3)butwillneedtoinputaguessfile(estimates='guess.txt')
Thefileshouldcontainforeachcomponent:
peakintensity,center,fwhm,optionalfixedparameterstring
#peakintensityinmapunit
#center,fwhminpixel
#fourthinputisanycombinationofpcf,indicatingwhichparameteristobekeptconstant

theresultofthefitcanbeaPythondictionary(asseeninslideaboutimstat):
fitresults=specfit(imagename='my.image',region='region.rgn')
Gaussianfitsresults(andtheirerrors)canbewritteninimages,namedfrominputparameters:
amp,amperr,center,centererr,fwhm,fwhmerr,integral,integralerr
modelandresidualimagescanalsobecreated(specifytheirnamesasinput)

28

ToolKit
For(very?)advancedusers,imageanalysistools:

CASA>:ia.#thenpressTABtogetacompactlist
Displayall110possibilities?(yorn)
ia.__class__ ia.collapse
ia.__delattr__ ia.continuumsub

ia.__doc__ ia.convertflux
ia.__format__ ia.convolve
ia.__getattribute__ ia.convolve2d
ia.__hash__ ia.coordmeasures
ia.__init__ ia.coordsys
ia.__new__ ia.decompose
ia.__reduce__ ia.deconvolvecomponentlist
ia.__reduce_ex__ Ia.deconvolvefrombeam
ia.__repr__ ia.done
ia.__setattr__ ia.echo
ia.__sizeof__ ia.fft
ia.__str__ ia.findsources

ia.__subclasshook__ ia.fitcomponents
ia.adddegaxes ia.fitpolynomial
ia.addnoise ia.fitprofile
ia.boundingbox ia.fromarray
ia.brightnessunit ia.fromascii
ia.calc ia.fromfits
ia.calcmask ia.fromimage
ia.close ia.fromrecord

ia.fromshape ia.moments
ia.rotate
ia.getchunk ia.name
ia.sepconvolve
ia.getregion ia.newimage
ia.set
ia.getslice ia.newimagefromarray ia.setboxregion
ia.hanning ia.newimagefromfile ia.setbrightnessunit
ia.haslock ia.newimagefromfits ia.setcoordsys
ia.histograms ia.newimagefromimage ia.sethistory
ia.history ia.newimagefromshape ia.setmiscinfo
ia.imagecalc ia.open
ia.setrestoringbeam
ia.imageconcat ia.outputvariant
ia.shape
ia.insert ia.pbcor
ia.statistics
ia.isconform ia.pixelvalue
ia.subimage
ia.isopen ia.putchunk
ia.summary
ia.ispersistent ia.putregion
ia.toASCII
ia.lock ia.rebin
ia.tofits
ia.makearray ia.regrid
ia.topixel
ia.makecomplex ia.remove
ia.torecord
ia.maketestimageia.removefile
ia.toworld
ia.maskhandler ia.rename
ia.transpose
ia.maxfitia.reorder
ia.twopointcorrelation
ia.miscinfo ia.replacemaskedpixelsia.type
ia.modify ia.restoringbeam ia.unlock

29

HavefunwithyourALMAEarlyScienceCycle0data!
AndwithCASA:)

30

You might also like