Example #1
0
def searchVS(h, cat='GCVS', caturl=None, maxSearchRadius=5):
    '''
    Search the area of the image in h (hdu, fits) for variable stars
    using the given catalogue. The cat imput parameter denotes the
    catalogue:

    'GCVS' - use the General Catalogue of Variable Stars
    'VSX'  - use the AAVSO Variable Star Index
    'USER' - use the custom url passed in caturl parameter

    The maximum search radius is specified by maxSearchRadius (deg).

    Returns a list of VS in the circle with the frame inscribed in it.
    '''

    if cat=='GCVS' :
        caturl='http://vizier.u-strasbg.fr/viz-bin/votable/-A?-source=B/vsx&'
    elif cat=='VSX' :
        caturl='http://heasarc.gsfc.nasa.gov/cgi-bin/vo/cone/coneGet.pl?table=aavsovsx&'
    else :
        caturl=caturl

    w=wcs.WCS(h.header, fix=False)
    cen=w.all_pix2world(array([[h.header['NAXIS1'], h.header['NAXIS2']]])/2,0)[0]
    # Half of the hypotenuse of the frame = radius of the search
    rad=sqrt(sum((real(eigvals(w.wcs.cd))*array([h.header['NAXIS1'], h.header['NAXIS2']]))**2))/2
    # Clamp to reasonable size
    rad=min(rad, maxSearchRadius)
    r=conesearch(caturl,pos=list(cen),radius=rad)
    return r
Example #2
0
def main(options):
   objName = options.srcID
   radInDeg = float(options.radius)
   outFileName = options.output
   inOnePatch = options.patch

   # Get the sources in the cut-out as a VO table 
   url = 'http://vo.astron.nl/tgssadr/q/cone/scs.xml'
   t = vo.conesearch(url, pos = vo.object2pos(objName), radius = radInDeg )

   f = open(outFileName, 'w')
   if options.patch:
      # Write all selected components as a single patch
      f.write("FORMAT = Name, Type, Patch, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147610000.0', SpectralIndex='[]'\n\n")
      # Get the coordinates of the source
      c = SkyCoord(float(vo.object2pos(objName)[0]), float(vo.object2pos(objName)[1]), unit='deg')
      newRA = c.to_string('hmsdms').split(' ')[0].replace('h',':').replace('m',':').replace('s','')
      newDec = c.to_string('hmsdms').split(' ')[1].replace('d','.').replace('m','.').replace('s','')
      # Create the patch
      f.write(' , , Patch, {ra}, {dec}\n'.format(ra=newRA, dec=newDec))
      for item in t:
         # VO table has RA and DEC in degrees. Convert it to hmsdms format
         c = SkyCoord(float(item['RA']), float(item['DEC']), unit='deg')
         newRA = c.to_string('hmsdms').split(' ')[0].replace('h',':').replace('m',':').replace('s','')
         newDec = c.to_string('hmsdms').split(' ')[1].replace('d','.').replace('m','.').replace('s','')
	 # Determine whether source is extended
	 sratio = item['Sint']/item['Spk']
	 if sratio > 1.25:
		srctype='GAUSSIAN'
		majaxsize = (max([item['MAJAX'],25.])**2-25.**2)**0.5
		minaxsize = (max([item['MINAX'],25.])**2-25.**2)**0.5
	 else:
		srctype='POINT'
		majaxsize = ""
		minaxsize = ""
         # Write an entry for this source into the output file inside the above defined patch
         f.write("{name}, {type}, Patch, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.8]\n".format(name=item['ID'], type=srctype, ra=newRA, dec=newDec, i=item['Sint']/1e3, ma=majaxsize, mi=minaxsize, pa=item['PA']))
   else:
      # Writes sources without a patch
      f.write("FORMAT = Name, Type, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147610000.0', SpectralIndex='[]'\n\n")
      for item in t:
         # VO table has RA and DEC in degrees. Convert it to hmsdms format
         c = SkyCoord(float(item['RA']), float(item['DEC']), unit='deg')
         newRA = c.to_string('hmsdms').split(' ')[0].replace('h',':').replace('m',':').replace('s','')
         newDec = c.to_string('hmsdms').split(' ')[1].replace('d','.').replace('m','.').replace('s','')
	 # Determine whether source is extended
	 sratio = item['Sint']/item['Spk']
	 if sratio > 1.25:
		srctype='GAUSSIAN'
		majaxsize = (max([item['MAJAX'],25.])**2-25.**2)**0.5
		minaxsize = (max([item['MINAX'],25.])**2-25.**2)**0.5
	 else:
		srctype='POINT'
		majaxsize = ""
		minaxsize = ""
         # Write an entry for this source into the output file
         f.write("{name}, {type}, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.8]\n".format(name=item['ID'], type=srctype, ra=newRA, dec=newDec, i=item['Sint']/1e3, ma=majaxsize, mi=minaxsize, pa=item['PA']))
   f.close()
