コード例 #1
0
def predictcomp(objname=None,
                standard=None,
                epoch=None,
                minfreq=None,
                maxfreq=None,
                nfreqs=None,
                prefix=None,
                antennalist=None,
                showplot=None,
                savefig=None,
                symb=None,
                include0amp=None,
                include0bl=None,
                blunit=None,
                bl0flux=None):
    """
    Writes a component list named clist to disk and returns a dict of
    {'clist': clist,
     'objname': objname,
     'angdiam': angular diameter in radians (if used in clist),
     'standard': standard,
     'epoch': epoch,
     'freqs': pl.array of frequencies, in GHz,
     'uvrange': pl.array of baseline lengths, in m,
     'amps':  pl.array of predicted visibility amplitudes, in Jy,
     'savedfig': False or, if made, the filename of a plot.}
    or False on error.

    objname: An object supported by standard.
    standard: A standard for calculating flux densities, as in setjy.
              Default: 'Butler-JPL-Horizons 2010'
    epoch: The epoch to use for the calculations.   Irrelevant for
           extrasolar standards.
    minfreq: The minimum frequency to use.
             Example: '342.0GHz'
    maxfreq: The maximum frequency to use.
             Default: minfreq
             Example: '346.0GHz'
             Example: '', anything <= 0, or None: use minfreq.
    nfreqs:  The number of frequencies to use.
             Default: 1 if minfreq == maxfreq,
                      2 otherwise.
    prefix: The component list will be saved to
              prefix + '<objname>_spw0_<minfreq><epoch>.cl'
            Default: ''
    antennalist: An array configuration file as used by simdata.
                 If given, a plot of S vs. |u| will be made.
                 Default: '' (None, just make clist.)
    showplot: Whether or not to show the plot on screen.
              Subparameter of antennalist.
              Default: Necessarily False if antennalist is not specified.
                       True otherwise.
    savefig: Filename for saving a plot of S vs. |u|.
             Subparameter of antennalist.
             Default: False (necessarily if antennalist is not specified)
             Examples: True (save to prefix + '.png')
                       'myplot.png' (save to myplot.png) 
    symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_
          default: '.'
    include0amp: Force the lower limit of the amplitude axis to 0.
                 Default: False
    include0bl: Force the lower limit of the baseline length axis to 0.
    blunit: Unit of the baseline length 
    bl0flux: show zero baseline flux
    """
    retval = False
    try:
        casalog.origin('predictcomp')
        # some parameter minimally required
        if objname == '':
            raise Exception, "Error, objname is undefined"
        if minfreq == '':
            raise Exception, "Error, minfreq is undefined"
        minfreqq = qa.quantity(minfreq)
        minfreqHz = qa.convert(minfreqq, 'Hz')['value']
        try:
            maxfreqq = qa.quantity(maxfreq)
        except Exception, instance:
            maxfreqq = minfreqq
        frequnit = maxfreqq['unit']
        maxfreqHz = qa.convert(maxfreqq, 'Hz')['value']
        if maxfreqHz <= 0.0:
            maxfreqq = minfreqq
            maxfreqHz = minfreqHz
        if minfreqHz != maxfreqHz:
            if nfreqs < 2:
                nfreqs = 2
        else:
            nfreqs = 1
        freqs = pl.linspace(minfreqHz, maxfreqHz, nfreqs)

        myme = metool()
        mepoch = myme.epoch('UTC', epoch)
        #if not prefix:
        ## meanfreq = {'value': 0.5 * (minfreqHz + maxfreqHz),
        ##             'unit': frequnit}
        ## prefix = "%s%s_%.7g" % (objname, epoch.replace('/', '-'),
        ##                         minfreqq['value'])
        ## if minfreqHz != maxfreqHz:
        ##     prefix += "to" + maxfreq
        ## else:
        ##     prefix += minfreqq['unit']
        ## prefix += "_"
        #    prefix = ''

        #
        if not prefix:
            if not os.access("./", os.W_OK):
                casalog.post(
                    "No write access in the current directory, trying to write cl to /tmp...",
                    "WARN")
                prefix = "/tmp/"
                if not os.access(prefix, os.W_OK):
                    casalog.post("No write access to /tmp to write cl file",
                                 "SEVERE")
                    return False
        else:
            prefixdir = os.path.dirname(prefix)
            if prefixdir == '/' and len(prefix) > 1:
                prefix = prefix + '/'
                prefixdir = os.path.dirname(prefix)
            if not os.path.exists(prefixdir):
                prefixdirs = prefixdir.split('/')
                if prefixdirs[0] == "" and len(prefixdirs) > 1:
                    rootdir = "/" + prefixdirs[1]
                else:
                    rootdir = "./"
                if os.access(rootdir, os.W_OK):
                    if prefixdir != '':
                        os.makedirs(prefixdir)
                else:
                    casalog.post(
                        "No write access to " + rootdir + " to write cl file",
                        "SEVERE")
                    return False

        # Get clist
        myim = imtool()
        if hasattr(myim, 'predictcomp'):
            casalog.post('local im instance created', 'DEBUG1')
        else:
            casalog.post('Error creating a local im instance.', 'SEVERE')
            return False
        #print "FREQS=",freqs
        # output CL file name is fixed : prefix+"spw0_"+minfreq+mepoch.cl
        minfreqGHz = qa.convert(qa.quantity(minfreq), 'GHz')['value']
        decimalfreq = minfreqGHz - int(minfreqGHz)
        decimalepoch = mepoch['m0']['value'] - int(mepoch['m0']['value'])
        if decimalfreq == 0.0:
            minfreqGHzStr = str(int(minfreqGHz)) + 'GHz'
        else:
            minfreqGHzStr = str(minfreqGHz) + 'GHz'

        if decimalepoch == 0.0:
            epochStr = str(int(mepoch['m0']['value'])) + 'd'
        else:
            epochStr = str(mepoch['m0']['value']) + 'd'
        outfilename = "spw0_" + objname + "_" + minfreqGHzStr + epochStr + '.cl'
        outfilename = prefix + outfilename
        if (os.path.exists(outfilename) and os.path.isdir(outfilename)):

            shutil.rmtree(outfilename)
            casalog.post("Removing the existing componentlist, " + outfilename)

        if standard == 'Butler-JPL-Horizons 2012':
            clist = predictSolarObjectCompList(objname, mepoch, freqs.tolist(),
                                               prefix)
        else:
            clist = myim.predictcomp(objname, standard, mepoch, freqs.tolist(),
                                     prefix)
        #print "created componentlist =",clist
        if os.path.isdir(clist):
            # The spw0 is useless here, but it is added by FluxStandard for the sake of setjy.
            casalog.post('The component list was saved to ' + clist)

            retval = {
                'clist': clist,
                'objname': objname,
                'standard': standard,
                'epoch': mepoch,
                'freqs (GHz)': 1.0e-9 * freqs,
                'antennalist': antennalist
            }
            mycl = cltool()
            mycl.open(clist)
            comp = mycl.getcomponent(0)
            zeroblf = comp['flux']['value']
            if standard == 'Butler-JPL-Horizons 2012':
                f0 = comp['spectrum']['frequency']['m0']['value']
            else:
                f0 = retval['freqs (GHz)'][0]
            casalog.post("Zero baseline flux %s @ %sGHz " % (zeroblf, f0),
                         'INFO')
            mycl.close(False)  # False prevents the stupid warning.
            for k in ('shape', 'spectrum'):
                retval[k] = comp[k]
            if antennalist:
                retval['spectrum']['bl0flux'] = {}
                retval['spectrum']['bl0flux']['value'] = zeroblf[0]
                retval['spectrum']['bl0flux']['unit'] = 'Jy'
                retval['savedfig'] = savefig
                if not bl0flux:
                    zeroblf = [0.0]
                retval.update(
                    plotcomp(retval,
                             showplot,
                             wantdict=True,
                             symb=symb,
                             include0amp=include0amp,
                             include0bl=include0bl,
                             blunit=blunit,
                             bl0flux=zeroblf[0]))
            else:
                retval['savedfig'] = None
        else:
            casalog.post("There was an error in making the component list.",
                         'SEVERE')
