Exemplo n.º 1
0
def PParse(infile, list, err):
    """ Parse text file

    Parse parameter format text file and copy to list
    The input file is basically free format with a keyword=value syntax.  
    Comments follow a "#" symbol.  String keywords should have no leading or
    trailing blanks before the end of the line or a comment delimiter.
    If a numeric value is followed by a comment there should be at least one
    blank before the comment delimiter.  Allowed types are:
    Str (String), Flt (float), Dbl (double), Int (int), Boo (boolean)

    Examples:
    # Comment
    $Key = SomeStr   Str (9)   # Some string
    Something
    $Key =  FArr     Flt (2)   # Array of 2 floats
    0.0 0.0
    $Key = CLEANBox  Int(4,1)  # Clean box with 4 ints
    0 0 0 0
    
    returns  0 on success, else 1
    infile   = Name of the input text file to parse
    list     = ObitInfoList to accept values.
    err      = ObitErr for reporting errors.
    """
    ################################################################
    # Checks
    if not InfoList.PIsA(list):
        raise TypeError,"list MUST be a Python Obit InfoList"
    ret = Obit.Parse(infile, list.me, err.me)
    if ret or err.isErr:
        OErr.printErrMsg(err, "Error Parsing "+infile)
    return ret
Exemplo n.º 2
0
def PCvtPixel(inID, inPixel, outID, err):
    """
    Return pixel location in outID corresponding to pixel inPixel in inID
    
    returns array of 2 floats giving pixel position in outID.

    * inID    = Python Obit ImageDesc for input
    * inPixel = array of floats giving position in image described by inID
      only first 2 used.
    * outID   = Python Obit ImageDesc for output
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inID):
        raise TypeError("inID MUST be a Python Obit ImageDesc")
    if not PIsA(outID):
        raise TypeError("outID MUST be a Python Obit ImageDesc")
    if not OErr.OErrIsA(err):
        raise TypeError("err MUST be an OErr")
    if inPixel[0].__class__ != float:
        print("class is", inPixel[0].__class__)
        raise TypeError("inPixel MUST be float")
    if len(inPixel) < 2:
        raise RuntimeError("inPixel has fewer then 2 entries")
    #
    outTmp = Obit.ImageDescCvtPixel(inID.me, outID.me, inPixel, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error converting pixel location")
    out = outTmp[0:2]
    return out
Exemplo n.º 3
0
def DescMakeIF(outUV, nIF, err):
    """ 
    Convert outUV descriptor divided into nIF IFs
    
    * outUV       = output Obit UV object
    * nIF         = number of desired output IFs
                    MUST be the same number of channels per IF
    * err         = Obit error/message stack
    """
    ################################################################
    d = outUV.Desc.Dict
    # Have IF axis?
    if d["jlocif"] >= 0:
        jlocif = d["jlocif"]
    else:  # create one
        jlocif = d['naxis']
        d['naxis'] += 1
        d['ctype'][jlocif] = "IF"
        d['crval'][jlocif] = 1.0
        d['crpix'][jlocif] = 1.0
        d['cdelt'][jlocif] = 1.0
        d['crota'][jlocif] = 0.0

    jlocf = d["jlocf"]
    nchan = d["inaxes"][jlocf] / nIF
    d["inaxes"][jlocif] = nIF
    d["inaxes"][jlocf] = nchan
    outUV.Desc.Dict = d
    UV.PGetIODesc(outUV).Dict = d  # And your little dog too
    # Update
    outUV.UpdateDesc(err)
    outUV.Open(UV.WRITEONLY, err)
    outUV.Close(err)
    #outUV.Header(err)
    OErr.printErrMsg(err, "Error converting Descriptor")
Exemplo n.º 4
0
def ClearErr(err=err):
    """ Print any errors and clear stack
    
    err  = Python Obit Error/message stack, default of PTObit version
    """
    ################################################################
    OErr.printErrMsg(err, "Error")
Exemplo n.º 5
0
def getname(cno, disk=Adisk):
    """ Return Obit object for AIPS file in cno on disk

    cno       = AIPS catalog slot number 
    disk      = AIPS disk number
    """
    ################################################################
    Adisk = disk
    user =  AIPS.AIPS.userno
    s = AIPSDir.PInfo(disk, user, cno, err)
    OErr.printErrMsg(err, "Error with AIPS catalog")
    # parse returned string
    Aname = s[0:12]
    Aclass = s[13:19]
    Aseq = int(s[20:25])
    Atype = s[26:28]
    if Atype == 'MA':
        out = Image.newPAImage("AIPS image", Aname, Aclass, disk, Aseq, True, err)
        print "AIPS Image",Aname, Aclass, disk, Aseq
    elif Atype == 'UV':
        out = UV.newPAUV("AIPS UV data", Aname, Aclass, disk, Aseq, True, err)
        print "AIPS UV",Aname, Aclass, disk, Aseq
    out.Aname  = Aname
    out.Aclass = Aclass
    out.Aseq   = Aseq 
    out.Atype  = Atype
    out.Disk   = disk
    out.Acno   = cno
    return out
Exemplo n.º 6
0
def PWebFetch(url, args, outfile, err):
    """ 
    Generic Fetch a web product

    Sends a http post request to url and sames response to outfile
    Throws exception on error
    * url     = where the request to be sent,
                e.g."https://www.cv.nrao.edu/cgi-bin/postage.pl"
    * args    = dict or arguments, e.g. {"arg1":"arg1"}
    * outfile = Name of the output file, absolute path or relative to CWD
                None => use name from server
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Package parameters
    encoded_args = urllib.urlencode(args)
    NVSShost = "https://www.cv.nrao.edu/cgi-bin/postage.pl"
    # fetch
    try:
        request = urllib2.Request(url)
        response = urllib2.urlopen(request, encoded_args)
        data = response.read()
    except Exception, exception:
        print exception
        OErr.PLog(err, OErr.Error, "Request from server failed")
        OErr.printErrMsg(err)