Example #3
0
def conesearch(ra,dec,radius,db_url,cp):
    """
    Search for objects inside the 'radius' around ('ra','dec,) in 'catalog'.
    
    Input:
        - ra      : right ascension (degrees)
        - dec     : declination (degrees)
        - radius  : search radius, value in degrees
        - catalog : options are 'sdss-7', '2mass', 'ukidss-8', 'usno-a2', 'usno-b1'
    """
    
    try:
        logging.debug("Position (%s,%s) and radius, in degrees, (%s)", ra, dec, radius)
        res = vo.conesearch( db_url, (ra,dec), radius, verbosity=3)
    except vo.dal.DALServiceError, e:
        logging.exception("Exception raised: %s", e)
        print "Service not responding"
        return None
Example #4
0
def conesearch(ra, dec, radius, db_url, cp):
    """
    Search for objects inside the 'radius' around ('ra','dec,) in 'catalog'.
    
    Input:
        - ra      : right ascension (degrees)
        - dec     : declination (degrees)
        - radius  : search radius, value in degrees
        - catalog : options are 'sdss-7', '2mass', 'ukidss-8', 'usno-a2', 'usno-b1'
    """

    try:
        logging.debug("Position (%s,%s) and radius, in degrees, (%s)", ra, dec,
                      radius)
        res = vo.conesearch(db_url, (ra, dec), radius, verbosity=3)
    except vo.dal.DALServiceError, e:
        logging.exception("Exception raised: %s", e)
        print "Service not responding"
        return None