コード例 #2
0
def ksc_sim_gauss(projname='sim_7m_array_1GHz_gaus',
                  antennalist='ksc-7m.cfg',
                  dishdiam=7,
                  imagename=None,
                  indirection='J2000 14h26m46.0s -14d31m22.0s',
                  incell='1arcsec',
                  frequency='1.0GHz',
                  inwidth='1MHz',
                  radec_offset=[100., 100.],
                  flux=50.,
                  majoraxis='40arcsec',
                  minoraxis='27arcsec',
                  positionangle='45.0deg',
                  imsize=[512, 512]):
    """
    Simulate observation of an input Gaussian model
    :param projname: project name for simobserve
    :param antennalist: cfg file of the array configuration
    :param dishdiam: diameter of each dish, in meters
    :param imagename: name (and path) for output clean image, psf, etc.
    :param indirection: phase center of the observation
    :param incell: pixel scale of the model/simulated image
    :param frequency: central frequency
    :param inwidth: frequency bandwidth
    :param radec_offset: offset of the Gaussian source from the phasecenter, in arcsec
    :param flux: total flux of the Gaussian source, in solar flux unit (sfu)
    :param majoraxis: FWHM size of the Gaussian source along the major axis
    :param minoraxis: FWHM size of the Gaussian source along the minor axis
    :param positionangle: position angle of the Gaussian source
    :param imsize: size of the model/simulated image, in pixels (x and y)
    :return:
    """

    # set voltage patterns and primary beams for KSC 7 m. This is a placeholder for now (but required for PB correction)
    vp = vptool()
    if len(vp.getvp(telescope='KSC').keys()) == 0:
        vprec = vp.setpbairy(telescope='KSC',
                             dishdiam='{0:.1f}m'.format(dishdiam),
                             blockagediam='0.75m',
                             maxrad='1.784deg',
                             reffreq='1.0GHz',
                             dopb=True)

    # make a Gaussian source
    cl = cltool()
    ia = iatool()
    cl.addcomponent(dir=indirection,
                    flux=flux * 1e4,
                    fluxunit='Jy',
                    freq=frequency,
                    shape="Gaussian",
                    majoraxis=majoraxis,
                    minoraxis=minoraxis,
                    positionangle=positionangle)
    ia.fromshape("Gaussian.im", imsize + [1, 1], overwrite=True)
    cs = ia.coordsys()
    cs.setunits(['rad', 'rad', '', 'Hz'])
    cell_rad = qa.convert(qa.quantity(incell), "rad")['value']
    cs.setincrement([-cell_rad, cell_rad], 'direction')
    ra_ref = qa.toangle(indirection.split(' ')[1])
    dec_ref = qa.toangle(indirection.split(' ')[2])
    ra = ra_ref['value'] - radec_offset[0] / 3600.
    dec = dec_ref['value'] - radec_offset[1] / 3600.
    cs.setreferencevalue([
        qa.convert('{0:.4f}deg'.format(ra), 'rad')['value'],
        qa.convert('{0:.4f}deg'.format(dec), 'rad')['value']
    ],
                         type="direction")
    cs.setreferencevalue("1.0GHz", 'spectral')
    cs.setincrement('10MHz', 'spectral')
    ia.setcoordsys(cs.torecord())
    ia.setbrightnessunit("Jy/pixel")
    ia.modify(cl.torecord(), subtract=False)
    ia.close()

    simobserve(project=projname,
               skymodel='Gaussian.im',
               indirection=indirection,
               incell=incell,
               incenter=frequency,
               inwidth=inwidth,
               hourangle='transit',
               refdate='2014/11/01',
               totaltime='120s',
               antennalist=antennalist,
               obsmode='int',
               overwrite=True)

    if not imagename:
        imagename = projname + '/tst'
    tclean(vis=projname + '/' + projname + '.' + antennalist.split('.')[0] +
           '.ms',
           imagename=imagename,
           imsize=imsize,
           cell=incell,
           phasecenter=indirection,
           niter=200,
           interactive=False)

    viewer(projname + '/' + projname + '.' + antennalist.split('.')[0] +
           '.skymodel')
    viewer(imagename + '.psf')
    viewer(imagename + '.image')
