Beispiel #1
0
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'
Beispiel #2
0
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'
Beispiel #3
0
    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])
Beispiel #4
0
    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)
Beispiel #5
0
    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)
Beispiel #6
0
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'
Beispiel #7
0
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'