Exemplo n.º 1
0
def get_hip(name):
    """
    Given a star's Bayer designation, queries
    VizieR and attempts to locate a Hipparcos
    star ID at the location.

    Returns an integer HIP ID if found, or None otherwise

    Maintains a .hip_cache_stars file to speed up lookups;
    you can delete the .hip_cache_stars file to perform
    fresh lookups.
    """
    # Search the Hipparcos catalog, and only return results that include
    # a HIP (Hipparcos) column, sorting the results by magnitude.  The
    # top result is almost certainly the star we want.
    v = Vizier(catalog='I/239/hip_main', columns=["HIP", "+Vmag"])

    try:
        result = v.query_object(name)
    except EOFError:
        # if we get no results we might get an EOFError
        return None
    try:
        table = result['I/239/hip_main']
    except TypeError:
        # A TypeError means that the results didn't include anything from
        # the I/239/hip_main catalog.  The "in" operator doesn't seem to
        # work with Table objects.
        return None
    else:
        return table['HIP'][0]
Exemplo n.º 2
0
Arquivo: getzp.py Projeto: rfinn/Virgo
def panstarrs_query(ra_deg, dec_deg, rad_deg, maxmag=20,
                    maxsources=10000):
    """
    Query PanSTARRS @ VizieR using astroquery.vizier
    :param ra_deg: RA in degrees
    :param dec_deg: Declination in degrees
    :param rad_deg: field radius in degrees
    :param maxmag: upper limit G magnitude (optional)
    :param maxsources: maximum number of sources
    :return: astropy.table object
    """
    vquery = Vizier(columns=['objID', 'RAJ2000', 'DEJ2000',
                             'e_RAJ2000', 'e_DEJ2000',
                             'gmag', 'e_gmag',
                             'rmag', 'e_rmag',
                             'imag', 'e_imag',
                             'zmag', 'e_zmag',
                             'ymag', 'e_ymag'],
                    column_filters={"gmag":
                                    ("<%f" % maxmag)},
                    row_limit=maxsources)

    field = coord.SkyCoord(ra=ra_deg, dec=dec_deg,
                           unit=(u.deg, u.deg),
                           frame='icrs')
    return vquery.query_region(field,
                               width=("%fd" % rad_deg),
                               catalog="II/349/ps1")[0]
Exemplo n.º 3
0
def query_nvss(options, ra0, dec0, s=">0.0", proj='SIN'):
	'''
	query_nvss: module which queries the NVSS using the Vizier protocol. 
	inputs: ra0, dec0, s="<20"
	ra0 = the central ra in degrees
	dec0 = the central dec in degrees
	s = the flux cutoff
	returns L, M (relative coordinates in degrees), N (number of sources), S (1.4GHz Flux
	Density in mJy)
	'''
	v = Vizier(column_filters={"S1.4":s})
	v.ROW_LIMIT = 10000
	result = v.query_region(coord.SkyCoord(ra=ra0, dec=dec0, unit=(u.deg, u.deg), frame='icrs'), 
	    radius=Angle(1, "deg"), catalog='NVSS')
	ra = result[0]['_RAJ2000']
	dec = result[0]['_DEJ2000']
	N = len(result[0])
	if proj.upper()=='SIN':
		L = (ra-ra0)*pl.cos(dec*deg2rad)
		M = dec-dec0
	if proj.upper()=='NCP':
		L = 57.2957795*pl.cos(deg2rad*dec)*pl.sin(deg2rad*(ra-ra0))
		M = 57.2957795*(pl.cos(deg2rad*dec0) - pl.cos(deg2rad*dec)*pl.cos(deg2rad*(ra-ra0)))/pl.sin(deg2rad*dec0) 
	S = result[0]['S1.4']
	ascii.write(result[0], options.outfile+'.dat', format='tab') 
	ann_writer(options, result[0])
	return L, M, N, S
Exemplo n.º 4
0
def get_catalog(object):
    from astroquery.vizier import Vizier
    viz = Vizier( columns=['Star', '*'])
    star = object.replace('_', ' ') + '*'
    try:
        return viz.query_constraints(catalog='II/183A/table2',Star=star)[0]
    except IndexError:
        return None
Exemplo n.º 5
0
def galaxies_in_box(center, ra_span, dec_span):

    """
    This function ...
    :param center:
    :param ra_span:
    :param dec_span:
    :return:
    """

    # Initialize a list to contain the galaxies
    names = []

    # Other way ?? Much more results ?
    #ra_radius = 0.5 * ra_span.value
    #dec_radius = 0.5 * dec_span.value
    #radius = math.sqrt(ra_radius**2 + dec_radius**2)
    #result_table = Ned.query_region(center, radius=radius)

    # Create a new Vizier object and set the row limit to -1 (unlimited)
    viz = Vizier(keywords=["galaxies", "optical"])
    viz.ROW_LIMIT = -1

    # Debugging
    log.debug("Querying the HYPERLEDA catalog ...")

    # Query Vizier and obtain the resulting table
    result = viz.query_region(center.to_astropy(), width=ra_span, height=dec_span, catalog=["VII/237"])

    # I noticed something strange happening once; where there were no entries in the result,
    # with the following parameters:
    #   center = (149.07614359, 69.24847936)
    #   ra_span = 1.600000128 deg
    #   dec_span = 1.3966667784 deg
    #   catalog = ["VII/237"]
    # When ra_span was only slightly changed (e.g. change the last digit to a '7'), output was normal
    # Thus, it seems that the query goes wrong with specific values of the width (and/or height), in which
    # case changing the value very slightly resolves the problem...
    # I am baffled by this and I see no reasonable explanation.
    if len(result) == 0:

        ra_span *= 1.0 + 1e-5
        result = viz.query_region(center.to_astropy(), width=ra_span, height=dec_span, catalog=["VII/237"])

    table = result[0]

    # Loop over the rows in the table
    for entry in table:
        name = "PGC " + str(entry["PGC"])
        coordinate = SkyCoordinate(ra=entry["_RAJ2000"], dec=entry["_DEJ2000"], unit="deg", frame="fk5")
        namepluscoordinate = (name, coordinate)
        names.append(namepluscoordinate)

    # Return the list of galaxies
    return names
Exemplo n.º 6
0
def serendipitous_variablestars(catalogs, display=True):
    """match catalogs with VSX catalog using astroquery.Vizier
    """

    if display:
        print('# match frames with variable star database... ', end=' ',
              flush=True)
    logging.info('match frames with variable star database')

    # derive center and radius of field of view of all images
    ra_deg, dec_deg, rad_deg = skycenter(catalogs)
    logging.info('FoV center (%.7f/%+.7f) and radius (%.2f deg) derived' %
                 (ra_deg, dec_deg, rad_deg))

    # derive observation midtime of sequence
    midtime = np.average([cat.obstime[0] for cat in catalogs])

    # setup Vizier query
    # note: column filters uses original Vizier column names
    # -> green column names in Vizier

    logging.info(('query Vizier for VSX at %7.3f/%+8.3f in '
                  + 'a %.2f deg radius') %
                 (ra_deg, dec_deg, rad_deg))

    field = coord.SkyCoord(ra=ra_deg, dec=dec_deg, unit=(u.deg, u.deg),
                           frame='icrs')

    vquery = Vizier(columns=['Name', 'RAJ2000', 'DEJ2000'])
    try:
        data = vquery.query_region(field,
                                   width=("%fd" % rad_deg),
                                   catalog="B/vsx/vsx")[0]
    except IndexError:
        if display:
            print('no data available from VSX')
            logging.error('no data available from VSX')
            return []

    objects = []
    for cat_idx, cat in enumerate(catalogs):
        for star in data:
            objects.append({'ident': star['Name'],
                            'obsdate.jd': cat.obstime[0],
                            'cat_idx': cat_idx,
                            'ra_deg': star['RAJ2000'],
                            'dec_deg': star['DEJ2000']})

    if display:
        print(len(objects)/len(catalogs), 'variable stars found')

    return objects
Exemplo n.º 7
0
def fetch_objects_in_box(box, catalog, keywords, radius, limit=None, column_filters=None):

    """
    This function ...
    :param box:
    :param catalog:
    :param keywords:
    :param radius:
    :param limit:
    :param column_filters:
    :return:
    """

    # Define the center coordinate for the box
    coordinate = SkyCoordinate(ra=box[0], dec=box[1], unit="deg", frame="fk5") # frame: icrs, fk5... ?

    # Make a Vizier object
    if column_filters is None:
        viz = Vizier(columns=['_RAJ2000', '_DEJ2000','B-V', 'Vmag', 'Plx'], keywords=keywords)
    else:
        viz = Vizier(columns=['_RAJ2000', '_DEJ2000','B-V', 'Vmag', 'Plx'], column_filters=column_filters, keywords=keywords)

    # No limit on the number of entries
    viz.ROW_LIMIT = limit if limit is not None else -1

    # Query the box of our image frame
    result = viz.query_region(coordinate.to_astropy(), width=box[3] * Unit("deg"), height=box[2] * Unit("deg"), catalog=catalog)

    region_string = "# Region file format: DS9 version 3.0\n"
    region_string += "global color=green\n"

    # Result may contain multiple tables (for different catalogs)
    for table in result:

        # For every entry in the table
        for entry in table:

            # Get the right ascension and the declination
            ra = entry[0]
            dec = entry[1]

            # Create a string with the coordinates of the star
            regline = "fk5;circle(%s,%s,%.2f\")\n" % (ra, dec, radius)

            # Add the parameters of this star to the region string
            region_string += regline

    # Return the region
    return regions.parse(region_string)
Exemplo n.º 8
0
def get_galaxy_s4g_one_component_info(name):

    """
    This function ...
    :param name:
    :return:
    """

    # The Vizier querying object
    vizier = Vizier()
    vizier.ROW_LIMIT = -1

    # Get the "galaxies" table
    result = vizier.query_object(name, catalog=["J/ApJS/219/4/galaxies"])

    # No results?
    if len(result) == 0: return None, None, None, None, None, None

    # Get table
    table = result[0]

    # PA: [0.2/180] Outer isophote position angle
    # e_PA: [0/63] Standard deviation in PA
    # Ell:  [0.008/1] Outer isophote ellipticity
    # e_Ell: [0/0.3] Standard deviation in Ell

    # PA1: Elliptical isophote position angle in deg
    # n: Sersic index
    # Re: effective radius in arcsec

    # Tmag: total magnitude

    s4g_name = table["Name"][0]

    pa = Angle(table["PA"][0] - 90., "deg")
    pa_error = Angle(table["e_PA"][0], "deg")

    ellipticity = table["Ell"][0]
    ellipticity_error = table["e_Ell"][0]

    n = table["n"][0]

    re = table["Re"][0] * u("arcsec")

    mag = table["Tmag"][0]

    # Return the results
    return s4g_name, pa, ellipticity, n, re, mag
def catalog_search(frame_wcs, shape, desired_catalog,
                   ra_column='RAJ2000',
                   dec_column='DEJ2000',
                   radius=0.5,
                   clip_by_frame=True):
    """
    Description: This function takes coordinate data from an image and a
    catalog name and returns the positions of those stars.
    Preconditions:frame_wcs is a WCS object, shape is tuple, list or array of
    numerical values, desired_catalog is a string and radius is a numerical
    value.
    Postconditions:
    """
    rad = radius * units.deg
    # Find the center of the frame
    center_coord = frame_wcs.all_pix2world([[shape[1] / 2, shape[0] / 2]], 0)
    center = SkyCoord(center_coord, frame='icrs', unit='deg')

    # Get catalog via cone search
    Vizier.ROW_LIMIT = -1  # Set row_limit to have no limit
    cat = Vizier.query_region(center, radius=rad, catalog=desired_catalog)
    # Vizier always returns list even if there is only one element. Grab that
    # element.
    cat = cat[0]
    cat_coords = SkyCoord(ra=cat[ra_column], dec=cat[dec_column])
    if clip_by_frame:
        in_fov = in_frame(frame_wcs, cat_coords)
    else:
        in_fov = np.ones([len(cat_coords)], dtype=np.bool)
    x, y = frame_wcs.all_world2pix(cat_coords.ra, cat_coords.dec, 0)
    return (cat[in_fov], x[in_fov], y[in_fov])
Exemplo n.º 10
0
def selected_catalog( ra, dec, FOV_base, FOV_height, catalog ):

     '''

     Vizier.query_region in selected FoV. The hist of the apparent blue magnitude
     and the sky coordinates are provided if GWGC catalog is selected

     '''

     from astroquery.vizier import Vizier 

     import astropy.coordinates as coord
     import astropy.units as u

     import aladinSAMP

     # setting rows limit
     Vizier.ROW_LIMIT = None

     # no reduced query size (rq)
     reduce_query_size = 1
     FOV_base_reduced, FOV_height_reduced = FOV_base * reduce_query_size, FOV_height * reduce_query_size

     FOV_base_str, FOV_height_str = str( FOV_base_reduced ) + 'd', str( FOV_height_reduced ) + 'd'

     result = Vizier.query_region(coord.SkyCoord(ra = ra, dec = dec, unit = (u.deg, u.deg), frame='icrs'),
                                  width = FOV_height_str, height = FOV_base_str, catalog = [ catalog ])

     result.pprint()
     print result.values()
Exemplo n.º 11
0
    def __init__(self, config=None):
    
        """
        The constructor ...
        """

        # Call the constructor of the base class
        super(SEDFetcher, self).__init__(config, "modeling")

        # -- Attributes --

        # The name of the galaxy
        self.galaxy_name = None

        # The NGC ID of the galaxy
        self.ngc_id = None

        # The Vizier querying object
        self.vizier = Vizier(keywords=["galaxies"])
        self.vizier.ROW_LIMIT = -1

        # The observed SED
        self.seds = dict()

        # The filters
        self.filters = dict()
Exemplo n.º 12
0
    def query_color(self,
                    ra,
                    dec,
                    radius=0.01,
                    min_mag=10,
                    max_mag=20,
                    max_sources=100):
        """

        Query NOMAD object
        @param ra: RA of field center for search, format: degrees or hh:mm:ss
        @type ra: str
        @param dec: DEC of field center for search, format: degrees or hh:mm:ss
        @type dec: str
        @param radius: Radius.
        @type radius: float
        @param min_mag: Minimum magnitude value of query.
        @type min_mag: float
        @param max_mag: Maximum magnitude value of query.
        @type max_mag: float
        @param max_sources: Maximum strs to be queried..
        @type max_sources: int
        @return: astropy.table
        """

        c = coord.SkyCoord(ra,
                           dec,
                           unit=(u.deg, u.deg),
                           frame='icrs')
        r = radius * u.deg

        vquery = Vizier(columns=['NOMAD1',
                                 'RAJ2000',
                                 'DEJ2000',
                                 'Bmag',
                                 'Vmag',
                                 'Rmag'],
                        column_filters={"Rmag":
                                        (">{:f}".format(min_mag)),
                                        "Rmag":
                                        ("<{:f}".format(max_mag))},
                        row_limit=max_sources)

        result = vquery.query_region(c, radius=r, catalog="NOMAD")[0]

        return(result)
Exemplo n.º 13
0
 def query_vizier(self, catalog='APASS'):
     '''
     Uses the astroquery environment to get the data from Vizier.
     Possible selection of catalogues:
     
     '''    
     result = Vizier.query_region("%.6f %.6f"%(self.ra, self.dec), radius=Angle(self.rad, "deg"), \
         catalog=catalog) #column_filters={"rmag":">%s"%self.minmag,"rmag":"<%s"%self.maxmag }
     return result[0]
Exemplo n.º 14
0
def green_catalog_download():
    # This allows easy access to Vizier tables:
    # https://astroquery.readthedocs.org/en/latest/vizier/vizier.html
    from astroquery.vizier import Vizier
    Vizier.ROW_LIMIT = -1
    # This is the 2014-05 version of Green's catalog
    # http://vizier.u-strasbg.fr/viz-bin/VizieR?-source=VII/272
    results = Vizier.get_catalogs(['VII/272'])
    table = results[0]
    return table
def get_hip(ra, dec, mag):
    """
    Given an RA (in hours and decimals), and Dec (in
    degrees and decimals), and a magnitude (in
    visual magnitudes), queries VizieR and attempts
    to locate a Hipparcos star ID at the location.

    Returns an integer HIP ID if found, or None otherwise

    Maintains a .hip_cache file to speed up lookups;
    you can delete the .hip_cache file to perform
    fresh lookups.
    """
    coord = SkyCoord(ra=Angle("{} hours".format(ra)),
                     dec=Angle("{} degree".format(dec)),
                     obstime="J2000.0")

    # Search the Hipparcos catalog, and only return results that include
    # a HIP (Hipparcos) column, sorting the results by magnitude.  The
    # top result is almost certainly the star we want.
    v = Vizier(catalog='I/239/hip_main', columns=["HIP", "+Vmag"])
    # Constrain the search to stars within 1 Vmag of our target
    v.query_constraints(Vmag="{}..{}".format(mag - 0.5, mag + 0.5))

    # Start with a targeted search, which returns more quickly from the
    # API. If that fails to find a star, query a 3 degree diameter circle
    # around the ra/dec.  This is because Sky & Telescope has a convention
    # of stopping their constellation lines a degree or so away from the
    # star, if that star isn't actually part of the constellation
    # (example: Alpheratz, which is part of the Pegasus figure, but the
    # star is in Andromeda)
    for radius in (0.05, 1.5):
        result = v.query_region(coord, radius=radius*u.deg)
        try:
            table = result['I/239/hip_main']
        except TypeError:
            # A TypeError means that the results didn't include anything from
            # the I/239/hip_main catalog.  The "in" operator doesn't seem to
            # work with Table objects.
            continue
        else:
            return table['HIP'][0]
    return None
Exemplo n.º 16
0
	def showVizierCatalogs(self):
		(ra, dec) = self.centre
		from astroquery.vizier import Vizier
		Vizier.ROW_LIMIT = 50
		from astropy import coordinates
		from astropy import units as u
		c = coordinates.SkyCoord(ra,dec,unit=('deg','deg'),frame='icrs')
		skyHeight= coordinates.Angle(self.raRange, unit = u.deg)
		results = Vizier.query_region(coordinates = c, radius= 1.0 * u.deg)
		print results
Exemplo n.º 17
0
    def query_circle(self, ra, dec, radius, catalog):
        """Vizier.query_region in a circle FoV."""

        Vizier.ROW_LIMIT = None
        radius_str = str(radius) + "d"

        query_result = Vizier.query_region(
            SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg), frame="icrs"), radius=radius_str, catalog=[catalog]
        )
        return query_result
Exemplo n.º 18
0
def calc_frame_phot_correction(objects, cat_file, vizier_var, phot_var, cat_name='SDSS', 
                                separation=2*u.arcsec, fields=['*']):
    positions = coords.SkyCoord(objects['ra'], objects['dec'], frame='icrs', unit='deg')
    
    print('Querying Vizier')
    v_cat = Vizier(columns=fields, catalog=catalog_info[cat_name]['vizier name'])
    result = v_cat.query_region(positions, radius=separation)
    # Vizier returns a table list with a table for each catalog
    # Since we have only chosen one catalog, we take the first (and only) table
    catalog = result[0] 
    catalog.rename_column('_RAJ2000','ra')
    catalog.rename_column('_DEJ2000','dec')
    catalog.rename_column(vizier_var, phot_var)
    # remove results that have bad photometry
    #catalog = catalog[catalog[phot_var]>-9000]
    
    # only keep the catalog entries that are primary stars
    catalog = catalog[catalog['cl']==catalog_info[cat_name]['class']['star']]
    catalog = (catalog[catalog[catalog_info[cat_name]['mode']] ==
                        catalog_info[cat_name]['modes']['primary']])

    print('Finding matches for catalog stars')
    # find the corresonding object for each entry in the catalog array
    dr = coords.Angle(separation).to('degree').value
    cat_coords = coords.SkyCoord(catalog['ra'], catalog['dec'], frame='icrs', unit='deg')
    matches, d2d, d3d = cat_coords.match_to_catalog_sky(positions)
    match_col = Column(matches)
    catalog['matches'] = match_col
    
    # Remove all sources with duplicate entries (there can be a difference between
    # the astropy catalog match and the match from Vizier in a few rare cases)
    duplicates = np.where(np.bincount(match_col)>1)[0]
    for duplicate in duplicates:
        match_col[np.where(match_col==duplicate)]=-1
    catalog = catalog[match_col>=0]    

    catalog = catalog.group_by('matches')
    print('Total matches:', len(catalog.groups.keys['matches']))
    
    cat_array=np.array(catalog)
    np.save(cat_file, cat_array)
    print('Saving file',cat_file)
    return catalog