コード例 #3
0
ファイル: eovsa_diskmodel.py プロジェクト: dgary50/suncasa
def mk_diskmodel(outname='disk', bdwidth='325MHz', direction='J2000 10h00m00.0s 20d00m00.0s',
                 reffreq='2.8GHz', flux=660000.0, eqradius='16.166arcmin', polradius='16.166arcmin',
                 pangle='21.1deg', index=None, cell='2.0arcsec', overwrite=True):
    ''' Create a blank solar disk model image (or optionally a data cube)
        outname       String to use for part of the image and fits file names (default 'disk')
        direction     String specifying the position of the Sun in RA and Dec.  Default
                        means use the standard string "J2000 10h00m00.0s 20d00m00.0s"
        reffreq       The reference frequency to use for the disk model (the frequency at which
                        the flux level applies). Default is '2.8GHz'.
        flux          The flux density, in Jy, for the entire disk. Default is 66 sfu.
        eqradius      The equatorial radius of the disk.  Default is
                        16 arcmin + 10" (for typical extension of the radio limb)
        polradius     The polar radius of the disk.  Default is
                        16 arcmin + 10" (for typical extension of the radio limb)
        pangle        The solar P-angle (geographic position of the N-pole of the Sun) in
                        degrees E of N.  This only matters if eqradius != polradius
        index         The spectral index to use at other frequencies.  Default None means
                        use a constant flux density for all frequencies.
        cell          The cell size (assumed square) to use for the image.  The image size
                        is determined from a standard radius of 960" for the Sun, divided by
                        cell size, increased to nearest power of 512 pixels. The default is '2.0arcsec',
                        which results in an image size of 1024 x 1024.
        Note that the frequency increment used is '325MHz', which is the width of EOVSA bands
          (not the width of individual science channels)
    '''

    diskim = outname + reffreq + '.im'
    if os.path.exists(diskim):
        if overwrite:
            os.system('rm -rf {}'.format(diskim))
        else:
            return diskim

    ia = iatool()
    cl = cltool()
    cl.done()
    ia.done()

    try:
        aspect = 1.01  # Enlarge the equatorial disk by 1%
        eqradius = qa.quantity(eqradius)
        diamajor = qa.quantity(2 * aspect * eqradius['value'], eqradius['unit'])
        polradius = qa.quantity(polradius)
        diaminor = qa.quantity(2 * polradius['value'], polradius['unit'])
        solrad = qa.convert(polradius, 'arcsec')
    except:
        print('Radius', eqradius, polradius,
              'does not have the expected format, number + unit where unit is arcmin or arcsec')
        return
    try:
        cell = qa.convert(qa.quantity(cell), 'arcsec')
        cellsize = float(cell['value'])
        diskpix = solrad['value'] * 2 / cellsize
        cell_rad = qa.convert(cell, 'rad')
    except:
        print('Cell size', cell, 'does not have the expected format, number + unit where unit is arcmin or arcsec')
        return

    # Add 90 degrees to pangle, due to angle definition in addcomponent() -- it puts the majoraxis vertical
    pangle = qa.add(qa.quantity(pangle), qa.quantity('90deg'))
    mapsize = ((int(diskpix) / 512) + 1) * 512
    # Flux density is doubled because it is split between XX and YY
    cl.addcomponent(dir=direction, flux=flux * 2, fluxunit='Jy', freq=reffreq, shape='disk',
                    majoraxis=diamajor, minoraxis=diaminor, positionangle=pangle)
    cl.setrefdirframe(0, 'J2000')

    ia.fromshape(diskim, [mapsize, mapsize, 1, 1], overwrite=True)
    cs = ia.coordsys()
    cs.setunits(['rad', 'rad', '', 'Hz'])
    cell_rad_val = cell_rad['value']
    cs.setincrement([-cell_rad_val, cell_rad_val], 'direction')
    epoch, ra, dec = direction.split()
    cs.setreferencevalue([qa.convert(ra, 'rad')['value'], qa.convert(dec, 'rad')['value']], type="direction")
    cs.setreferencevalue(reffreq, 'spectral')
    cs.setincrement(bdwidth, 'spectral')
    ia.setcoordsys(cs.torecord())
    ia.setbrightnessunit("Jy/pixel")
    ia.modify(cl.torecord(), subtract=False)
    ia.close()
    ia.done()
    # cl.close()
    cl.done()
    return diskim
