casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
task_widebandpbcor.py
Go to the documentation of this file.
00001 ################################################
00002 # Task to do wideband PB-corrections on images produced by MS-MFS.
00003 #
00004 # v1.0: 2012.09.10, U.R.V.
00005 #
00006 ################################################
00007 import os
00008 import numpy as np
00009 import shutil
00010 from scipy import linalg
00011 from taskinit import *
00012 im,cb,ms,tb,fg,me,ia,po,sm,cl,cs,rg,sl,dc,vp,msmd,fi,fn=gentools()
00013 
00014 def widebandpbcor(vis='',
00015                   imagename='mfim',
00016                   nterms=2,
00017                   threshold='1mJy',
00018                   action='pbcor',
00019                   reffreq = '1.5GHz',
00020                   pbmin=0.001, 
00021                   field='',
00022                   spwlist=[0],
00023                   chanlist=[0],
00024                   weightlist=[1]):
00025    """
00026    Wide-Band PB-correction.  Specify a list of spwids and channel numbers at which
00027    to compute primary beams. Supply weights to use for each beam.  All three lists
00028    spwlist, chanlist, weightlist must be of the same length.  It is enough to
00029    make one PB per spw (middle channel). 
00030    """   
00031    casalog.origin('widebandpbcor')
00032 
00033    # Check nterms
00034    if nterms < 1:
00035        casalog.post('Please specify a valid number of Taylor-terms (>0)', 'SEVERE')
00036        return False
00037 
00038    # Check that all required input images exist on disk
00039    taylorlist=[]
00040    residuallist=[]
00041    for i in range(0,nterms):
00042         taylorlist.append(imagename+'.image.tt'+str(i));
00043         residuallist.append(imagename+'.residual.tt'+str(i));
00044         if(not os.path.exists(taylorlist[i])):
00045             casalog.post('Taylor-coeff Restored Image : ' + taylorlist[i] + ' not found.','SEVERE')
00046             return False
00047         if(not os.path.exists(residuallist[i])):
00048             casalog.post('Taylor-coeff Residual Image : ' + residuallist[i] + ' not found.','SEVERE')
00049             return False
00050 
00051    casalog.post('Using images ' + str(taylorlist) + ' and ' + str(residuallist), 'NORMAL')
00052 
00053    ## Read imsize, cellsize, reffreq, phasecenter from the input images.
00054    ia.open( taylorlist[0] )
00055    imsize = [ ia.shape()[0], ia.shape()[1] ]
00056    iminfo = ia.summary()
00057    ia.close()
00058    
00059    ## Get cell size
00060    cellx = str( abs (qa.convert( qa.quantity( iminfo['incr'][0] , iminfo['axisunits'][0] ) , 'arcsec' )['value'] ) ) + ' arcsec'
00061    celly = str( abs (qa.convert( qa.quantity( iminfo['incr'][1] , iminfo['axisunits'][1] ) , 'arcsec' )['value'] ) ) + ' arcsec'
00062 
00063    ## Get phasecenter
00064    pcra = qa.quantity( iminfo['refval'][0] , iminfo['axisunits'][0] )
00065    pcdec = qa.quantity( iminfo['refval'][1] , iminfo['axisunits'][1] )
00066    pcdir = me.direction('J2000', pcra, pcdec )
00067 
00068    phasecenter = 'J2000 ' + qa.formxxx(pcdir['m0'],'hms') + ' ' + qa.formxxx(pcdir['m1'],'dms')
00069 
00070    ## Get reffreq, if not specified.
00071    if len(reffreq)==0:
00072        rfreq = qa.convert( qa.quantity( iminfo['refval'][3] , iminfo['axisunits'][3] ) , 'GHz' )
00073        reffreq = str( rfreq['value'] ) + rfreq['unit']
00074 
00075    casalog.post('Using imsize : ' + str(imsize) + ' and cellsize : ' + str(cellx) + ', ' + str(celly) + ' with phasecenter : ' + phasecenter + ' and reffreq : ' + reffreq, 'NORMAL')
00076 
00077    if type(threshold) != str:
00078        casalog.post('Please specify imthreshold as a string with units','SEVERE')
00079        return False
00080    imthreshold = qa.convert( qa.quantity(threshold) , 'Jy' )['value']
00081 
00082 
00083    ret = False
00084    if action=='pbcor':
00085 
00086        # Extract thresholds
00087        pbthreshold = pbmin
00088 
00089        casalog.post('Using a pblimit of ' + str(pbthreshold))
00090 
00091        if len(chanlist) < nterms or len(spwlist) < nterms or len(weightlist) < nterms:
00092            casalog.post('Please specify channel/spw/weight lists of lengths >= nterms', 'SEVERE')
00093            return False
00094 
00095        # Make a list of PBs from all the specifield spw/chan pairs.
00096        if len(chanlist) != len(spwlist) :
00097            casalog.post("Spwlist and Chanlist must be the same length", 'SEVERE')
00098            return False
00099        if len(spwlist) != len(weightlist) :
00100            casalog.post("Spwlist and Weightlist must be the same length", 'SEVERE')
00101            return False
00102 
00103        casalog.post('Calculating PBs for spws : ' + str(spwlist) + '  weightlist : ' + str(weightlist) + '  chanlist : ' + str(chanlist) , 'NORMAL');
00104 
00105        pbdirname = imagename + '.pbcor.workdirectory'
00106        if not os.path.exists(pbdirname):
00107            os.system('mkdir '+pbdirname)
00108 
00109        pblist = _makePBList(msname=vis, pbprefix=pbdirname + '/' + imagename+'.pb.', field=field, spwlist=spwlist, chanlist=chanlist, imsize=imsize, cellx=cellx, celly=celly, phasecenter=phasecenter)
00110        if len(pblist)==0:
00111            return False
00112 
00113        pbcubename = pbdirname + '/' + imagename+'.pb.cube'
00114 
00115        casalog.post('Concatenating PBs at all specified frequencies into a cube','NORMAL')
00116        newia = ia.imageconcat(outfile=pbcubename,infiles=pblist,relax=True,overwrite=True)
00117        newia.close()
00118 
00119        # Delete individual pb images
00120        for pbim in pblist:
00121            shutil.rmtree(pbim)
00122 
00123        # Make lists of image names
00124        pblist=[]
00125        imlist=[]
00126        imlistpbcor=[]
00127        for i in range(0,nterms):
00128            imlist.append(imagename+'.image.tt'+str(i))
00129            pblist.append(pbdirname+'/'+imagename+'.pb.tt'+str(i));
00130            imlistpbcor.append(imagename+'.pbcor.image.tt'+str(i));
00131            
00132        # Calculate Taylor Coeffs from this cube
00133        ret = _calcTaylorFromCube(imtemplate=imagename+'.image.tt0',reffreq=reffreq,cubename=pbcubename,newtay=pblist, pbthreshold=pbthreshold, weightlist=weightlist);
00134        if ret==False:
00135            return False
00136 
00137        # Calculate PB alpha and beta ( just for information )
00138        pbalphaname = pbdirname+'/'+imagename+'.pb.alpha'
00139        _calcPBAlpha(pbtay=pblist, pbthreshold=pbthreshold,pbalphaname=pbalphaname)
00140 
00141        # Divide out the PB polynomial
00142        ret = _dividePBTaylor(imlist,pblist,imlistpbcor,pbthreshold);
00143        if ret==False:
00144            return False
00145 
00146    # Recalculate Alpha.
00147    if(ret==True or action=='calcalpha'):
00148        if nterms==1:
00149            casalog.post('Cannot compute spectral index with only one image', 'WARN')
00150            return True
00151        if ret==True:
00152            imname = imagename+'.pbcor'
00153        else:
00154            imname = imagename
00155        residuallist=[];
00156        imagelist=[];
00157        for ii in range(0,nterms):
00158            residuallist.append(imagename+'.residual.tt'+str(ii));
00159            imagelist.append(imname+'.image.tt'+str(ii));
00160        _compute_alpha_beta(imname, nterms, imagelist, residuallist, imthreshold, [], True);
00161 
00162 
00163 
00164 ###############################################
00165 
00166 def _calcPBAlpha(pbtay=[], pbthreshold=0.1,pbalphaname='pbalpha.im'):
00167     nterms = len(pbtay)
00168     if nterms<2:
00169         return False
00170     
00171     if(os.path.exists(pbalphaname)):
00172        rmcmd = 'rm -rf ' + pbalphaname
00173        os.system(rmcmd)
00174     if(not os.path.exists(pbalphaname)):
00175        cpcmd = 'cp -r ' + pbtay[0] + ' ' + pbalphaname
00176        os.system(cpcmd)
00177 
00178     ia.open(pbalphaname)
00179     alpha = ia.getchunk()
00180     ia.close()
00181 
00182     ptay=[]
00183     ia.open(pbtay[0])
00184     ptay.append(ia.getchunk())
00185     ia.close()
00186     ia.open(pbtay[1])
00187     ptay.append(ia.getchunk())
00188     ia.close()
00189 
00190     ptay[0][ ptay[0] < pbthreshold  ] = 1.0
00191     ptay[1][ ptay[0] < pbthreshold  ] = 0.0
00192 
00193     alpha = ptay[1]/ptay[0]
00194 
00195     ia.open(pbalphaname)
00196     ia.putchunk(alpha)
00197     ia.calcmask(mask='"'+pbtay[0]+'"'+'>'+str(pbthreshold));
00198     ia.close()
00199 
00200 
00201 #################################################
00202 def _makePBList(msname='',pbprefix='',field='',spwlist=[],chanlist=[], imsize=[], cellx='10.0arcsec', celly='10.0arcsec',phasecenter=''):
00203    #print 'Making PB List from the following spw,chan pairs';
00204    pblist = []
00205    try:
00206      for aspw in range(0,len(spwlist)):
00207          #print 'spw=', spwlist[aspw], ' chan=',chanlist[aspw]
00208          im.open(msname);
00209          sspw = str(spwlist[aspw])+':'+str(chanlist[aspw])
00210          ret = im.selectvis(field=field, spw=sspw);
00211          if(ret==False):
00212              casalog.post('Error in constructing PBs at the specified spw:chan of '+ sspw ,'SEVERE')
00213              return []
00214          im.defineimage(nx=imsize[0],ny=imsize[1], cellx=cellx,celly=celly, 
00215                              nchan=1,start=chanlist[aspw], stokes='I',
00216                              mode='channel',spw=[spwlist[aspw]],phasecenter=phasecenter);
00217          im.setvp(dovp=True,usedefaultvp=True,telescope='EVLA');
00218          pbname = pbprefix + str(spwlist[aspw])+'.'+str(chanlist[aspw])
00219          im.makeimage(type='pb', image=pbname, compleximage="", verbose=False);
00220          pblist.append(pbname)
00221          im.close();
00222    except:
00223        casalog.post('Error in constructing PBs at the specified frequencies. Please check spwlist/chanlist','SEVERE')
00224        return []
00225    return pblist
00226     
00227 
00228 ##############################################################################
00229 def _calcTaylorFromCube(imtemplate="",reffreq='1.42GHz',cubename="sim.pb",newtay=[],pbthreshold=0.0001,weightlist=[]):
00230    for tay in range(0,len(newtay)):
00231      if(os.path.exists(newtay[tay])):
00232        rmcmd = 'rm -rf '+newtay[tay]
00233        os.system(rmcmd)
00234      if(not os.path.exists(newtay[tay])):
00235        cpcmd = 'cp -r ' + imtemplate + ' ' + newtay[tay]
00236        os.system(cpcmd)
00237 
00238    ia.open(cubename);
00239    pbcube = ia.getchunk();
00240    csys = ia.coordsys();
00241    shp = ia.shape();
00242    ia.close();
00243 
00244    if(csys.axiscoordinatetypes()[3] == 'Spectral'):
00245        restfreq = csys.restfrequency()['value'][0]/1e+09; # convert more generally..
00246        freqincrement = csys.increment()['numeric'][3]/1e+09;
00247        freqlist = [];
00248        for chan in range(0,shp[3]): 
00249              freqlist.append(restfreq + chan * freqincrement);
00250    elif(csys.axiscoordinatetypes()[3] == 'Tabular'):
00251        freqlist = (csys.torecord()['tabular2']['worldvalues'])/1e+09;
00252    else:
00253        casalog.post('Unknown frequency axis. Exiting.','SEVERE');
00254        return False;
00255 
00256    reffreqGHz = qa.convert(qa.quantity(reffreq), 'GHz')['value']
00257    freqs = (np.array(freqlist,'f')-reffreqGHz)/reffreqGHz;
00258 
00259    casalog.post("Using PBs at " + str(freqlist) + " GHz, to compute Taylor coefficients about " + str(reffreqGHz) + " GHz", 'NORMAL')
00260    #print freqs;
00261 
00262    nfreqs = len(freqlist)
00263    if len(weightlist)==0:
00264      weightarr = np.ones( freqs.shape )
00265    else:
00266      if len(weightlist) != nfreqs:
00267        casalog.post('Weight list must be the same length as nFreq : ' + nfreqs , 'SEVERE')
00268        return False
00269      else:
00270        weightarr = np.array(weightlist)
00271 
00272    nterms = len(newtay);
00273    if(nterms>5):
00274      casalog.post('Cannot handle more than 5 terms for PB computation','SEVERE')
00275      return False;
00276    ptays=[];
00277    if(nterms>0):
00278      ia.open(newtay[0]);
00279      ptays.append( ia.getchunk() );
00280      ptays[0].fill(0.0);
00281      ia.close();
00282      pstart=[0.0];
00283    if(nterms>1):
00284      ia.open(newtay[1]);
00285      ptays.append( ia.getchunk() );
00286      ptays[1].fill(0.0);
00287      ia.close();
00288      pstart=[0.0,0.0];
00289    if(nterms>2):
00290      ia.open(newtay[2]);
00291      ptays.append( ia.getchunk() );
00292      ptays[2].fill(0.0);
00293      ia.close();
00294      pstart=[0.0,0.0,0.0];
00295    if(nterms>3):
00296      ia.open(newtay[3]);
00297      ptays.append( ia.getchunk() );
00298      ptays[3].fill(0.0);
00299      ia.close();
00300      pstart=[0.0,0.0,0.0,0.0];
00301    if(nterms>4):
00302      ia.open(newtay[4]);
00303      ptays.append( ia.getchunk() );
00304      ptays[4].fill(0.0);
00305      ia.close();
00306      pstart=[0.0,0.0,0.0,0.0,0.0];
00307    
00308    ##### Fit a nterms-term polynomial to each point !!!
00309   
00310    # Linear fit
00311    ptays=_linfit(ptays, freqs, pbcube[:,:,0,:], weightarr);
00312 
00313    # Set all values below the pbthreshold, to zero
00314    for tt in range(0,nterms):
00315        ptays[tt][ ptays[0]<pbthreshold  ] = 0.0
00316 
00317    # Write to disk.
00318    if(nterms>0):
00319      ia.open(newtay[0]);
00320      ia.putchunk(ptays[0]);
00321      ia.close();
00322    if(nterms>1):
00323      ia.open(newtay[1]);
00324      ia.putchunk(ptays[1]);
00325      ia.close();
00326    if(nterms>2):
00327      ia.open(newtay[2]);
00328      ia.putchunk(ptays[2]);
00329      ia.close();
00330    if(nterms>3):
00331      ia.open(newtay[3]);
00332      ia.putchunk(ptays[3]);
00333      ia.close();
00334    if(nterms>4):
00335      ia.open(newtay[4]);
00336      ia.putchunk(ptays[4]);
00337      ia.close();
00338 
00339  ####################################################
00340 def _linfit(ptays, freqs, pcube, wts):
00341   #print 'Calculating PB Taylor Coefficients by applying Inv Hessian to Taylor-weighted sums'
00342   nterms=len(ptays);
00343   hess = np.zeros( (nterms,nterms) );
00344   rhs = np.zeros( (nterms,1) );
00345   soln = np.zeros( (nterms,1) );
00346   shp = ptays[0].shape;
00347   if(len(freqs) != pcube.shape[2]):
00348       casalog.post('Mismatch in frequency axes : '+ len(freqs)+ ' and ' + pcube.shape[2] , 'SEVERE');
00349       return ptays;
00350   if(len(freqs) != len(wts)):
00351       casalog.post('Mismatch in lengths of freqs : '+ len(freqs)+ ' and wts : '+ len(wts) , 'SEVERE');
00352       return ptays;
00353   
00354   for ii in range(0,nterms):
00355     for jj in range(0,nterms):
00356        hess[ii,jj]= np.mean( freqs**(ii+jj) * wts);
00357 
00358   normval = hess[0,0]
00359   hess = hess/normval;
00360 
00361   invhess = linalg.inv(hess);
00362   casalog.post('Hessian : ' + str(hess) , 'NORMAL')
00363   casalog.post('Inv Hess : ' + str(invhess), 'NORMAL')
00364 
00365   casalog.post('Calculating Taylor-coefficients for the PB spectrum', 'NORMAL')
00366   
00367   for x in range(0,shp[0]):
00368     for y in range(0,shp[1]):
00369       for ii in range(0,nterms):
00370           rhs[ii,0]=np.mean( (freqs**(ii)) * pcube[x,y,:] * wts)/normval;
00371       soln = np.dot(invhess,rhs);
00372       for ii in range(0,nterms):
00373           ptays[ii][x,y]=soln[ii,0];
00374     if(x%100 == 0):
00375       casalog.post('--- finished rows '+str(x)+ ' to '+ str(x+99), 'NORMAL');
00376 ##      casalog.post('--- finished rows '+str(x)+ ' to '+ str(np.min(x+99,shp[0])), 'NORMAL');
00377 
00378   return ptays;  
00379 
00380 #############
00381 
00382 #############
00383 def _dividePB(nterms,pbcoeffs,targetpbs):
00384    if(len(pbcoeffs) != nterms or len(targetpbs) != nterms):
00385         casalog.post("To divide out the PB spectrum, PB coeffs and target images must have same nterms", 'SEVERE')
00386         return [];
00387    correctedpbs=[];
00388 
00389    if(nterms==1):
00390        det = pbcoeffs[0]
00391        det[abs(det)==0.0]=1.0;
00392        correctedpbs.append( targetpbs[0] / det);
00393 
00394    if(nterms==2):
00395        det = pbcoeffs[0]**2;
00396        det[abs(det)==0.0]=1.0;
00397        correctedpbs.append( pbcoeffs[0] * targetpbs[0] / det);
00398        correctedpbs.append( (-1*pbcoeffs[1]*targetpbs[0] + pbcoeffs[0] * targetpbs[1])/det );
00399        
00400    if(nterms==3):
00401        det = pbcoeffs[0]**3;
00402        det[abs(det)==0.0]=1.0;
00403        correctedpbs.append( (pbcoeffs[0]**2) * targetpbs[0] / det);
00404        correctedpbs.append( ( -1*pbcoeffs[0]*pbcoeffs[1]*targetpbs[0] + (pbcoeffs[0]**2)*targetpbs[1]   )/det );
00405        correctedpbs.append( ( (pbcoeffs[1]**2 - pbcoeffs[0]*pbcoeffs[2])*targetpbs[0] + (-1*pbcoeffs[0]*pbcoeffs[1])*targetpbs[1] + (pbcoeffs[0]**2)*targetpbs[2]   )/det);
00406 
00407    return correctedpbs;
00408 
00409 #####
00410 ##############################################################################
00411 def _dividePBTaylor(imlist=[],pblist=[],imlistpbcor=[],pbthreshold=0.1):
00412    casalog.post("Dividing the Image polynomial by the PB polynomial",'NORMAL')
00413 
00414    if len(imlist) != len(pblist):
00415        casalog.post("Image list and PB list must be of the same length",'SEVERE')
00416        return False
00417    if len(imlist) != len(imlistpbcor):
00418        casalog.post("Image list and imlistpbcor must be of the same length",'SEVERE')
00419        return False
00420 
00421    nterms = len(imlist)
00422 
00423    # Read PB coefficient images   
00424    pbcoeffs=[]
00425    for tay in range(0,nterms):
00426       if(not os.path.exists(pblist[tay])):
00427            casalog.post("PB Coeff " + pblist[tay] + " does not exist ", 'SEVERE');
00428            return False;
00429       ia.open(pblist[tay]);
00430       pbcoeffs.append(ia.getchunk());
00431       ia.close();
00432 
00433    # Read Images to normalize   
00434    inpimages=[];   
00435    for tay in range(0,nterms):
00436       if(not os.path.exists(imlist[tay])):
00437            casalog.post("Image Coeff " + imlist[tay] + " does not exist ", 'SEVERE');
00438            return False;
00439       ia.open(imlist[tay]);
00440       inpimages.append(ia.getchunk());
00441       ia.close();
00442 
00443    # Divide the two polynomials.
00444    normedims = _dividePB(nterms,pbcoeffs,inpimages);
00445  
00446    if(len(normedims)==0):
00447       casalog.post("Could not divide the beam",'SEVERE');
00448       return False;    
00449 
00450    for tay in range(0,nterms):
00451       imtemp = imlist[0]
00452       normname =  imlistpbcor[tay]
00453       casalog.post("Writing PB-corrected images " + normname);
00454       if os.path.exists(normname):
00455           rmcmd = 'rm -rf '+normname
00456           os.system(rmcmd)
00457       cpcmd = 'cp -r '+imtemp + ' ' + normname;
00458       os.system(cpcmd);
00459       ia.open(normname);
00460       ia.putchunk(normedims[tay]);
00461       ia.calcmask(mask='"'+pblist[0]+'"'+'>'+str(pbthreshold));
00462       ia.close();
00463 
00464    return True;
00465 ###################################################
00466 
00467 ####################################################
00468 def  _compute_alpha_beta(imagename, nterms, taylorlist, residuallist, threshold, beamshape, calcerror):
00469    imtemplate = imagename+'.image.tt0';
00470    nameintensity = imagename+'.image.tt0';
00471    namealpha = imagename+'.image.alpha';
00472    nameerror = namealpha+'.error';
00473    namebeta = imagename+'.image.beta';
00474 
00475    #if(os.path.exists(nameintensity)):
00476    #      rmcmd = 'rm -rf ' + nameintensity;
00477    #      os.system(rmcmd);
00478    #print 'Creating new image : ', nameintensity   
00479    #cpcmd = 'cp -r ' + imtemplate + ' ' + nameintensity;
00480    #os.system(cpcmd);
00481 
00482    if(os.path.exists(namealpha)):
00483          rmcmd = 'rm -rf ' + namealpha;
00484          os.system(rmcmd);
00485    casalog.post( 'Creating new image : ' + namealpha, 'NORMAL')   
00486    cpcmd = 'cp -r ' + imtemplate + ' ' + namealpha;
00487    os.system(cpcmd);
00488 
00489    if(calcerror==True):
00490        if(os.path.exists(nameerror)):
00491              rmcmd = 'rm -rf ' + nameerror;
00492              os.system(rmcmd);
00493        casalog.post( 'Creating new image : ' + nameerror , 'NORMAL' )   
00494        cpcmd = 'cp -r ' + imtemplate + ' ' + nameerror;
00495        os.system(cpcmd);
00496 
00497    if(nterms>2):
00498      if(os.path.exists(namebeta)):
00499             rmcmd = 'rm -rf ' + namebeta;
00500             os.system(rmcmd);
00501      casalog.post( 'Creating new image : ' +  namebeta, 'NORMAL') 
00502      cpcmd = 'cp -r ' + imtemplate + ' ' + namebeta;
00503      os.system(cpcmd);
00504 
00505    ## Open and read the images to compute alpha/beta with
00506    ptay=[];
00507    for i in range(0,nterms):
00508        ia.open(taylorlist[i]);
00509        ptay.append(ia.getchunk());
00510        ia.close();
00511 
00512    ## If calc error, open residual images too
00513    if(calcerror==True):
00514        pres=[];
00515        for i in range(0,nterms):
00516           ia.open(residuallist[i]);
00517           pres.append(ia.getchunk());
00518           ia.close();
00519 
00520    ## Initialize arrays of empty images
00521    #ia.open(nameintensity);
00522    #intensity = ia.getchunk();
00523    #intensity.fill(0.0);
00524    #ia.close();
00525    ia.open(namealpha);
00526    alpha = ia.getchunk();
00527    alpha.fill(0.0);
00528    ia.close();
00529    if(calcerror):
00530      ia.open(nameerror);
00531      aerror = ia.getchunk();
00532      aerror.fill(0.0);
00533      ia.close();
00534    if(nterms>2):
00535      ia.open(namebeta);
00536      beta = ia.getchunk();
00537      beta.fill(0.0);
00538      ia.close();
00539 
00540 
00541    ## Calc alpha,beta from ptay0,ptay1,ptay2
00542    #intensity = ptay[0];
00543    #ia.open(nameintensity);
00544    #ia.putchunk(intensity);
00545    #ia.close();
00546 
00547    ptay[0][ptay[0]<threshold]=1.0;
00548    ptay[1][ptay[0]<threshold]=0.0;
00549    if(nterms>2):
00550       ptay[2][ptay[0]<threshold]=0.0;
00551 
00552    alpha = ptay[1]/ptay[0];
00553 
00554    if(nterms>2):
00555       beta = (ptay[2]/ptay[0]) - 0.5*alpha*(alpha-1);
00556 
00557    ia.open(namealpha);
00558    ia.putchunk(alpha);
00559    ia.calcmask(mask='"'+nameintensity+'"'+'>'+str(threshold));
00560    ia.close();
00561    if(nterms>2):
00562      ia.open(namebeta);
00563      ia.putchunk(beta);
00564      ia.calcmask(mask='"'+nameintensity+'"'+'>'+str(threshold));
00565      ia.close();
00566 
00567    # calc error
00568    if(calcerror):
00569       aerror =  np.abs(alpha) * np.sqrt( (pres[0]/ptay[0])**2 + (pres[1]/ptay[1])**2 );
00570       ia.open(nameerror);
00571       ia.putchunk(aerror);
00572       ia.calcmask(mask='"'+nameintensity+'"'+'>'+str(threshold));
00573       ia.close();
00574 
00575 
00576    # Set the new restoring beam, if beamshape was used
00577    if(beamshape != []):
00578       if(  _set_clean_beam(nameintensity,beamshape) == False ):
00579            return False;
00580       if(  _set_clean_beam(namealpha,beamshape) == False):
00581            return False;
00582       if(nterms>2):
00583            if( _set_clean_beam(namebeta,beamshape) == False):
00584                 return False;
00585       if(calcerror==True):
00586            if( _set_clean_beam(nameerror,beamshape) == False):
00587                 return False;
00588 
00589 ####################################################
00590 # Set the restoring beam to the new one.
00591 def _set_clean_beam(imname,beamshape):
00592       ia.open(imname);
00593       try:
00594           ia.setrestoringbeam(major=beamshape[0],minor=beamshape[1],pa=beamshape[2]);
00595       except Exception, e:
00596           casalog.post( "Error setting restoring beam : " + e , 'WARN');
00597           ia.close();
00598           return False;
00599       ia.close();
00600       return True;
00601 
00602 ####################################################