Exemplo n.º 7
0
def PPutBoolean (inList, name, dim, data, err):
    """ Add an boolean entry (1,0), error if conflict

    inList   = input Python InfoList
    name     = name of desired entry
    dim      = dimensionality of array as list, e.g. [1,1,1,1,1] for scalar
               MUST have 5 entries
    data     = data as a 1-D array of boolean (1,0)
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if data[0].__class__ != bool:
        print "class is" , data[0].__class__
        raise TypeError,"data MUST be bool"
    if len(dim) < 5:
        raise RuntimeError,"dim has fewer then 5 entries"
    prod = 1
    for x in dim:
        if (x>0):
            prod = prod*x
    if prod < len(data):
         raise RuntimeError,"more data than defined in dim"
    if prod > len(data):
        raise RuntimeError,"less data than defined in dim"
    Obit.InfoListPutBoolean(inList.me, name, dim, data, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error adding entry")
Exemplo n.º 8
0
def PAddDir(newDir, err, URL=None):
    """ Add a new FITS directory

    returns FITS disk number
    newDir   = new directory path
    err      = Python Obit Error/message stack
    URL      = URL if on a remote host (Only if using OTObit/ParselTongue)
    """
    ################################################################
    global FITSdisks, nFITS
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    retDisk = Obit.FITSAddDir(newDir, err.me)
    FITSdisks.append(newDir)
    nFITS = len(FITSdisks)
    #print "DEBUG nFITS",nFITS
    if err.isErr:
        OErr.printErrMsg(err, "Error adding FITS directory")
        # Update ObitTalk stuff
    try:
        FITS.FITS.disks.append(FITS.FITSDisk(URL, retDisk, newDir))
    except:
        pass
    else:
        pass
    return retDisk;
Exemplo n.º 9
0
    def __init__(self):
        """
        Constructor

        Largely derived from
        https://github.com/bill-cotton/Obit/blob/master/ObitSystem/Obit/share/scripts/AIPSSetup.py
        """

        # Get the current configuration
        cfg = kc.get_config()

        self.err = err = OErr.OErr()
        self.obitsys = OSystem.OSystem("Pipeline", 1, cfg['userno'], 0, [" "],
                                       0, [" "], True, False, err)
        OErr.printErrMsg(err, "Error starting Obit System")

        # Setup AIPS userno
        AIPS.userno = cfg['userno']

        # Setup Obit Environment
        ObitTalkUtil.SetEnviron(AIPS_ROOT=cfg['aipsroot'],
                                AIPS_VERSION=cfg['aipsversion'],
                                OBIT_EXEC=cfg['obitexec'],
                                DA00=cfg['da00'],
                                ARCH="LINUX",
                                aipsdirs=cfg['aipsdirs'],
                                fitsdirs=cfg['fitsdirs'])
Exemplo n.º 10
0
def PAddDir(newDir, err, URL=None):
    """
    Add a new FITS directory
    
    returns FITS disk number

    * newDir   = new directory path
    * err      = Python Obit Error/message stack
    * URL      = URL if on a remote host (Only if using OTObit/ParselTongue)
    """
    ################################################################
    global FITSdisks, nFITS
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"
    #
    retDisk = Obit.FITSAddDir(newDir, err.me)
    FITSdisks.append(newDir)
    nFITS = len(FITSdisks)
    #print "DEBUG nFITS",nFITS
    if err.isErr:
        OErr.printErrMsg(err, "Error adding FITS directory")
        # Update ObitTalk stuff
    try:
        FITS.FITS.disks.append(FITS.FITSDisk(URL, retDisk, newDir))
    except:
        pass
    else:
        pass
    return retDisk
Exemplo n.º 11
0
def PTableCCT2Spec (inImage, outImage, nTerm,
                    inCCVer, outCCVer, err, startCC=0, endCC=0):
    """ Convert an (tabulated) TSpec CC Table to spectral parameter table

    Output CC Table will have fitted spectra rather than tabulated spectra.
    Tabulated spectrum fitted with spectrum weighting by primary beam
    inImage   input Obit Python Image 1
              Must have freq axis type = "SPECLNMF"
              Optional parameters on List member:
                 "dropNeg" boolean if True drop negative components [True] 
                 "doPBCor" boolean if True Primary beam correct [False] 
    outImage  output Obit Python image must be type ObitImageWB
              This can be created by ImageUtil.PImageT2Spec
    nTerm     Number of output Spectral terms, 2=SI, 3=also curve.
    inCCVer   Input CCTable to convert, 0=> highest
    outCCVer  Output CCTable, 0=>1
    err       Python Obit Error/message stack
    startCC   First 1-rel component to convert
    endCC     Last 1-rel component to convert, 0=> all
    """
    ################################################################
    # Checks
    if not Image.PIsA(inImage):
        raise TypeError,"inImage MUST be a Python Obit Image"
    if not Image.PIsA(outImage):
        raise TypeError,"outImage MUST be a Python Obit Image"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    Obit.TableCCUtilT2Spec(inImage.me, outImage.me, nTerm, inCCVer, \
                           outCCVer, startCC, endCC, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error Converting CC Table")
Exemplo n.º 12
0
def PPutString (inList, name, dim, data, err):
    """ Add an string entry, error if conflict

    inList   = input Python InfoList
    name     = name of desired entry
    dim      = dimensionality of array as list, e.g. [1,1,1,1,1] for scalar
               MUST have 5 entries
    data     = data as a 1-D array of strings (rectangular char array)
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if data[0].__class__ != str:
        print "class is" , data[0].__class__
        raise TypeError,"data MUST be a string"
    if len(dim) < 5:
        raise RuntimeError,"dim has fewer then 5 entries"
    prod = 1
    for x in dim:
        if (x>0):
            prod = prod*x
    if prod < len(data):
         raise RuntimeError,"more data than defined in dim"
    # Call depends on whether single string, 1 or 2 D arrays
    if (dim[1]>1):    # array of strings
        Obit.InfoListPutString(inList.me, name, dim, data, err.me)
    else:             # single
        Obit.InfoListPutSString(inList.me, name, dim, data, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error adding entry")
Exemplo n.º 13
0
def PSetDir(disk, newName, err, URL=None):
    """
    Set the directory name for a given AIPS directory
    
    returns disk number actually used

    * disk     = AIPS disk number, <=0 => assign
    * newName  = new directory path
    * err      = Python Obit Error/message stack
    * URL      = URL if on a remote host (Only if using OTObit/ParselTongue)
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"
    #
    retDisk = Obit.AIPSSetDirname(disk, newName, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error setting AIPS directory name")
    AIPSdisks.append(newName)
    nAIPS = len(AIPSdisks)
    if (disk <= 0):
        try:
            AIPS.AIPS.disks.append(AIPS.AIPSDisk(URL, retDisk, newName))
        except:
            pass
        else:
            pass
    return retDisk
Exemplo n.º 14
0
def PNVSSFetch (RA, Dec, outfile, err, \
                Type = 'image/xfits', Equinox = '2000', \
                ObjName='unnamed', Size = '0.50 0.50', \
                Poltype = 'I', MAPROJ = 'SIN',
                rotate = 0.0, Cells=[15.,15.]):
    """ 
    Postage Stamp server for the NRAO/VLA Sky Survey (1.4 GHz)

    Fetch a postage stamp (AKA cutout) FITS image, jpeg or contour from the NVSS
    If a FITS file, returns an ObitImage object pointing to the result,
    otherwise the output file name
    If something goes wrong with the request or download, the output file
    will likely contain an HTML file explaining the results.
    Throws exception on error
    * RA      = Right Ascension as 'hh mm ss.sss'
    * Dec     = Declination as 'sdd mm ss.ss'
    * outfile = Name of the output file, absolute path or relative to CWD
                None => use name from server
    * err     = Python Obit Error/message stack
    * Type    = Type = "type" of result;
                'image/jpeg' = jpeg image,
                'application/octet-stream' = fits file
                'application/postscript' = contour plot (postscript)
                'image/x-fits' = fits image
                (default = /image/jpeg)
    * Equinox = coordinate equinox ('2000' or '1950')
    * ObjName = object name - used for labeling only (optional)
    * Size    = field size (RA,dec) in deg. (default 0.50 0.50)
    * Poltype = total intensity 'I' or 'IQU' (default 'I')
    * MAPROJ  = Map projection type: 'SIN', 'TAN', 'ARC', 'NCP',
                'GLS', 'MER', 'AIT','STG'
    * rotate  = Rotation on sky in deg in sense of from North to East
    * Cells   = pixel spacing in aseconds (default 15. 15.)
    """
    ################################################################
    # Package parameters
    query_args = {
        'Type': Type,
        'Equinox': Equinox,
        'ObjName': ObjName,
        'RA': RA,
        'Dec': Dec,
        'Size': Size,
        'Poltype': Poltype,
        'MAPROJ': MAPROJ,
        'rotate': str(rotate),
        'Cells': str(Cells[0]) + ' ' + str(Cells[1])
    }
    NVSSURL = "https://www.cv.nrao.edu/cgi-bin/postage.pl"
    # fetch
    PWebFetch(NVSSURL, query_args, outfile, err)
    # Get fits image if requested
    if (Type == 'image/x-fits') or (Type == 'application/octet-stream'):
        #print "Get FITS"
        outfits = Image.newPFImage(ObjName, outfile, 0, True, err)
        OErr.printErrMsg(err,
                         "Problem with FITS image, see contents of outfile")
    else:
        return outfile
    return outfits
Exemplo n.º 15
0
def VLAClearCal(uv, err, doGain=True, doBP=False, doFlag=False):
    """ Clear previous calibration

    Delete all SN tables, all CL but CL 1
    uv       = UV data object to clear
    err      = Obit error/message stack
    doGain   = If True, delete SN and CL tables
    doBP     = If True, delete BP tables
    doFlag   = If True, delete FG tables
    """
    ################################################################
    # Gain tables
    if doGain:
        uv.ZapTable("AIPS SN",-1,err)
        ver = uv.GetHighVer("AIPS CL")
        while (ver>1):
            uv.ZapTable ('AIPS CL', ver, err)
            ver = ver-1
    # Bandpass
    if doBP:
        uv.ZapTable("AIPS BP",-1,err)
    # Flag tables
    if doFlag:
        uv.ZapTable("AIPS FG",-1,err)
    OErr.printErrMsg(err, "VLAClearCal: Error reseting calibration")
Exemplo n.º 16
0
def PEdit (inHis, startr, endr, err):
    """
    Edit History
    
    Deletes a range of history records.
    return 0 on success, else failure

    * inHis    = input Python History
    * startr   = first (1-rel) history record to delete
    * endr     = highest (1-rel) history record to delete, 0=>to end
    * err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inHis):
        raise TypeError("inHis MUST be a History")
    if not OErr.OErrIsA(err):
        raise TypeError("err MUST be an OErr")
    #
    ret = POpen (inHis, READWRITE, err)
    ret = Obit.HistoryEdit(inHis.me, startr, endr, err.me)
    OErr.printErr(err)
    if err.isErr:
        OErr.printErrMsg(err, "Error Editing History")
    ret = PClose (inHis, err)
    return ret