コード例 #4
0
ファイル: task_predictcomp.py プロジェクト: keflavich/casa
def predictcomp(objname=None, standard=None, epoch=None,
                minfreq=None, maxfreq=None, nfreqs=None, prefix=None,
                antennalist=None, showplot=None, savefig=None, symb=None,
                include0amp=None, include0bl=None, blunit=None, bl0flux=None):
    """
    Writes a component list named clist to disk and returns a dict of
    {'clist': clist,
     'objname': objname,
     'angdiam': angular diameter in radians (if used in clist),
     'standard': standard,
     'epoch': epoch,
     'freqs': pl.array of frequencies, in GHz,
     'uvrange': pl.array of baseline lengths, in m,
     'amps':  pl.array of predicted visibility amplitudes, in Jy,
     'savedfig': False or, if made, the filename of a plot.}
    or False on error.

    objname: An object supported by standard.
    standard: A standard for calculating flux densities, as in setjy.
              Default: 'Butler-JPL-Horizons 2010'
    epoch: The epoch to use for the calculations.   Irrelevant for
           extrasolar standards.
    minfreq: The minimum frequency to use.
             Example: '342.0GHz'
    maxfreq: The maximum frequency to use.
             Default: minfreq
             Example: '346.0GHz'
             Example: '', anything <= 0, or None: use minfreq.
    nfreqs:  The number of frequencies to use.
             Default: 1 if minfreq == maxfreq,
                      2 otherwise.
    prefix: The component list will be saved to
              prefix + 'spw0_<objname>_<minfreq><epoch>.cl'
            Default: ''
    antennalist: An array configuration file as used by simdata.
                 If given, a plot of S vs. |u| will be made.
                 Default: '' (None, just make clist.)
    showplot: Whether or not to show the plot on screen.
              Subparameter of antennalist.
              Default: Necessarily False if antennalist is not specified.
                       True otherwise.
    savefig: Filename for saving a plot of S vs. |u|.
             Subparameter of antennalist.
             Default: False (necessarily if antennalist is not specified)
             Examples: True (save to prefix + '.png')
                       'myplot.png' (save to myplot.png) 
    symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_
          default: '.'
    include0amp: Force the lower limit of the amplitude axis to 0.
                 Default: False
    include0bl: Force the lower limit of the baseline length axis to 0.
    blunit: Unit of the baseline length 
    bl0flux: show zero baseline flux
    """
    retval = False
    try:
        casalog.origin('predictcomp')
        # some parameter minimally required
        if objname=='':
          raise Exception, "Error, objname is undefined"
        if minfreq=='':
          raise Exception, "Error, minfreq is undefined" 
        minfreqq = qa.quantity(minfreq)
        minfreqHz = qa.convert(minfreqq, 'Hz')['value']
        try:
            maxfreqq = qa.quantity(maxfreq)
        except Exception, instance:
            maxfreqq = minfreqq
        frequnit = maxfreqq['unit']
        maxfreqHz = qa.convert(maxfreqq, 'Hz')['value']
        if maxfreqHz <= 0.0:
            maxfreqq = minfreqq
            maxfreqHz = minfreqHz
        if minfreqHz != maxfreqHz:
            if nfreqs < 2:
                nfreqs = 2
        else:
            nfreqs = 1
        freqs = pl.linspace(minfreqHz, maxfreqHz, nfreqs)

        myme = metool()
        mepoch = myme.epoch('UTC', epoch)
        #if not prefix:
            ## meanfreq = {'value': 0.5 * (minfreqHz + maxfreqHz),
            ##             'unit': frequnit}
            ## prefix = "%s%s_%.7g" % (objname, epoch.replace('/', '-'),
            ##                         minfreqq['value'])
            ## if minfreqHz != maxfreqHz:
            ##     prefix += "to" + maxfreq
            ## else:
            ##     prefix += minfreqq['unit']
            ## prefix += "_"
        #    prefix = ''
        
        #
        if not prefix:
          if not os.access("./",os.W_OK):
            casalog.post("No write access in the current directory, trying to write cl to /tmp...","WARN")
            prefix="/tmp/"
            if not os.access(prefix, os.W_OK):
              casalog.post("No write access to /tmp to write cl file", "SEVERE")
              return False
        else:
          prefixdir=os.path.dirname(prefix)
          if not os.path.exists(prefixdir):
            prefixdirs = prefixdir.split('/')
            if prefixdirs[0]=="":
              rootdir = "/" + prefixdirs[1]
            else:
              rootdir = "./"
            if os.access(rootdir,os.W_OK):
              os.makedirs(prefixdir) 
            else:
              casalog.post("No write access to "+rootdir+" to write cl file", "SEVERE")
              return False
       
        # Get clist
        myim = imtool()
        if hasattr(myim, 'predictcomp'):
            casalog.post('local im instance created', 'DEBUG1')
        else:
            casalog.post('Error creating a local im instance.', 'SEVERE')
            return False
        #print "FREQS=",freqs
        if standard=='Butler-JPL-Horizons 2012':
            clist = predictSolarObjectCompList(objname, mepoch, freqs.tolist(), prefix)
        else:
            clist = myim.predictcomp(objname, standard, mepoch, freqs.tolist(), prefix)
        #print "created componentlist =",clist
        if os.path.isdir(clist):
            # The spw0 is useless here, but it is added by FluxStandard for the sake of setjy.
            casalog.post('The component list was saved to ' + clist)
            
            retval = {'clist': clist,
                      'objname': objname,
                      'standard': standard,
                      'epoch': mepoch,
                      'freqs (GHz)': 1.0e-9 * freqs,
                      'antennalist': antennalist}
            mycl = cltool()
            mycl.open(clist)
            comp = mycl.getcomponent(0)
            zeroblf=comp['flux']['value']
            if standard=='Butler-JPL-Horizons 2012':
              f0=comp['spectrum']['frequency']['m0']['value']
            else:
              f0=retval['freqs (GHz)'][0]
            casalog.post("Zero baseline flux %s @ %sGHz " % (zeroblf, f0),'INFO')
            mycl.close(False)               # False prevents the stupid warning.
            for k in ('shape', 'spectrum'):
                retval[k] = comp[k]
            if antennalist:
                retval['spectrum']['bl0flux']={}
                retval['spectrum']['bl0flux']['value']=zeroblf[0]
                retval['spectrum']['bl0flux']['unit']='Jy'
                retval['savedfig'] = savefig
                if not bl0flux:
                  zeroblf=[0.0]
                retval.update(plotcomp(retval, showplot, wantdict=True, symb=symb,
                                       include0amp=include0amp, include0bl=include0bl, blunit=blunit, bl0flux=zeroblf[0]))
            else:
                retval['savedfig'] = None
        else:
            casalog.post("There was an error in making the component list.",
                         'SEVERE')