Example #5
0
def coneSearch(VOService, position, radius):
    """
    Returns table from a VO cone search.

    Parameters
    ----------
    VOService : str
        Name of VO service to query (must be one of 'WENSS' or 'NVSS')
    position : list of floats
        A list specifying a new position as [RA, Dec] in either makesourcedb
        format (e.g., ['12:23:43.21', '+22.34.21.2']) or in degrees (e.g.,
        [123.2312, 23.3422])
    radius : float or str, optional
        Radius in degrees (if float) or 'value unit' (if str; e.g.,
        '30 arcsec') for cone search region in degrees
    """
    import pyvo as vo

    log = logging.getLogger('LSMTool.Load')

    # Define allowed cone-search databases. These are the ones we know how to
    # convert to makesourcedb-formated sky models.
    columnMapping = {
        'nvss':{'NVSS':'name', 'RAJ2000':'ra', 'DEJ2000':'dec', 'S1.4':'i',
            'MajAxis':'majoraxis', 'MinAxis':'minoraxis', 'referencefrequency':1.4e9},
        'wenss':{'Name':'name', 'RAJ2000':'ra', 'DEJ2000':'dec', 'Sint':'i',
            'MajAxis':'majoraxis', 'MinAxis':'minoraxis', 'PA':'orientation',
            'referencefrequency':325e6}
        }

    if VOService.lower() in allowedVOServices:
        url = allowedVOServices[VOService.lower()]
    else:
        raise ValueError('VO query service not known. Allowed services are: '
            '{0}'.format(allowedVOServices.keys()))

    # Get raw VO catalog
    log.debug('Querying VO service...')
    try:
        position = [RA2Angle(position[0])[0].value, Dec2Angle(position[1])[0].value]
    except TypeError:
        raise ValueError('VO query positon not understood.')
    try:
        radius = Angle(radius, unit='degree').value
    except TypeError:
        raise ValueError('VO query radius not understood.')
    VOcatalog = vo.conesearch(url, position, radius=radius)

    log.debug('Creating table...')
    try:
        table = Table.read(VOcatalog.votable)
    except IndexError:
        # Empty query result
        log.error('No sources found. Sky model is empty.')
        table = makeEmptyTable()
        return table

    # Remove unneeded columns
    colsToRemove = []
    for colName in table.colnames:
        if colName not in columnMapping[VOService.lower()]:
            colsToRemove.append(colName)
        elif columnMapping[VOService.lower()][colName] not in allowedColumnNames:
            colsToRemove.append(colName)
    for colName in colsToRemove:
        table.remove_column(colName)

    # Rename columns to match makesourcedb conventions
    for colName in table.colnames:
        if colName != allowedColumnNames[columnMapping[VOService.lower()][colName]]:
            table.rename_column(colName, allowedColumnNames[columnMapping[
                VOService.lower()][colName]])

    # Convert RA and Dec to Angle objects
    log.debug('Converting RA...')
    RARaw = table['Ra'].data.tolist()
    RACol = Column(name='Ra', data=RA2Angle(RARaw))
    def raformat(val):
        return Angle(val, unit='degree').to_string(unit='hourangle', sep=':')
    RACol.format = raformat
    RAIndx = table.keys().index('Ra')
    table.remove_column('Ra')
    table.add_column(RACol, index=RAIndx)

    log.debug('Converting Dec...')
    DecRaw = table['Dec'].data.tolist()
    DecCol = Column(name='Dec', data=Dec2Angle(DecRaw))
    def decformat(val):
        return Angle(val, unit='degree').to_string(unit='degree', sep='.')
    DecCol.format = decformat
    DecIndx = table.keys().index('Dec')
    table.remove_column('Dec')
    table.add_column(DecCol, index=DecIndx)

    # Make sure Name is a str column
    NameRaw = table['Name'].data.tolist()
    NameCol = Column(name='Name', data=NameRaw, dtype='{}100'.format(numpy_type))
    table.remove_column('Name')
    table.add_column(NameCol, index=0)

    # Convert flux and axis values to floats
    for name in ['I', 'MajorAxis', 'MinorAxis', 'Orientation']:
        if name in table.colnames:
            indx = table.index_column(name)
            intRaw = table[name].data.tolist()
            floatCol = Column(name=name, data=intRaw, dtype='float')
            table.remove_column(name)
            table.add_column(floatCol, index=indx)


    # Add source-type column
    types = ['POINT'] * len(table)
    if 'majoraxis' in columnMapping[VOService.lower()].values():
        for i, maj in enumerate(table[allowedColumnNames['majoraxis']]):
            if maj > 0.0:
                types[i] = 'GAUSSIAN'
    col = Column(name='Type', data=types, dtype='{}100'.format(numpy_type))
    table.add_column(col, index=1)

    # Add reference-frequency column
    refFreq = columnMapping[VOService.lower()]['referencefrequency']
    col = Column(name='ReferenceFrequency', data=np.array([refFreq]*len(table), dtype=np.float))
    table.add_column(col)

    # Set column units and default values
    def fluxformat(val):
        return '{0:0.3f}'.format(val)
    for i, colName in enumerate(table.colnames):
        log.debug("Setting units for column '{0}' to {1}".format(
            colName, allowedColumnUnits[colName.lower()]))
        if colName == 'I':
            table.columns[colName].unit = 'mJy'
            table.columns[colName].convert_unit_to('Jy')
            table.columns[colName].format = fluxformat
        else:
            table.columns[colName].unit = allowedColumnUnits[colName.lower()]

        if hasattr(table.columns[colName], 'filled') and allowedColumnDefaults[colName.lower()] is not None:
            fillVal = allowedColumnDefaults[colName.lower()]
            if colName == 'SpectralIndex':
                while len(fillVal) < 1:
                    fillVal.append(0.0)
            log.debug("Setting default value for column '{0}' to {1}".
                format(colName, fillVal))
            table.columns[colName].fill_value = fillVal

    return table