Exemplo n.º 17
0
 def Histo(self, blc, trc, nbin, range, err):
     """ Computes histograms
     
     self     = object 
     blc      = BLC (1-rel) in image
     trc      = TRC (1-rel) in image
     nbin     = number of bins (should be odd)
     range    = range in units of Image RMS about 0
     err      = Obit error/message stack
     """
     ################################################################
     # Checks
     if not PIsA(self):
         raise TypeError("self MUST be a Python Obit PixHistFDR")
     # make sure blc, trc are long
     lblc = []
     ltrc = []
     for t in trc:
         ltrc.append(int(t))
     for t in blc:
         lblc.append(int(t))
     Obit.PixHistFDRHisto(self.me, lblc, ltrc, nbin, range, err.me)
     if err.isErr:
         OErr.printErrMsg(err, "Error creating PixHistFDR histogram")
     return
Exemplo n.º 18
0
def AllDest (err, disk=None, Atype="  ", Aname="            ", Aclass="      ", Aseq=0):
    """ Delete AIPS files matching a pattern

    Strings use AIPS wild cards:
        blank => any
        '?'   => one of any character
        "*"   => arbitrary string
    disk      = AIPS disk number, 0=>all
    Atype     = AIPS entry type, 'MA' or 'UV'; '  => all
    Aname     = desired AIPS name, using AIPS wildcards, None -> don't check
    Aclass    = desired AIPS class, using AIPS wildcards, None -> don't check
    Aseq      = desired AIPS sequence, 0=> any
    """
    ################################################################
    global Adisk
    if disk==None:
        disk = Adisk
    else:
        if disk>0:
            Adisk = disk
    # NO Confirm
    #prompt = "Do you really want to delete all AIPS "+Atype+" files on disk(s) "\
    #         +str(disk)+"\nwith names matching "+Aname+"."+Aclass+"."+str(Aseq)+ \
    #         " y/n "
    #ans = raw_input(prompt)
    #if ans.startswith('y'):
    AIPSDir.PAllDest (disk, err, Atype=Atype, Aname=Aname, Aclass=Aclass,
                      Aseq=Aseq)
    #else:
    #    print "Not confirmed"
    OErr.printErrMsg(err, "Error with destroying AIPS enreies")