Exemplo n.º 19
0
    def get_s4g_properties(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Querying the S4G catalog ...")

        # The Vizier querying object
        vizier = Vizier(columns=['Name', 'RAJ2000', 'DEJ2000', 'amaj', 'ell', 'Dmean', "e_Dmean", "PA"])
        vizier.ROW_LIMIT = -1

        # Get parameters from S4G catalog
        result = vizier.query_object(self.galaxy_name, catalog=["J/PASP/122/1397/s4g"])
        table = result[0]

        # Galaxy name for S4G catalog
        self.properties.name = table["Name"][0]

        # Galaxy center from decomposition (?)
        ra_center = table["RAJ2000"][0]
        dec_center = table["DEJ2000"][0]
        center = SkyCoordinate(ra=ra_center, dec=dec_center, unit="deg", frame='fk5')
        self.properties.center = center

        # Center position
        #self.properties.center = SkyCoordinate(ra=self.info["RA"][0], dec=self.info["DEC"][0], unit="deg") # center position from DustPedia

        # Distance
        self.properties.distance = table["Dmean"][0] * u("Mpc")
        self.properties.distance_error = table["e_Dmean"][0] * u("Mpc")

        # Major axis, ellipticity, position angle
        self.properties.major_arcsec = table["amaj"][0] * u("arcsec")
        self.properties.major = (self.properties.distance * self.properties.major_arcsec).to("pc", equivalencies=dimensionless_angles())

        # Ellipticity
        self.properties.ellipticity = table["ell"][0]
        self.properties.position_angle = Angle(table["PA"][0] + 90.0, u("deg"))
Exemplo n.º 20
0
def get_usnob1_cat(ra, dec, blim):
    ra_u = ra*u.degree
    dec_u = dec*u.degree
    coords = SkyCoord(ra_u, dec_u, frame='icrs') #Should this be ICRS or FK5
    #Only Class 0 (stars) - unable to implement this at the current time. Need to understand
    #USNO-B1 s/g classification
    v = Vizier(columns=['USNO-B1.0', '_RAJ2000', '_DEJ2000', 
                        'B1mag', 'R1mag', 'B2mag', 'R2mag', 
                        'pmRA', 'pmDE', 'Imag', 'B1s/g', '_r'],
                row_limit=500000,
               column_filters={"B2mag":">6", 'B2mag':'<{}'.format(blim)}) #B2mag fainter than 6, brighter than blim
    new_table_list = v.query_region(coords, 
                                 radius=900*u.arcsecond, #Search 900 arcseconds
                                 catalog = 'I/284')
    if len(new_table_list) ==0:
        return None
    else:
        new_table = new_table_list[0]
    #Get the 5000 closest
    new_table.sort('_r')
    if len(new_table) > 5000:
        new_table.remove_rows(np.arange(5001, len(new_table)))
    #Sort with brightest star first
    new_table.sort(['B2mag'])
    

    #Fill in blank values with 99.99
    new_table['B1mag'].fill_value = 99.99
    new_table['R1mag'].fill_value = 99.99
    new_table['B2mag'].fill_value = 99.99
    new_table['R2mag'].fill_value = 99.99
    new_table['Imag'].fill_value = 99.99
    new_table['pmRA'].fill_value = 99.99
    new_table['pmDE'].fill_value = 99.99
    filled_table = new_table.filled()
    filled_table.write('search.ub1', overwrite=True, format='ascii.fixed_width_no_header', delimiter=' ')
    
    searchcenter_ofile = open('searchcenter.ub1', 'w')
    searchcenter_ofile.write('{},{}'.format(ra, dec))
    searchcenter_ofile.close()
    return 'success'
Exemplo n.º 21
0
def GAIAplx(ra,de):
    v = Vizier(columns=["*", "+_r"], catalog='I/345/gaia2')
    pos=coord.SkyCoord(ra=ra, dec=de,unit=(u.hourangle,u.deg),frame='icrs',obstime='J2000')
    result=v.query_region(pos, radius="10s", catalog='I/345/gaia2')
    # Moving the positions to 2000
    try:
        nlines=len(result[0]['RA_ICRS'])
        deltat=-15.5
        sep=[]
        for ig,name in enumerate(result[0]['Source']):
            raold=result[0]['RA_ICRS'].data[ig]+(result[0]['pmRA'].data[ig] *deltat)/3600000.
            deold=result[0]['DE_ICRS'].data[ig]+(result[0]['pmDE'].data[ig] *deltat)/3600000.
            posold = coord.ICRS(ra=raold * u.deg, dec=deold * u.deg)
            sep.append(pos.separation(posold).arcsecond)
        indG=np.argmin(sep)
        if sep[indG]<1.5 and result[0]['Plx'].data[indG]>0:
            return str(round(result[0]['Plx'].data[indG],2)), str(round(result[0]['e_Plx'].data[indG],2))
    except:
        return 'NULL','NULL'

    return 'NULL','NULL'
Exemplo n.º 22
0
    def gaia_query(self, ra_deg, dec_deg, rad_deg, max_mag=20,
                   max_coo_err=1,
                   max_sources=100):

        """
        Query Gaia DR1 @ VizieR using astroquery.vizier
        parameters: ra_deg, dec_deg, rad_deg: RA, Dec, field
        @param ra_deg: RA in degrees
        @type ra_dec: float
        @param dec_deg: DEC in degrees
        @type dec_deg: float
        @param max_mag: Limit G magnitude to be queried object(s)
        @type max_mag: float
        @max_coo_err: Max error of position
        @type max_coo_err: float
        @max_sources: Maximum number of sources
        @type max_sources: int
        @returns: astropy.table object
        """

        vquery = Vizier(columns=['Source', 'RA_ICRS',
                                 'DE_ICRS', 'e_RA_ICRS',
                                 'e_DE_ICRS', 'phot_g_mean_mag',
                                 'pmRA', 'pmDE',
                                 'e_pmRA', 'e_pmDE',
                                 'Epoch', 'Plx'],
                        column_filters={"phot_g_mean_mag":
                                        ("<{:f}".format(max_mag)),
                                        "e_RA_ICRS":
                                        ("<{:f}".format(max_coo_err)),
                                        "e_DE_ICRS":
                                        ("<{:f}".format(max_coo_err))},
                        row_limit=max_sources)
 
        field = coord.SkyCoord(ra=ra_deg, dec=dec_deg,
                               unit=(u.deg, u.deg),
                               frame='icrs')
        return(vquery.query_region(field,
                                   width="{:f}d".format(rad_deg),
                                   catalog="I/337/gaia")[0])
Exemplo n.º 23
0
    def query_box(self, ra, dec, base, height, catalog):
        """Vizier.query_region in a square/rectangular FoV."""

        Vizier.ROW_LIMIT = None
        base_str, height_str = str(base) + "d", str(height) + "d"

        query_result = Vizier.query_region(
            SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg), frame="icrs"),
            width=height_str,
            height=base_str,
            catalog=[catalog],
        )
        return query_result
Exemplo n.º 24
0
def gaia_query(ra_deg, dec_deg, rad_deg, maxmag=20, 
               maxsources=10000): 
    """
    Query Gaia DR1 @ VizieR using astroquery.vizier
    parameters: ra_deg, dec_deg, rad_deg: RA, Dec, field 
                                          radius in degrees
                maxmag: upper limit G magnitude (optional)
                maxsources: maximum number of sources
    returns: astropy.table object
    """
    vquery = Vizier(columns=['Source', 'RA_ICRS', 'DE_ICRS', 
                             'phot_g_mean_mag'], 
                    column_filters={"phot_g_mean_mag": 
                                    ("<%f" % maxmag)}, 
                    row_limit = maxsources) 
 
    field = coord.SkyCoord(ra=ra_deg, dec=dec_deg, 
                           unit=(u.deg, u.deg), 
                           frame='icrs')
    return vquery.query_region(field, 
                               width=("%fd" % rad_deg), 
                               catalog="I/337/gaia")[0] 
Exemplo n.º 25
0
def query_cat(catalog, min_ra, max_ra, min_dec, max_dec, columns=None,
        column_filters=None):
    """
    Use vizquery to get a reference catalog from vizier
    """
    from astroquery.vizier import Vizier
    import numpy as np
    from astropy.coordinates import SkyCoord
    # Build vizquery statement
    width = int(np.ceil((max_ra-min_ra)*60))
    height = int(np.ceil((max_dec-min_dec)*60))
    center = SkyCoord((min_ra+max_ra)/2, (min_dec+max_dec)/2, unit='deg')
    
    # If no column filters are specified, use the defaults
    if column_filters is None:
        if catalog.startswith('SDSS'):
            column_filters = {
                'cl': '=6',
                'q_mode':'=+'
            }
        elif catalog.startswith('UKIDSS'):
            column_filters = {
                'cl': '=-1',
                'm': '=1'
            }
        else:
            column_filters = {}
    # Query the catalog in Vizier
    logger.info('columns:{0}'.format(columns))
    v = Vizier(columns=columns, column_filters=column_filters, 
        catalog=catalog_info[catalog]['info']['vizier_id'])
    v.ROW_LIMIT=200000
    result = v.query_region(center, width='{0}m'.format(width*1.25), 
        height='{0}m'.format(height*1.25))
    logger.warn(result[0].columns)
    refcat = result[0]
    
    return refcat
Exemplo n.º 26
0
def get_k2_epic_catalog():
    """
    Parameters
    ----------

    Returns
    -------
    """
    global k2_epic_table

    if k2_epic_table is None:
        catalogs = Vizier.get_catalogs(huber2016)
        k2_epic_table = catalogs[0]  # This is the table with the data
        k2_epic_table.add_index('EPIC')
    return k2_epic_table
Exemplo n.º 27
0
def get_duncan_catalog():
    """
    Parameters
    ----------

    Returns
    -------
    """
    global sindex_catalog

    if sindex_catalog is None:
        catalogs = Vizier.get_catalogs(duncan1991)
        sindex_catalog = catalogs[0]  # This is the table with the data

    return sindex_catalog
Exemplo n.º 28
0
def getSDSS(galaxy):
    """
    Query SDSS through Vizier, pick out only the stellar sources,
    and put the SDSS magnitudes into AB
    """
    Vizier.ROW_LIMIT = -1 # Removes row limit on output table
    result = Vizier.query_region(galaxy, radius=Angle(0.1, "deg"), catalog='SDSS')
    # Only select stellar sources
    index = []
    for i, entry in enumerate(result[1]):
        if entry['cl'] != 6:
            index.append(i)
    result[1].remove_rows(index)

    # SDSS magnitudes are not exactly in AB so need to correct
    return result[1]
Exemplo n.º 29
0
	def getVizierObjects(self, catalogName):
		""" Make a request to Vizier to get an Astropy Table of catalog object for this field. """
		(ra, dec) = self.centre
		
		availableCatalogs = catalogMetadata.keys()
		if catalogName not in availableCatalogs:
			print "The definitions for this catalogue are unknown. Available catalogues are:", availableCatalogs
			return
		
		# First look for a cached copy of this data
		filenameParts = self.filename.split('.')
		catalogCache = filenameParts[0] + "_" + catalogName + "_cache.fits"
		cached = False
		if not self.ignorecache:
			print "Looking for a cached copy of the catalogue:", catalogCache, 
			if os.path.exists(catalogCache):
				print "FOUND"
				cached = True
			else: print "NOT FOUND"
	
		if cached:
			newCatalog = Table.read(catalogCache)
		else:			
			print "Going online to fetch %s results from Vizier with mag limit %f."%(catalogName, self.magLimit)
			from astroquery.vizier import Vizier
			Vizier.ROW_LIMIT = 1E5
			Vizier.column_filters={"r":"<%d"%self.magLimit}
			from astropy import coordinates
			from astropy import units as u
			c = coordinates.SkyCoord(ra,dec,unit=('deg','deg'),frame='icrs')
			skyRA  = coordinates.Angle(self.raRange, unit = u.deg)
			skyDEC = coordinates.Angle(self.decRange, unit = u.deg)
			print "Sky RA, DEC range:", skyRA, skyDEC
			print "going to Astroquery for:", catalogMetadata[catalogName]['VizierLookup']
			result = Vizier.query_region(coordinates = c, width = skyRA, height = skyDEC, catalog = catalogMetadata[catalogName]['VizierName'], verbose=True)
			print result
			newCatalog = result[catalogMetadata[catalogName]['VizierName']]
			newCatalog.pprint()
			
			
			# Write the new catalog to the cache file
			newCatalog.write(catalogCache, format='fits', overwrite=True)
		
		self.addCatalog(newCatalog, catalogName)
		
		return
Exemplo n.º 30
0
    def __init__(self, config=None):

        """
        The constructor ...
        :param config:
        :return:
        """

        # Call the constructor of the base class
        super(GalaxyDecomposer, self).__init__(config)

        # The NGC name of the galaxy
        self.ngc_id = None
        self.ngc_id_nospaces = None

        # The Vizier querying object
        self.vizier = Vizier()
        self.vizier.ROW_LIMIT = -1

        # The bulge and disk parameters
        self.parameters = Map()

        # The SKIRT execution context
        self.skirt = SkirtExec()

        # The bulge and disk model
        self.bulge = None
        self.disk = None

        # The bulge and disk image
        self.bulge_image = None
        self.disk_image = None
        self.model_image = None

        # The projection systems
        self.projections = dict()

        # The instruments
        self.instruments = dict()

        # The reference coordinate system
        self.reference_wcs = None

        # The PSF (of the reference image) for convolution with the simulated images
        self.psf = None
Exemplo n.º 31
0
from astroquery.vizier import Vizier



v = Vizier(columns=['Vmag', 'b-y','m1','c1','Beta'], catalog="II/215/catalog")
result =  v.query_object('HD  48915')[0][0]
print (result)
Exemplo n.º 32
0
                        unit=u.arcsec), index=3)

    # remove error ellipse columns
    data.remove_column('errMaj')
    data.remove_column('errMin')
    data.remove_column('errPA')

    return data


max_mag = 21
max_sources = 1e5

vquery = Vizier(columns=['2MASS', 'RAJ2000', 'DEJ2000', 'errMaj', 'errMin',
                         'errPA', 'Jmag', 'e_Jmag', 'Hmag', 'e_Hmag', 'Kmag',
                         'e_Kmag', 'Qflg'],
                column_filters={"Jmag": ("<%f" % max_mag)},
                row_limit=max_sources)

data = numpy.genfromtxt('../catalogs/PSZ2_unconfirmed_catalog - Master.csv',
                     delimiter=',', names=True, dtype=None)

for i, (ra, dec, name) in enumerate(zip(data['RA'], data['DEC'],
                                        data['Name'])):
    print(data['Name'][i])

    result = work(vquery, ra, dec, '{}'.format(name))
    ascii.write(result, format='csv', output='./2MASS/%s_2MASS_catalog.csv' %
                (name.decode()))
    sleep(1)
