Exemplo n.º 1
0
def imsubimage(
    imagename, outfile, box, region, chans, stokes, mask, dropdeg,
    overwrite, verbose, stretch, keepaxes
):
    casalog.origin('imsubimage')
    myia = iatool()
    myia.dohistory(False)
    outia = None
    try:
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        if (len(outfile) == 0):
            raise Exception, "outfile must be specified."
        xregion = region
        if (type(region) != type({})):
            xregion = _rg.frombcs(
                csys=myia.coordsys().torecord(), shape=myia.shape(), box=box,
                chans=chans, stokes=stokes, stokescontrol="a", region=region
            )
        outia = myia.subimage(
            outfile=outfile, region=xregion, mask=mask, dropdeg=dropdeg,
            overwrite=overwrite, list=verbose, stretch=stretch, keepaxes=keepaxes
        )
        try:
            param_names = imsubimage.func_code.co_varnames[:imsubimage.func_code.co_argcount]
            param_vals = [eval(p) for p in param_names]   
            write_image_history(
                outia, sys._getframe().f_code.co_name,
                param_names, param_vals, casalog
            )
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance), 'WARN')
        return True
Exemplo n.º 2
0
def imcollapse(imagename=None,
               function=None,
               axes=None,
               outfile=None,
               box=None,
               region=None,
               chans=None,
               stokes=None,
               mask=None,
               overwrite=None,
               stretch=None):
    casalog.origin('imcollapse')
    try:
        if (len(outfile) == 0):
            raise Exception, "oufile must be specified"
        myia = iatool()
        myia.dohistory(False)
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        outia = myia.collapse(function, axes, outfile, region, box, chans,
                              stokes, mask, overwrite, stretch)
        try:
            param_names = imcollapse.func_code.co_varnames[:imcollapse.
                                                           func_code.
                                                           co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        outia.done()
        return True
Exemplo n.º 3
0
def impbcor(
    imagename=None, pbimage=None, outfile=None, overwrite=None,
    box=None, region=None, chans=None, stokes=None, mask=None,
    mode=None, cutoff=None,  stretch=None
):
    casalog.origin('impbcor')
    myia = iatool()
    try:
        myia.dohistory(False)
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        if (len(outfile) == 0):
            raise Exception, "outfile must be specified"
        outia = myia.pbcor(
            pbimage=pbimage, outfile=outfile, overwrite=overwrite,
            box=box, region=region, chans=chans, stokes=stokes,
            mask=mask, mode=mode, cutoff=cutoff, stretch=stretch
        )
        try:
            param_names = impbcor.func_code.co_varnames[:impbcor.func_code.co_argcount]
            param_vals = [eval(p) for p in param_names]   
            write_image_history(
                outia, sys._getframe().f_code.co_name,
                param_names, param_vals, casalog
            )
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance), 'WARN')
        outia.done()
        return True