Example #6
0
def coneSearch(VOService, position, radius):
    """
    Returns table from a VO cone search.

    Parameters
    ----------
    VOService : str
        Name of VO service to query (must be one of 'WENSS' or 'NVSS')
    position : list of floats
        A list specifying a new position as [RA, Dec] in either makesourcedb
        format (e.g., ['12:23:43.21', '+22.34.21.2']) or in degrees (e.g.,
        [123.2312, 23.3422])
    radius : float or str, optional
        Radius in degrees (if float) or 'value unit' (if str; e.g.,
        '30 arcsec') for cone search region in degrees
    """
    import pyvo as vo

    log = logging.getLogger('LSMTool.Load')

    # Define allowed cone-search databases. These are the ones we know how to
    # convert to makesourcedb-formated sky models.
    columnMapping = {
        'nvss': {
            'NVSS': 'name',
            'RAJ2000': 'ra',
            'DEJ2000': 'dec',
            'S1.4': 'i',
            'MajAxis': 'majoraxis',
            'MinAxis': 'minoraxis',
            'referencefrequency': 1.4e9
        },
        'wenss': {
            'Name': 'name',
            'RAJ2000': 'ra',
            'DEJ2000': 'dec',
            'Sint': 'i',
            'MajAxis': 'majoraxis',
            'MinAxis': 'minoraxis',
            'PA': 'orientation',
            'referencefrequency': 325e6
        }
    }

    if VOService.lower() in allowedVOServices:
        url = allowedVOServices[VOService.lower()]
    else:
        raise ValueError('VO query service not known. Allowed services are: '
                         '{0}'.format(allowedVOServices.keys()))

    # Get raw VO catalog
    log.debug('Querying VO service...')
    try:
        position = [
            RA2Angle(position[0])[0].value,
            Dec2Angle(position[1])[0].value
        ]
    except TypeError:
        raise ValueError('VO query positon not understood.')
    try:
        radius = Angle(radius, unit='degree').value
    except TypeError:
        raise ValueError('VO query radius not understood.')
    VOcatalog = vo.conesearch(url, position, radius=radius)

    log.debug('Creating table...')
    try:
        table = Table.read(VOcatalog.votable)
    except IndexError:
        # Empty query result
        log.error('No sources found. Sky model is empty.')
        table = makeEmptyTable()
        return table

    # Remove unneeded columns
    colsToRemove = []
    for colName in table.colnames:
        if colName not in columnMapping[VOService.lower()]:
            colsToRemove.append(colName)
        elif columnMapping[
                VOService.lower()][colName] not in allowedColumnNames:
            colsToRemove.append(colName)
    for colName in colsToRemove:
        table.remove_column(colName)

    # Rename columns to match makesourcedb conventions
    for colName in table.colnames:
        if colName != allowedColumnNames[columnMapping[VOService.lower()]
                                         [colName]]:
            table.rename_column(
                colName,
                allowedColumnNames[columnMapping[VOService.lower()][colName]])

    # Convert RA and Dec to Angle objects
    log.debug('Converting RA...')
    RARaw = table['Ra'].data.tolist()
    RACol = Column(name='Ra', data=RA2Angle(RARaw))

    def raformat(val):
        return Angle(val, unit='degree').to_string(unit='hourangle', sep=':')

    RACol.format = raformat
    RAIndx = table.keys().index('Ra')
    table.remove_column('Ra')
    table.add_column(RACol, index=RAIndx)

    log.debug('Converting Dec...')
    DecRaw = table['Dec'].data.tolist()
    DecCol = Column(name='Dec', data=Dec2Angle(DecRaw))

    def decformat(val):
        return Angle(val, unit='degree').to_string(unit='degree', sep='.')

    DecCol.format = decformat
    DecIndx = table.keys().index('Dec')
    table.remove_column('Dec')
    table.add_column(DecCol, index=DecIndx)

    # Make sure Name is a str column
    NameRaw = table['Name'].data.tolist()
    NameCol = Column(name='Name',
                     data=NameRaw,
                     dtype='{}100'.format(numpy_type))
    table.remove_column('Name')
    table.add_column(NameCol, index=0)

    # Convert flux and axis values to floats
    for name in ['I', 'MajorAxis', 'MinorAxis', 'Orientation']:
        if name in table.colnames:
            indx = table.index_column(name)
            intRaw = table[name].data.tolist()
            floatCol = Column(name=name, data=intRaw, dtype='float')
            table.remove_column(name)
            table.add_column(floatCol, index=indx)

    # Add source-type column
    types = ['POINT'] * len(table)
    if 'majoraxis' in columnMapping[VOService.lower()].values():
        for i, maj in enumerate(table[allowedColumnNames['majoraxis']]):
            if maj > 0.0:
                types[i] = 'GAUSSIAN'
    col = Column(name='Type', data=types, dtype='{}100'.format(numpy_type))
    table.add_column(col, index=1)

    # Add reference-frequency column
    refFreq = columnMapping[VOService.lower()]['referencefrequency']
    col = Column(name='ReferenceFrequency',
                 data=np.array([refFreq] * len(table), dtype=np.float))
    table.add_column(col)

    # Set column units and default values
    def fluxformat(val):
        return '{0:0.3f}'.format(val)

    for i, colName in enumerate(table.colnames):
        log.debug("Setting units for column '{0}' to {1}".format(
            colName, allowedColumnUnits[colName.lower()]))
        if colName == 'I':
            table.columns[colName].unit = 'mJy'
            table.columns[colName].convert_unit_to('Jy')
            table.columns[colName].format = fluxformat
        else:
            table.columns[colName].unit = allowedColumnUnits[colName.lower()]

        if hasattr(table.columns[colName], 'filled') and allowedColumnDefaults[
                colName.lower()] is not None:
            fillVal = allowedColumnDefaults[colName.lower()]
            if colName == 'SpectralIndex':
                while len(fillVal) < 1:
                    fillVal.append(0.0)
            log.debug("Setting default value for column '{0}' to {1}".format(
                colName, fillVal))
            table.columns[colName].fill_value = fillVal

    return table