Exemplo n.º 33
0
def get_catalog(params, map_struct):
    if not os.path.isdir(params["catalogDir"]):
        os.makedirs(params["catalogDir"])

    catalogFile = os.path.join(params["catalogDir"],
                               "%s.hdf5" % params["galaxy_catalog"])
    """AB Magnitude zero point."""
    MAB0 = -2.5 * np.log10(3631.e-23)
    pc_cm = 3.08568025e18
    const = 4. * np.pi * (10. * pc_cm)**2.

    if params["galaxy_catalog"] == "2MRS":
        if not os.path.isfile(catalogFile):
            import astropy.constants as c

            cat, = Vizier.get_catalogs('J/ApJS/199/26/table3')

            ra, dec = cat["RAJ2000"], cat["DEJ2000"]
            cz = cat["cz"]
            magk = cat["Ktmag"]

            z = (u.Quantity(cat['cz']) / c.c).to(u.dimensionless_unscaled)

            completeness = 0.5
            alpha = -1.0
            MK_star = -23.55
            MK_max = MK_star + 2.5 * np.log10(
                gammaincinv(alpha + 2, completeness))
            MK = magk - cosmo.distmod(z)
            idx = (z > 0) & (MK < MK_max)

            ra, dec = ra[idx], dec[idx]
            z = z[idx]
            magk = magk[idx]

            distmpc = cosmo.luminosity_distance(z).to('Mpc').value

            with h5py.File(catalogFile, 'w') as f:
                f.create_dataset('ra', data=ra)
                f.create_dataset('dec', data=dec)
                f.create_dataset('z', data=z)
                f.create_dataset('magk', data=magk)
                f.create_dataset('distmpc', data=distmpc)

        else:
            with h5py.File(catalogFile, 'r') as f:
                ra, dec = f['ra'][:], f['dec'][:]
                z = f['z'][:]
                magk = f['magk'][:]
                distmpc = f['distmpc'][:]
        r = distmpc * 1.0
        mag = magk * 1.0

    elif params["galaxy_catalog"] == "GLADE":
        if not os.path.isfile(catalogFile):
            cat, = Vizier.get_catalogs('VII/281/glade2')

            ra, dec = cat["RAJ2000"], cat["DEJ2000"]
            distmpc, z = cat["Dist"], cat["z"]
            magb, magk = cat["Bmag"], cat["Kmag"]
            # Keep track of galaxy identifier
            GWGC, PGC, HyperLEDA = cat["GWGC"], cat["PGC"], cat["HyperLEDA"]
            _2MASS, SDSS = cat["_2MASS"], cat["SDSS-DR12"]

            idx = np.where(distmpc >= 0)[0]
            ra, dec = ra[idx], dec[idx]
            distmpc, z = distmpc[idx], z[idx]
            magb, magk = magb[idx], magk[idx]
            GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
            _2MASS, SDSS = _2MASS[idx], SDSS[idx]

            with h5py.File(catalogFile, 'w') as f:
                f.create_dataset('ra', data=ra)
                f.create_dataset('dec', data=dec)
                f.create_dataset('distmpc', data=distmpc)
                f.create_dataset('magb', data=magb)
                f.create_dataset('magk', data=magk)
                f.create_dataset('z', data=z)
                # Add galaxy identifier
                f.create_dataset('GWGC', data=GWGC)
                f.create_dataset('PGC', data=PGC)
                f.create_dataset('HyperLEDA', data=HyperLEDA)
                f.create_dataset('2MASS', data=_2MASS)
                f.create_dataset('SDSS', data=SDSS)

        else:
            with h5py.File(catalogFile, 'r') as f:
                ra, dec = f['ra'][:], f['dec'][:]
                distmpc, z = f['distmpc'][:], f['z'][:]
                magb, magk = f['magb'][:], f['magk'][:]
                GWGC, PGC, _2MASS = f['GWGC'][:], f['PGC'][:], f['2MASS'][:]
                HyperLEDA, SDSS = f['HyperLEDA'][:], f['SDSS'][:]
                # Convert bytestring to unicode
                GWGC = GWGC.astype('U')
                PGC = PGC.astype('U')
                HyperLEDA = HyperLEDA.astype('U')
                _2MASS = _2MASS.astype('U')
                SDSS = SDSS.astype('U')

        # Keep only galaxies with finite B mag when using it in the grade
        if params["galaxy_grade"] == "S":
            idx = np.where(~np.isnan(magb))[0]
            ra, dec, distmpc = ra[idx], dec[idx], distmpc[idx]
            magb, magk = magb[idx], magk[idx]
            GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
            _2MASS, SDSS = _2MASS[idx], SDSS[idx]

        r = distmpc * 1.0
        mag = magb * 1.0

    elif params["galaxy_catalog"] == "CLU":
        if not os.path.isfile(catalogFile):
            raise ValueError("Please add %s." % catalogFile)

        t = Table.read(catalogFile)
        name = t["name"]
        ra, dec = t["ra"], t["dec"]
        sfr_fuv, mstar = t["sfr_fuv"], t["mstar"]
        distmpc, magb = t["distmpc"], t["magb"]
        a, b2a, pa = t["a"], t["b2a"], t["pa"]
        btc = t["btc"]

        idx = np.where(distmpc >= 0)[0]
        ra, dec = ra[idx], dec[idx]
        sfr_fuv, mstar = sfr_fuv[idx], mstar[idx]
        distmpc, magb = distmpc[idx], magb[idx]
        a, b2a, pa = a[idx], b2a[idx], pa[idx]
        btc = btc[idx]

        idx = np.where(~np.isnan(magb))[0]
        ra, dec = ra[idx], dec[idx]
        sfr_fuv, mstar = sfr_fuv[idx], mstar[idx]
        distmpc, magb = distmpc[idx], magb[idx]
        a, b2a, pa = a[idx], b2a[idx], pa[idx]
        btc = btc[idx]

        z = -1 * np.ones(distmpc.shape)
        r = distmpc * 1.0
        mag = magb * 1.0

    n, cl = params["powerlaw_n"], params["powerlaw_cl"]
    dist_exp = params["powerlaw_dist_exp"]

    prob_scaled = copy.deepcopy(map_struct["prob"])
    prob_sorted = np.sort(prob_scaled)[::-1]
    prob_indexes = np.argsort(prob_scaled)[::-1]
    prob_cumsum = np.cumsum(prob_sorted)
    index = np.argmin(np.abs(prob_cumsum - cl)) + 1
    prob_scaled[prob_indexes[index:]] = 0.0
    prob_scaled = prob_scaled**n

    theta = 0.5 * np.pi - dec * 2 * np.pi / 360.0
    phi = ra * 2 * np.pi / 360.0
    ipix = hp.ang2pix(map_struct["nside"], ra, dec, lonlat=True)

    if "distnorm" in map_struct:
        if map_struct["distnorm"] is not None:

            #creat an mask to cut at 3 sigma in distance
            mask = np.zeros(len(r))

            condition_indexer = np.where(
                (r < (map_struct["distmu"][ipix] +
                      (3 * map_struct["distsigma"][ipix])))
                & (r > (map_struct["distmu"][ipix] -
                        (3 * map_struct["distsigma"][ipix]))))
            mask[condition_indexer] = 1

            Sloc = prob_scaled[ipix] * (map_struct["distnorm"][ipix] * norm(
                map_struct["distmu"][ipix], map_struct["distsigma"][ipix]).pdf(
                    r))**params["powerlaw_dist_exp"] / map_struct["pixarea"]

            #multiplie the Sloc by 1 or 0 according to the 3 sigma condistion
            Sloc = Sloc * mask
            idx = np.where(condition_indexer)[0]
        else:
            Sloc = copy.copy(prob_scaled[ipix])
            idx = np.arange(len(r)).astype(int)
    else:
        Sloc = copy.copy(prob_scaled[ipix])
        idx = np.arange(len(r)).astype(int)

    # this happens when we are using a tiny catalog...
    if len(idx) == 0:
        idx = np.arange(len(r)).astype(int)
    if np.all(Sloc == 0.0):
        Sloc[:] = 1.0

    L_nu = const * 10.**((mag + MAB0) / (-2.5))
    idx2 = np.where(~np.isfinite(L_nu))[0]
    L_nu[idx2] = 0.0
    L_nu = L_nu / np.nanmax(L_nu[idx])
    L_nu = L_nu**params["catalog_n"]
    L_nu[L_nu < 0.001] = 0.001
    L_nu[L_nu > 1.0] = 1.0
    Slum = L_nu / np.sum(L_nu)

    mlim, M_KNmin, M_KNmax = 22, -17, -12
    L_KNmin = const * 10.**((M_KNmin + MAB0) / (-2.5))
    L_KNmax = const * 10.**((M_KNmax + MAB0) / (-2.5))

    Llim = 4. * np.pi * (r * 1e6 * pc_cm)**2. * 10.**((mlim + MAB0) / (-2.5))
    Sdet = (L_KNmax - Llim) / (L_KNmax - L_KNmin)
    Sdet[Sdet < 0.01] = 0.01
    Sdet[Sdet > 1.0] = 1.0

    # Set nan values to zero
    Sloc[np.isnan(Sloc)] = 0
    Slum[np.isnan(Slum)] = 0

    S = Sloc * Slum * Sdet

    prob = np.zeros(map_struct["prob"].shape)
    if params["galaxy_grade"] == "Sloc":
        for j in range(len(ipix)):
            prob[ipix[j]] += Sloc[j]
        grade = Sloc
    elif params["galaxy_grade"] == "S":
        for j in range(len(ipix)):
            prob[ipix[j]] += S[j]
        grade = S

    #prob[prob==0] = 1e-10
    prob = prob / np.sum(prob)

    map_struct['prob_catalog'] = prob
    if params["doUseCatalog"]:
        map_struct['prob'] = prob

    idx = np.where(~np.isnan(grade))[0]
    grade = grade[idx]
    ra, dec, Sloc, S = ra[idx], dec[idx], Sloc[idx], S[idx]
    distmpc, z = distmpc[idx], z[idx]
    if params["galaxy_catalog"] == "GLADE":
        GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
        _2MASS, SDSS = _2MASS[idx], SDSS[idx]
    """
    Sthresh = np.max(grade)*0.01
    idx = np.where(grade >= Sthresh)[0]
    grade = grade[idx]
    ra, dec, Sloc, S = ra[idx], dec[idx], Sloc[idx], S[idx]
    distmpc, z = distmpc[idx], z[idx]
    if params["galaxy_catalog"] == "GLADE":
        GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
        _2MASS, SDSS = _2MASS[idx], SDSS[idx]
    """

    idx = np.argsort(grade)[::-1]
    grade = grade[idx]

    ra, dec, Sloc, S = ra[idx], dec[idx], Sloc[idx], S[idx]
    distmpc, z = distmpc[idx], z[idx]
    if params["galaxy_catalog"] == "GLADE":
        GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
        _2MASS, SDSS = _2MASS[idx], SDSS[idx]

    # Keep only galaxies within 3sigma in distance
    mask = Sloc > 0
    ra, dec, Sloc, S = ra[mask], dec[mask], Sloc[mask], S[mask]
    distmpc, z = distmpc[mask], z[mask]
    if params["galaxy_catalog"] == "GLADE":
        GWGC, PGC, HyperLEDA = GWGC[mask], PGC[mask], HyperLEDA[mask]
        _2MASS, SDSS = _2MASS[mask], SDSS[mask]

    if len(ra) > 2000:
        print('Cutting catalog to top 2000 galaxies...')
        idx = np.arange(2000).astype(int)
        ra, dec, Sloc, S = ra[idx], dec[idx], Sloc[idx], S[idx]
        distmpc, z = distmpc[idx], z[idx]
        if params["galaxy_catalog"] == "GLADE":
            GWGC, PGC, HyperLEDA = GWGC[idx], PGC[idx], HyperLEDA[idx]
            _2MASS, SDSS = _2MASS[idx], SDSS[idx]

    # now normalize the distributions
    S = S / np.sum(S)
    Sloc = Sloc / np.sum(Sloc)

    catalog_struct = {}
    catalog_struct["ra"] = ra
    catalog_struct["dec"] = dec
    catalog_struct["Sloc"] = Sloc
    catalog_struct["S"] = S

    if params["writeCatalog"]:
        catalogfile = os.path.join(params["outputDir"], 'catalog.csv')
        fid = open(catalogfile, 'w')
        cnt = 1
        if params["galaxy_catalog"] == "GLADE":
            fid.write(
                "id, RAJ2000, DEJ2000, Sloc, S, Dist, z, GWGC, PGC, HyperLEDA, 2MASS, SDSS\n"
            )
            for a, b, c, d, e, f, g, h, i, j, k in zip(ra, dec, Sloc, S,
                                                       distmpc, z, GWGC, PGC,
                                                       HyperLEDA, _2MASS,
                                                       SDSS):
                fid.write(
                    "%d, %.5f, %.5f, %.5e, %.5e, %.4f, %.4f, %s, %s, %s, %s, %s\n"
                    % (cnt, a, b, c, d, e, f, g, h, i, j, k))
                cnt = cnt + 1
        else:
            fid.write("id, RAJ2000, DEJ2000, Sloc, S, Dist, z\n")
            for a, b, c, d, e, f in zip(ra, dec, Sloc, S, distmpc, z):
                fid.write("%d, %.5f, %.5f, %.5e, %.5e, %.4f, %.4f\n" %
                          (cnt, a, b, c, d, e, f))
                cnt = cnt + 1

        fid.close()

    return map_struct, catalog_struct
Exemplo n.º 34
0
    def __init__(
        self, path_to_iad_file, hip_num, num_secondary_bodies,
        alphadec0_epoch=1991.25, renormalize_errors=False
    ):

        self.path_to_iad_file = path_to_iad_file
        self.renormalize_errors = renormalize_errors

        # infer if the IAD file is an older DVD file or a new file
        with open(path_to_iad_file, 'r') as f:
            first_char = f.readline()[0]

            # newer format files don't start with comments
            if first_char == '#':
                dvd_file = False
            else:
                dvd_file = True

        self.hip_num = hip_num
        self.num_secondary_bodies = num_secondary_bodies
        self.alphadec0_epoch = alphadec0_epoch

        # dvd files don't contain the Hipparcos astrometric solution, so
        # we need to look it up
        if dvd_file:

            # load best-fit astrometric solution from Sep 08 van Leeuwen catalog
            # (https://cdsarc.unistra.fr/ftp/I/311/ReadMe)
            Vizier.ROW_LIMIT = -1
            hip_cat = Vizier(
                catalog='I/311/hip2', 
                columns=[
                    'RArad', 'e_RArad', 'DErad', 'e_DErad', 'Plx', 'e_Plx', 'pmRA', 
                    'e_pmRA', 'pmDE', 'e_pmDE', 'F2', 'Sn'
                ]
            ).query_constraints(HIP=self.hip_num)[0]

            self.plx0 = hip_cat['Plx'][0] # [mas]
            self.pm_ra0 = hip_cat['pmRA'][0] # [mas/yr]
            self.pm_dec0 = hip_cat['pmDE'][0] # [mas/yr]
            self.alpha0 = hip_cat['RArad'][0] # [deg]
            self.delta0 = hip_cat['DErad'][0] # [deg]
            self.plx0_err = hip_cat['e_Plx'][0] # [mas]
            self.pm_ra0_err = hip_cat['e_pmRA'][0] # [mas/yr]
            self.pm_dec0_err = hip_cat['e_pmDE'][0] # [mas/yr]
            self.alpha0_err = hip_cat['e_RArad'][0] # [mas]
            self.delta0_err = hip_cat['e_DErad'][0] # [mas]

            solution_type = hip_cat['Sn'][0]
            f2 = hip_cat['F2'][0]
        
        else:
            
            # read the Hipparcos best-fit solution from the IAD file
            astrometric_solution = pd.read_csv(path_to_iad_file, skiprows=9, sep='\s+', nrows=1)
            self.plx0 = astrometric_solution['Plx'].values[0] # [mas]
            self.pm_ra0 = astrometric_solution['pm_RA'].values[0] # [mas/yr]
            self.pm_dec0 = astrometric_solution['pm_DE'].values[0] # [mas/yr]
            self.alpha0 = astrometric_solution['RAdeg'].values[0] # [deg]
            self.delta0 = astrometric_solution['DEdeg'].values[0] # [deg]
            self.plx0_err =  astrometric_solution['e_Plx'].values[0] # [mas]
            self.pm_ra0_err = astrometric_solution['e_pmRA'].values[0] # [mas/yr]
            self.pm_dec0_err = astrometric_solution['e_pmDE'].values[0] # [mas/yr]
            self.alpha0_err = astrometric_solution['e_RA'].values[0] # [mas]
            self.delta0_err = astrometric_solution['e_DE'].values[0] # [mas]

            solution_details = pd.read_csv(path_to_iad_file, skiprows=5, sep='\s+', nrows=1)

            solution_type = solution_details['isol_n'].values[0]
            f2 = solution_details['F2'].values[0]


        if solution_type != 5:
            raise ValueError(
                """
                Currently, we only handle stars with 5-parameter astrometric 
                solutions from Hipparcos. Let us know if you'd like us to add 
                functionality for stars with >5 parameter solutions.
                """
            )

        # read in IAD
        if dvd_file:
            iad = np.transpose(np.loadtxt(path_to_iad_file, skiprows=1))
        else:
            iad = np.transpose(np.loadtxt(path_to_iad_file))

        n_lines = len(iad)

        times = iad[1] + 1991.25
        self.cos_phi = iad[3] # scan direction
        self.sin_phi = iad[4]
        self.R = iad[5] # abscissa residual [mas]
        self.eps = iad[6] # error on abscissa residual [mas]

        # reject negative errors (scans that were rejected by Hipparcos team)
        good_scans = np.where(self.eps > 0)[0]

        if n_lines - len(good_scans) > 0:
            print('{} Hipparcos scans rejected.'.format(n_lines - len(good_scans)))
        times = times[good_scans]
        self.cos_phi = self.cos_phi[good_scans]
        self.sin_phi = self.sin_phi[good_scans]
        self.R = self.R[good_scans]
        self.eps = self.eps[good_scans]

        epochs = Time(times, format='decimalyear')
        self.epochs = epochs.decimalyear
        self.epochs_mjd = epochs.mjd

        if self.renormalize_errors:
            D = len(epochs) - 6
            G = f2

            f = (
                G * np.sqrt(2 / (9 * D)) + 
                1 - 
                (2 / (9 * D))
            )**(3/2)

            self.eps *= f

        # compute Earth XYZ position in barycentric coordinates
        bary_pos, _ = get_body_barycentric_posvel('earth', epochs)
        self.X = bary_pos.x.value # [au]
        self.Y = bary_pos.y.value # [au]
        self.Z = bary_pos.z.value # [au]

        # reconstruct ephemeris of star given van Leeuwen best-fit (Nielsen+ 2020 Eqs 1-2) [mas]
        changein_alpha_st = (
            self.plx0 * (
                self.X * np.sin(np.radians(self.alpha0)) - 
                self.Y * np.cos(np.radians(self.alpha0))
            ) + (self.epochs - 1991.25) * self.pm_ra0
        )

        changein_delta = (
            self.plx0 * (
                self.X * np.cos(np.radians(self.alpha0)) * np.sin(np.radians(self.delta0)) + 
                self.Y * np.sin(np.radians(self.alpha0)) * np.sin(np.radians(self.delta0)) - 
                self.Z * np.cos(np.radians(self.delta0))
            ) + (self.epochs - 1991.25) * self.pm_dec0
        )

        # compute abcissa point (Nielsen+ Eq 3)
        self.alpha_abs_st = self.R * self.cos_phi + changein_alpha_st
        self.delta_abs = self.R * self.sin_phi + changein_delta
Exemplo n.º 35
0
error_tot = np.sqrt(error.dot(error.T)) * 1e3
if error_tot > 100:
    warnings.warn("Satellite position off by more than 100 m")

velocity_stk_eci = np.array([1.031261, 0.146421, 7.510402])
error = np.array([position_ecef.velocity.d_x.value,position_ecef.velocity.d_y.value,position_ecef.velocity.d_z.value]) - \
        velocity_stk_eci

error_tot = np.sqrt(error.dot(error.T)) * 1e3
if error_tot > 500:
    warnings.warn("Satellite velocity off by more than 500 m/s")

#Find look vector for tangent point of MATS (92 km in orbit plane)

#Find orbit plane for two positions

#test star gazing
Vizier.ROW_LIMIT = 50
catalog_list = Vizier.find_catalogs('UCAC4')
catalogs = Vizier.get_catalogs(catalog_list.keys())

v = Vizier(columns=['_RAJ2000', '_DEJ2000', 'Vmag'],
           column_filters={"Vmag": "<10"})

result = v.query_region(coord.SkyCoord(ra=299.590,
                                       dec=35.201,
                                       unit=(u.deg, u.deg),
                                       frame='icrs'),
                        width="60m",
                        height="60m",
                        catalog=["I/322A"])
Exemplo n.º 36
0
def WDGaiaRadius(ra,dec,teff,teff_err=None,searchradius=5.0,modelmass=0.6,
                 modelpath='AllModels/',A_G=0):
    """Estimate WD Radius from Gaia astrometry.
    
    Queries for Gaia data and distances from Bailer-Jones et al. (2018, ApJ, 156, 2).
    Scales Bergeron et al. DA (no DBs currently) cooling models 
    (http://www.astro.umontreal.ca/~bergeron/CoolingModels/)
    until the radius reproduces the Gaia magnitude at the parallactic distance.
    Corrects for extinction if coefficient A_G is provided in magnitudes, 
    following the prescription of Gentile-Fusillo et al. (2019, MNRAS, 482, 4570).
    Uses https://github.com/keatonb/BergeronToPandas to read in Bergeron models.
    If error on Teff given, includes contribution roughly in quadrature.
    Returns measurement and lower, upper bounds defined by Bailer-Jones et al. 
    confidence interval.
    
    ra, dec should be in decimal degrees
    teff,teff_err in Kelvin from spectroscopy
    searchradius is in arcseconds
    modelmass in solar units must match a file from the Bergeron models
                that is new enough to include synthetic Gaia magnitudes.
    """
    #First query Gaia sources
    coord = SkyCoord(ra=ra, dec=dec, unit=(u.degree, u.degree), frame='icrs')
    searchradius = u.Quantity(searchradius, u.arcsec)
    j = Gaia.cone_search_async(coord, searchradius)
    r = j.get_results()
    print("Gaia sources within {}: {}".format(searchradius,len(r)))
    if len(r) > 0:
        r.sort("dist")
        #Accept nearest
        sourceid = r["source_id"][0]
        Gmag = r["phot_g_mean_mag"][0]
        print("Nearest has Gaia G mag of {}.".format(Gmag))
        b = r["b"][0] #Galactic latitude in degrees
        #Extinction correction following Gentile-Fusillo et al. 2019
        parallax = r["parallax"][0]*1e-3 #arcsec
        extcorr = -A_G*(1. - np.exp(-np.sin(np.abs(b*np.pi/180)) / (200*parallax)))
        Gmag += extcorr
        print("Extinction correction of {} then applied to get G = {} mag.".format(extcorr,Gmag))
        
        
        #Then get Bailer-Jones distance
        v = Vizier(columns=['*'],
                column_filters={"Source":str(sourceid)}).get_catalogs('I/347')
        dist = np.array([v[0]["rest"][0],v[0]["b_rest"][0],v[0]["B_rest"][0]])
        print("Distance constraints from Bailer-Jones et al: {}".format(dist))
        
        #Referencing Bergeron cooling models
        modelfile = os.path.join(modelpath, "Table_Mass_{:.1f}".format(modelmass))
        print("Referencing Bergeron model file at "+modelfile)
        
        models = list(BergeronToPandas(modelfile).values())[0]
        
        #Constants
        G = 6.67259e-8 #cm3 g-1 s-2
        Msun = 1.99e33 #g
        Rsun = 6.96e10 #cm
        
        modelteff = models['Teff'].values
        modellogg = models['logg'].values
        modelradius = np.sqrt(G*modelmass*Msun/(10.**modellogg))/Rsun #solar radii
        
        modelGmag = models['G'].values
        
        #Define interpolation functions
        teff2radius = interp1d(modelteff,modelradius)
        teff2Gmag = interp1d(modelteff,modelGmag)
        
        distancemodulus = 5.*np.log10(dist)-5.
        
        #Start with values assuming along loaded model track
        trackradius = teff2radius(teff)
        trackGmag = teff2Gmag(teff)
        estGmag = trackGmag + distancemodulus 
        
        #Scale to measured magnitude
        remaining = estGmag - Gmag
        fluxratio = 2.512**remaining
        radiusratio = np.sqrt(fluxratio)
        gaiaradius = trackradius * radiusratio
        
        #Include effect of Teff_err if given
        if teff_err is not None:
            testteff = np.array([teff,teff+teff_err,teff-teff_err])
            trackradius = teff2radius(testteff)
            trackGmag = teff2Gmag(testteff)
            estGmag = trackGmag + distancemodulus[0]
            remaining = estGmag - Gmag
            fluxratio = 2.512**remaining
            radiusratio = np.sqrt(fluxratio)
            gr2 = trackradius * radiusratio
            #combine roughly in quadrature
            gaiaradius = gaiaradius[0] + np.sqrt((gaiaradius - gaiaradius[0])**2. + 
                                                 (gr2 - gr2[0])**2.)*np.array([1,-1,1])
        return gaiaradius
    else: #No Gaia results?
        print("Returning 'None's")
        return None,None,None
Exemplo n.º 37
0
import astropy.units as u
from astropy.coordinates import SkyCoord
from astroquery.vizier import Vizier
import numpy as np

import mixfit
import matplotlib.pyplot as plt
import json
from scipy.stats import norm
from mpl_toolkits.mplot3d import Axes3D

center_coord = SkyCoord('02h21m00s +57d07m42s')
vizier = Vizier(
    column_filters={'Bmag': '<13'},  # число больше — звёзд больше
    row_limit=10000)