Exemplo n.º 4
0
def rmfit(
    imagename,
    rm,
    rmerr,
    pa0,
    pa0err,
    nturns,
    chisq,
    sigma,
    rmfg,
    rmmax,
    maxpaerr,
):
    casalog.origin('prom')
    myia = iatool()
    myia.dohistory(False)
    mypo = potool()
    tmpim = ""
    try:
        if len(imagename) == 0:
            raise Exception, "imagename must be specified."
        if type(imagename) == type(['s']):
            # negative axis value means concatenate along spectral axis
            tmpim = tempfile.mkdtemp(suffix=".im", prefix="_rmfit_concat")
            myia = myia.imageconcat(outfile=tmpim,
                                    infiles=imagename,
                                    relax=True,
                                    axis=-1,
                                    overwrite=True)
            if not myia:
                raise Exception("Unable to concatenate images.")
            myia.done()
            mypo.open(tmpim)
        else:
            if (not mypo.open(imagename)):
                raise Exception, "Cannot create image analysis tool using " + imagename
        mypo.rotationmeasure(rm=rm,
                             rmerr=rmerr,
                             pa0=pa0,
                             pa0err=pa0err,
                             nturns=nturns,
                             chisq=chisq,
                             sigma=sigma,
                             rmfg=rmfg,
                             rmmax=rmmax,
                             maxpaerr=maxpaerr)
        try:
            param_names = rmfit.func_code.co_varnames[:rmfit.func_code.
                                                      co_argcount]
            param_vals = [eval(p) for p in param_names]
            for im in [rm, rmerr, pa0, pa0err, nturns, chisq]:
                write_image_history(im,
                                    sys._getframe().f_code.co_name,
                                    param_names, param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')

        return True
Exemplo n.º 5
0
def imrebin(imagename, outfile, factor, region, box, chans, stokes, mask,
            dropdeg, overwrite, stretch, crop):
    casalog.origin('imrebin')
    valid = True
    # because there is a bug in the tasking layer that allows float
    # arrays through when the spec is for intArray
    for x in factor:
        if x != int(x):
            valid = False
            break
    if not valid:
        for i in range(len(factor)):
            factor[i] = int(factor[i])
        casalog.post(
            "factor is not an int array, it will be adjusted to " +
            str(factor), 'WARN')
    myia = iatool()
    myia.dohistory(False)
    outia = None
    try:
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        if (len(outfile) == 0):
            raise Exception, "outfile must be specified."
        if (type(region) != type({})):
            myrg = rgtool()
            reg = myrg.frombcs(csys=myia.coordsys().torecord(),
                               shape=myia.shape(),
                               box=box,
                               chans=chans,
                               stokes=stokes,
                               stokescontrol="a",
                               region=region)
        else:
            reg = region
        outia = myia.rebin(outfile=outfile,
                           bin=factor,
                           region=reg,
                           mask=mask,
                           dropdeg=dropdeg,
                           overwrite=overwrite,
                           stretch=stretch,
                           crop=crop)
        try:
            param_names = imrebin.func_code.co_varnames[:imrebin.func_code.
                                                        co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 6
0
def immoments(imagename, moments, axis, region, box, chans, stokes, mask,
              includepix, excludepix, outfile, stretch):
    retValue = None
    casalog.origin('immoments')
    _myia = iatool()
    try:
        _myia.dohistory(False)
        # First check to see if the output file exists.  If it
        # does then we abort.  CASA doesn't allow files to be
        # over-written, just a policy.
        if (len(outfile) > 0 and os.path.exists(outfile)):
            raise Exception, 'Output file, '+outfile+\
              ' exists. immoment can not proceed, please\n'\
              'remove it or change the output file name.'
        elif (len(outfile) == 1):
            raise Exception, 'outfile is not specified but must be'
        _myia.open(imagename)
        reg = _rg.frombcs(csys=_myia.coordsys().torecord(),
                          shape=_myia.shape(),
                          box=box,
                          chans=chans,
                          stokes=stokes,
                          stokescontrol="a",
                          region=region)
        if isinstance(axis, str):
            axis = _myia.coordsys().findaxisbyname(axis)
        outia = _myia.moments(moments=moments,
                              axis=int(axis),
                              mask=mask,
                              region=reg,
                              includepix=includepix,
                              excludepix=excludepix,
                              outfile=outfile,
                              drop=False,
                              stretch=stretch)
        created_images = _immoments_get_created_images(outia.name(), outfile)
        created_images.append(outia)
        try:
            param_names = immoments.func_code.co_varnames[:immoments.func_code.
                                                          co_argcount]
            param_vals = [eval(p) for p in param_names]
            method = sys._getframe().f_code.co_name
            for im in created_images:
                write_image_history(im, method, param_names, param_vals,
                                    casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 7
0
def impv(
    imagename, outfile, mode, start, end, center, length, pa, width,
    unit, overwrite, region, chans, stokes, mask, stretch
):
    casalog.origin('impv')
    try:
        if len(outfile) == 0:
            raise Exception, "outfile must be specified."
        mymode = mode.lower()
        if mymode.startswith('c'):
            if len(start) == 0 or len(end) == 0:
                raise Exception, "When mode='coords', start and end must both be specified."
            center = ""
            length = ""
            pa = ""
        elif mymode.startswith('l'):
            if (
                len(center) == 0 
                or (
                    not isinstance(length, (int, long, float))
                    and len(length) == 0
                )
                or len(pa) == 0
            ):
                raise Exception, "When mode='length', center, length, and pa must all be specified."
            start = ""
            end = ""
        else:
            raise Exception, "Unsupported value for mode."
        myia = iatool()
        myia.dohistory(False)
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        outia = myia.pv(
            outfile=outfile, start=start, end=end, center=center,
            length=length, pa=pa, width=width, unit=unit,
            overwrite=overwrite, region=region, chans=chans,
            stokes=stokes, mask=mask, stretch=stretch, wantreturn=True
        )
        try:
            param_names = impv.func_code.co_varnames[:impv.func_code.co_argcount]
            param_vals = [eval(p) for p in param_names]   
            write_image_history(
                outia, sys._getframe().f_code.co_name,
                param_names, param_vals, casalog
            )
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance), 'WARN')
        return True
Exemplo n.º 8
0
def imfit(imagename, box, region, chans, stokes, mask, includepix, excludepix,
          residual, model, estimates, logfile, append, newestimates, complist,
          overwrite, dooff, offset, fixoffset, stretch, rms, noisefwhm,
          summary):
    casalog.origin('imfit')
    myia = iatool()
    try:
        myia.dohistory(False)
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        result_dict = myia.fitcomponents(box=box,
                                         region=region,
                                         chans=chans,
                                         stokes=stokes,
                                         mask=mask,
                                         includepix=includepix,
                                         excludepix=excludepix,
                                         residual=residual,
                                         model=model,
                                         estimates=estimates,
                                         logfile=logfile,
                                         append=append,
                                         newestimates=newestimates,
                                         complist=complist,
                                         overwrite=overwrite,
                                         dooff=dooff,
                                         offset=offset,
                                         fixoffset=fixoffset,
                                         stretch=stretch,
                                         rms=rms,
                                         noisefwhm=noisefwhm,
                                         summary=summary)
        try:
            param_names = imfit.func_code.co_varnames[:imfit.func_code.
                                                      co_argcount]
            param_vals = [eval(p) for p in param_names]
            for im in [residual, model]:
                write_image_history(im,
                                    sys._getframe().f_code.co_name,
                                    param_names, param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return result_dict
Exemplo n.º 9
0
def imdev(imagename, outfile, region, box, chans, stokes, mask, overwrite,
          stretch, grid, anchor, xlength, ylength, interp, stattype, statalg,
          zscore, maxiter):
    _myia = iatool()
    _myrg = rgtool()
    _mycs = cstool()
    try:
        casalog.origin('imdev')
        _myia.open(imagename)
        _mycs = _myia.coordsys()
        csrec = _mycs.torecord()
        shape = _myia.shape()
        reg = _myrg.frombcs(csrec, shape, box, chans, stokes, "a", region)
        outia = _myia.deviation(outfile=outfile,
                                region=reg,
                                mask=mask,
                                overwrite=overwrite,
                                stretch=stretch,
                                grid=grid,
                                anchor=anchor,
                                xlength=xlength,
                                ylength=ylength,
                                interp=interp,
                                stattype=stattype,
                                statalg=statalg,
                                zscore=zscore,
                                maxiter=maxiter)
        try:
            param_names = imdev.func_code.co_varnames[:imdev.func_code.
                                                      co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        outia.done()
        return True
Exemplo n.º 10
0
def imtrans(imagename, outfile, order):
    casalog.origin('imtrans')
    myia = iatool()
    myia.dohistory(False)
    outia = None
    try:
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        if (len(outfile) == 0):
            raise Exception, "outfile parameter must be specified."
        outia = myia.transpose(outfile=outfile, order=order)
        try:
            param_names = imtrans.func_code.co_varnames[:imtrans.func_code.
                                                        co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 11
0
def immath(imagename, mode, outfile, expr, varnames, sigma, polithresh, mask,
           region, box, chans, stokes, stretch, imagemd):
    # Tell CASA who will be reporting
    casalog.origin('immath')
    tmpFilePrefix = '_immath_tmp' + str(os.getpid()) + '_'
    _myia = iatool()
    _myia.dohistory(False)
    outia = iatool()
    try:
        _immath_initial_cleanup(tmpFilePrefix)
        outfile = _immath_check_outfile(outfile)
        # Find the list of filenames in the expression
        # also do a quick check to see if all of the files
        # exist
        tmpfilenames = ''
        filenames = imagename
        if mode == 'evalexpr':
            tmpfilenames = _immath_parse(expr)
        if isinstance(filenames, str):
            filenames = [filenames]
        varnames = _immath_varnames(varnames, filenames, tmpfilenames)
        filenames = _immath_filenames(filenames, tmpfilenames, varnames, mode)
        expr = expr.replace(' ', '')
        if mode == 'spix':
            expr = _immath_dospix(len(filenames), varnames)
        elif mode == 'pola':
            _immath_new_pola(filenames, outfile, tmpFilePrefix, mask, region,
                             box, chans, stokes, stretch, polithresh, _myia)
            return True
        elif mode == 'poli':
            _immath_new_poli(filenames, outfile, tmpFilePrefix, mask, region,
                             box, chans, stokes, stretch, sigma, _myia)
            return True
        if box or chans or stokes or region or mask:
            (subImages,
             file_map) = _immath_createsubimages(box, chans, stokes, region,
                                                 mask, stretch, filenames,
                                                 _myia, tmpFilePrefix)
            if imagemd:
                casalog.post(
                    "Specifying region, box, chan, or stokes will " +
                    "create smaller sub-images. The image " +
                    "metadata specified in imagemd will have to " +
                    "conform to the output, not the input image " +
                    "dimensions. Please check your output image " +
                    "for accurate header definition.", 'WARN')
            (expr, varnames,
             subImages) = _immath_updateexpr(expr, varnames, subImages,
                                             filenames, file_map)
            outia = _immath_compute(imagename, expr, outfile, imagemd, _myia)
        else:
            # If the user didn't give any region or mask information
            # then just evaluated the expression with the filenames in it.
            outia = _immath_dofull(imagename, imagemd, outfile, mode, expr,
                                   varnames, filenames, _myia)
        try:
            param_names = immath.func_code.co_varnames[:immath.func_code.
                                                       co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 12
0
def imsmooth(imagename, kernel, major, minor, pa, targetres, kimage, scale,
             region, box, chans, stokes, mask, outfile, stretch, overwrite,
             beam):
    casalog.origin('imsmooth')
    ikernel = kernel.startswith('i')
    ckernel = kernel.startswith('c')
    bkernel = kernel.startswith('b')
    gkernel = kernel.startswith('g')
    if (not (gkernel or bkernel or ckernel or ikernel)):
        casalog.post('Unsupported kernel, ' + kernel, 'SEVERE')
        return False

    if (not ikernel and type(beam) == str):
        if len(beam) != 0:
            err = "beam cannot be a non-empty string"
            casalog.post(err, "SEVERE")
            raise Exception(err)
        beam = {}

    # First check to see if the output file exists.  If it
    # does then we abort.  CASA doesn't allow files to be
    # over-written, just a policy.
    if (len(outfile) < 1):
        outfile = 'imsmooth_results.im'
        casalog.post( "The outfile paramter is empty, consequently the" \
                      +" smoothed image will be\nsaved on disk in file, " \
                      + outfile, 'WARN')
    _myia = iatool()
    _myia.dohistory(False)
    retia = iatool()
    _myia.open(imagename)
    mycsys = _myia.coordsys()
    myrg = rgtool()
    reg = myrg.frombcs(mycsys.torecord(), _myia.shape(), box, chans, stokes,
                       "a", region)
    myrg.done()
    mycsys.done()
    _myia.done()
    # If the values given are integers we assume they are given in
    # arcsecs and alter appropriately
    if not ikernel:
        if isinstance(major, (int, long, float)):
            major = str(major) + 'arcsec'
        if isinstance(minor, (int, long, float)):
            minor = str(minor) + 'arcsec'
        if isinstance(pa, (int, long, float)):
            pa = str(pa) + 'deg'

    try:
        if (gkernel or ckernel):
            _myia.open(imagename)
            if ckernel:
                beam = _myia.commonbeam()
                # add a small epsilon to avoid convolving with a null beam to reach
                # a target resolution that already exists
                beam['major'] = qa.mul(beam['major'], 1 + 1e-10)
                beam['minor'] = qa.mul(beam['minor'], 1 + 1e-10)
                major = ""
                minor = ""
                pa = ""
                targetres = True
            if (beam and (major or minor or pa)):
                raise Exception, "You may specify only beam or the set of major/minor/pa"
            if not beam:
                if not major:
                    raise Exception, "Major axis must be specified"
                if not minor:
                    raise Exception, "Minor axis must be specified"
                if not pa:
                    raise Exception, "Position angle must be specified"

            outia = _myia.convolve2d(axes=[0, 1],
                                     region=reg,
                                     major=major,
                                     minor=minor,
                                     pa=pa,
                                     outfile=outfile,
                                     mask=mask,
                                     stretch=stretch,
                                     targetres=targetres,
                                     overwrite=overwrite,
                                     beam=beam)
        elif (bkernel):
            if not major or not minor:
                raise Exception, "Both major and minor must be specified."
            # BOXCAR KERNEL
            #
            # Until convolve2d supports boxcar we will need to
            # use sepconvolve to do this.
            #
            # BIG NOTE!!!!!
            # According to Gaussian2D documentation the default position
            # angle aligns the major axis along the y-axis, which typically
            # be lat.  So this means that we need to use the major quantity
            # on the y axis (or 1) for sepconvolve.

            _myia.open(imagename)
            casalog.post( "ia.sepconvolve( axes=[0,1],"+\
                          "types=['boxcar','boxcar' ],"+\
                          "widths=[ "+str(minor)+", "+str(major)+" ],"+ \
                          "region="+str(reg)+",outfile="+outfile+" )",\
                          'DEBUG2' )
            #retValue = ia.sepconvolve( axes=[0,1], types=['box','box' ],\
            #                           widths=[ minor, major ], \
            #                           region=reg,outfile=outfile )
            outia = _myia.sepconvolve(axes=[0, 1],
                                      types=['box', 'box'],
                                      widths=[minor, major],
                                      region=reg,
                                      outfile=outfile,
                                      mask=mask,
                                      stretch=stretch,
                                      overwrite=overwrite)
        elif ikernel:
            _myia.open(imagename)
            outia = _myia.convolve(outfile=outfile,
                                   kernel=kimage,
                                   scale=scale,
                                   region=reg,
                                   mask=mask,
                                   overwrite=overwrite,
                                   stretch=stretch)
        else:
            casalog.post('Unrecognized kernel type: ' + kernel, 'SEVERE')
            return False
        try:
            param_names = imsmooth.func_code.co_varnames[:imsmooth.func_code.
                                                         co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(outia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 13
0
def importfits(fitsimage, imagename, whichrep, whichhdu, zeroblanks, overwrite,
               defaultaxes, defaultaxesvalues, beam):
    """Convert an image FITS file into a CASA image:

	Keyword arguments:
	fitsimage -- Name of input image FITS file
		default: none; example='3C273XC1.fits'
	imagename -- Name of output CASA image
		default: none; example: imagename='3C273XC1.image'
	whichrep -- If fits image has multiple coordinate reps, choose one.
		default: 0 means first; example: whichrep=1
	whichhdu -- If its file contains multiple images, choose one (0 = first HDU, -1 = first valid image)
		default=-1 ; example: whichhdu=1
	zeroblanks -- Set blanked pixels to zero (not NaN)
		default=True; example: zeroblanks=True
	overwrite -- Overwrite pre-existing imagename
		default=False; example: overwrite=True
	defaultaxes -- Add the default 4D coordinate axes where they are missing
	        default=False, example: defaultaxes=True
	defaultaxesvalues -- List of values to assign to added degenerate axes when defaultaxes==True (ra,dec,freq,stokes)
	        default = [], example: defaultaxesvalues=['13.5h', '-2.5deg', '88.5GHz', 'Q'] 
	beam -- List of values to be used to define the synthesized beam [BMAJ,BMIN,BPA] (as in the FITS keywords)
	        default = [] (i.e. take from FITS file), example: beam=['0.35arcsec', '0.24arcsec', '25deg']

	"""

    #Python script
    casalog.origin('importfits')
    _myia = iatool()
    tmpname = imagename
    reorder = False
    addaxes = False
    adddir = False
    addstokes = False
    addfreq = False
    defaultorder = ['Right Ascension', 'Declination', 'Stokes', 'Frequency']
    addbeam = False

    try:
        _myia.dohistory(False)
        if os.path.exists(imagename):
            if not overwrite:
                raise RuntimeError, 'Output image exists already and you did not set overwrite to True.'
            else:
                os.system('rm -rf ' + imagename)

        if defaultaxes:
            if len(defaultaxesvalues) != 4:
                raise TypeError, 'When defaultaxes==True, parameter defaultaxesvalues must be provided as a list of 4 values: RA, Dec, Freq, Stokes,\n e.g. [\'13.5h\', \'-2.5deg\', \'88.5GHz\', \'I\']\nFor existing axes, empty strings can be given as values.'
            _myia.open(fitsimage)
            _mycs = _myia.coordsys()
            acts = _mycs.axiscoordinatetypes()
            cnames = _mycs.names()
            _myia.close()
            if ('Direction' in acts and not ('Right Ascension' in cnames
                                             and 'Declination' in cnames)):
                raise RuntimeError, 'Non-standard direction axes. Cannot add default axes.'
            if ('Spectral' in acts and not 'Frequency' in cnames):
                raise RuntimeError, 'Non-standard spectral axis. Cannot add default axes.'
            if ('Stokes' in acts and not 'Stokes' in cnames):
                raise RuntimeError, 'Non-standard Stokes axis. Cannot add default axes.'

            if not ('Right Ascension' in cnames and 'Declination' in cnames):
                addaxes = True
                adddir = True
            if not ('Frequency' in cnames):
                addaxes = True
                addfreq = True
            if not ('Stokes' in cnames):
                addaxes = True
                addstokes = True
            if not addaxes and cnames != defaultorder:
                reorder = True
            if addaxes or reorder:
                tmpname = imagename + '.tmp'
                os.system('rm -rf ' + tmpname)

        if beam != []:  # user has set beam
            if type(beam) != list or len(beam) != 3 or not (type(
                    beam[0]) == str and type(beam[1]) == str
                                                            and type(beam[2])):
                raise TypeError, "Parameter beam is invalid (should be list of 3 strings or empty): " + str(
                    beam)
            qabeam = []
            for i in range(0, 3):
                try:
                    qabeam.append(qa.quantity(beam[i]))
                    tmp = qa.toangle(qabeam[i])
                except:
                    raise TypeError, "Parameter beam[" + str(
                        i) + "] is invalid (should be an angle): " + str(
                            beam[i])
            if (qa.convert(qabeam[0], 'arcsec') >= qa.convert(
                    qabeam[1], 'arcsec')):
                addbeam = True
            else:
                raise TypeError, "Parameter beam[" + str(
                    i
                ) + "] is invalid (major axis must be >= minor axis): " + str(
                    beam)

        _myia.fromfits(tmpname, fitsimage, whichrep, whichhdu, zeroblanks)
        _myia.close()

        if addaxes:
            casalog.post('Adding missing coodinate axes ...', 'INFO')
            tmpname2 = imagename + '.tmp2'
            os.system('rm -rf ' + tmpname2)

            _myia.open(tmpname)
            ia2 = _myia.adddegaxes(outfile=tmpname2,
                                   direction=True,
                                   spectral=True,
                                   stokes=defaultaxesvalues[3],
                                   silent=True)
            _myia.close()
            os.system('rm -rf ' + tmpname)
            ia2.close()
            ia2.open(tmpname2)

            # set the right reference values in the added axes
            _mynewcs = ia2.coordsys()
            raval = 0.
            decval = 0.
            freqval = 0.
            if adddir:
                ra = defaultaxesvalues[0]
                if type(ra) == int or type(ra) == float:
                    raval = ra
                else:
                    qara = qa.quantity(qa.angle(ra)[0])
                    if qara['unit'].find('deg') < 0:
                        raise TypeError, "RA default value is not a valid angle quantity " % ra
                    raval = qara['value']

                dec = defaultaxesvalues[1]
                if type(dec) == int or type(dec) == float:
                    decval = dec
                else:
                    qadec = qa.quantity(qa.angle(dec)[0])
                    if qadec['unit'].find('deg') < 0:
                        raise TypeError, "DEC default value is not a valid angle quantity " % dec
                    decval = qadec['value']

                _mynewcs.setunits(value='deg deg', type='direction')
                _mynewcs.setreferencevalue(type='direction',
                                           value=[raval, decval])

            if addfreq:
                freq = defaultaxesvalues[2]
                if type(freq) == int or type(freq) == float:
                    freqval = freq
                else:
                    qafreq = qa.quantity(freq)
                    if qafreq['unit'].find('Hz') < 0:
                        raise TypeError, "Freq default value is not a valid frequency quantity " % freq
                    freqval = qa.convertfreq(qafreq, 'Hz')['value']
                _mynewcs.setunits(value='Hz', type='spectral')
                _mynewcs.setreferencevalue(type='spectral', value=freqval)
                _mynewcs.setrestfrequency(freqval)

            # Note: stokes default value was already set in adddegaxes

            if adddir or addfreq:
                ia2.setcoordsys(_mynewcs.torecord())

            ia2.close()

            cnames = _mynewcs.names()

            if len(cnames) == 4 and not (cnames == defaultorder):
                # need to reorder
                reorder = True
                tmpname = tmpname2
            else:
                os.system('mv ' + tmpname2 + ' ' + imagename)

        if reorder:
            casalog.post('Transposing coodinate axes ...', 'INFO')
            _myia.open(tmpname)
            ia2 = _myia.transpose(outfile=imagename, order=defaultorder)
            _myia.close()
            ia2.close()
            os.system('rm -rf ' + tmpname)

        _myia.open(imagename)
        if addbeam:
            _myia.setrestoringbeam(beam[0], beam[1], beam[2])
        else:
            mybeam = _myia.restoringbeam()
            if mybeam == {}:  # the fits image had no beam
                casalog.post(
                    "This image has no beam or angular resolution provided, so you will not receive warnings from\n"
                    "tasks such as imregrid if your image pixels do not sample the the angular resolution well.\n"
                    "(This only affects warnings, not any functionality).\n"
                    "Providing a beam and brightness units in an image can also be useful for flux calculations.\n"
                    "If you wish to add a beam or brightness units to your image, please use\n"
                    "the \"beam\" parameter or ia.setrestoringbeam() and ia.setbrightnessunit()",
                    'WARN')
        try:
            param_names = importfits.func_code.co_varnames[:importfits.
                                                           func_code.
                                                           co_argcount]
            param_vals = [eval(p) for p in param_names]
            write_image_history(_myia,
                                sys._getframe().f_code.co_name, param_names,
                                param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')
        return True
Exemplo n.º 14
0
def specfit(imagename, box, region, chans, stokes, axis, mask, ngauss, poly,
            estimates, minpts, multifit, model, residual, amp, amperr, center,
            centererr, fwhm, fwhmerr, integral, integralerr, wantreturn,
            stretch, logresults, pampest, pcenterest, pfwhmest, pfix, gmncomps,
            gmampcon, gmcentercon, gmfwhmcon, gmampest, gmcenterest, gmfwhmest,
            gmfix, logfile, append, pfunc, goodamprange, goodcenterrange,
            goodfwhmrange, sigma, outsigma):
    casalog.origin('specfit')
    retval = None
    myia = iatool()
    myia.dohistory(False)
    try:
        if (not myia.open(imagename)):
            raise Exception, "Cannot create image analysis tool using " + imagename
        target_time = time.time()
        retval = myia.fitprofile(box=box,
                                 region=region,
                                 chans=chans,
                                 stokes=stokes,
                                 axis=axis,
                                 mask=mask,
                                 ngauss=ngauss,
                                 poly=poly,
                                 estimates=estimates,
                                 minpts=minpts,
                                 multifit=multifit,
                                 model=model,
                                 residual=residual,
                                 amp=amp,
                                 amperr=amperr,
                                 center=center,
                                 centererr=centererr,
                                 fwhm=fwhm,
                                 fwhmerr=fwhmerr,
                                 integral=integral,
                                 integralerr=integralerr,
                                 stretch=stretch,
                                 logresults=logresults,
                                 pampest=pampest,
                                 pcenterest=pcenterest,
                                 pfwhmest=pfwhmest,
                                 pfix=pfix,
                                 gmncomps=gmncomps,
                                 gmampcon=gmampcon,
                                 gmcentercon=gmcentercon,
                                 gmfwhmcon=gmfwhmcon,
                                 gmampest=gmampest,
                                 gmcenterest=gmcenterest,
                                 gmfwhmest=gmfwhmest,
                                 gmfix=gmfix,
                                 logfile=logfile,
                                 append=append,
                                 pfunc=pfunc,
                                 goodamprange=goodamprange,
                                 goodcenterrange=goodcenterrange,
                                 goodfwhmrange=goodfwhmrange,
                                 sigma=sigma,
                                 outsigma=outsigma)
        try:
            param_names = specfit.func_code.co_varnames[:specfit.func_code.
                                                        co_argcount]
            param_vals = [eval(p) for p in param_names]
            ims = [model, residual]
            for x in [
                    amp, amperr, center, centererr, fwhm, fwhmerr, integral,
                    integralerr
            ]:
                if x:
                    ims.extend(get_created_images(x, target_time))
            for im in ims:
                write_image_history(im,
                                    sys._getframe().f_code.co_name,
                                    param_names, param_vals, casalog)
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance),
                         'WARN')

    except Exception, instance:
        casalog.post('*** Error *** ' + str(instance), 'SEVERE')
        retval = None
Exemplo n.º 15
0
def imcontsub(
    imagename, linefile, contfile, fitorder,
    region, box, chans, stokes
):
    casalog.origin('imcontsub')
    filesExist=False
    if ( len( linefile ) > 0 ):
        if ( os.path.exists( linefile ) ):
            casalog.post('Error: file ' + linefile
                          +' already exists, please delete before continuing.',\
                          'SEVERE' )
            filesExist=True
    else:
        casalog.post("The linefile parameter is empty, consequently the"
                      +" spectral line image will NOT be\nsaved on disk.", \
                      'WARN')
            
    if ( len( contfile ) > 0 ):
            if ( os.path.exists( contfile ) ):
                casalog.post( 'Error: Unable to continue file '+contfile\
                              +' already exists, please delete before continuing.',\
                          'SEVERE' )
                filesExist=True
    else:
        casalog.post("The contfile parameter is empty, consequently the"
                      +" continuum image will NOT be\nsaved on disk.", \
                      'WARN')
    if ( filesExist ):
        return False
    
    _myia = iatool()
    _myia.dohistory(False)
    _myia.open(imagename)
    mycsys = _myia.coordsys()
    if isinstance(box, list):
        box = ', '.join([str(b) for b in box])

    # Don't mix chans up with reg!  reg selects a subset for output, and chans
    # selects a subset to define the line-free channels.
    myrg = rgtool()
    reg = myrg.frombcs(
        csys=mycsys.torecord(), shape=_myia.shape(),
        box=box, stokes=stokes, stokescontrol="f",
        region=region
    )
    channels = []
    if chans != None and len(chans) > 0:
        channels = myrg.selectedchannels(chans, _myia.shape())
    
    try:
        # Now do the continuum subtraction.
        lineim = _myia.continuumsub(
            outline=linefile, outcont=contfile, region=reg,
            channels=channels, fitorder=fitorder,
            overwrite=False
        )
        if not lineim:
            raise Exception("ia.continuumsub did not complete successfully")
        try:
            param_names = imcontsub.func_code.co_varnames[:imcontsub.func_code.co_argcount]
            param_vals = [eval(p) for p in param_names]
            for x in [lineim, contfile]:
                write_image_history(
                    x, sys._getframe().f_code.co_name,
                    param_names, param_vals, casalog
                )
        except Exception, instance:
            casalog.post("*** Error \'%s\' updating HISTORY" % (instance), 'WARN')
        lineim.done()
        return True
Exemplo n.º 16
0
                res = myimd.add(hdkey, hdvalue)
            elif mode.startswith('d'):
                res = myimd.remove(hdkey, hdvalue)
            elif mode.startswith('g'):
                return myimd.get(hdkey)
            elif mode.startswith('l'):
                return myimd.list(True)
            elif mode.startswith('p'):
                res = myimd.set(hdkey, hdvalue)
            if res:
                try:
                    param_names = imhead.func_code.co_varnames[:imhead.
                                                               func_code.
                                                               co_argcount]
                    param_vals = [eval(p) for p in param_names]
                    write_image_history(imagename,
                                        sys._getframe().f_code.co_name,
                                        param_names, param_vals, casalog)
                except Exception, instance:
                    casalog.post(
                        "*** Error \'%s\' updating HISTORY" % (instance),
                        'WARN')
            return res
        except Exception, instance:
            casalog.post(str('*** Error *** ') + str(instance), 'SEVERE')
            return False
        finally:
            myimd.done()
        casalog.post('Unknown imhead mode ' + str(mode), 'SEVERE')
        return False