Example #7
0
def main(srcID, radius, DoDec=True, output="tgss.skymodel"):
    """
   tgss2bbs2: 
   
   This inputs are srcID (string) as a co-ordinate or object ID
                   radius (float) is radius in degrees, converted in caller function
                   DoDec (bool) Option to do deconvolution
   The result is saved in atext file which is both logged locally and sent to the user
        through wget or through the browser
   """
    patch = True

    objName = srcID
    radInDeg = float(radius)
    outFileName = output
    inOnePatch = patch

    # Get the sources in the cut-out as a VO table
    url = 'http://vo.astron.nl/tgssadr/q/cone/scs.xml'
    try:
        t = vo.conesearch(url,
                          pos=get_icrs_coordinates(objName),
                          radius=radInDeg)
    except IndexError:
        f = open(outFileName, 'w')
        f.write(
            "Index Error when polling VirtualObservatory. Bad object name??")
        f.close()
        return

    f = open(outFileName, 'w')
    if patch:
        # Write all selected components as a single patch
        f.write(
            "FORMAT = Name, Type, Patch, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147500000.0', SpectralIndex='[]'\n\n"
        )
        # Get the coordinates of the source
        c = radec_to_string.radec_to_string(
            [
                get_icrs_coordinates(objName).ra.value,
                get_icrs_coordinates(objName).dec.value
            ],
            separators=[':', ':', '$', '.', ".", ''])
        newRA = c.split("$")[0]
        newDec = c.split("$")[1]
        # Create the header
        f.write(' , , Patch, {ra}, {dec}\n'.format(ra=newRA, dec=newDec))

        for item in t:
            # VO table has RA and DEC in degrees. Convert it to hmsdms format
            coords = radec_to_string.radec_to_string(
                [float(item['RA']), float(item['DEC'])],
                separators=[':', ':', '$', '.', ".", ''])
            newRA = coords.split("$")[0]
            newDec = coords.split("$")[1]
            #use radec_to_string to convert coordinates instead of Astropy
            if ((item['Sint'] / item['Spk']) >
                (2 * math.sqrt(0.027**2 +
                               (0.784 * (item['Spk'] / item['Island_RMS'])**
                                (-0.925))**2) + 1.071)):
                srctp = 'GAUSSIAN'
                if not DoDec:
                    maja = item['MAJAX']
                    mina = item['MINAX']
                    pax = item['PA']

                else:
                    bmaj1, bmin1, bpa1 = Beam_deconv_new.psfTGSS1(item["DEC"])
                    A1, B1, C1 = Beam_deconv_new.elliptic2quadratic(
                        bmaj1, bmin1, bpa1)
                    A2, B2, C2 = Beam_deconv_new.elliptic2quadratic(
                        item["MAJAX"], item["MINAX"], item["PA"])
                    Ak, Bk, Ck = Beam_deconv_new.deconvolve(
                        A2, B2, C2, A1, B1, C1)
                    maja, mina, pax = Beam_deconv_new.quadratic2elliptic(
                        Ak, Bk, Ck)
                    if maja == None:
                        maja = ""
                        mina = ""
                        pax = ""
                    else:
                        ## Some nice pretty formatting
                        maja = "{0:0.1f}".format(maja)
                        mina = "{0:0.1f}".format(mina)
                        pax = "{0:0.1f}".format(pax)
                if pax < 10 and pax != "":
                    pa1 = "{0:.2f}".format(float(pax))
                else:
                    pa1 = pax
                if item['PA'] > 0:
                    paxi = ' ' + str(pa1)
                else:
                    paxi = pa1
                if pax == '' or pax == 'nan':  #Deconvolution fails to converge. Made it into a point source for now
                    srctp = 'POINT   '
                    maja = '    '
                    mina = '    '
                    paxi = '     '
            else:
                srctp = 'POINT   '
                maja = '    '
                mina = '    '
                paxi = '     '

        # Write an entry for this source into the output file inside the above defined patch
            f.write(
                "{name}, {src}, Patch, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.73]\n"
                .format(name=item['ID'],
                        src=srctp,
                        ra=newRA,
                        dec=newDec,
                        i='{0: >9}'.format(format(item['Sint'] / 1e3, '.4f')),
                        ma=maja,
                        mi=mina,
                        pa=paxi))
    else:
        # Writes sources without a patch
        f.write(
            "FORMAT = Name, Type, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147610000.0', SpectralIndex='[]'\n\n"
        )
        for item in t:
            # VO table has RA and DEC in degrees. Convert it to hmsdms format
            coords = radec_to_string.radec_to_string(
                [float(item['RA']), float(item['DEC'])],
                separators=[':', ':', '$', '.', ".", ''])
            newRA = coords.split("$")[0]
            newDec = coords.split("$")[1]
            # Write an entry for this source into the output file
            #Case Gaussian
            f.write(
                "{name}, GAUSSIAN, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.8]\n"
                .format(name=item['ID'],
                        ra=newRA,
                        dec=newDec,
                        i=item['Sint'] / 1e3,
                        ma=item['MAJAX'],
                        mi=item['MINAX'],
                        pa=item['PA']))
    f.close()