stars = vizier.query_region(center_coord,
                            width=1.5 * u.deg,
                            height=1.5 * u.deg,
                            catalog='USNO-A2.0')[0]
# print(stars)
ra = stars['RAJ2000'].data  # прямое восхождение, аналог долготы
dec = stars['DEJ2000'].data  # склонение, аналог широты
x1 = (ra - ra.mean()) * np.cos(dec / 180 * np.pi)
x2 = dec


def data(tmp):
    for i in range(len(x1)):
        tmp.append([x1[i], x2[i]])
    tmp = np.asarray(tmp)
    return tmp
Exemplo n.º 38
0
         if args.individual == 'True' or args.individual == 'yes':
             for sci in sci_list:
                 with fits.open(red_path + os.path.basename(sci),
                                mode='update') as hdr_ind:
                     header = hdr_ind[0].header
                     header['CRVAL1'] = gaia_star[0][0]
                     header['CRVAL2'] = gaia_star[0][1]
                     header['CRPIX1'] = source_star[0][0]
                     header['CRPIX2'] = source_star[0][1]
 if args.phot == 'True' or args.phot == 'yes':
     zp_cal = True
     if fil == 'Y':
         twomass_filter = 'Ymag'
         twomass = Vizier.query_region(SkyCoord(
             hdr[0].header['CRVAL1'] * u.deg,
             hdr[0].header['CRVAL2'] * u.deg,
             frame='fk5'),
                                       catalog="II/319",
                                       radius=4 * u.arcmin)[0]
     else:
         twomass_filter = fil.lower() + '_m'
         twomass = Irsa.query_region(SkyCoord(
             hdr[0].header['CRVAL1'] * u.deg,
             hdr[0].header['CRVAL2'] * u.deg,
             frame='fk5'),
                                     catalog="fp_psc",
                                     spatial="Cone",
                                     radius=4 * u.arcmin)
     if len(twomass) != 0:
         pass
     else:
         log.info('No 2MASS stars available in this field.')
Exemplo n.º 39
0
 Ng = 0 #we put the object to the beggining, so its index = 0 now
 with open(outfile, 'a') as f:
     f.write('Gaia index of the object: ' + str(Ng) + '\n')
     f.write('-----------------------------------------------------------------------------------------------' + '\n')
 #all the cats without ucac4 (it will be after all ##############################################################
 # --------------------------------------------------------------------------------------------------------------
 for icat in range(len(names)):
     object = True
     Ncatname = Nnames[icat]
     catname = names[icat]
     link = links[icat]
     #print(catname)
     test = True
     try:
         table = Vizier(columns=['all']).query_region(
             coord.SkyCoord(ra=str(ra0), dec=str(dec0), unit=(u.deg, u.deg), frame='icrs'), Angle(fov, "deg"),
             catalog=[link])[0]
     except IndexError:
         test = False
         print(Ncatname + ': connection attempt FAILED')
         logstring = logstring + '\t' + '|' + 'nan' + '\t' + 'nan' + '\t' + 'nan' + '\t' + 'nan' + '\t' + 'nan' + '\t' + 'nan'
         with open(outfile, 'a') as f:
             f.write(catname + ': connection attempt FAILED' + '\n')
     #break
     if test:
         print(Ncatname + ': SUCCESS!  PREVIOUS NUMBER OF STARS IN FOV = ' + str(fov*3600) + ' arcsec: ', len(table))
         # break
         #if (catname == '2MASS All-Sky'):
         #    print(table.columns)
         # print(table.columns)
         # for column in table.columns:
Exemplo n.º 40
0
bj = np.zeros(len(data), dtype=str)
bh = np.zeros(len(data), dtype=str)
bk = np.zeros(len(data), dtype=str)
flag = np.zeros(len(data), dtype=int)

start, J, H, K, sig_J, sig_H, sig_K, qj, qh, qk, bj, bh, bk, flag = pickle.load(
    open(datafile.split('.')[0] + '_X2MASS_progress.pkl', 'rb'))

pdb.set_trace()
for i in range(start, len(data)):
    queryname = 'Gaia DR2 ' + str(
        data.source_id.values[i])  ##The official object name out of Gaia
    try:
        #stuff0 =  Vizier.query_region(queryname,radius="0d0m5s",catalog='I/345/gaia2')
        stuff1 = Vizier.query_region(queryname,
                                     radius="0d0m3s",
                                     catalog='II/246/out')
    except:  ##try at least twice before quitting
        print('Excepted on first query??!!??')
        #stuff0 =  Vizier.query_region(queryname,radius="0d0m5s",catalog='I/345/gaia2')
        stuff1 = Vizier.query_region(queryname,
                                     radius="0d0m3s",
                                     catalog='II/246/out')
    #if len(stuff0) == 0:
    #    print('Cant find Gaia DR2 entry, thats bad...')
    #    pdb.set_trace()

    if (len(stuff1) > 1): pdb.set_trace()
    if (len(stuff1) == 1
        ):  ##if something in 2mass and assuming Gaia source is found
        cl = np.argmin(stuff1[0]['_r'])