Exemplo n.º 19
0
def PMakeImage (inUV, outImage, channel, doBeam, doWeight, err):
    """ Grids UV, FFTs and makes corrections for the gridding convolution.

    inUV     = Input Python uv data. Should be in form of Stokes to be imaged
               will all calibration and selection applied.
    outImage = Python Image to be written.  Must be previously instantiated.
               Beam normalization factor is written to output Beam
               infoList as SUMWTS
    channel  = Which frequency channel to image, 0->all.
    doBeam   = if TRUE also make beam.  Will make the myBeam member of outImage.
               If FALSE, and myGrid->BeamNorm 0.0 then reads SUMWTS value 
               from beam infolist
    doWeigh  = if TRUE Apply uniform weighting corrections to uvdata before imaging
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not UV.PIsA(inUV):
        raise TypeError,"inUV MUST be a Python Obit UV"
    if not Image.PIsA(outImage):
        print "Actually ",outImage.__class__
        raise TypeError,"outImage MUST be a Python Obit Image"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    Obit.ImageUtilMakeImage(inUV.me, outImage.me, channel, doBeam, doWeight, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error creating Image from UV data")
Exemplo n.º 20
0
def PReimage (inCleanVis, uvdata, err):
    """
    See if an image needs to be remade
    
    See if an image needs to be remade because a source which exceeds
    the flux  threshold is not centered (as determined by moments)
    on the reference pixel (within toler pixel).
    A new (96x96) field is added centered on the offending source and a negative
    clean window added to the position of the source in its original window.
    Avoid duplicates of the same source and ensure that all occurances of this 
    source in any exant field has a negative clean window added.
    Multiple centering sources per facet are allowed
    A boolean entry "autoCenField" with value True is added to the info member of any
    image members added to the mosaic member.

    * inCleanVis  = Python CleanVis object
    * uvdata      = Python uv data from which image is made
    * err         = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inCleanVis):
        raise TypeError,"inCleanVis MUST be a Python ObitCleanVis"
    if not UV.PIsA(uvdata):
        raise TypeError,"uvData MUST be a Python Obit UV"
    #
    out = Obit.CleanVisReimage(inCleanVis.me, uvdata.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error in Reimage")
    return out
Exemplo n.º 21
0
def PPBImage (pntImage, outImage, err,
              minGain=0.1, outPlane=[1,1,1,1,1], antSize=25.0):
    """ Calculate an image with a primary beam pattern

    Make an image of the antenna primary beam pattern based on the pointing
    position in an image.
    pntImage = Python Image giving pointing position (ObsRA, ObsDec)
    outImage = Python Image to be written.  Must be previously instantiated.
    err      = Python Obit Error/message stack
    minGain  = minimum allowed gain (lower values blanked).
    outPlane = 5 element int array with 1, rel. plane number [1,1,1,1,1]
               giving location of plane to be written
    antSize  = Antenna diameter assumed, default 25m
    """
    ################################################################
    # Checks
    if not Image.PIsA(pntImage):
        print "Actually ",pntImage.__class__
        raise TypeError,"pntImage MUST be a Python Obit Image"
    if not Image.PIsA(outImage):
        print "Actually ",outImage.__class__
        raise TypeError,"outImage MUST be a Python Obit Image"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    if len(outPlane) != 5:
        raise TypeError,"outPlane must have 5 elements"
    #
    Obit.ImageUtilPBImage(outImage.me, outImage.me,
                          outPlane, antSize, minGain, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error with primary beam image")
Exemplo n.º 22
0
def PInterpolateImage (inImage, outImage, err, 
                       inPlane=[1,1,1,1,1], outPlane=[1,1,1,1,1], hwidth=2):
    """ Interpolates one image onto another's grid.

    Pixels in outImage are interpolated from inImage
    inImage  = Input Python Image.
    outImage = Python Image to be written.  Must be previously instantiated.
    err      = Python Obit Error/message stack
    inPlane  = 5 element int array with 1, rel. plane number [1,1,1,1,1]
               giving location of plane to be interpolated
    outPlane = 5 element int array with 1, rel. plane number [1,1,1,1,1]
               giving location of plane to be written
    hwidth   = half width of interpolation kernal [1-4] default 2
    """
    ################################################################
    # Checks
    if not Image.PIsA(inImage):
        raise TypeError,"inImage MUST be a Python Obit Image"
    if not Image.PIsA(outImage):
        print "Actually ",outImage.__class__
        raise TypeError,"outImage MUST be a Python Obit Image"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    if len(inPlane) != 5:
        raise TypeError,"inPlane must have 5 elements"
    if len(outPlane) != 5:
        raise TypeError,"outPlane must have 5 elements"
    #
    Obit.ImageUtilInterpolateImage(inImage.me, outImage.me,
                                   inPlane, outPlane, hwidth, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error interpolating Image")
Exemplo n.º 23
0
def GetFreqArr(inUV, err, inc = 1):
    """
    Get Array of channel frequencies in data
    
    Return list of channel Frequencies (Hz)
    * inUV     = Obit UV data with tables
    * err      = Python Obit Error/message stack
    * inc      = increment in channel
    """
    ################################################################
    # Checks
    if not UV.PIsA(inUV):
        print("Actually ",inUV.__class__)
        raise TypeError("inUV MUST be a Python Obit UV")
    d = inUV.Desc.Dict # UV data descriptor dictionary
    refFreq = d["crval"][ d["jlocf"]]    # reference frequency
    nchan   = d["inaxes"][ d["jlocf"]]   # Number of channels per IF
    nif     = d["inaxes"][ d["jlocif"]]  # Number of IFs
    chwid   = abs(d["cdelt"][ d["jlocf"]]) # channel width from header
    fqtab = inUV.NewTable(Table.READONLY,"AIPS FQ",1,err)
    fqtab.Open(Table.READONLY,err)
    fqrow = fqtab.ReadRow(1, err)   # Only bother with first
    OErr.printErrMsg(err) # catch table errors
    IFfreq   = fqrow['IF FREQ']     # IF offset
    ChWidth  = fqrow['CH WIDTH']    # IF channel width
    sideband = fqrow['SIDEBAND']    # IF sizeband, 1=USB, -1=LSB
    freqs = []
    for iif in range(0,nif):
        for ifq in range(0,nchan,inc):
            frq =  refFreq + IFfreq[iif] + sideband[iif] * ifq * min (chwid, ChWidth[iif])
            freqs.append(frq)
    # End loops
    return freqs
Exemplo n.º 24
0
def PInfo(disk, user, cno, err):
    """
    Get information for a  AIPS catalog slot number
    
    Returned string s:
        ======  =============
        Aname   s[0:12]
        Aclass  s[13:19]
        Aseq    int(s[20:25])
        Atype   s[26:28]
        ======  =============
    
    returns string describing entry, None=>empty

    * disk     = AIPS disk number
    * user     = AIPS user number
    * cno      = AIPS catalog slot to deassign
    * err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"
    #
    ret = Obit.AIPSDirInfo(disk, user, cno, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error reading AIPS catalog header")
    return ret
Exemplo n.º 25
0
def CreateSU(inUV, outUV, err):
    """
    Write data in meta to SU table
    
    * inUV       = list of input Obit UV objects (freq order)
    * outUV       = output Obit UV object, defined but not instantiated
    * err         = Obit error/message stack
    """
    ###############################################################
    # Create SU table
    idd = inUV.Desc.Dict  # Info from input header
    nIF = idd["inaxes"][idd["jlocif"]]  # how many IFs
    sutab = outUV.NewTable(Table.READWRITE, "AIPS SU", 1, err, numIF=nIF)
    if err.isErr:
        OErr.printErrMsg(err, "Error with SU table")
    sutab.Open(Table.READWRITE, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error opening SU table")
    # Update header
    sutab.keys['RefDate'] = idd["obsdat"]
    sutab.keys['Freq'] = idd["crval"][idd["jlocf"]]
    Table.PDirty(sutab)  # Force update
    row = sutab.ReadRow(1, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error reading SU table")
    irow = 1
    IFZero = []  #  Array of NIF zeroes
    for i in range(0, nIF):
        IFZero.append(0.0)

    row['ID. NO.'] = [1]
    row['SOURCE'] = [idd["object"]]
    row['RAEPO'] = [idd["crval"][idd["jlocr"]]]
    row['DECEPO'] = [idd["crval"][idd["jlocd"]]]
    row['RAOBS'] = [idd["obsra"]]
    row['DECOBS'] = [idd["obsdec"]]
    row['EPOCH'] = [idd["equinox"]]
    row['RAAPP'] = [0.0]
    row['DECAPP'] = [0.0]
    row['BANDWIDTH'] = [idd["cdelt"][idd["jlocf"]]]
    row['Table name'] = 'AIPS SU'
    row['IFLUX'] = IFZero
    row['QFLUX'] = IFZero
    row['UFLUX'] = IFZero
    row['VFLUX'] = IFZero
    row['FREQOFF'] = IFZero
    row['RESTFREQ'] = IFZero
    row['LSRVEL'] = IFZero
    row['CALCODE'] = ['    ']
    row['NumFields'] = 22
    row['QUAL'] = [0]
    row['PMRA'] = [0.0]
    row['PMDEC'] = [0.0]
    row['_status'] = [1]
    sutab.WriteRow(irow, row, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error writing SU table")
    sutab.Close(err)
    if err.isErr:
        OErr.printErrMsg(err, "Error closing SU table")
Exemplo n.º 26
0
def PSubArr(inFA, blc, trc, err):
    """  
    Return a slice of an FArray
    
    returns Slice in FArray
    
    * inFA = input Python FArray
    * blc  = array giving (1-rel) lower index of first cell to copy, e.g. [1,1]
    * trc  = array giving (1-rel) highest index of first cell to copy
    * err  = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inFA):
        print("Actually ", inFA.__class__)
        raise TypeError("inFA MUST be a Python Obit FArray")
    lblc = []
    ltrc = []  # Make sure blc,trc are long
    for b in blc:
        lblc.append(int(b))
    for b in trc:
        ltrc.append(int(b))
    outFA = FArray("None")
    outFA.me = Obit.FArraySubArr(inFA.me, lblc, ltrc, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error slicing FArray")
    return outFA
Exemplo n.º 27
0
def POverlap (inID1, inID2, err):
    """
    Determine if there is any overlap between images
    
    Compares ImageDesc objects to see if the associated
    images overlap on the sky.
    Returns True if so sles False

    * inID1   = First Python Obit ImageDesc for test
    * inID2   = Second Python Obit ImageDesc for test
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inID1):
        raise TypeError,"inID1 MUST be a Python Obit ImageDesc"
    if not PIsA(inID2):
        raise TypeError,"inID2 MUST be a Python Obit ImageDesc"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    res = Obit.ImageDescOverlap (inID1.me, inID2.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error determining overlap")
    return res!=0
Exemplo n.º 28
0
def PMakeImage(inUV, outImage, channel, doBeam, doWeight, err):
    """
    Grids UV, FFTs and makes corrections for the gridding convolution.

    * inUV     = Input Python uv data. Should be in form of Stokes to be imaged
      will all calibration and selection applied.
    * outImage = Python Image to be written.  Must be previously instantiated.
      Beam normalization factor is written to output Beam infoList as SUMWTS
    * channel  = Which frequency channel to image, 0->all.
    * doBeam   = if TRUE also make beam.  Will make the myBeam member of outImage.
      If FALSE, and myGrid->BeamNorm 0.0 then reads SUMWTS value from beam infolist
    * doWeigh  = if TRUE Apply uniform weighting corrections to uvdata before imaging
    * err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not UV.PIsA(inUV):
        raise TypeError("inUV MUST be a Python Obit UV")
    if not Image.PIsA(outImage):
        print("Actually ", outImage.__class__)
        raise TypeError("outImage MUST be a Python Obit Image")
    if not err.IsA():
        raise TypeError("err MUST be an OErr")
    #
    Obit.ImageUtilMakeImage(inUV.me, outImage.me, channel, doBeam, doWeight,
                            err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error creating Image from UV data")
Exemplo n.º 29
0
    def ZapTable(self, tabType, tabVer, err):
        """
        Destroy specified table
        
        Returns 0 on success

        * self      = Python OData object
        * tabType   = Table type, e.g. "AIPS CC"
        * tabVer    = table version, integer
        * err       = Python Obit Error/message stack
        """
        inOData = self
        # Checks
        if not self.ODataIsA():
            raise TypeError, "input MUST be a Python Obit OData"
        if not OErr.OErrIsA(err):
            raise TypeError, "err MUST be an OErr"
        #
        # Open/Close to (re)Read header to be sure it's up to date
        inOData.Open(READONLY, err)
        inOData.Close(err)

        # delete table
        ret = Obit.ODataZapTable(inOData.cast(myClass), tabType, tabVer,
                                 err.me)
        if err.isErr:
            OErr.printErrMsg(err, "Error Zapping OData data Table")
        # Update header
        inOData.UpdateTables(err)
        return ret
Exemplo n.º 30
0
def PTableCCFixTSpec (inImage, inCCVer, refFreq, nTerm, terms, \
                      err, startCC=1, endCC=0, ):
    """ Convert an (tabulated) TSpec CC Table to spectral parameter table

    Output CC Table will have fitted spectra rather than tabulated spectra.
    Tabulated spectrum fitted with spectrum weighting by primary beam
    inImage   input Obit Python Image 1
              Must have freq axis type = "SPECLNMF"
    inCCVer   CCTable to modify, 0=> highest
    refFreq   Reference frequency for spectrum (Hz)
    nTerm     Number of terms in spectrum
    err       Python Obit Error/message stack
    startCC   First 1-rel component to consider
    endCC     Last 1-rel component to consider, 0=> all
    """
    ################################################################
    # Checks
    if not Image.PIsA(inImage):
        raise TypeError("inImage MUST be a Python Obit Image")
    if not err.IsA():
        raise TypeError("err MUST be an OErr")
    #
    Obit.TableCCUtilFixTSpec(inImage.me, inCCVer, refFreq, nTerm, terms, \
                             startCC, endCC, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error Modifying CC Table")
Exemplo n.º 31
0
def GetTargetPos(OTF, Target, err):
    """ Get target position from OTFTarget table

    return [raepo, decepo] in deg
    Loop through target table on OTF looking for Target and return position
    
    OTF      = OTF data file to check
    Target   = Name of target e.g. "MARS"
    """
    ################################################################
    # Checks
    if not OTF.OTFIsA():
        raise TypeError, "OTF MUST be a Python Obit OTF"
    if type(Target) != str:
        raise TypeError, "Target MUST be a string"
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"

    tarTab = OTF.NewTable(Table.READONLY, "OTFTarget", 1, err)
    tarTab.Open(Table.READONLY, err)
    OErr.printErrMsg(err, "Error with OTFTarget table")
    norow = tarTab.Desc.Dict["nrow"]
    for irow in range(1, norow + 1):
        row = tarTab.ReadRow(irow, err)
        if row["TARGET"][0].strip() == Target.strip():
            out = [row["RAEPO"][0], row["DECEPO"][0]]
            tarTab.Close(err)
            return out

    tarTab.Close(err)
    # Didn't find it if it gets here
    OErr.printErrMsg(err, "Error getting Target")
    raise RuntimeError, "Failed to find target " + Target + " in OTFTarget on " + OTF.GetName(
    )
    return [None, None]
Exemplo n.º 32
0
def PGetPos (inID, inPixel, err):
    """
    Return position of pixel inPixel in inID
    
    returns array of 2 floats giving (RA, Dec) in deg of pixel inPixel

    * inID    = Python Obit ImageDesc for input
    * inPixel = array of floats giving position in image described by inID
      only first 2 used.
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inID):
        raise TypeError,"inID MUST be a Python Obit ImageDesc"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    if inPixel[0].__class__ != float:
        print "class is" , inPixel[0].__class__
        raise TypeError,"inPixel MUST be float"
    if len(inPixel) < 2:
        raise RuntimeError,"inPixel has fewer then 2 entries"
    #
    outTmp = Obit.ImageDescGetPos (inID.me, inPixel, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error converting pixel location to position")
    out = outTmp[0:2]
    return out
Exemplo n.º 33
0
def UpdateDescriptor(outUV, meta, err):
    """
    Update information in data descriptor

    NB: Cannot change geometry of visibilities
    * outUV    = Obit UV object
    * meta     = dict with data meta data
    * err      = Python Obit Error/message stack to init
    """
    ################################################################
    chinc = meta["spw"][0][2]  # Frequency increment
    reffreq = meta["spw"][0][1]  # reference frequency
    nchan = meta["spw"][0][0]  # number of channels
    nif = len(meta["spw"])  # Number of IFs
    nstok = meta["nstokes"]  # Number of Stokes products
    desc = outUV.Desc.Dict
    outUV.Desc.Dict = desc
    desc['obsdat'] = meta["obsdate"]
    desc['observer'] = meta["observer"]
    desc['JDObs'] = UVDesc.PDate2JD(meta["obsdate"])
    desc['naxis'] = 6
    desc['inaxes'] = [3, nstok, nchan, nif, 1, 1, 0]
    desc['cdelt'] = [1.0, -1.0, chinc, 1.0, 0.0, 0.0, 0.0]
    desc['crval'] = [1.0, -5.0, reffreq, 1.0, 0.0, 0.0, 0.0]
    desc['crota'] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    outUV.Desc.Dict = desc
    outUV.UpdateDesc(err)
    if err.isErr:
        OErr.printErrMsg(err, "Error updating UV descriptor")
Exemplo n.º 34
0
Arquivo: VLACal.py Projeto: mauch/Obit
def VLAClearCal(uv, err, doGain=True, doBP=False, doFlag=False):
    """ Clear previous calibration

    Delete all SN tables, all CL but CL 1
    uv       = UV data object to clear
    err      = Obit error/message stack
    doGain   = If True, delete SN and CL tables
    doBP     = If True, delete BP tables
    doFlag   = If True, delete FG tables
    """
    ################################################################
    # Gain tables
    if doGain:
        uv.ZapTable("AIPS SN", -1, err)
        ver = uv.GetHighVer("AIPS CL")
        while (ver > 1):
            uv.ZapTable('AIPS CL', ver, err)
            ver = ver - 1
    # Bandpass
    if doBP:
        uv.ZapTable("AIPS BP", -1, err)
    # Flag tables
    if doFlag:
        uv.ZapTable("AIPS FG", -1, err)
    OErr.printErrMsg(err, "VLAClearCal: Error reseting calibration")
Exemplo n.º 35
0
def PUVImage(InImager,
             err,
             field=0,
             doWeight=False,
             doBeam=True,
             doFlatten=False):
    """ Form image optionally doing the calibration/weighting and flatten stages

    UV Data is imaged to form dirty beam. Control parameters are those on UV data
    passed at UVImager creation.
    InImager  = UVImager object
    field     = field number (1-rel) to image, 0=> all
    err       = Python Obit Error/message stack
    doWeight  = Do weighting (Uniform, tapering,...) before imaging
                If True then input data is modified.
    doBeam    = Make Beam before image, must be done once.
    doFlatten = Flatten image mosaic onto single image
    """
    ################################################################
    #
    # Checks
    if not PIsA(InImager):
        print "input class actually ", InImager.__class__
        raise TypeError, 'PUVImage: Bad input UVImager'

    #
    Obit.UVImagerImage(InImager.me, field, doWeight, doBeam, doFlatten, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error Imaging data")
Exemplo n.º 36
0
 def _verify(self, desc):
     # Initialize Obit if needed
     if not OSystem.PIsInit() and desc:
         AIPSdirs = desc["dirs"]
         userno   = desc["userno"]
         popsno   = 1
         if not self.err:
             self.err=OErr.OErr()
         self.ObitSys=OSystem.OSystem ("", popsno, userno, \
                                       len(AIPSdirs), AIPSdirs, \
                                       0, [], True, False, self.err)
         OErr.printErrMsg(self.err, "Error with Obit startup")
         self.doInit = True
     else:
         self.doInit = False
     try:
         data = self._init(desc)
     except OErr.OErr as err:
         print(err)
         #OErr.printErrMsg(err, "AIPSData._verify")
         if self.doInit:   # Initialized Obit?
             OSystem.Shutdown(self.ObitSys)
         raise RuntimeError("Cannot open data set %s" % desc['name'])
     #OErr.printErrMsg(self.err, "AIPSData._verify")
     return data
Exemplo n.º 37
0
def PWebFetch(url, args, outfile, err):
    """ 
    Generic Fetch a web product

    Sends a http post request to url and sames response to outfile
    Throws exception on error
    * url     = where the request to be sent,
                e.g."https://www.cv.nrao.edu/cgi-bin/postage.pl"
    * args    = dict or arguments, e.g. {"arg1":"arg1"}
    * outfile = Name of the output file, absolute path or relative to CWD
                None => use name from server
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Package parameters
    encoded_args = six.moves.urllib.parse.urlencode(args)
    NVSShost = "https://www.cv.nrao.edu/cgi-bin/postage.pl"
    # fetch
    try:
        request = six.moves.urllib.request.Request(url)
        response = six.moves.urllib.request.urlopen(request, encoded_args)
        data = response.read()
    except Exception as exception:
        print(exception)
        OErr.PLog(err, OErr.Error, "Request from server failed")
        OErr.printErrMsg(err)
    if outfile == None:  # Name from server?
        outfile = os.path.basename(response.headers['URI'])
    fd = open(outfile, "wb")
    fd.write(data)
    fd.close()
    # Info
    print("Response code =", response.code, response.msg)
    print("Response type =", response.headers["Content-Type"])
Exemplo n.º 38
0
def PSetDir(disk, newName, err, URL=None):
    """ Set the directory name for a given AIPS directory

    returns disk number actually used
    disk     = AIPS disk number, <=0 => assign
    newName  = new directory path
    err      = Python Obit Error/message stack
    URL      = URL if on a remote host (Only if using OTObit/ParselTongue)
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    retDisk = Obit.AIPSSetDirname(disk, newName, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error setting AIPS directory name")
    AIPSdisks.append(newName)
    nAIPS = len(AIPSdisks)
    if (disk<=0):
        try:
            AIPS.AIPS.disks.append(AIPS.AIPSDisk(URL, retDisk, newName))
        except:
            pass
        else:
            pass
    return retDisk;
Exemplo n.º 39
0
def PSelInc(inFA, outFA, blc, trc, inc, err):
    """  
Select elements in an FArray by increment

* inFA = input Python FArray
* outFA= output Python FArray
* blc  = array giving (1-rel) lower index of first cell to copy, e.g. [1,1]
* trc  = array giving (1-rel) highest index of first cell to copy
* inc  = increment on each axis
* err  = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inFA):
        print("Actually ", inFA.__class__)
        raise TypeError("inFA MUST be a Python Obit FArray")
    if not PIsA(outFA):
        print("Actually ", outFA.__class__)
        raise TypeError("outFA MUST be a Python Obit FArray")
    lblc = []
    ltrc = []
    linc = []  # Make sure blc,trc,inc are long
    for b in blc:
        lblc.append(int(b))
    for b in trc:
        ltrc.append(int(b))
    for b in inc:
        ltrc.append(int(b))
    Obit.FArraySelInc(inFA.me, outFA.me, lblc, ltrc, linc, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error selecting FArray")
    return
Exemplo n.º 40
0
def PAllDest(disk, err, Atype="  ", Aname=None, Aclass=None, Aseq=0):
    """
    Delete selected AIPS catalog entries
    
    Entries can be selected using Atype, Aname, Aclass, Aseq,
    using AIPS wildcards
    A "?" matches one of any character, "*" matches any string
    all blanks matches anything

    * disk     = AIPS disk number, 0=>all
    * err      = Python Obit Error/message stack
    * type     = optional file type
    * Aname    = desired name, using AIPS wildcards, None -> don't check
    * Aclass   = desired class, using AIPS wildcards, None -> don't check
    * Aseq     = desired sequence, 0=> any
    * first    = optional first slot number (1-rel)
    * last     = optional last slot number
    * giveList = If true, return list of CNOs matching
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"
    #
    if (disk < 0) or (disk > (len(AIPS.AIPS.disks) + 1)):
        raise RuntimeError, "Disk " + str(disk) + " out of range"
    # disks
    if disk > 0:
        disks = [disk]
    else:
        disks = range(1, len(AIPS.AIPS.disks))
    user = OSystem.PGetAIPSuser()
    # loop over disks
    for dsk in disks:
        ncno = PNumber(dsk, user, err)
        OErr.printErrMsg(err, "Error getting number of cnos")

        for cno in range(1, ncno):
            line = PInfo(dsk, user, cno, err)
            OErr.printErrMsg(err, "Error reading entry")
            if WantDir(line, type=Atype, Aname=Aname, Aclass=Aclass,
                       Aseq=Aseq):
                # parse directory string
                Tname = line[0:12]
                Tclass = line[13:19]
                Tseq = int(line[20:25])
                Ttype = line[26:28]
                z = None
                if Ttype == 'MA':
                    z = Image.newPAImage("Zap image", Tname, Tclass, dsk, Tseq, True, err, \
                               verbose=False)
                    print "Zap AIPS Image", Tname, Tclass, dsk, Tseq
                elif Ttype == 'UV':
                    z = UV.newPAUV("Zap UV data", Tname, Tclass, dsk, Tseq, True, err, \
                                   verbose=False)
                    print "Zap AIPS UV", Tname, Tclass, dsk, Tseq
                # Delete entry
                if z:
                    z.Zap(err)
                    del z
Exemplo n.º 41
0
    def CopyTables(self, outOData, exclude, include, err):
        """
        Copy Tables from one OData to another

        * self      = Python OData object
        * outOData     = Output Python OData object, must be defined
        * exclude   = list of table types to exclude (list of strings)
          has priority
        * include   = list of table types to include (list of strings)
        * err       = Python Obit Error/message stack
        """
        ################################################################
        # Checks
        if not self.ODataIsA():
            raise TypeError, "self MUST be a Python Obit OData"
        if not outOData.ODataIsA():
            raise TypeError, "outOData MUST be a Python Obit OData"
        if not OErr.OErrIsA(err):
            raise TypeError, "err MUST be an OErr"
        #
        ret = Obit.ODataCopyTables  (self.cast(myClass), outOData.cast(myClass), \
                                     exclude, include, err.me)
        if err.isErr:
            OErr.printErrMsg(err, "Error copying Tables")
        return ret
Exemplo n.º 42
0
def PGetPixel (inID, inPos, err):
    """
    Return pixel location in inID corresponding position inPos
    
    returns array of 2 floats giving pixel position in outID.

    * inID    = Python Obit ImageDesc for input
    * inPos   = array of floats (RA, dec) in deg
    * err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inID):
        raise TypeError,"inID MUST be a Python Obit ImageDesc"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    if inPos[0].__class__ != float:
        print "class is" , inPos[0].__class__
        raise TypeError,"inPos MUST be float"
    if len(inPos) < 2:
        raise RuntimeError,"inPos has fewer then 2 entries"
    #
    outTmp = Obit.ImageDescGetPixel (inID.me, inPos, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error determining pixel")
    out = outTmp[0:2]
    return out
Exemplo n.º 43
0
def PAllDest(disk, err, Atype = "  ",  Aname=None, Aclass=None, Aseq=0):
    """ Delete selected AIPS catalog entries

    Entries can be selected using Atype, Aname, Aclass, Aseq,
    using AIPS wildcards
    A "?" matches one of any character, "*" matches any string
    all blanks matches anything
    disk     = AIPS disk number, 0=>all
    err      = Python Obit Error/message stack
    type     = optional file type
    Aname    = desired name, using AIPS wildcards, None -> don't check
    Aclass   = desired class, using AIPS wildcards, None -> don't check
    Aseq     = desired sequence, 0=> any
    first    = optional first slot number (1-rel)
    last     = optional last slot number
    giveList = If true, return list of CNOs matching
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    if (disk<0) or (disk>(len(AIPS.AIPS.disks)+1)):
        raise RuntimeError,"Disk "+str(disk)+" out of range"
    # disks
    if disk>0:
        disks=[disk]
    else:
        disks= range(1,len(AIPS.AIPS.disks))
    user = OSystem.PGetAIPSuser()
    # loop over disks
    for dsk in disks:
        ncno = PNumber (dsk, user, err)
        OErr.printErrMsg(err, "Error getting number of cnos")
        
        for cno in range(1, ncno):
            line=PInfo(dsk, user, cno, err);
            OErr.printErrMsg(err, "Error reading entry")
            if WantDir(line, type=Atype, Aname=Aname, Aclass=Aclass,
                       Aseq=Aseq):
                # parse directory string
                Tname = line[0:12]
                Tclass = line[13:19]
                Tseq = int(line[20:25])
                Ttype = line[26:28]
                z = None
                if Ttype == 'MA':
                    z = Image.newPAImage("Zap image", Tname, Tclass, dsk, Tseq, True, err, \
                               verbose=False)
                    print "Zap AIPS Image",Tname, Tclass, dsk, Tseq
                elif Ttype == 'UV':
                    z = UV.newPAUV("Zap UV data", Tname, Tclass, dsk, Tseq, True, err, \
                                   verbose=False)
                    print "Zap AIPS UV",Tname, Tclass, dsk, Tseq
                # Delete entry
                if z:
                    z.Zap(err)
                    del z
Exemplo n.º 44
0
def PFit (inImageFit, err, input=FitInput):
    """ Fit a model to an image

    Resultant model left in FitRegion reg
    inImageFit = Python ImageFit object
    image      = ObitImage to be fitted
    reg        = Fit region defining what is to be fitted and initial guess
    err        = Python Obit Error/message stack
    input      = input parameter dictionary
    
    Input dictionary entries:
    fitImage    = Image to be fitted
    fitRegion   = FitRegion to be fitted
    MaxIter  int Maximum number of iterations [def. 10 per fitted parameter]
    prtLv    int Message level, 0=>none [def 0]
    PosGuard float Distance (cells) from edge to allow center  [def no bound]
    FluxLow  float Lower bounds on Flux density [def no bound]
    GMajUp   float Major axis upper bound (cells) [def no bound]
    GMajLow  float Major axis lower bound (cells) [def no bound]
    GMinUp   float Minor axis upper bound (cells) [def no bound]
    GMinLow  float Minor axis lower bound (cells) [def no bound]
    """
    ################################################################
    # Get input parameters
    fitImage   = input["fitImage"]
    fitRegion  = input["fitRegion"]
    # Checks
    if not PIsA(inImageFit):
        raise TypeError,"inImageFit MUST be a Python Obit ImageFit"
    if not Image.PIsA(fitImage):
        raise TypeError,"fitImage MUST be a Python Obit Image"
    if not FitRegion.PIsA(fitRegion):
        raise TypeError,"fitRegion MUST be a Python Obit FitRegion"
    #
    dim = [1,1,1,1,1]
    #
    # Set control values on ImageFit
    inInfo = PGetList(inImageFit)    # 
    InfoList.PAlwaysPutInt    (inInfo, "MaxIter",  dim, [input["MaxIter"]])
    InfoList.PAlwaysPutInt    (inInfo, "prtLv",    dim, [input["prtLv"]])
    InfoList.PAlwaysPutDouble (inInfo, "PosGuard", dim, [input["PosGuard"]])
    InfoList.PAlwaysPutDouble (inInfo, "FluxLow",  dim, [input["FluxLow"]])
    InfoList.PAlwaysPutDouble (inInfo, "GMajUp",   dim, [input["GMajUp"]])
    InfoList.PAlwaysPutDouble (inInfo, "GMajLow",  dim, [input["GMajLow"]])
    InfoList.PAlwaysPutDouble (inInfo, "GMinUp",   dim, [input["GMinUp"]])
    InfoList.PAlwaysPutDouble (inInfo, "GMinLow",  dim, [input["GMinLow"]])
    #
    # Do operation
    sm = inImageFit.cast(myClass)  # cast pointer
    ret = Obit.ImageFitFit(sm, fitImage.me, fitRegion.me, err.me)
    if ret==0:
        print "Fit converged"
    else:
        print "Fit hit iteration limit"
    if err.isErr:
        OErr.printErrMsg(err, "Error Fitting model")
Exemplo n.º 45
0
def AUcat(disk=Adisk, first=1, last=1000):
    """ Catalog listing of AIPS UV data files on disk disk

    disk      = AIPS disk number to list
    first     = lowest slot number to list
    last      = highest slot number to list
    """
    ################################################################
    Adisk = disk
    AIPSDir.PListDir(disk, err, type=AIPSDir.UVType, first=first, last=last)
    OErr.printErrMsg(err, "Error with AIPS catalog")
Exemplo n.º 46
0
def Acat(disk=Adisk, first=1, last=1000):
    """ Catalog listing of AIPS files on disk disk

    The class remembers the last disk accessed
    disk      = AIPS disk number to list
    first     = lowest slot number to list
    last      =highest slot number to list
    """
    ################################################################
    Adisk = disk
    AIPSDir.PListDir(disk, err, first=first, last=last)
    OErr.printErrMsg(err, "Error with AIPS catalog")
Exemplo n.º 47
0
def PUVWeight (InImager, err, input=UVWeightInput):
    """ Apply any calibration/editing/selection and do UV weighting

    UV Data is calibrated and weighted, values in input override those given
    when the UVImage was created.  This operation is optionally done in PUVImage.
    err     = Python Obit Error/message stack
    input   = input parameter dictionary
    
    Input dictionary entries:
    InImager   = Input Python UVImager to image
    Robust   = Briggs robust parameter. (AIPS definition)
    UVTaper  = UV plane taper, sigma in klambda,deg as [maj, min, pa]
    WtSize   = Size of weighting grid in cells [same as image nx]
    WtBox    = Size of weighting box in cells [def 1]
    WtFunc   = Weighting convolution function [def. 1]
               1=Pill box, 2=linear, 3=exponential, 4=Gaussian
               if positive, function is of radius, negative in u and v.
    WtPower  = Power to raise weights to.  [def = 1.0]
               Note: a power of 0.0 sets all the output weights to 1 as modified
               by uniform/Tapering weighting.
               Applied in determinng weights as well as after.
    Channel  = Channel (1-rel) number to image, 0-> all.
    """
    ################################################################
    # Get input parameters
    Channel  = input["Channel"]
    WtSize   = input["WtSize"]
    #
    # Checks
    if not PIsA(InImager):
        raise TypeError, 'PUVWeight: Bad input UVImager'

    # Set control values on UV 
    dim[0] = 1; dim[1] = 1; dim[2] = 1; dim[3] = 1; dim[4] = 1
    inInfo = UV.PGetList(PGetUV(InImager))
    InfoList.PAlwaysPutFloat  (inInfo, "Robust", dim, [input["Robust"]])
    InfoList.PAlwaysPutInt    (inInfo, "WtBox",  dim, [input["WtBox"]])
    InfoList.PAlwaysPutInt    (inInfo, "WtFunc", dim, [input["WtFunc"]])
    InfoList.PAlwaysPutFloat  (inInfo, "WtPower",dim, [input["WtPower"]])
    dim[1] = len(input["UVTaper"])
    InfoList.PAlwaysPutFloat  (inInfo, "Taper",  dim, input["UVTaper"])
    if (WtSize>0):
        print "WtSize", WtSize
        # Change name for C routine.
        dim[0] = 1;
        InfoList.PAlwaysPutInt  (inInfo, "nuGrid",  dim, [WtSize])
        InfoList.PAlwaysPutInt  (inInfo, "nvGrid",  dim, [WtSize])
    #
    Obit.UVImagerWeight (InImager.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error weighting UV data")
Exemplo n.º 48
0
def PZap (inHis, err):
    """ Destroy the persistent form of a History

    inHis    = input Python Obit History
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inHis):
        raise TypeError,"inHis MUST be a History"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    Obit.HistoryZap (inHis.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error deleting History")
Exemplo n.º 49
0
def PNumber(disk, user, err):
    """ Return highest current allowed AIPS catalog Slot number

    disk     = AIPS disk number
    user     = AIPS user number
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    ret = Obit.AIPSDirNumber(disk, user, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error obtaining highest AIPS catalog number")
    return ret
Exemplo n.º 50
0
def PRestore (clean, err):
    """ Restore subtracted CLEAN components to residual image

    clean     = Clean object containing mosaic
    err       = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(clean):
        raise TypeError,"mosaic MUST be a Python Obit CleanImage"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    Obit.CleanImageRestore(clean.me,  err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error defining window")
Exemplo n.º 51
0
def PGetMosaic (InImager, err):
    """ Return the member ImageMosaic

    returns ImageMosaic
    InImager  = Python ImageMosaic object
    err       = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(InImager):
        raise TypeError,"InImager MUST be a Python Obit UVImager"
    #
    out    = ImageMosaic.ImageMosaic("None", 1)
    out.me = Obit.UVImagerGetMosaic(InImager.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error obtaining Mosaic member")
    return out
Exemplo n.º 52
0
def PCopy (inFA, err):
    """  Make copy an FArray

    returns copy
    inFA = input Python FArray
    err  = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inFA):
        print "Actually ",inFA.__class__
        raise TypeError,"inFA MUST be a Python Obit FArray"
    outFA = FArray("None")
    outFA.me = Obit.FArrayCopy (inFA.me, outFA.me, err.me);
    if err.isErr:
        OErr.printErrMsg(err, "Error copying FArray")
    return outFA
Exemplo n.º 53
0
def PClone (inFA, err):
    """  Make copy the structure of an FArray

    Zero fill and return FArray with same structure as in
    inFA  = input Python FArray
    err  = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inFA):
        print "Actually ",inFA.__class__
        raise TypeError,"inFA MUST be a Python Obit FArray"
    outFA = FArray("Clone")
    Obit.FArrayClone (inFA.me, outFA.me, err.me);
    if err.isErr:
        OErr.printErrMsg(err, "Error zero cloning FArray")
    return outFA
Exemplo n.º 54
0
def PRemove(disk, user, cno, err):
    """ Deallocate AIPS catalog slot number

    disk     = AIPS disk number
    user     = AIPS user number
    cno      = AIPS catalog slot to deassign
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    ret = Obit.AIPSDirRemoveEntry(disk, user, cno, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error removing AIPS catalog entry")
    return ret
Exemplo n.º 55
0
def PDump(infile, list, err):
    """ Dump list to text file

    Dump parameter format text file and copy to list
    returns  0 on success, else 1
    outfile  = Name of the output text file to write
    list     = ObitInfoList to dump
    err      = ObitErr for reporting errors.
    """
    ################################################################
    # Checks
    if not InfoList.PIsA(list):
        raise TypeError,"list MUST be a Python Obit InfoList"
    ret = Obit.Dump(infile, list.me, err.me)
    if ret or err.isErr:
        OErr.printErrMsg(err, "Error Dumping to "+infile)
    return ret
Exemplo n.º 56
0
def PClose (inHis, err):
    """ Close History

    return 0 on success, else failure
    inHis    = input Python History
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inHis):
        raise TypeError,"inHis MUST be a History"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    ret = Obit.HistoryClose(inHis.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error closing History")
    return ret
Exemplo n.º 57
0
def PUVFlatten (InImager, err):
    """ Flatten ImageMosaic member

    The images of the mosaic member are flattened to a single image.
    This operation is optionally done in PUVImage.          
    InImager  = UVImager object
    err       = Python Obit Error/message stack
    """
    ################################################################
    #
    # Checks
    if not PIsA(InImager):
        raise TypeError, 'PUVFlatten : Bad input UVImager'

    #
    Obit.UVImagerFlatten (InImager.me, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error flattening mosaic")
Exemplo n.º 58
0
def PTimeStamp (inHis, label, err):
    """ Write timestamp and label to History

    return 0 on success, else failure
    inHis    = input Python History
    label    = character string for label
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inHis):
        raise TypeError,"inHis MUST be a History"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    ret = Obit.HistoryTimeStamp(inHis.me, label, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error writing History time stamp")
Exemplo n.º 59
0
def PCompressCC (inSkyModel, err):
    """ Compress CC tables

    Compresses CC tables on all Images in mosaic
    inSkyModel  = Python SkyModel object to compress
    err         = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not PIsA(inSkyModel):
        raise TypeError,"inSkyModel MUST be a Python Obit SkyModel"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be an OErr"
    #
    smi = inSkyModel.cast(myClass)  # cast pointer
    Obit.SkyModelCompressCC (smi, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error copying SkyModel")
Exemplo n.º 60
0
def PAddWindow (inCleanImage, field, window, err):
    """ Add a window to a field to be CLEANed

    inCleanImage  = Python CleanImage object
    field         = Which field (1-rel)is the window in?
    window        = set of 4 integers:
                    if window[0]<0 box is round and
                    window[1]=radius, [2,3] = center
                    else rectangular and
                    blc=(window[0],window[1]), trc= blc=(window[2],window[3])
    """
    ################################################################
    # Checks
    if not PIsA(inCleanImage):
        raise TypeError,"inCleanImage MUST be a Python ObitCleanImage"
    #
    Obit.CleanImageAddWindow(inCleanImage.me, field, window, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error adding window")