def main(ms_input, SkymodelPath, Radius=1.5, ResultsFile, DoDownload="True"):

    """
    Download the LoTSS skymodel for the target field

    Parameters
    ----------
    ms_input : str
        String from the list (map) of the target MSs
    SkymodelPath : str
        Full name (with path) to the skymodel; if YES is true, the LOTSS skymodel will be downloaded here
    Radius : float (default = 1.5)
        Radius for the LOTSS cone search in degrees
    DoDownload : str ("Force" or "True" or "False")
        Download or not the LOTSS skymodel.
        "Force": download skymodel from LOTSS, delete existing skymodel if needed.
        "True" or "Yes": use existing skymodel file if it exists, download skymodel from 
                         LOTSS if it does not.
        "False" or "No": Do not download skymodel, raise an exception if skymodel
                         file does not exist.
    
    """

    FileExists = os.path.isfile(SkymodelPath)
    if (not FileExists and os.path.exists(SkymodelPath)):
        raise ValueError("download_lotss_skymodel: WTF! Path: \"%s\" exists but is not a file!"%(SkymodelPath))
    download_flag = False
    if DoDownload.upper() == "FORCE":
        if FileExists:
            os.remove(SkymodelPath)
        download_flag = True
    elif DoDownload.upper() == "TRUE" or DoDownload.upper() == "YES":
        if FileExists:
            print "USING the exising skymodel in "+ SkymodelPath
            return
        else:
            download_flag = True
    elif DoDownload.upper() == "FALSE" or DoDownload.upper() == "NO":
         if FileExists:
            print "USING the exising skymodel in "+ SkymodelPath
            return
         else:
            raise ValueError("download_lotss_skymodel: Path: \"%s\" does not exist and LOTSS download is disabled!"%(SkymodelPath))

    # If we got here, then we are supposed to download the skymodel.
    assert download_flag == True # Jaja, belts and suspenders...
    print "DOWNLOADING LOTSS Skymodel for the target into "+ SkymodelPath

    # Reading a MS to find the coordinate (pyrap)
    #[RATar,DECTar]=grab_coo_MS(input2strlist_nomapfile(ms_input)[0])
    #mypos = ( RATar, DECTar )
    mypos = grab_coo_MS(input2strlist_nomapfile(ms_input)[0])

    ## this is the tier 1 database to query
    url = 'http://vo.astron.nl/lofartier1/q/cone/scs.xml'

    t = vo.conesearch( url, pos=mypos, radius=Radius )

    ## convert to VO table
    tb = t.votable.to_table()
    ## find unresolved
    nsrcs = float( len( tb.columns['Resolved'] ) )
    unresolved_index = np.where( tb.columns['Resolved'] == 'U' )[0]
    perc_unres = len( unresolved_index ) / nsrcs * 100.
    print 'Percentage of sources which are unresolved: '+str( perc_unres )
    utb = tb[unresolved_index]
 
    ## sort by flux
    flux_sort = utb.argsort('Total_flux')
    utb_sorted = utb[ flux_sort[::-1] ]

    ## keep only RA, DEC, Source_id and reorder the columns
    utb_sorted.keep_columns(['RA','DEC','Source_id'])

    utb_final = utb_sorted[ 'RA', 'DEC', 'Source_id' ]

    utb_final.write( ResultsFile, format='ascii.csv' )

    return
    def getdataforRADEC(self, ra, dec, alldata=None,
        ramin=None, ramax=None, decmin=None, decmax=None, size=None):

        if alldata==None:
            alldata=self.alldata

        if ra<0.0:ra+=360.0
        if ra>=360.0:ra-=360.0

        if ramin!=None:
            if (ra-ramin)<-180:
                ramin-=360.0
                ramax-=360.0
            elif (ra-ramin)>180:
                ramin+=360.0
                ramax+=360.0

        radius = 0.5
        if size!=None:
            radius = np.sqrt(2)/2.0*size

        if self.options.debug:
            print('DEBUG: skipping download!')
        else:
            print('Downloading data')
            import pyvo
            Mmax=21.0
            if (self.options.Mmax!=None):
                Mmax = self.options.Mmax
            objects = pyvo.conesearch(self.options.cathtml, pos=(ra,dec), radius=size)
            tbdata = objects.table

            tbdata = self.add_magnitude(tbdata,
                'i1_f_ap1', 'L', 'i1_df_ap1', 'L_err')
            tbdata = self.add_magnitude(tbdata,
                'i2_f_ap1', 'M', 'i2_df_ap1', 'M_err')
            tbdata = self.add_magnitude(tbdata,
                'i3_f_ap1', 'N', 'i3_df_ap1', 'N_err')
            tbdata = self.add_magnitude(tbdata,
                'i4_f_ap1', 'Q', 'i4_df_ap1', 'Q_err')

        if not tbdata:
            print('Data download failed.  Exiting...')
            return(1)

        # calculate mags
        if self.options.verbose>1:
            print('calculating mags...')

        if ramin!=None:
            mask = ((tbdata['ra']<ramax) & (tbdata['ra']>ramin) &
                (tbdata['dec']<decmax) & (tbdata['dec']>decmin))
            data2keep = tbdata[mask]
        else:
            data2keep = tbdata

        print(data2keep)
        if self.options.requiregrizy:
            mask = ((data2keep[self.fluxcolname('L')] > 0) &
                    (data2keep[self.fluxcolname('M')] > 0) &
                    (data2keep[self.fluxcolname('N')] > 0) &
                    (data2keep[self.fluxcolname('Q')] > 0))
            data2keep = data2keep[mask]

        # check if there are limits on the mags and uncertainties
        for filt in self.filterlist:
            if self.options.Mmin!=None:
                mask = (data2keep[self.fluxcolname(filt)]>=self.options.Mmin)
                data2keep = data2keep[mask]
            if self.options.Mmax!=None:
                mask = (data2keep[self.fluxcolname(filt)]<=self.options.Mmax)
                data2keep = data2keep[mask]
            if self.options.dMmin!=None:
                mask = (data2keep[self.errcolname(filt)]>=self.options.dMmin)
                data2keep = data2keep[mask]
            if self.options.dMmax!=None:
                mask = (data2keep[self.errcolname(filt)]<=self.options.dMmax)
                data2keep = data2keep[mask]

        if alldata is None:
            self.alldata = table.Table(data2keep, masked=True)
        else:
            alldata = vstack(alldata, data2keep)
            self.alldata = table.unique(alldata, keys=['ra', 'dec'])

        return(0)