Exemplo n.º 41
0
class SEDFetcher(OldConfigurable):
    """
    This class ...
    """
    def __init__(self, config=None):
        """
        The constructor ...
        """

        # Call the constructor of the base class
        super(SEDFetcher, self).__init__(config, "modeling")

        # -- Attributes --

        # The name of the galaxy
        self.galaxy_name = None

        # The NGC ID of the galaxy
        self.ngc_id = None

        # The Vizier querying object
        self.vizier = Vizier(keywords=["galaxies"])
        self.vizier.ROW_LIMIT = -1

        # The observed SED
        self.seds = dict()

        # The filters
        self.filters = dict()

    # -----------------------------------------------------------------

    @classmethod
    def from_arguments(cls, arguments):
        """
        This function ...
        :param arguments:
        :return:
        """

        # Create a new SEDFetcher instance
        if arguments.config is not None: fetcher = cls(arguments.config)
        elif arguments.settings is not None: fetcher = cls(arguments.settings)
        else: fetcher = cls()

        # Set the output path
        if arguments.output_path is not None:
            fetcher.config.output_path = arguments.output_path

        # Run from the command line, so always write out the SEDs
        fetcher.config.write_seds = True
        fetcher.config.writing.seds_path = "SEDs"

        # Return the new instance
        return fetcher

    # -----------------------------------------------------------------

    def run(self, galaxy_name):
        """
        This function ...
        :param galaxy_name
        """

        # 1. Call the setup function
        self.setup(galaxy_name)

        # 2. If requested, query the GALEX ultraviolet atlas of nearby galaxies catalog (Gil de Paz+, 2007)
        if "GALEX" in self.config.catalogs: self.get_galex()

        # 3. If requested, query the 2MASS Extended sources catalog (IPAC/UMass, 2003-2006)
        if "2MASS" in self.config.catalogs: self.get_2mass()

        # SDSS ?
        # Ilse "Voor de galaxieen in de noordelijke hemisfeer heb je SDSS data beschikbaar, en die kan je dan
        # beter gebruiken (ipv. SINGS) om je fit te constrainen in het optische gebied. Er zal binnenkort een nieuwe
        # paper van Daniel Dale uitkomen met gehercalibreerde fluxen in de optische banden, die je dan kan gebruiken.

        # 5. If requested, query the Radial distribution in SINGS galaxies (I.) catalogs (Munoz-Mateos+, 2009)
        # Opm. Ilse: "voor vele SINGS galaxieen is de calibratie van de optische data heel slecht, dus krijg je een
        # offset en datapunten die een beetje random blijken te zijn."
        if "SINGS" in self.config.catalogs: self.get_sings()

        # If requested, query the LVL global optical photometry (Cook+, 2014) catalog
        if "LVL" in self.config.catalogs: self.get_lvl()

        # If requested, query the Spitzer Local Volume Legacy: IR photometry (Dale+, 2009)
        if "Spitzer" in self.config.catalogs: self.get_spitzer()

        # If requested, query the Spitzer/IRS ATLAS project source (Hernan-Caballero+, 2011)
        if "Spitzer/IRS" in self.config.catalogs: self.get_spitzer_irs()

        # If requested, query the Compendium of ISO far-IR extragalactic data (Brauher+, 2008)
        if "IRAS" in self.config.catalogs: self.get_iras()

        # If requested, query the Imperial IRAS-FSC redshift catalogue (IIFSCz) (Wang+, 2009)
        if "IRAS-FSC" in self.config.catalogs: self.get_iras_fsc()

        # If requested, query the S4G catalog for IRAC fluxes
        if "S4G" in self.config.catalogs: self.get_s4g()

        # If requested, query the Spectroscopy and abundances of SINGS galaxies (Moustakas+, 2010) catalog
        if "Emission lines" in self.config.catalogs: self.get_emission_lines()

        # If requested, query the Atlas of UV-to-MIR galaxy SEDs (Brown+, 2014)
        if "Brown" in self.config.catalogs: self.get_brown()

        # If requested, query the Planck Catalog of Compact Sources Release 1 (Planck, 2013)
        if "Planck" in self.config.catalogs: self.get_planck()

        # SPECIFIC for M81: not enabled, no time to figure out the unit conversion now
        #if self.ngc_id == "NGC 3031": self.get_m81()

        # Other interesting catalogs:
        # http://vizier.cfa.harvard.edu/viz-bin/VizieR-3?-source=J/ApJS/199/22
        # http://vizier.cfa.harvard.edu/viz-bin/VizieR-3?-source=J/ApJS/212/18/sample&-c=NGC%203031&-c.u=arcmin&-c.r=2&-c.eq=J2000&-c.geom=r&-out.max=50&-out.form=HTML%20Table&-oc.form=sexa
        # http://vizier.cfa.harvard.edu/viz-bin/VizieR-3?-source=J/ApJS/220/6

        # Writing
        self.write()

    # -----------------------------------------------------------------

    def setup(self, galaxy_name):
        """
        This function ...
        :param galaxy_name:
        :return:
        """

        # Call the setup function of the base class
        super(SEDFetcher, self).setup()

        # Set the galaxy name
        self.galaxy_name = galaxy_name

        # Get the NGC ID of the galaxy
        self.ngc_id = catalogs.get_ngc_name(self.galaxy_name)

        # Create a dictionary of filters
        keys = [
            "Ha", "FUV", "NUV", "U", "B", "V", "R", "J", "H", "K", "IRAS 12",
            "IRAS 25", "IRAS 60", "IRAS 100", "I1", "I2", "I3", "I4",
            "MIPS 24", "MIPS 70", "MIPS 160", "SDSS u", "SDSS g", "SDSS r",
            "SDSS i", "SDSS z"
        ]
        for key in keys:
            self.filters[key] = Filter.from_string(key)

    # -----------------------------------------------------------------

    def get_galex(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info(
            "Getting fluxes from the GALEX ultraviolet atlas of nearby galaxies ..."
        )

        # GALEX: "J/ApJS/173/185" of "J/ApJS/173/185/galex": B and V (2007ApJS..173..185G)
        # Interesting columns:
        #
        # - "MajAxis": Major-axis diameter of the D25 ellipse [arcmin]
        # - "MinAxis": Minor-axis diameter of the D25 ellipse [arcmin]
        # - "PA": Position angle of the D25 ellipse [deg]
        # - "Dist": Distance to the galaxy [Mpc]
        # - "Morph": Morphological type
        # - "T": Morphological type T
        # - "FUV": FUV (120-177nm) image mean sky background [ct/s]
        # - "sigFUV": Mean standard deviation of the FUV sky. Note (2): Measured by averaging the standard deviation within several regions around the position of the object. [ct/s]
        # - "e_FUV": The standard deviation of the mean FUV sky [ct/s]
        # - "NUV": Mean NUV (177-300nm) sky background [ct/s]
        # - "sigNUV": Mean standard deviation of the NUV sky [ct/s]
        # - "e_NUV": The standard deviation of the mean NUV sky [ct/s]
        # - "D25FUV": Observed D25 ellipse FUV band AB magnitude [mag]
        # - "e_D25FUV": Uncertainty in D25FUV [mag]
        # - "D25NUV": Observed D25 ellipse NUV band AB magnitude [mag]
        # - "e_D25NUV": Uncertainty in D25NUV [mag]
        # - "AFUV": Foreground FUV extinction [mag]
        # - "ANUV": Foreground NUV extinction [mag]
        # - "asyFUV": Observed asymptotic FUV (120-177nm) AB magnitude [mag]
        # - "e_asyFUV": Uncertainty in asyFUV [mag]
        # - "asyNUV": Observed asymptotic NUV (177-300nm) AB magnitude [mag]
        # - "e_asyNUV": Uncertainty in asyNUV [mag]
        # - "logFUV": Log of the FUV (120-177nm) luminosity [W]
        # - "logNUV": Log of the NUV (177-300nm) luminosity [W]
        # - "Umag": Johnson U band integrated magnitude [mag] Note (1): In the Vega scale. Published as part of the RC3 catalog, Cat. VII/155)
        # - "e_Umag": Uncertainty in Umag [mag]
        # - "Bmag": Johnson B band integrated magnitude [mag]
        # - "e_Bmag": Uncertainty in Bmag [mag]
        # - "Vmag": Johnson V band integrated magnitude [mag]
        # - "e_Vmag": Uncertainty in Vmag [mag]
        # - "Jmag": 2MASS J band total magnitude [mag]
        # - "e_Jmag": Uncertainty in Jmag [mag]
        # - "Hmag": 2MASS H band total magnitude [mag]
        # - "e_Hmag": Uncertainty in Hmag [mag]
        # - "Kmag": 2MASS K band total magnitude [mag]
        # - "e_Kmag": Uncertainty in Kmag [mag]
        # - "F12um": IRAS 12 micron flux density [Jy]
        # - "e_F12um": Uncertainty in F12um [Jy]
        # - "F25um": IRAS 25 micron flux density [Jy]
        # - "e_F25um": Uncertainty in F25um [Jy]
        # - "F60um": IRAS 60 micron flux density [Jy]
        # - "e_F60um": Uncertainty in F60um [Jy]
        # - "F100um": IRAS 100 micron flux density [Jy]
        # - "e_F100um": Uncertainty in F100um [Jy]

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/ApJS/173/185/galex")
        # Result is a list of tables, we only have one table with one entry

        # Create an SED
        sed = ObservedSED()

        # All AB magnitudes

        # FUV --

        if not result[0]["asyFUV"].mask[0]:

            fuv_mag = result[0]["asyFUV"][0]
            fuv_mag_error = result[0][0]["e_asyFUV"]
            fuv_mag_lower = fuv_mag - fuv_mag_error
            fuv_mag_upper = fuv_mag + fuv_mag_error

            # flux
            fuv = unitconversion.ab_to_jansky(fuv_mag)
            fuv_lower = unitconversion.ab_to_jansky(fuv_mag_upper)
            fuv_upper = unitconversion.ab_to_jansky(fuv_mag_lower)
            fuv_error = ErrorBar(fuv_lower, fuv_upper, at=fuv)
            sed.add_entry(self.filters["FUV"], fuv, fuv_error)

        # NUV --

        if not result[0]["asyNUV"].mask[0]:

            nuv_mag = result[0][0]["asyNUV"]
            nuv_mag_error = result[0][0]["e_asyNUV"]
            nuv_mag_lower = nuv_mag - nuv_mag_error
            nuv_mag_upper = nuv_mag + nuv_mag_error

            # flux
            nuv = unitconversion.ab_to_jansky(nuv_mag)
            nuv_lower = unitconversion.ab_to_jansky(nuv_mag_upper)
            nuv_upper = unitconversion.ab_to_jansky(nuv_mag_lower)
            nuv_error = ErrorBar(nuv_lower, nuv_upper, at=nuv)
            sed.add_entry(self.filters["NUV"], nuv, nuv_error)

        # U band --

        if not result[0]["Umag"].mask[0]:

            # From Vega magnitude system to AB magnitudes
            u_mag = unitconversion.vega_to_ab(result[0][0]["Umag"], "U")
            u_mag_error = unitconversion.vega_to_ab(result[0][0]["e_Umag"],
                                                    "U")
            u_mag_lower = u_mag - u_mag_error
            u_mag_upper = u_mag + u_mag_error

            # U band flux
            u = unitconversion.ab_to_jansky(u_mag)
            u_lower = unitconversion.ab_to_jansky(u_mag_upper)
            u_upper = unitconversion.ab_to_jansky(u_mag_lower)
            u_error = ErrorBar(u_lower, u_upper, at=u)
            sed.add_entry(self.filters["U"], u, u_error)

        # B band --

        if not result[0]["Bmag"].mask[0]:

            b_mag = unitconversion.vega_to_ab(result[0][0]["Bmag"], "B")
            b_mag_error = unitconversion.vega_to_ab(result[0][0]["e_Bmag"],
                                                    "B")
            b_mag_lower = b_mag - abs(b_mag_error)
            b_mag_upper = b_mag + abs(b_mag_error)

            #print("bmag", b_mag)
            #print("bmagerror", b_mag_error)
            #print("bmaglower", b_mag_lower)
            #print("bmagupper", b_mag_upper)

            # B band flux
            b = unitconversion.ab_to_jansky(b_mag)
            b_lower = unitconversion.ab_to_jansky(b_mag_upper)
            b_upper = unitconversion.ab_to_jansky(b_mag_lower)
            b_error = ErrorBar(b_lower, b_upper, at=b)
            sed.add_entry(self.filters["B"], b, b_error)

        # V band --

        if not result[0]["Vmag"].mask[0]:

            v_mag = unitconversion.vega_to_ab(result[0][0]["Vmag"], "V")
            v_mag_error = unitconversion.vega_to_ab(result[0][0]["e_Vmag"],
                                                    "V")
            v_mag_lower = v_mag - v_mag_error
            v_mag_upper = v_mag + v_mag_error

            # V band flux
            v = unitconversion.ab_to_jansky(v_mag)
            v_lower = unitconversion.ab_to_jansky(v_mag_upper)
            v_upper = unitconversion.ab_to_jansky(v_mag_lower)
            v_error = ErrorBar(v_lower, v_upper, at=v)
            sed.add_entry(self.filters["V"], v, v_error)

        # In 2MASS magnitude system -> can be converted directly into Jy (see below)

        # J band --

        if not result[0]["Jmag"].mask[0]:

            j_mag = result[0][0]["Jmag"]
            j_mag_error = result[0][0]["e_Jmag"]
            j_mag_lower = j_mag - j_mag_error
            j_mag_upper = j_mag + j_mag_error

            # J band flux
            j = unitconversion.photometry_2mass_mag_to_jy(j_mag, "J")
            j_lower = unitconversion.photometry_2mass_mag_to_jy(
                j_mag_upper, "J")
            j_upper = unitconversion.photometry_2mass_mag_to_jy(
                j_mag_lower, "J")
            j_error = ErrorBar(j_lower, j_upper, at=j)
            sed.add_entry(self.filters["J"], j, j_error)

        # H band --

        if not result[0]["Hmag"].mask[0]:

            h_mag = result[0][0]["Hmag"]
            h_mag_error = result[0][0]["e_Hmag"]
            h_mag_lower = h_mag - h_mag_error
            h_mag_upper = h_mag + h_mag_error

            # H band flux
            h = unitconversion.photometry_2mass_mag_to_jy(h_mag, "H")
            h_lower = unitconversion.photometry_2mass_mag_to_jy(
                h_mag_upper, "H")
            h_upper = unitconversion.photometry_2mass_mag_to_jy(
                h_mag_lower, "H")
            h_error = ErrorBar(h_lower, h_upper, at=h)
            sed.add_entry(self.filters["H"], h, h_error)

        # K band --

        if not result[0]["Kmag"].mask[0]:

            k_mag = result[0][0]["Kmag"]
            k_mag_error = result[0][0]["e_Kmag"]
            k_mag_lower = k_mag - k_mag_error
            k_mag_upper = k_mag + k_mag_error

            # K band flux
            k = unitconversion.photometry_2mass_mag_to_jy(k_mag, "Ks")
            k_lower = unitconversion.photometry_2mass_mag_to_jy(
                k_mag_upper, "Ks")
            k_upper = unitconversion.photometry_2mass_mag_to_jy(
                k_mag_lower, "Ks")
            k_error = ErrorBar(k_lower, k_upper, at=k)
            sed.add_entry(self.filters["K"], k, k_error)

        # F12 band flux

        if not result[0]["F12um"].mask[0]:

            f12 = result[0][0]["F12um"]
            f12_error = ErrorBar(result[0][0]["e_F12um"])
            sed.add_entry(self.filters["IRAS 12"], f12, f12_error)

        # F25 band flux

        if not result[0]["F25um"].mask[0]:

            f25 = result[0][0]["F25um"]
            f25_error = ErrorBar(result[0][0]["e_F25um"])
            sed.add_entry(self.filters["IRAS 25"], f25, f25_error)

        # F60 band flux

        if not result[0]["F60um"].mask[0]:

            f60 = result[0][0]["F60um"]
            f60_error = ErrorBar(result[0][0]["e_F60um"])
            sed.add_entry(self.filters["IRAS 60"], f60, f60_error)

        # F100 band flux

        if not result[0]["F100um"].mask[0]:

            f100 = result[0][0]["F100um"]
            f100_error = ErrorBar(result[0][0]["e_F100um"])
            sed.add_entry(self.filters["IRAS 100"], f100, f100_error)

        # Add the SED to the dictionary
        self.seds["GALEX"] = sed

    # -----------------------------------------------------------------

    def get_2mass(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the 2MASS Extended Catalog ...")

        # 2MASS Extended Catalog: "VII/233/xsc": J, H, K (2006AJ....131.1163S)
        # Interesting columns:
        #
        # - "J.ext": J magnitude in r.ext (j_m_ext) [mag]
        # - "e_J.ext": σ(J.ext) (j_msig_ext) [mag]
        # - "H.ext": H magnitude in r.ext (h_m_ext) [mag]
        # - "e_H.ext": σ(H.ext) (h_msig_ext) [mag]
        # - "K.ext": J magnitude in r.ext (k_m_ext) [mag]
        # - "e_K.ext": σ(K.ext) (k_msig_ext) [mag]
        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="VII/233/xsc")

        # Create an SED
        sed = ObservedSED()

        # In 2MASS magnitude system -> can be converted directly into Jy (see below)
        j_mag = result[0][0]["J.ext"]
        j_mag_error = result[0][0]["e_J.ext"]
        j_mag_lower = j_mag - j_mag_error
        j_mag_upper = j_mag + j_mag_error

        h_mag = result[0][0]["H.ext"]
        h_mag_error = result[0][0]["e_H.ext"]
        h_mag_lower = h_mag - h_mag_error
        h_mag_upper = h_mag + h_mag_error

        k_mag = result[0][0]["K.ext"]
        k_mag_error = result[0][0]["e_K.ext"]
        k_mag_lower = k_mag - k_mag_error
        k_mag_upper = k_mag + k_mag_error

        # J band flux
        j = unitconversion.photometry_2mass_mag_to_jy(j_mag, "J")
        j_lower = unitconversion.photometry_2mass_mag_to_jy(j_mag_upper, "J")
        j_upper = unitconversion.photometry_2mass_mag_to_jy(j_mag_lower, "J")
        j_error = ErrorBar(j_lower, j_upper, at=j)
        sed.add_entry(self.filters["J"], j, j_error)

        # H band flux
        h = unitconversion.photometry_2mass_mag_to_jy(h_mag, "H")
        h_lower = unitconversion.photometry_2mass_mag_to_jy(h_mag_upper, "H")
        h_upper = unitconversion.photometry_2mass_mag_to_jy(h_mag_lower, "H")
        h_error = ErrorBar(h_lower, h_upper, at=h)
        sed.add_entry(self.filters["H"], h, h_error)

        # K band flux
        k = unitconversion.photometry_2mass_mag_to_jy(k_mag, "Ks")
        k_lower = unitconversion.photometry_2mass_mag_to_jy(k_mag_upper, "Ks")
        k_upper = unitconversion.photometry_2mass_mag_to_jy(k_mag_lower, "Ks")
        k_error = ErrorBar(k_lower, k_upper, at=k)
        sed.add_entry(self.filters["K"], k, k_error)

        # Add the SED to the dictionary
        self.seds["2MASS"] = sed

    # -----------------------------------------------------------------

    def get_sings(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the SINGS catalog ...")

        # Radial distribution in SINGS galaxies. I.
        # J/ApJ/703/1569/table1	(c)Sample (75 rows)
        # J/ApJ/703/1569/table2	UV, optical and NIR surface photometry profiles (2206 rows)
        # J/ApJ/703/1569/table3	UV, optical (SDSS) and NIR photometry profiles (2161 rows)
        # J/ApJ/703/1569/table4	IRAC and MIPS surface photometry (4319 rows)
        # J/ApJ/703/1569/table5	UV, optical, and near-IR asymptotic magnitudes for SINGS galaxies lacking SDSS data (43 rows)
        # J/ApJ/703/1569/table6	UV, optical (SDSS), and near-IR asymptotic magnitudes (32 rows)
        # J/ApJ/703/1569/table7	IRAC and MIPS asymptotic magnitudes (75 rows)
        # J/ApJ/703/1569/table8	Non-parametrical morphological estimators (300 rows)

        result = self.vizier.get_catalogs("J/ApJ/703/1569")

        # Result is a TableList with 8 tables (0 to 7)
        # We need:
        # - Table6 -> index 5
        # - Table7 -> index 6

        # Table6
        # - "Name": Galaxy name (NGC ...)
        # - "FUV": GALEX FUV 0.153um-band AB magnitude [mag]
        # - "e_FUV": FUV uncertainty [mag]
        # - "NUV": GALEX NUV 0.227um-band AB magnitude [mag]
        # - "e_NUV": NUV uncertainty [mag]
        # - "umag": SDSS u-band 0.354um AB magnitude [mag]
        # - "e_umag": umag uncertainty [mag]
        # - "gmag": SDSS g-band 0.477um AB magnitude [mag]
        # - "e_gmag": gmag uncertainty [mag]
        # - "rmag": SDSS r-band 0.623um AB magnitude [mag]
        # - "e_rmag": rmag uncertainty [mag]
        # - "imag": SDSS i-band 0.762um AB magnitude [mag]
        # - "e_imag": imag uncertainty [mag]
        # - "zmag": SDSS z-band 0.913um AB magnitude [mag]
        # - "e_zmag": zmag uncertainty [mag]
        # - "Jmag": 2MASS J-band 1.25um AB magnitude [mag]
        # - "e_Jmag": Jmag uncertainty [mag]
        # - "Hmag": 2MASS H-band 1.65um AB magnitude [mag]
        # - "e_Hmag": Hmag uncertainty [mag]
        # - "Ksmag": 2MASS Ks-band 2.17um AB magnitude [mag]
        # - "e_Ksmag": Ksmag uncertainty [mag]

        # Find the row index that corresponds with the specified galaxy

        galaxy_index = tables.find_index(result[5], self.ngc_id)

        # FUV
        fuv_mag = result[5][galaxy_index]["FUV"]
        fuv_mag_error = result[5][galaxy_index]["e_FUV"]
        fuv_mag_lower = fuv_mag - fuv_mag_error
        fuv_mag_upper = fuv_mag + fuv_mag_error

        # NUV
        nuv_mag = result[5][galaxy_index]["NUV"]
        nuv_mag_error = result[5][galaxy_index]["e_NUV"]
        nuv_mag_lower = nuv_mag - nuv_mag_error
        nuv_mag_upper = nuv_mag + nuv_mag_error

        # u
        u_mag = result[5][galaxy_index]["umag"]
        u_mag_error = result[5][galaxy_index]["e_umag"]
        u_mag_lower = u_mag - u_mag_error
        u_mag_upper = u_mag + u_mag_error

        # g
        g_mag = result[5][galaxy_index]["gmag"]
        g_mag_error = result[5][galaxy_index]["e_gmag"]
        g_mag_lower = g_mag - abs(g_mag_error)
        g_mag_upper = g_mag + abs(g_mag_error)

        #print("gmag", g_mag)
        #print("gmagerror", g_mag_error)
        #print("gmaglower", g_mag_lower)
        #print("gmagupper", g_mag_upper)

        # r
        r_mag = result[5][galaxy_index]["rmag"]
        r_mag_error = result[5][galaxy_index]["e_rmag"]
        r_mag_lower = r_mag - r_mag_error
        r_mag_upper = r_mag + r_mag_error

        # i
        i_mag = result[5][galaxy_index]["imag"]
        i_mag_error = result[5][galaxy_index]["e_imag"]
        i_mag_lower = i_mag - i_mag_error
        i_mag_upper = i_mag + i_mag_error

        # z
        z_mag = result[5][galaxy_index]["zmag"]
        z_mag_error = result[5][galaxy_index]["e_zmag"]
        z_mag_lower = z_mag - z_mag_error
        z_mag_upper = z_mag + z_mag_error

        # J
        j_mag = result[5][galaxy_index]["Jmag"]
        j_mag_error = result[5][galaxy_index]["e_Jmag"]
        j_mag_lower = j_mag - j_mag_error
        j_mag_upper = j_mag + j_mag_error

        # H
        h_mag = result[5][galaxy_index]["Hmag"]
        h_mag_error = result[5][galaxy_index]["e_Hmag"]
        h_mag_lower = h_mag - h_mag_error
        h_mag_upper = h_mag + h_mag_error

        # Ks
        k_mag = result[5][galaxy_index]["Ksmag"]
        k_mag_error = result[5][galaxy_index]["e_Ksmag"]
        k_mag_lower = k_mag - k_mag_error
        k_mag_upper = k_mag + k_mag_error

        # Create an SED
        sed = ObservedSED()

        # FUV
        fuv = unitconversion.ab_to_jansky(fuv_mag)
        fuv_lower = unitconversion.ab_to_jansky(fuv_mag_upper)
        fuv_upper = unitconversion.ab_to_jansky(fuv_mag_lower)
        fuv_error = ErrorBar(fuv_lower, fuv_upper, at=fuv)
        sed.add_entry(self.filters["FUV"], fuv, fuv_error)

        # NUV
        nuv = unitconversion.ab_to_jansky(nuv_mag)
        nuv_lower = unitconversion.ab_to_jansky(nuv_mag_upper)
        nuv_upper = unitconversion.ab_to_jansky(nuv_mag_lower)
        nuv_error = ErrorBar(nuv_lower, nuv_upper, at=nuv)
        sed.add_entry(self.filters["NUV"], nuv, nuv_error)

        # u
        u = unitconversion.ab_to_jansky(u_mag)
        u_lower = unitconversion.ab_to_jansky(u_mag_upper)
        u_upper = unitconversion.ab_to_jansky(u_mag_lower)
        u_error = ErrorBar(u_lower, u_upper, at=u)
        sed.add_entry(self.filters["SDSS u"], u, u_error)

        # g
        g = unitconversion.ab_to_jansky(g_mag)
        g_lower = unitconversion.ab_to_jansky(g_mag_upper)
        g_upper = unitconversion.ab_to_jansky(g_mag_lower)
        g_error = ErrorBar(g_lower, g_upper, at=g)
        sed.add_entry(self.filters["SDSS g"], g, g_error)

        # r
        r = unitconversion.ab_to_jansky(r_mag)
        r_lower = unitconversion.ab_to_jansky(r_mag_upper)
        r_upper = unitconversion.ab_to_jansky(r_mag_lower)
        r_error = ErrorBar(r_lower, r_upper, at=r)
        sed.add_entry(self.filters["SDSS r"], r, r_error)

        # i
        i = unitconversion.ab_to_jansky(i_mag)
        i_lower = unitconversion.ab_to_jansky(i_mag_upper)
        i_upper = unitconversion.ab_to_jansky(i_mag_lower)
        i_error = ErrorBar(i_lower, i_upper, at=i)
        sed.add_entry(self.filters["SDSS i"], i, i_error)

        # z
        z = unitconversion.ab_to_jansky(z_mag)
        z_lower = unitconversion.ab_to_jansky(z_mag_upper)
        z_upper = unitconversion.ab_to_jansky(z_mag_lower)
        z_error = ErrorBar(z_lower, z_upper, at=z)
        sed.add_entry(self.filters["SDSS z"], z, z_error)

        # J
        j = unitconversion.ab_to_jansky(j_mag)
        j_lower = unitconversion.ab_to_jansky(j_mag_upper)
        j_upper = unitconversion.ab_to_jansky(j_mag_lower)
        j_error = ErrorBar(j_lower, j_upper, at=j)
        sed.add_entry(self.filters["J"], j, j_error)

        # H
        h = unitconversion.ab_to_jansky(h_mag)
        h_lower = unitconversion.ab_to_jansky(h_mag_upper)
        h_upper = unitconversion.ab_to_jansky(h_mag_lower)
        h_error = ErrorBar(h_lower, h_upper, at=h)
        sed.add_entry(self.filters["H"], h, h_error)

        # Ks
        k = unitconversion.ab_to_jansky(k_mag)
        k_lower = unitconversion.ab_to_jansky(k_mag_upper)
        k_upper = unitconversion.ab_to_jansky(k_mag_lower)
        k_error = ErrorBar(k_lower, k_upper, at=k)
        sed.add_entry(self.filters["K"], k, k_error)

        # Table7: IRAC and MIPS asymptotic magnitudes
        # - "logF3.6": Spitzer/IRAC 3.6um flux density [logJy]
        # - "e_logF3.6": logF3.6 uncertainty [logJy]
        # - "logF4.5": Spitzer/IRAC 4.5um flux density [logJy]
        # - "e_logF4.5": logF4.5 uncertainty [logJy]
        # - "logF5.8": Spitzer/IRAC 5.8um flux density [logJy]
        # - "e_logF5.8": logF5.8 uncertainty [logJy]
        # - "logF8.0": Spiter/IRAC 8.0um flux density [logJy]
        # - "e_logF8.0": logF8.0 uncertainty [logJy]
        # - "logF24": Spiter/MIPS 24um flux density [logJy]
        # - "e_logF24": logF24 uncertainty [logJy]
        # - "logF70": Spiter/MIPS 70um flux density [logJy]
        # - "e_logF70": logF70 uncertainty [logJy]
        # - "logF160": Spiter/MIPS 160um flux density [logJy]
        # - "e_logF160": logF160 uncertainty [logJy]

        # Table7 -> index 6

        galaxy_index = tables.find_index(result[6], self.ngc_id)

        # 3.6 micron
        i1_log = result[6][galaxy_index]["logF3.6"]
        i1_log_error = result[6][galaxy_index]["e_logF3.6"]
        i1_log_lower = i1_log - i1_log_error
        i1_log_upper = i1_log + i1_log_error

        # 4.5 micron
        i2_log = result[6][galaxy_index]["logF4.5"]
        i2_log_error = result[6][galaxy_index]["e_logF4.5"]
        i2_log_lower = i2_log - i2_log_error
        i2_log_upper = i2_log + i2_log_error

        # 5.8 micron
        i3_log = result[6][galaxy_index]["logF5.8"]
        i3_log_error = result[6][galaxy_index]["e_logF5.8"]
        i3_log_lower = i3_log - i3_log_error
        i3_log_upper = i3_log + i3_log_error

        # 8.0 micron
        i4_log = result[6][galaxy_index]["logF8.0"]
        i4_log_error = result[6][galaxy_index]["e_logF8.0"]
        i4_log_lower = i4_log - i4_log_error
        i4_log_upper = i4_log + i4_log_error

        #print("i4log", i4_log)
        #print("i4_log_error", i4_log_error)
        #print("i4_log_lower", i4_log_lower)
        #print("i4_log_upper", i4_log_upper)

        # 24 micron
        mips24_log = result[6][galaxy_index]["logF24"]
        mips24_log_error = result[6][galaxy_index]["e_logF24"]
        mips24_log_lower = mips24_log - mips24_log_error
        mips24_log_upper = mips24_log + mips24_log_error

        # 70 micron
        mips70_log = result[6][galaxy_index]["logF70"]
        mips70_log_error = result[6][galaxy_index]["e_logF70"]
        mips70_log_lower = mips70_log - mips70_log_error
        mips70_log_upper = mips70_log + mips70_log_error

        # 160 micron
        mips160_log = result[6][galaxy_index]["logF160"]
        mips160_log_error = result[6][galaxy_index]["e_logF160"]
        mips160_log_lower = mips160_log - mips160_log_error
        mips160_log_upper = mips160_log + mips160_log_error

        # Calculate data points and errobars in Janskys, add to the SED

        # 3.6 micron
        i1 = 10.**i1_log
        i1_lower = 10.**i1_log_lower
        i1_upper = 10.**i1_log_upper
        i1_error = ErrorBar(i1_lower, i1_upper, at=i1)
        sed.add_entry(self.filters["I1"], i1, i1_error)

        # 4.5 micron
        i2 = 10.**i2_log
        i2_lower = 10.**i2_log_lower
        i2_upper = 10.**i2_log_upper
        i2_error = ErrorBar(i2_lower, i2_upper, at=i2)
        sed.add_entry(self.filters["I2"], i2, i2_error)

        # 5.8 micron
        i3 = 10.**i3_log
        i3_lower = 10.**i3_log_lower
        i3_upper = 10.**i3_log_upper
        i3_error = ErrorBar(i3_lower, i3_upper, at=i3)
        sed.add_entry(self.filters["I3"], i3, i3_error)

        # 8.0 micron
        i4 = 10.**i4_log
        i4_lower = 10.**i4_log_lower
        i4_upper = 10.**i4_log_upper
        i4_error = ErrorBar(i4_lower, i4_upper, at=i4)
        sed.add_entry(self.filters["I4"], i4, i4_error)

        # 24 micron
        mips24 = 10.**mips24_log
        mips24_lower = 10.**mips24_log_lower
        mips24_upper = 10.**mips24_log_upper
        mips24_error = ErrorBar(mips24_lower, mips24_upper, at=mips24)
        sed.add_entry(self.filters["MIPS 24"], mips24, mips24_error)

        # 70 micron
        mips70 = 10.**mips70_log
        mips70_lower = 10.**mips70_log_lower
        mips70_upper = 10.**mips70_log_upper
        mips70_error = ErrorBar(mips70_lower, mips70_upper, at=mips70)
        sed.add_entry(self.filters["MIPS 70"], mips70, mips70_error)

        # 160 micron
        mips160 = 10.**mips160_log
        mips160_lower = 10.**mips160_log_lower
        mips160_upper = 10.**mips160_log_upper
        mips160_error = ErrorBar(mips160_lower, mips160_upper, at=mips160)
        sed.add_entry(self.filters["MIPS 160"], mips160, mips160_error)

        # Add the SED to the dictionary
        self.seds["SINGS"] = sed

    # -----------------------------------------------------------------

    def get_lvl(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the LVL catalog ...")

        # Create an SED
        sed = ObservedSED()

        # "J/MNRAS/445/881": LVL global optical photometry (Cook+, 2014)
        #  - "J/MNRAS/445/881/sample": Galaxies of the Spitzer Local Volume Legacy (LVL): properties (table1) and R25 photometry
        #  - "J/MNRAS/445/881/table3": Photometry within the IR apertures of Dale et al. (2009, Cat. J/ApJ/703/517) (258 rows)
        #  - "J/MNRAS/445/881/table4": Photometry within the UV apertures of Lee et al. (2011, Cat. J/ApJS/192/6) (258 rows)

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/MNRAS/445/881/sample")

        # ALL IN AB MAGNITUDE SYSTEM
        # Umag
        # Bmag
        # Vmag
        # Rmag
        # umag
        # gmag
        # rmag
        # imag
        # zmag

        # On SimBad, only sdss bands are used, from /sample ...

        relevant_bands = [("U", "U"), ("B", "B"), ("V", "V"), ("R", "R"),
                          ("u", "SDSS u"), ("g", "SDSS g"), ("r", "SDSS r"),
                          ("i", "SDSS i"), ("z", "SDSS z")]
        for band_prefix_catalog, filter_name in relevant_bands:

            column_name = band_prefix_catalog + "mag"
            error_column_name = "e_" + column_name

            # Skip masked values
            if result[0][column_name].mask[0]: continue

            # AB magnitude
            magnitude = result[0][0][column_name]
            magnitude_error = result[0][0][error_column_name]
            magnitude_lower = magnitude - magnitude_error
            magnitude_upper = magnitude + magnitude_error

            # Convert to Jy
            fluxdensity = unitconversion.ab_to_jansky(magnitude)
            fluxdensity_lower = unitconversion.ab_to_jansky(magnitude_upper)
            fluxdensity_upper = unitconversion.ab_to_jansky(magnitude_lower)
            fluxdensity_error = ErrorBar(fluxdensity_lower,
                                         fluxdensity_upper,
                                         at=fluxdensity)

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["LVL"] = sed

    # -----------------------------------------------------------------

    def get_spitzer(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the Spitzer catalog ...")

        # "J/ApJ/703/517": The Spitzer Local Volume Legacy: IR photometry (Dale+, 2009)
        # "J/ApJ/703/517/sample": Galaxy sample (table 1) and infrared flux densities (table 2) (258 rows)

        # Create an SED
        sed = ObservedSED()

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/ApJ/703/517/sample")

        # F1.25: 2MASS J band (1.25 micron) flux density [Jy]
        # e_F1.25: Uncertainty in F1.25 [Jy]
        # F1.65: 2MASS H band (1.65 micron) flux density [Jy]
        # e_F1.65: Uncertainty in F1.65 [Jy]
        # F2.17: 2MASS Ks band (2.17 micron) flux density [Jy]
        # e_F2.17: Uncertainty in F2.17 [Jy]
        # F3.6: Spitzer/IRAC 3.5 micron band flux density [Jy]
        # e_F3.6: Uncertainty in F3.6 [Jy]
        # F4.5: Spitzer/IRAC 4.5 micron band flux density [Jy]
        # e_F4.5: Uncertainty in F4.5 [Jy]
        # F5.8: Spitzer/IRAC 5.8 micron band flux density [Jy]
        # e_F5.8: Uncertainty in F5.8 [Jy]
        # F8.0: Spitzer/IRAC 8.0 micron band flux density [Jy]
        # e_F8.0: Uncertainty in F8.0 [Jy]
        # F24: Spitzer/MIPS 24 micron flux density [Jy]
        # e_F24: Uncertainty in F24 [Jy]
        # F70: Spitzer/MIPS 70 micron band flux density [Jy]
        # e_F70: Uncertainty in F70 [Jy]
        # F160: Spitzer/MIPS 160 micron band flux density [Jy]
        # e_F160: Uncertainty in F160 [Jy]

        relevant_bands = [("1.25", "J"), ("1.65", "H"), ("2.17", "K"),
                          ("3.6", "I1"), ("4.5", "I2"), ("5.8", "I3"),
                          ("8.0", "I4"), ("24", "MIPS 24"), ("70", "MIPS 70"),
                          ("160", "MIPS 160")]
        for band_prefix_catalog, filter_name in relevant_bands:

            column_name = "F" + band_prefix_catalog
            error_column_name = "e_" + column_name

            # Skip masked values
            if result[0][column_name].mask[0]: continue

            # Flux and error already in Jy
            fluxdensity = result[0][0][column_name]
            fluxdensity_error = ErrorBar(result[0][0][error_column_name])

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["Spitzer"] = sed

    # -----------------------------------------------------------------

    def get_spitzer_irs(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the Spitzer/IRS catalog ...")

        # "J/MNRAS/414/500": Spitzer/IRS ATLAS project source (Hernan-Caballero+, 2011)
        # - "J/MNRAS/414/500/catalog": Spitzer/IRS ATLAS project source catalog, version 1.0 (739 rows)

        # !! Parentheses () are converted into underscores _ in the resulting Astropy tables!!

        # F(3.6): IRAC1 (3.6um) flux density [Jy]
        # e_F(3.6): rms uncertainty on F(3.6) [Jy]
        # F(8.0): IRAC4 (8.0um) flux density [Jy]
        # e_F(8.0): rms uncertainty on F(8.0) [Jy]
        # F(24): 24um flux density [Jy]
        # e_F(24): rms uncertainty on F(24) [Jy]
        # F(70): 70um or similar band flux density [Jy]
        # e_F(70): rms uncertainty on F(70) [Jy]

        # Create an SED
        sed = ObservedSED()

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/MNRAS/414/500/catalog")

        relevant_bands = [("3.6", "I1"), ("8.0", "I4"), ("24", "MIPS 24"),
                          ("70", "MIPS 70")]
        for band_prefix_catalog, filter_name in relevant_bands:

            column_name = "F_" + band_prefix_catalog + "_"
            error_column_name = "e_" + column_name

            # Skip masked values
            if result[0][column_name].mask[0]: continue

            # Flux and error already in Jy
            fluxdensity = result[0][0][column_name]
            fluxdensity_error = ErrorBar(result[0][0][error_column_name])

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["Spitzer-IRS"] = sed

    # -----------------------------------------------------------------

    def get_iras(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the IRAS catalog ...")

        # "J/ApJS/178/280": Compendium of ISO far-IR extragalactic data (Brauher+, 2008)
        # - "J/ApJS/178/280/table1": *Galaxies and properties

        # F12: IRAS 12um band flux density [Jy]
        # F25: IRAS 25um band flux density [Jy]
        # F60: IRAS 60um band flux density [Jy]
        # F100: IRAS 100um band flux density [Jy]

        # No errors ...

        # Create an SED
        sed = ObservedSED()

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/ApJS/178/280/table1")

        relevant_bands = [("12", "IRAS 12"), ("25", "IRAS 25"),
                          ("60", "IRAS 60"), ("100", "IRAS 100")]
        for band_prefix_catalog, filter_name in relevant_bands:

            column_name = "F" + band_prefix_catalog

            # Skip masked values
            if result[0][column_name].mask[0]: continue

            # Flux and error already in Jy
            fluxdensity = result[0][0][column_name]
            fluxdensity_error = ErrorBar(0.0)

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["IRAS"] = sed

    # -----------------------------------------------------------------

    def get_iras_fsc(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Getting fluxes from the IRAS-FSC catalog ...")

        # "J/MNRAS/398/109": Imperial IRAS-FSC redshift catalogue (IIFSCz) (Wang+, 2009)
        # - "J/MNRAS/398/109/iifsczv4": IIFSCz Catalogue (MRR+LW 18/04/09)[spectrum/SED] (60303 rows)

        # S12um: IRAS-FSC flux at 12um [Jy]
        # S25um: IRAS-FSC flux at 25um [Jy]
        # S60um: IRAS-FSC flux at 60um [Jy]
        # S100um: IRAS-FSC flux at 100um [Jy]

        # not used in Simbad:
        # umag: SDSS u magnitude [mag: which system??]
        # e_umag:
        # gmag:
        # e_gmag:
        # rmag:
        # e_rmag:
        # imag:
        # e_imag:
        # zmag:
        # e_zmag:

        # Jmag: 2MASS J magnitude [mag: which system??]
        # e_Jmag: rms uncertainty on Jmag [mag: which system??]
        # Hmag: 2MASS H magnitude [mag]
        # e_Hmag: rms uncertainty on Hmag [mag]
        # Kmag: 2MASS K magnitude [mag]
        # e_Kmag rms uncertainty on Kmag [mag]

        # Create an SED
        sed = ObservedSED()

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/MNRAS/398/109/iifsczv4")

        relevant_bands = [("12", "IRAS 12"), ("25", "IRAS 25"),
                          ("60", "IRAS 60"), ("100", "IRAS 100")]
        for band_prefix_catalog, filter_name in relevant_bands:

            # Flux and error already in Jy
            fluxdensity = result[0][0]["S" + band_prefix_catalog + "um"]
            fluxdensity_error = ErrorBar(0.0)

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["IRAS-FSC"] = sed

    # -----------------------------------------------------------------

    def get_s4g(self):
        """
        This function ...
        :return:
        """

        # Create an SED
        sed = ObservedSED()

        # Get parameters from S4G catalog
        result = self.vizier.query_object(self.galaxy_name,
                                          catalog=["J/PASP/122/1397/s4g"])
        table = result[0]

        # Magnitudes
        i1_mag = table["__3.6_"][0]
        i2_mag = table["__4.5_"][0]
        i1_mag_error = table["e__3.6_"][0]
        i2_mag_error = table["e__4.5_"][0]

        i1_fluxdensity = unitconversion.ab_to_jansky(i1_mag)
        i1_fluxdensity_lower = unitconversion.ab_to_jansky(i1_mag +
                                                           i1_mag_error)
        i1_fluxdensity_upper = unitconversion.ab_to_jansky(i1_mag -
                                                           i1_mag_error)
        i1_error = ErrorBar(i1_fluxdensity_lower,
                            i1_fluxdensity_upper,
                            at=i1_fluxdensity)

        # Add data point to SED
        sed.add_entry(self.filters["I1"], i1_fluxdensity, i1_error)

        i2_fluxdensity = unitconversion.ab_to_jansky(i2_mag)
        i2_fluxdensity_lower = unitconversion.ab_to_jansky(i2_mag +
                                                           i2_mag_error)
        i2_fluxdensity_upper = unitconversion.ab_to_jansky(i2_mag -
                                                           i2_mag_error)
        i2_error = ErrorBar(i2_fluxdensity_lower,
                            i2_fluxdensity_upper,
                            at=i2_fluxdensity)

        # Add data point to SED
        sed.add_entry(self.filters["I2"], i2_fluxdensity, i2_error)

        # Add the SED to the dictionary
        self.seds["S4G"] = sed

    # -----------------------------------------------------------------

    def get_brown(self):
        """
        This function ...
        :return:
        """

        # J/ApJS/212/18/sample
        # AB magnitudes for the sample with neither foreground nor intrinsic dust extinction corrections, and modeled Milky Way foreground dust extinction

        # Create an SED
        sed = ObservedSED()

        # FUV: [12.5/22.9] GALEX FUV AB band magnitude
        # e_FUV:
        # UVW2:
        # e_UVW2:
        # UVM2:
        # e_UVM2:
        # NUV:
        # e_NUV:
        # UVW1:
        # e_UVW1:
        # Umag: [11.9/15.7] Swift/UVOT U AB band magnitude
        # e_Umag:
        # umag:
        # e_umag:
        # gmag:
        # e_gmag:
        # Vmag:
        # e_Vmag:
        # rmag:
        # e_rmag:
        # imag:
        # e_imag:
        # zmag:
        # e_zmag:
        # Jmag:
        # e_Jmag:
        # Hmag:
        # e_Hmag:
        # Ksmag:
        # e_Ksmag:
        # W1mag:
        # e_W1mag:
        # [3.6]:
        # e_[3.6]:
        # [4.5]:
        # e_[4.5]:
        # W2mag:
        # e_W2mag:
        # [5.8]:
        # e_[5.8]:
        # [8.0]:
        # e_[8.0]:
        # W3mag:
        # e_W3mag:
        # W4mag:
        # e_W4mag:
        # W4'mag: Corrected WISE W4 AB band magnitude
        # e_W4'mag:
        # [24]:
        # e_[24]:

        pass

    # -----------------------------------------------------------------

    def get_planck(self):
        """
        This function ...
        :return:
        """

        # Create an SED
        sed = ObservedSED()

        # The second release is not yet available ... ??

    # -----------------------------------------------------------------

    def get_emission_lines(self):
        """
        This function ...
        :return:
        """

        # Create an SED
        sed = ObservedSED()

        # J/ApJS/190/233/Opt

        # Get result
        result = self.vizier.get_catalogs("J/ApJS/190/233/Opt")
        table = result[0]

        galaxy_index = tables.find_index(table, self.ngc_id, "Name")

        # FHa: The Hα 6563 Angstrom line flux (aW/m2)
        # e_FHa: Uncertainty in Ha (aW/m2)
        # FNII: The [NII] 6584Å line flux (aW/m2)
        # e_FNII: Uncertainty in NII (aW/m2)

        # H alpha
        ha_flux = table["FHa"][galaxy_index] * Unit("aW/m2")
        ha_flux_error = table["e_FHa"][galaxy_index] * Unit("aW/m2")

        # NII
        n2_flux = table["FNII"][galaxy_index] * Unit("aW/m2")
        n2_flux_error = table["e_FNII"][galaxy_index] * Unit("aW/m2")

        ha_filter = self.filters["Ha"]
        ha_wavelength = ha_filter.centerwavelength() * Unit("micron")
        ha_frequency = ha_wavelength.to("Hz", equivalencies=spectral())

        # Calculate flux density
        ha_fluxdensity = (ha_flux / ha_frequency).to("Jy")
        ha_fluxdensity_error = (ha_flux_error / ha_frequency).to("Jy")
        ha_errorbar = ErrorBar(ha_fluxdensity_error)

        # Add entry
        sed.add_entry(ha_filter, ha_fluxdensity, ha_errorbar)

        # Add the SED to the dictionary
        self.seds["Lines"] = sed

    # -----------------------------------------------------------------

    def get_m81(self):
        """
        This function ...
        :return:
        """

        # UV through far-IR analysis of M81 (Perez-Gonzalez+, 2006)
        # "J/ApJ/648/987"
        # Two tables:
        # - "J/ApJ/648/987/table1": Positions and photometry (GLOBALBKG and LOCALBKG cases) for the regions selected at 160um resolution
        # - "J/ApJ/648/987/table2": Positions and photometry for the regions selected at 24um resolution

        # Table 1

        #result = self.vizier.query_object(self.galaxy_name, catalog="J/ApJ/648/987/table1")

        # Looks like this (only 3 matches)
        #1	M81	09 55 32.2	+69 03 59.0	680.0	40.78	43.18	42.84	42.63	42.61	41.98	42.67	42.99
        #2	Reg02	09 55 32.2	+69 03 59.0	64.0	39.67	42.63	42.28	41.98	41.76	41.25	41.83	41.78
        #3	Reg03	09 55 32.2	+69 03 59.0	104.0	39.40	42.38	42.03	41.76	41.58	40.90	41.62	41.78

        #galaxy_index = tables.find_index(result, self.galaxy_name)

        # Table 2

        # Interesting rows:
        # - logLFUV: Log of the FUV luminosity [1e-7 W] or [erg/s]
        # - logLNUV: Log of the NUV luminosity [1e-7 W] or [erg/s]
        # - logLHa: Log of the H-alpha luminosity [1e-7 W] or [erg/s]
        # - logL8: Log of the 8um luminosity [1e-7 W] or [erg/s]
        # - logL24: Log of the 24um luminosity [1e-7 W] or [erg/s]

        result = self.vizier.query_object(self.galaxy_name,
                                          catalog="J/ApJ/648/987/table2")

        galaxy_index = tables.find_index(result[0], self.galaxy_name)

        # Create an SED
        sed = ObservedSED()

        relevant_bands = [("FUV", "FUV"), ("NUV", "NUV"), ("Ha", "Ha"),
                          ("8", "I4"), ("24", "MIPS 24")]
        for band_prefix_catalog, filter_name in relevant_bands:

            # Flux and error already in Jy
            log = result[0][galaxy_index]["logL" + band_prefix_catalog]
            flux = 10.**log  # In erg/s

            frequency = 0.0  # TODO: calculate this!

            # Also: calculate the amount of flux per unit area ! : divide also by 4 pi d_galaxy**2 !

            fluxdensity = flux / frequency
            fluxdensity_error = ErrorBar(0.0)

            # Add data point to SED
            sed.add_entry(self.filters[filter_name], fluxdensity,
                          fluxdensity_error)

        # Add the SED to the dictionary
        self.seds["IRAS-FSC"] = sed

    # -----------------------------------------------------------------

    def write(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Writing ...")

        # If requested, write out the SEDs
        if self.config.write_seds: self.write_seds()

    # -----------------------------------------------------------------

    def write_seds(self):
        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Writing the SEDs ...")

        # Determine the full path to the SEDs directory
        path = self.full_output_path(self.config.writing.seds_path)

        # Create the SEDs directory if necessary
        fs.create_directory(path)

        # Loop over the different SEDs
        for label in self.seds:

            # Debugging info
            log.debug("Writing SED from " + label)

            # Determine the path to the new SED file
            sed_path = fs.join(path, label + ".dat")

            # Save the SED at the specified location
            self.seds[label].save(sed_path)
Exemplo n.º 42
0
def search(image, headinfo, target_coords, syntax, catalog_syntax, filter_):

    """
    Search area around transient/target location in photometric catalogs

    Current catalog (selectable in syntax):

        - Skymapper: Southern Hemisphere
        - Pan Starrs: North of declination -30 degree
        - Apass: All-sky survey
        - 2MASS: JHK all sky survey

    Future:
        - SDSS: Future implemtation
        - Ability to make custom catalog from different surveys


    Input:

        - Image: Numpy 2D array
        - headinfo: astropy.io.fits.header.Header
        - target_coords: astropy.coordinates.sky_coordinate.SkyCoord
        - syntax: dict
        - catalog_syntax: dict
        - filter_: str

    Output:

        - data:  pandas DataFrame

    """

    import warnings

    if not syntax['catalog_warnings'] or syntax['master_warnings']:
            warnings.filterwarnings("ignore")

    import numpy as np
    import os,sys
    import requests
    import pathlib
    import shutil
    import os.path
    import logging
    from functools import reduce

    from astropy.table import Table
    from astropy.wcs import wcs
    from astroquery.vizier import Vizier
    from astropy.io.votable import parse_single_table
    from astropy.coordinates import Angle

    from autophot.packages.functions import r_dist
    logger = logging.getLogger(__name__)

    try:

        # Get wxs information
        w1 = wcs.WCS(headinfo)

        # Radius around target
        radius  = float(syntax['radius'])

        # Target name, if applicable
        target = syntax['target_name']

        # Get workdirectory location,, create directory if needed
        dirname = os.path.join(syntax['wdir'],'catalog_queries')
        pathlib.Path(dirname).mkdir(parents = True, exist_ok=True)

        '''
        Getting target Ra and Dec

        - if target is none but a Ra and DEC is given, create new target name

        - if ra and dec not given us center of image as location - for quick reduction of image

        '''
        # if target or it's ra/dec - set target name
        if target == None:
             if syntax['target_ra'] != None and syntax['target_dec'] != None:
                 target = 'target_ra_'+str(round(syntax['target_ra']))+'_dec_'+str(round(syntax['target_dec']))
                 logger.info('New target name: %s' %target)
             else:
                 #  if not just call target
                 target = 'target'

        # Search limitation with Pan Starrs rlimited to 0.5 deg
        if radius > 0.5 and syntax['catalog'] == 'pan_starrs' :
                    logger.warning('Search Limitation with PanStarrs API -> Radius = 0.5 [deg] ')
                    radius = 0.5

        # Choosen catalog for input.yml, create directory for catalog if needed
        catalog_dir = syntax['catalog']
        pathlib.Path(os.path.join(dirname ,catalog_dir)).mkdir(parents = True, exist_ok=True)

        # Folder for target, create directory if needed
        target_dir =   reduce(os.path.join,[dirname,catalog_dir,target.lower()])
        pathlib.Path(target_dir).mkdir(parents = True, exist_ok=True)

        # Filename of fetchec catalog
        fname = str(target) + '_r_' + str(radius)

        # Can force to use certain catalog - untested 03-10-19
        if syntax['force_catalog_csv']:
            logger.info('Using '+syntax['force_catalog_csv_name']+' as catalog')
            fname = str(syntax['force_catalog_csv_name']) + '_r_' + str(radius)

        # if catalog is found via it's filename - use this and return data
        if os.path.isfile(os.path.join(target_dir,fname+'.csv')):
            logger.info('Catalog found for Target: %s\nCatalog: %s \nFile: %s' % (target,str(catalog_dir).upper(),fname))
            data = Table.read(os.path.join(target_dir,fname+'.csv'),format = 'csv')
            data = data.to_pandas()

        else:
            # If no previously catalog found - look for one
            logger.info('Searching for new catalog: %s ' % syntax['catalog'])

            if syntax['catalog'] in ['gaia']:

                import astropy.units as u
                from astroquery.gaia import Gaia
                import warnings
                warnings.filterwarnings('ignore')

                width = u.Quantity(radius, u.deg)
                height = u.Quantity(radius, u.deg)

                data = Gaia.query_object_async(coordinate=target_coords, width=width, height=height)

                data = data.to_pandas()
                data.to_csv(fname+'.csv', sep=',',index = False)

                # Move file to new location - 'catalog queries'
                shutil.move(os.path.join(os.getcwd(), fname+'.csv'),
                            os.path.join(target_dir, fname+'.csv'))

                warnings.filterwarnings('default')

            if syntax['catalog'] in ['apass','2mass']:

                # No row limit
                Vizier.ROW_LIMIT = -1
                catalog_search = Vizier.query_region(target_coords,
                                                     radius = Angle(radius,'deg'),
                                                     catalog = syntax['catalog'])

                # Select first catalog from list
                data = catalog_search[0].to_pandas()
                data.to_csv(fname+'.csv', sep=',',index = False)


                # Move file to new location - 'catalog queries'
                shutil.move(os.path.join(os.getcwd(), fname+'.csv'),
                            os.path.join(target_dir, fname+'.csv'))


            # some catalogs need specific download path using 'requests'
            if syntax['catalog'] in ['pan_starrs','skymapper']:

                mindet=1

                if syntax['catalog'] == 'pan_starrs':

                    server=('https://archive.stsci.edu/'+'panstarrs/search.php')
                    params = {'RA': target_coords.ra.degree, 'DEC': target_coords.dec.degree,
                              'SR': radius, 'max_records': 10000,
                              'outputformat': 'VOTable',
                              'ndetections': ('>%d' % mindet)}

                if syntax['catalog'] == 'skymapper':

                    server=('http://skymapper.anu.edu.au/sm-cone/public/query?')
                    params = {'RA': target_coords.ra.degree, 'DEC': target_coords.dec.degree,
                              'SR': radius,
                              'RESPONSEFORMAT': 'VOTABLE'}

                with open('temp.xml', "wb") as f:

                    logger.info('Downloading from %s'  % syntax['catalog'] )
                    response = requests.get(server,params = params)
                    f.write(response.content)

                # Parse local file into astropy.table object
                data = parse_single_table('temp.xml')

                # Delete temporary file
                os.remove('temp.xml')

                # Convert table to dataframe
                data_table = data.to_table(use_names_over_ids=True)
                data = data_table.to_pandas()

                # invalid entries in panstarrs are -999 - change to nans
                if syntax['catalog'] == 'pan_starrs':
                    data = data.replace(-999,np.nan)

                # No sources in field - temporary fix - will add "check different catalog"
                if len(data) == 0:
                    logging.critical('Catalog: %s : does not cover field' %  syntax['catalog'])
                    sys.exit()

                # Save to csv and move to 'catalog_queries'
                data.to_csv(fname+'.csv',index = False)

                shutil.move(os.path.join(os.getcwd(), fname+'.csv'),
                            os.path.join(target_dir,  fname+'.csv'))


        # Add in x and y pixel locatins under wcs
        x_pix,y_pix = w1.wcs_world2pix(data[catalog_syntax['RA']], data[catalog_syntax['DEC']],1)

        data.insert(loc = 5, column = 'x_pix', value = x_pix)
        data.insert(loc = 6, column = 'y_pix', value = y_pix)

        # Remove boundary sources
        data = data[data.x_pix < image.shape[1] - syntax['pix_bound']]
        data = data[data.x_pix > syntax['pix_bound']]
        data = data[data.y_pix < image.shape[0] - syntax['pix_bound']]
        data = data[data.y_pix > syntax['pix_bound']]

        logger.info('Catalog length: %d' % len(data))

        warnings.filterwarnings("default")

    except Exception as e:
        logger.exception(e)
        data = None

    return data
Exemplo n.º 43
0
from astroquery.vizier import Vizier
import numpy as np
import scipy.optimize as op



catalog_list = Vizier.find_catalogs('New white dwarf SDSS DR12')
print({k:v.description for k,v in catalog_list.items()})

Vizier.ROW_LIMIT = -1
catalogs = Vizier.get_catalogs(list(catalog_list))


# Our model has a temperature effect, then absorption features on top of the model


# Constants
h_planck = 4.136e-15 # in eV*s
c_light = 2.998e10   # in cgs
k_boltz = 8.617e-5   # in eV/K


# Balmer line centers (in cgs):
lambda_balmer = np.array([6563, 4861, 4341, 4102, 3970, 3889])
window_dict = {}



# Lorentz distribution:
def lorentz(C_coeff, x_center, gamma, x):
    return -C_coeff / (np.pi * gamma * (1.0 + ((x-x_center)/gamma)**2))
Exemplo n.º 44
0
from astroquery.vizier import Vizier
from astroquery.simbad import Simbad
import requests
from bs4 import BeautifulSoup
import numpy as np
from astropy.table import Table, vstack
from astropy.io import ascii
from astropy import units as u
from astropy.coordinates import SkyCoord, get_constellation
import pandas as pd
import glob, os

print('Downloading constellation_borders.csv...')
# This loads all the catalogs by the keyword "constellation"
catalogue_list = Vizier.find_catalogs("Constellation")
Vizier.ROW_LIMIT = -1
# Following table contains the relevant data
catalog = Vizier.get_catalogs("VI/49")[1]
catalog.remove_columns(['cst', 'type'])
coords = SkyCoord(catalog['RAJ2000'], catalog['DEJ2000'], unit="deg")
const = coords.get_constellation()
const = ['Bootes' if x == 'Boötes' else x
         for x in const]  # fixing for the unicode problem
catalog.add_column(const, name="Constellation", index=2)
catalog.write("constellation_borders.csv", format="csv", overwrite="True")
print('Done - Constellation borders\n')

print('Downloading messier_objects.csv...')

#Download magnitdue data from astropixels/SEDS
Exemplo n.º 45
0
########################################################################################################

output_path = '/mnt/dwf/archive_NOAO_data/data_outputs/'
output_cats = '/mnt/dwf/archive_NOAO_data/data_outputs/' + year + '/' + month + '/' + field + '/vizier_cats/'

if not os.path.exists(output_cats):
    os.makedirs(output_cats)
else:
    pass

AAVOS = 'II/336'
#v = Vizier(columns = ['mag', '_RAJ2000', '_DEJ2000'], catalog = AAVOS)
#result = v.query_region(field_RA_DEC, radius=Angle(1.5, "deg"))
result = Vizier.query_region(field_RA_DEC,
                             radius=Angle(1.5, "deg"),
                             catalog=AAVOS)

AAVOS_table = Table()
AAVOS_table['RA'] = result[0]['RAJ2000']
AAVOS_table['DEC'] = result[0]['DEJ2000']
AAVOS_table['g_mag'] = result[0]['g_mag']
AAVOS_table['g_mag_err'] = result[0]['e_g_mag']
AAVOS_table['r_mag'] = result[0]['r_mag']
AAVOS_table['r_mag_err'] = result[0]['e_r_mag']
AAVOS_table['i_mag'] = result[0]['i_mag']
AAVOS_table['i_mag_err'] = result[0]['e_i_mag']

AAVOS_output = 'AAVOS.ascii'
AAVOS_table.write(output_cats + AAVOS_output, format='ascii', overwrite=True)
Exemplo n.º 46
0
    def overlay_catalog(self, magstep=0.5, row_limit=1000):
        Vizier.ROW_LIMIT = row_limit
        # Get WCS Info From Image Header
        h = self.image.get_header()
        wcs = WCS(h)

        nx, ny = self.image.shape
        result = wcs.all_pix2world(np.array(nx / 2), np.array(ny / 2), 1)
        center = SkyCoord(result[0], result[1], frame='icrs', unit='deg')
        center_str = center.to_string("hmsdms", precision=1, sep=':')
        footprint = wcs.calc_footprint()
        FoV = ((max(footprint[:, 0]) - min(footprint[:, 0])) *
               np.cos(center.dec.deg * np.pi / 180),
               max(footprint[:, 1]) - min(footprint[:, 1]))
        log.info(f'Found WCS with center coordinate: {center_str}')
        log.info(f'WCS has approximate diameter of {max(FoV):.2f} deg '\
                 f'({max(FoV)*60:.1f} arcmin)')
        FoV = ((max(footprint[:, 0]) - min(footprint[:, 0])),
               max(footprint[:, 1]) - min(footprint[:, 1]))

        catalog_names = ['Gaia DR2', 'UCAC5', '2MASS PSC']
        catalog_IDs = ['I/345', 'I/340', 'II/246']
        colors = ['green', 'lightblue', 'red']
        radii = [10, 13, 16]
        RAcolname = ['RA_ICRS', 'RAJ2000', 'RAJ2000']
        DEcolname = ['DE_ICRS', 'DEJ2000', 'DEJ2000']
        magname = ['Gmag', None, None]

        result = Vizier.query_region(center,
                                     width=1.05 * FoV[0] * u.deg,
                                     height=1.05 * FoV[1] * u.deg,
                                     catalog=catalog_IDs)
        # Overlay Stars
        for i, name in enumerate(catalog_names[:1]):
            stars = result.values()[i]

            maxmag = max(stars[magname[i]])
            nextmag = np.ceil(maxmag / magstep) * magstep - magstep
            if magname[i] is not None:
                while len(stars) == Vizier.ROW_LIMIT and nextmag > 10:
                    log.warning(f'Retrieved {len(stars)} stars which is at '
                                f'the limit of {row_limit} for this query.')
                    nextmag -= magstep
                    log.info(f'Reducing {magname[i]} limit to {nextmag:.2f}')
                    vquery = Vizier(
                        column_filters={magname[i]: f"<{nextmag:.1f}"},
                        row_limit=Vizier.ROW_LIMIT)
                    stars = vquery.query_region(center,
                                                width=1.05 * FoV[0] * u.deg,
                                                height=1.05 * FoV[1] * u.deg,
                                                catalog=catalog_IDs[i])[0]
            log.info(f'Retrieved {len(stars)} stars from {name} '
                     f'catalog and marking in {colors[i]}')

            for j, star in enumerate(stars):
                c = SkyCoord(star[RAcolname[i]] * u.deg,
                             star[DEcolname[i]] * u.deg)
                c_str = c.to_string('hmsdms', sep=':', precision=1)
                x, y = wcs.all_world2pix(c.ra.deg, c.dec.deg, 1)
                log.debug(f"{name} {c_str} {x:.1f} {y:.1f}")
                if (x > 0) and (x <= nx) and (y > 0) and (y <= ny):
                    log.debug(f"Plotting {name}: {c_str} {x:.1f} {y:.1f}")
                    self.canvas.add(
                        self.dc.Circle(x,
                                       y,
                                       radius=radii[i],
                                       alpha=0.7,
                                       color=colors[i]))
                    self.canvas.add(
                        self.dc.Circle(x,
                                       y,
                                       radius=0.5,
                                       alpha=0.7,
                                       color=colors[i]))
            log.info('  Done.')
Exemplo n.º 47
0
def query_catalogue(infile, catalogue, radius, minflux=0.0):
    '''
	query_catalogue: module to query the FIRST, NVSS, or WENSS catalogue from Vizier and write it to a record array
	skycoords: coordinates of the pointing centre in astropy format
	catalogue: catalogue to ask for (NVSS, WENSS, or FIRST)
	radius: radius around the pointing centre to ask for in degreees
	minflux: minimum real source flux to receive from a VIZIER query. Default is 0.0 since for most operations you want all sources in the radius region
	returns: record array with RA, DEC, Major axis, Minor axis, parallactic angle, and flux of the sources in the catalogue
	'''
    try:
        if catalogue == 'FIRST':
            v = Vizier(columns=["*", "+_r", "_RAJ2000", "_DEJ2000", "PA"],
                       column_filters={"Fint": ">" + str(minflux)})
            v.ROW_LIMIT = -1
            sources = v.query_region(getradec(infile),
                                     radius=Angle(radius, "deg"),
                                     catalog=catalogue)
            maj_axis = sources[0]['Maj']
            min_axis = sources[0]['Min']
            flux = sources[0]['Fint'] / 1000.0
        elif catalogue == 'NVSS':
            v = Vizier(columns=["*", "+_r", "_RAJ2000", "_DEJ2000", "PA"],
                       column_filters={"S1.4": ">" + str(minflux)})
            v.ROW_LIMIT = -1
            sources = v.query_region(getradec(infile),
                                     radius=Angle(radius, "deg"),
                                     catalog=catalogue)
            maj_axis = sources[0]['MajAxis']
            min_axis = sources[0]['MinAxis']
            flux = sources[0]['S1.4'] / 1000.0
        elif catalogue == 'WENSS':
            v = Vizier(columns=["*", "+_r", "_RAJ2000", "_DEJ2000", "PA"],
                       column_filters={"Sint": ">" + str(minflux)})
            v.ROW_LIMIT = -1
            sources = v.query_region(getradec(infile),
                                     radius=Angle(radius, "deg"),
                                     catalog=catalogue)
            maj_axis = sources[0]['MajAxis']
            min_axis = sources[0]['MinAxis']
            flux = sources[0]['Sint'] / 1000.0
        catlength = len(sources[0])
        dtype = [('RA', float), ('DEC', float), ('MajAxis', float),
                 ('MinAxis', float), ('PA', float), ('flux', float),
                 ('dist', float)
                 ]  # create a structured array with the source data
        cat = np.zeros((catlength, ), dtype=dtype)
        cat['RA'] = sources[0]['_RAJ2000']
        cat['DEC'] = sources[0]['_DEJ2000']
        cat['MajAxis'] = maj_axis
        cat['MinAxis'] = min_axis
        cat['PA'] = sources[0]['PA']
        cat['flux'] = flux
        cat['dist'] = sources[0]['_r']
        cat = np.rec.array(
            cat
        )  # transform the structured array to a record array for easier handling
    except IndexError:
        cat = []
    return cat
Exemplo n.º 48
0
def get_gaia_dr3_paralax(filename = 'gaiadr2/gaiaid_sc.rdb', fileout= 'gaiadr2/tmp_dr3.rdb', append= True):
  if os.path.isfile(fileout):
    filetmp = open(fileout,"r")
    strlines = filetmp.readlines()
    filetmp.close()
    name_tmp, gaiaid_tmp = np.loadtxt(fileout, unpack=True,usecols=(0,1), skiprows=2, delimiter="\t", dtype=str)
  else:
    print("Fresh start")
    gaiaid_tmp = []
    strlines =     ['name\tgaia_id\tPlx\te_Plx\tGmag\te_Gmag\tRPmag\te_RPmag\tBPmag\te_BPmag\tFG\te_FG\tG_flux_std_n\n']
    strlines.append('----\t-------\t---\t-----\t----\t------\t-----\t-------\t-----\t-------\t--\t----\t------------\n')

  print("Result GAIA vizier")
  vq2 = Vizier(columns=['Source','Plx','e_Plx', 'FG','e_FG','Gmag','e_Gmag', 'BPmag','e_BPmag', 'RPmag','e_RPmag', 'o_Gmag'], row_limit=5000) 

  name, gaia_id = np.loadtxt(filename, unpack=True, usecols=(0,1), skiprows=2, delimiter="\t", dtype=str)
  radius_search = 10.0*u.arcsec

  #ist = 3100
  #for i,gaiadr2 in enumerate(gaia_id[ist:]):
  #  i += ist
  for i,gaiadr2 in enumerate(gaia_id):
    print(i, len(gaia_id), name[i], gaiadr2)
    if gaiadr2 in gaiaid_tmp and name[i] in name_tmp:
      print("This one already in place")
      continue
    if gaiadr2 == "-1":
      print(name[i], "No gaia id dr2")
      strlines.append('%s\t%s\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n' % (name[i], gaiadr2))
    else:
      result_gaia_vizier_dr3=vq2.query_object("Gaia DR2 "+str(gaiadr2), catalog=["I/350/gaiaedr3"], radius=radius_search*15.)
      try:
        iline3 = np.where(result_gaia_vizier_dr3[0]['Source'] == int(gaiadr2))[0][0]
        print(result_gaia_vizier_dr3[0]['Source','Plx','e_Plx', 'Gmag', 'e_Gmag', 'FG', 'e_FG', 'RPmag', 'e_RPmag', 'BPmag', 'e_BPmag'][iline3])
        std_g_flux_norm1_v = result_gaia_vizier_dr3[0]['e_FG'][iline3]*np.sqrt(result_gaia_vizier_dr3[0]['o_Gmag'][iline3])/result_gaia_vizier_dr3[0]['FG'][iline3]
      except IndexError:
        result_gaia_vizier_dr3=vq2.query_object("Gaia DR2 "+str(gaiadr2), catalog=["I/350/gaiaedr3"], radius=radius_search*25.)
        try:
          iline3 = np.where(result_gaia_vizier_dr3[0]['Source'] == int(gaiadr2))[0][0]
          print(result_gaia_vizier_dr3[0]['Source','Plx','e_Plx', 'Gmag', 'e_Gmag', 'FG', 'e_FG', 'RPmag', 'e_RPmag', 'BPmag', 'e_BPmag'][iline3])
          std_g_flux_norm1_v = result_gaia_vizier_dr3[0]['e_FG'][iline3]*np.sqrt(result_gaia_vizier_dr3[0]['o_Gmag'][iline3])/result_gaia_vizier_dr3[0]['FG'][iline3]

        except IndexError:
          result_gaia_vizier_dr3 =  [Table( [[-1], [-1],[-1], [-1] ,[-1], [-1] ,[-1] ,[-1]   ,[-1] , [-1]    ] ,
                                   names=('Plx','e_Plx','Gmag','e_Gmag','FG','e_FG','RPmag','e_RPmag','BPmag','e_BPmag')) ]
          std_g_flux_norm1_v = -1
          iline3=0
      print("Iline2:", iline3)
      strlines.append('%s\t%s\t%7.4f\t%7.4f\t%7.4f\t%7.4f\t%7.4f\t%7.4f\t%7.4f\t%7.4f\t%.3e\t%.3e\t%10.7f\n' % (name[i], gaiadr2, 
        result_gaia_vizier_dr3[0]['Plx'][iline3], result_gaia_vizier_dr3[0]['e_Plx'][iline3],
        result_gaia_vizier_dr3[0]['Gmag'][iline3], result_gaia_vizier_dr3[0]['e_Gmag'][iline3],
        result_gaia_vizier_dr3[0]['RPmag'][iline3], result_gaia_vizier_dr3[0]['e_RPmag'][iline3],
        result_gaia_vizier_dr3[0]['BPmag'][iline3], result_gaia_vizier_dr3[0]['e_BPmag'][iline3],
        result_gaia_vizier_dr3[0]['FG'][iline3], result_gaia_vizier_dr3[0]['e_FG'][iline3],
        std_g_flux_norm1_v))
      print(strlines[-1])
  if append:     
    fileo = open(fileout, "a")
  else:
    fileo = open(fileout, "w")
  for line in strlines:
    fileo.write(line)
  fileo.close()
Exemplo n.º 49
0
    def table(self):
        if self._table is None:

            table = Vizier.get_catalogs('J/A+A/552/A16/limb1-4')[0]
            self._table = table
        return self._table
Exemplo n.º 50
0
import numpy as np
from astroquery.vizier import Vizier
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy import table
import numpy as np

usnob_cat = Vizier.find_catalogs('USNO-B1.0')

def get_usnob1_cat(ra, dec, blim):
    ra_u = ra*u.degree
    dec_u = dec*u.degree
    coords = SkyCoord(ra_u, dec_u, frame='icrs') #Should this be ICRS or FK5
    #Only Class 0 (stars) - unable to implement this at the current time. Need to understand
    #USNO-B1 s/g classification
    v = Vizier(columns=['USNO-B1.0', '_RAJ2000', '_DEJ2000', 
                        'B1mag', 'R1mag', 'B2mag', 'R2mag', 
                        'pmRA', 'pmDE', 'Imag', 'B1s/g', '_r'],
                row_limit=500000,
               column_filters={"B2mag":">6", 'B2mag':'<{}'.format(blim)}) #B2mag fainter than 6, brighter than blim
    new_table_list = v.query_region(coords, 
                                 radius=900*u.arcsecond, #Search 900 arcseconds
                                 catalog = 'I/284')
    if len(new_table_list) ==0:
        return None
    else:
        new_table = new_table_list[0]
    #Get the 5000 closest
    new_table.sort('_r')
    if len(new_table) > 5000:
        new_table.remove_rows(np.arange(5001, len(new_table)))
Exemplo n.º 51
0
def add_gaia_figure_elements(tpf, fig, magnitude_limit=18):
    """Make the Gaia Figure Elements"""
    # Get the positions of the Gaia sources
    c1 = SkyCoord(tpf.ra, tpf.dec, frame='icrs', unit='deg')
    # Use pixel scale for query size
    pix_scale = 4.0  # arcseconds / pixel for Kepler, default
    if tpf.mission == 'TESS':
        pix_scale = 21.0
    # We are querying with a diameter as the radius, overfilling by 2x.
    from astroquery.vizier import Vizier
    Vizier.ROW_LIMIT = -1
    result = Vizier.query_region(c1, catalog=["I/345/gaia2"],
                                 radius=Angle(np.max(tpf.shape[1:]) * pix_scale, "arcsec"))
    no_targets_found_message = ValueError('Either no sources were found in the query region '
                                          'or Vizier is unavailable')
    too_few_found_message = ValueError('No sources found brighter than {:0.1f}'.format(magnitude_limit))
    if result is None:
        raise no_targets_found_message
    elif len(result) == 0:
        raise too_few_found_message
    result = result["I/345/gaia2"].to_pandas()
    result = result[result.Gmag < magnitude_limit]
    if len(result) == 0:
        raise no_targets_found_message

    # Apply correction for proper motion
    year = ((tpf.time[0].jd - 2457206.375) * u.day).to(u.year)
    pmra = ((np.nan_to_num(np.asarray(result.pmRA)) * u.milliarcsecond/u.year) * year).to(u.deg).value
    pmdec = ((np.nan_to_num(np.asarray(result.pmDE)) * u.milliarcsecond/u.year) * year).to(u.deg).value
    result.RA_ICRS += pmra
    result.DE_ICRS += pmdec

    # Convert to pixel coordinates
    radecs = np.vstack([result['RA_ICRS'], result['DE_ICRS']]).T
    coords = tpf.wcs.all_world2pix(radecs, 0)

    # Gently size the points by their Gaia magnitude
    sizes = 64.0 / 2**(result['Gmag']/5.0)
    one_over_parallax = 1.0 / (result['Plx']/1000.)
    source = ColumnDataSource(data=dict(ra=result['RA_ICRS'],
                                        dec=result['DE_ICRS'],
                                        pmra=result['pmRA'],
                                        pmde=result['pmDE'],
                                        source=result['Source'].astype(str),
                                        Gmag=result['Gmag'],
                                        plx=result['Plx'],
                                        one_over_plx=one_over_parallax,
                                        x=coords[:, 0] + tpf.column,
                                        y=coords[:, 1] + tpf.row,
                                        size=sizes))

    r = fig.circle('x', 'y', source=source, fill_alpha=0.3, size='size',
                   line_color=None, selection_color="firebrick",
                   nonselection_fill_alpha=0.0, nonselection_line_color=None,
                   nonselection_line_alpha=0.0, fill_color="firebrick",
                   hover_fill_color="firebrick", hover_alpha=0.9,
                   hover_line_color="white")

    fig.add_tools(HoverTool(tooltips=[("Gaia source", "@source"),
                                      ("G", "@Gmag"),
                                      ("Parallax (mas)", "@plx (~@one_over_plx{0,0} pc)"),
                                      ("RA", "@ra{0,0.00000000}"),
                                      ("DEC", "@dec{0,0.00000000}"),
                                      ("pmRA", "@pmra{0,0.000} mas/yr"),
                                      ("pmDE", "@pmde{0,0.000} mas/yr"),
                                      ("x", "@x"),
                                      ("y", "@y")],
                            renderers=[r],
                            mode='mouse',
                            point_policy="snap_to_data"))
    return fig, r
def find_source(alt_az, lat_lon=local_latlong,
                minute=minute, hour=hour,
                day=day, month=month, year=year, tz_offset=5,
                return_all_sources=True):
    """Find a source given some coordinates.

    Args:
        alt_az: Tuple of altitude and azimuth (decimal degrees)
        lat_lon: Tuple of latitude and longitude (decimal degrees)
        time: Clock time (?)

    Returns:
        source_name (str):
    """
    ra_dec = altaz_to_radec(alt_az, pos=lat_lon,
                            minute=minute, hour=hour, day=day,
                            month=month, year=year, tz_offset=5)

    coords = coordinates.SkyCoord(ra=ra_dec[0], dec=ra_dec[1],
                                  unit=(u.deg, u.deg), frame='icrs')
    # Get the actual results
    # For some reason, if this goes too big it stops seeing the actual source.
    r = 500 * u.arcminute
    results = Vizier.query_region(coords, radius=r, catalog='V/50')[0]
    df = results.to_pandas()

    candidate_sources = filter(None, [n for n in df['HD']])
    sources = []
    dmax, vmax = 0, 0
    for s in candidate_sources:
        source_info = df.loc[df['HD'] == s]
        name = source_info['Name']
        mag = round(float(source_info['Vmag']), 2)

        temp_ra = source_info['RAJ2000'].tolist()[0]
        temp_dec = source_info['DEJ2000'].tolist()[0]
        source_ra_hms = tuple(map(float, temp_ra.split()))
        source_dec_dms = tuple(map(float, temp_dec.split()))
        source_ra = Angle(source_ra_hms, unit='hourangle').degree
        source_dec = Angle(source_dec_dms, unit=u.deg).degree

        dist_from_center = np.sqrt((source_ra - ra_dec[0])**2 +
                                   (source_dec - ra_dec[1])**2)

        score = float(c1 * mag + c2 * dist_from_center)
        source_dict = {'HD': source_info['HD'].values[0],
                       'Name': source_info['Name'].values[0],
                       'RA': source_ra,
                       'DEC': source_dec,
                       'Distance': dist_from_center,
                       'Vmag': source_info['Vmag'],
                       'Score': score}

        sources.append(source_dict)

        dmax = dist_from_center if dist_from_center > dmax else dmax
        vmax = mag if mag > vmax else mag

    for s in range(len(sources)):
        d = sources[s]['Distance']/dmax
        mag = sources[s]['Vmag'].values[0]/vmax
        score = c1 * mag + c2 * d
        sources[s]['Score'] = score
        sources[s]['Scaled-Distance'] = d
        sources[s]['Scaled-Mag'] = mag

    sources_df = pd.DataFrame(sources)


    # Note that this loop is supremely janky, but df.loc'ing wasn't working.
    # best_source = sources_df.loc[sources_df['Score'] == sources_df['Score'].min]
    best_source_idx = 0
    # best_score = np.array([])
    best_score = 10000
    for i in range(len(sources)):
        score = sources[i]['Score']
        if score < best_score:
            best_source_idx = i
            best_score = score

    name = sources_df['Name'].values[0]
    out = {'Coords': ra_dec,
           'HD-Name': 'HD' + str(int(sources[best_source_idx]['HD'])),
           'Name': sources[best_source_idx]['Name'],
           'Score': sources[best_source_idx]['Score'],
           'Scaled-Distance': sources[best_source_idx]['Scaled-Distance'],
           'Scaled-Mag': sources[best_source_idx]['Scaled-Mag']
           }
    return out
Exemplo n.º 53
0
"""
This is the code used to generate the polynomial relations
used in sedkit's calculations
"""
from pkg_resources import resource_filename

import astropy.io.ascii as ii
import astropy.units as q
import astropy.table as at
from astroquery.vizier import Vizier
from bokeh.plotting import figure, show
import numpy as np

from . import utilities as u

V = Vizier(columns=["**"])


class SpectralTypeRadius:
    def __init__(self, order=8, name='Spectral Type vs. Radius'):
        """Initialize the object

        Parameters
        ----------
        order: int
            The order polynomial to fit to the spt-radius data
        """
        self.name = name
        self.generate(order)

    def get_radius(self, spt, plot=False):
def find_location(source_name, source_alt_az,
                  minute=minute_now, hour=hour_now, day=day_now,
                  month=month_now, year=year_now, plot_grids=True):
    """Find out where we are on Earth.

    Args:
        source_name (str):
        source_ra_dec (tuple of floats):
        minute, hour, day, month, year (ints):

    Returns:
        lat_long (tuple of floats): your location.
    """

    alt, az = source_alt_az
    source_obj = Vizier.query_object(source_name, catalog='V/50')[0]
    source_ra_dec = (source_obj['RAJ2000'][0], source_obj['DEJ2000'][0])

    source_ra_hms = tuple(map(float, source_ra_dec[0].split()))
    source_dec_dms = tuple(map(float, source_ra_dec[1].split()))

    source_ra = Angle(source_ra_hms, unit='hourangle').degree
    source_dec = Angle(source_dec_dms, unit=u.deg).degree


    lat_crit = 0.01
    step = 20
    lats = np.linspace(-90, 90, step)
    longs = np.linspace(-180., 180., 2*step)
    lat_min, lat_max = 0, len(lats) - 1
    long_min, long_max = 0, len(longs) - 1

    real_lat, real_long = 41.55, -72.65

    counter = 0
    while abs(lats[1] - lats[0]) > lat_crit:
        lats = np.linspace(lats[lat_min], lats[lat_max], step)
        longs = np.linspace(longs[long_min], longs[long_max], 2*step)

        score_grid = np.zeros((len(lats), len(longs)))

        # Run the grid
        for i in range(len(lats)):
            for j in range(len(longs)):
                lat, long = lats[i], longs[j]

                ra, dec = altaz_to_radec((alt, az), pos=(lat, long),
                                         minute=minute, hour=hour, day=day,
                                         month=month, year=year, tz_offset=5)

                score = np.sqrt((ra - source_ra)**2 + (dec - source_dec)**2)
                score_grid[i, j] = score

        idx = np.where(score_grid == np.nanmin(score_grid))
        lat_min = idx[0][0] - 2 if idx[0][0] > 1 else 0
        lat_max = idx[0][0] + 2 if idx[0][0] < len(lats) - 2 else len(lats) - 1

        long_min = idx[1][0] - 2 if idx[1][0] > 1 else 0
        long_max = idx[1][0] + 2 if idx[1][0] < len(longs) - 2 else len(longs) - 1

        plt.matshow(score_grid, cmap='magma_r')
        plt.contour(score_grid, cmap='magma')
        xtick_locs = np.arange(0, len(longs), len(longs)/6)
        xtick_labs = [int(longs[i]) for i in xtick_locs]
        plt.xticks(xtick_locs, xtick_labs)

        ytick_locs = np.arange(0, len(lats), len(lats)/6)
        ytick_labs = [int(lats[i]) for i in ytick_locs]
        plt.yticks(ytick_locs, ytick_labs)

        i, j = 0, 0
        while longs[i] < real_long and i < len(longs) - 1:
            i += 1
        while lats[j] < real_lat and j < len(lats) - 1:
            j += 1

        print i, j
        if i != 0 and j != 0 and i != len(longs) and i != len(lats):
            plt.plot([i], [j], 'or')
        plt.savefig('window-evolution' + str(counter) + '.png')
        plt.close

        counter += 1

    return (lats[idx[0][0]], longs[idx[1][0]])
















    outname = 'latlong-gridsearch-results_' + str(res)
    score_df = pd.DataFrame(score_grid)
    score_df.to_csv(outname + '.csv')

    if plot_grids is True:
        lat_coord = (90 + local_latlong[0]) * res
        long_coord = (180 + local_latlong[1]) * res

        plt.contour(score_grid)
        plt.plot([lat_coord], [long_coord], 'or')
        plt.matshow(score_grid, cmap='magma')

        xtick_locs = np.arange(0, len(longs), len(longs)/6)
        xtick_labs = [int(longs[i]) for i in xtick_locs]
        plt.xticks(xtick_locs, xtick_labs)

        # plt.ylim(max(lats), min(lats))
        ytick_locs = np.arange(0, len(lats), len(lats)/10)
        ytick_labs = [int(lats[i]) for i in ytick_locs]
        plt.yticks(ytick_locs, ytick_labs)

        plt.savefig(outname + '.png', dpi=200)
        plt.show(block=False)


    return {'RA': ra_grid, 'DEC': dec_grid, 'SCORE': score_grid}
Exemplo n.º 55
0
#!/bin/env python

# Downloads the gleam catalog as a VOTable from Vizier
# This is required for running reference sim 1.4.

import os
import sys

try:
    from astroquery.vizier import Vizier
except ImportError as e:
    raise ImportError(
        "astroquery module required to use the download_gleam script") from e

catalog_dir = "first_generation/catalog_files/"
name = "gleam.vot"

opath = os.path.join(catalog_dir, name)
if os.path.exists(opath):
    print("GLEAM already downloaded to {}.".format(opath))
    sys.exit()
Vizier.ROW_LIMIT = -1
Vizier.columns = ['GLEAM', 'RAJ2000', 'DEJ2000', 'Fintwide']
catname = 'VIII/100/gleamegc'
tab = Vizier.get_catalogs(catname)[0]
tab.write(opath, format='votable')

print("GLEAM catalog downloaded and saved to " + opath)
def find_location_gs(source_name, source_alt_az,
                  minute, hour, day, month, year,
                  plot_grids=True):
    """Find out where we are on Earth.

    Args:
        source_name (str):
        source_ra_dec (tuple of floats):
        minute, hour, day, month, year (ints):

    Returns:
        lat_long (tuple of floats): your location.
    """

    alt, az = source_alt_az
    source_obj = Vizier.query_object(source_name, catalog='V/50')[0]
    source_ra_dec = (source_obj['RAJ2000'][0], source_obj['DEJ2000'][0])

    source_ra_hms = tuple(map(float, source_ra_dec[0].split()))
    source_dec_dms = tuple(map(float, source_ra_dec[1].split()))

    source_ra = Angle(source_ra_hms, unit='hourangle').degree
    source_dec = Angle(source_dec_dms, unit=u.deg).degree

    lats = np.arange(-90., 90, res)
    longs = np.arange(-180, 180, res)

    ra_grid = np.zeros((len(lats), len(longs)))
    dec_grid = np.zeros((len(lats), len(longs)))
    score_grid = np.zeros((len(lats), len(longs)))

    # Run the grid
    lat_counter, long_counter = 0, 0
    for i in range(len(lats)):
        for j in range(len(longs)):
            # Need to sort out angular units
            lat, long = lats[i], longs[j]

            ra, dec = altaz_to_radec((alt, az), pos=(lat, long),
                                     minute=minute, hour=hour, day=day,
                                     month=month, year=year, tz_offset=5)

            # pos_grid[i, j] = {'RA': ra, 'DEC': dec}
            ra_grid[i, j] = ra
            dec_grid[i, j] = dec

            # Bad - planar:
            score = np.sqrt((ra - source_ra)**2 + (dec - source_dec)**2)

            # Good - spherical:
            # score = np.arccos(np.sin(dec) * np.sin(source_dec) + np.cos(dec) * np.cos(source_dec) * np.cos(abs(ra - source_ra)))

            score_grid[i, j] = score

            verbose = False
            if verbose is True:
                print('RA, Source RA:', ra, source_ra)
                print('DEC, Source DEC:', dec, source_dec)
                print('Score:', score)
                print('\n')
            else:
                step = long_counter + lat_counter * len(lats)
                print (str(step) + '/' + str(len(lats) * len(longs)))
            long_counter += 1

    outname = 'latlong-gridsearch-results_' + str(res)
    score_df = pd.DataFrame(score_grid)
    score_df.to_csv(outname + '.csv')

    if plot_grids is True:
        lat_coord = (90 + local_latlong[0]) * res
        long_coord = (180 + local_latlong[1]) * res

        plt.contour(score_grid)
        plt.plot([lat_coord], [long_coord], 'or')
        plt.matshow(score_grid, cmap='magma')

        xtick_locs = np.arange(0, len(longs), len(longs)/6)
        xtick_labs = [int(longs[i]) for i in xtick_locs]
        plt.xticks(xtick_locs, xtick_labs)

        # plt.ylim(max(lats), min(lats))
        ytick_locs = np.arange(0, len(lats), len(lats)/10)
        ytick_labs = [int(lats[i]) for i in ytick_locs]
        plt.yticks(ytick_locs, ytick_labs)

        plt.savefig(outname + '.png', dpi=200)
        plt.show(block=False)


    return {'RA': ra_grid, 'DEC': dec_grid, 'SCORE': score_grid}
Exemplo n.º 57
0
from astroquery.simbad import Simbad

S = Simbad()
S.add_votable_fields('rv_value')

dir = sys.argv[1]
files = glob.glob(dir + '/*p08.fits')
templates = glob.glob('/home/rajikak/tools/RV_standards/*')

print("*************")

for file in files:
    a = pyfits.open(file)
    object_name = a[1].header['OBJNAME']

    #get RV data on the standard:
    #From Vizier table:
    result = Vizier.query_object(object_name)
    interesting_table = result['J/ApJS/141/503/table1']
    object_RV = float(interesting_table[0]['__RV_']) / 1000.

    flux_stamp, wave = ps.read_and_find_star_p08(file)
    spectrum, sig = ps.weighted_extract_spectrum(flux_stamp)
    rv, rv_sig = ps.calc_rv_template(spectrum, wave, sig, templates,
                                     ([0, 5400], [6870, 6890]))
    rv += a[1].header['RADVEL']

    print("object_name: " + object_name)
    print("object RV: " + str(object_RV) + "km/s")
    print("Retrieved RV from standards: " + str(rv) + "km/s")
    print("*************")
Exemplo n.º 58
0
plt.ylim(755.1,755.5)
plt.ylabel('fistar Centroid Location')
plt.xlabel('Frame Number, Cadence')
plt.savefig('fistarYDrift.png',dpi=200,bbox_inches='tight')
plt.show()
#%% m soares code from 5/13/2020
import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)

from astropy.io import fits 
from astropy.table import Table
from astroquery.mast import Catalogs
from astroquery.vizier import Vizier

v = Vizier()
from astropy import coordinates
from astropy import units as u

#Live dangerously
import warnings
warnings.filterwarnings("ignore")


# interface with astrometry package instead of opening this fits file
tbl = fits.open('/Users/msoares/Desktop/corr.fits')[1].data




Exemplo n.º 59
0
    def post(self, obj_id):
        """
        ---
        description: |
            get cross-match with Vizier and post them as an annotation
            based on cross-matches to some catalog
            (default is VII/290, i.e. the million quasar catalog).
        parameters:
          - in: path
            name: obj_id
            required: true
            schema:
              type: string
            description: ID of the object to retrieve the Vizier crossmatch for
        requestBody:
          content:
            application/json:
              schema:
                type: object
                properties:
                  catalog:
                    required: false
                    type: string
                    description: |
                      The name of the catalog key, associated with a
                      catalog cross match,
                      from which the data should be retrieved.
                      Default is VII/290.
                  crossmatchRadius:
                    required: false
                    type: number
                    description: |
                      Crossmatch radius (in arcseconds) to retrieve photoz's
                      Default is 2.
                  group_ids:
                    required: false
                    type: array
                    items:
                      type: integer
                    description: |
                      List of group IDs corresponding to which groups
                      should be able to view annotation.
                      Defaults to all of requesting user's groups.
        responses:
          200:
            content:
              application/json:
                schema: Success
          400:
            content:
              application/json:
                schema: Error
        """
        obj = Obj.query.get(obj_id)
        if obj is None:
            return self.error('Invalid object id.')

        data = self.get_json()

        group_ids = data.pop('group_ids', None)
        if not group_ids:
            groups = self.current_user.accessible_groups
        else:
            try:
                groups = Group.get_if_accessible_by(
                    group_ids, self.current_user, raise_if_none=True
                )
            except AccessError:
                return self.error(
                    'At least some of the groups are not accessible.', status=403
                )

        author = self.associated_user_object

        catalog = data.pop('catalog', "VII/290")
        radius_arcsec = data.pop('crossmatchRadius', 2.0)
        candidate_coord = SkyCoord(ra=obj.ra * u.deg, dec=obj.dec * u.deg)

        tl = Vizier.query_region(
            coordinates=candidate_coord,
            catalog=catalog,
            radius=radius_arcsec * u.arcsec,
        )

        if len(tl) == 0:
            return self.error("No successful cross-match available.")

        if len(tl) > 1:
            return self.error("Should only have one table from that query.")
        df = tl[0].filled(fill_value=-99).to_pandas()
        keys = [
            'Qpct',
            'z',
        ]
        annotations = []
        for index, row in df.iterrows():
            annotation_data = {
                k: row.to_dict().get(k, None)
                for k in keys
                if not row.to_dict().get(k, None) == -99
            }

            origin = f"{catalog}-{row['Name']}"
            annotation = Annotation(
                data=annotation_data,
                obj_id=obj_id,
                origin=origin,
                author=author,
                groups=groups,
            )
            annotations.append(annotation)

        if len(annotations) == 0:
            return self.error("No crossmatch annotation available.")

        DBSession().add_all(annotations)
        try:
            self.verify_and_commit()
        except IntegrityError:
            return self.error("Annotation already posted.")

        self.push_all(
            action='skyportal/REFRESH_SOURCE',
            payload={'obj_key': obj.internal_key},
        )
        return self.success()
Exemplo n.º 60
0
from astroquery.vizier import Vizier
from astropy import coordinates
from astropy import units as u

v = Vizier()

c = coordinates.SkyCoord(0, 0, unit=('deg', 'deg'), frame='icrs')
result = v.query_region(c, radius=2 * u.deg, catalog=["I/337", "I/345"])

print(result)

#catalog_list = Vizier.find_catalogs('gaia', max_catalogs = 1000)
#print({k:v.description for k,v in catalog_list.items()})