Exemplo n.º 1
0
class SimbadHarvester(AbstractHarvester):
    """
    The ``SimbadHarvester`` is the interface to the SIMBAD catalog. At present, it is only queryable by identifier. For
    information regarding identifier format, please see http://simbad.u-strasbg.fr/simbad/sim-fid or
    https://astroquery.readthedocs.io/en/latest/simbad/simbad.html.
    """
    name = 'Simbad'

    def __init__(self, *args, **kwargs):
        self.simbad = Simbad()
        self.simbad.add_votable_fields('pmra', 'pmdec', 'ra(d)', 'dec(d)',
                                       'id', 'parallax', 'distance')

    def query(self, term):
        self.catalog_data = self.simbad.query_object(term)

    def to_target(self):
        target = super().to_target()
        votable_fields = [
            'RA_d', 'DEC_d', 'PMRA', 'PMDEC', 'ID', 'Distance_distance'
        ]
        result = {}
        for key in votable_fields:
            if str(self.catalog_data[key][0]) not in ['--', '']:
                result[key] = self.catalog_data[key][0]
        target.type = 'SIDEREAL'
        target.ra = result.get('RA_d')
        target.dec = result.get('DEC_d')
        target.pm_ra = result.get('PMRA')
        target.pm_dec = result.get('PMDEC')
        target.distance = result.get('Distance_distance')
        target.name = result.get('ID',
                                 b'').decode('UTF-8').split(',')[0].replace(
                                     ' ', '')
        return target
Exemplo n.º 2
0
    def __init__(self, targ_name):
        """
        Construct and execute a Simbad query object.

        :param targ_name:  The SIMBADNAME value for the current exoplanet.
        :type targ_name:  str
        """

        # Initialize an astroquery Simbad class object.
        simbad_info = Simbad()

        # Set up the list of filters and errors to query.
        self.filters = ['B', 'V', 'J', 'H', 'K']
        f = ['flux({0})'.format(x) for x in self.filters]
        fe = ['flux_error({0})'.format(y) for y in self.filters]
        fields = f + fe

        # Add the list of filters and errors to the fields queried.
        [simbad_info.add_votable_fields(f) for f in fields]

        # Execute the Simbad query.  self.results is now an astropy Table
        # object if valid results were returned.
        self.results = simbad_info.query_object(targ_name)

        # Convert masked values to NaN (some flux values return '--').
        for col in self.results.colnames:
            if self.results[col][0] is np.ma.masked:
                self.results[col][0] = np.nan

        # Add BMV info to the results Table.
        self._add_bmv_info()

        # Wait to avoid a Simbad IP blacklist (somewhere around 4-5
        # queries/sec)
        time.sleep(0.4)
def classify_file(filename, astroquery=True):
    """
    This function uses the fits header information and the Simbad database to classify the object
    :param filename: The filename of the observation to be classified
    :return:
    """
    # Read in the header and get the object name
    header = fits.getheader(filename)
    object = header['object']
    print object

    # Default values
    plx = 30.0

    # Make a Simbad object
    if astroquery:
        sim = Simbad()
        sim.add_votable_fields('plx', 'sp')
        data = sim.query_object(object)
        plx = data['PLX_VALUE'].item()
        spt_full = data['SP_TYPE'].item()
        spt = spt_full[0] + re.search(r'\d*\.?\d*', spt_full[1:]).group()
    else:
        link = pySIMBAD.buildLink(object)
        data = pySIMBAD.simbad(link)
        plx = data.Parallax()
        spt_full = data.SpectralType().split()[0]
        spt = spt_full[0] + re.search(r'\d*\.?\d*', spt_full[1:]).group()

    d = {'Object': object,
         'plx': plx,
         'SpT': spt,
         'exptime': header['exptime']}
    return d
Exemplo n.º 4
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    if result is None or len(result) == 0: raise ValueError("Galaxy name '" + galaxy_name + "' could not be recognized")

    # Loop over the results
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Exemplo n.º 5
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Exemplo n.º 6
0
def GetData(starname, safe_spt=False):
    """
    Search simbad for information about the given star. 
    :param starname: A simbad-queryable name for the star
    :param safe_spt: If True, convert spectral types with 'm' in them to '5': eg. 'Am' --> 'A5'
    """
    logging.info('Getting stellar data for {}'.format(starname))
    if starname in data_cache:
        return data_cache[starname]

    data = stardata()
    # Try the pre-downloaded database first
    dr = stellar_data.DatabaseReader(DB_NAME)
    star = dr.query_object(starname)
    dr.db_con.close()
    if len(star) > 0:
        star = star.ix[0]
        data.main_id = star.main_id
        data.spectype = star.spectral_type
        if safe_spt:
            data.spectype = data.spectype.replace('m', '5')
        data.Vmag = star.Vmag
        data.Kmag = star.Kmag
        data.ra = convert_to_hex(star.RA, delimiter=':')
        data.dec = convert_to_hex(star.DEC, delimiter=':', force_sign=True)
        data.par = star.parallax
        data_cache[starname] = data 

        return data

    # If we get here, the star was not found in the stellar_data database
    # Fall back on astroquery.
    try:
        Simbad.SIMBAD_URL = 'http://simbak.cfa.harvard.edu/simbad/sim-script'
        star = Simbad.query_object(starname)
    except astroquery.exceptions.TimeoutError:
        Simbad.SIMBAD_URL = 'http://simbad.u-strasbg.fr/simbad/sim-script'
        star = Simbad.query_object(starname)
    if star is None:
        logging.warn('Simbad query for object "{}" failed!'.format(starname))
        data.main_id = starname
        data.spectype = 'Unknown'
        data.Vmag = np.nan
        data.Kmag = np.nan
        data.ra = 'Unknown'
        data.dec = 'Unknown'
        data.par = np.nan
        return data

    data.main_id = star['MAIN_ID'].item()
    data.spectype = star['SP_TYPE'].item()
    if safe_spt:
        data.spectype = data.spectype.replace('m', '5')
    data.Vmag = star['FLUX_V'].item()
    data.Kmag = star['FLUX_K'].item()
    data.ra = star['RA'].item().strip().replace(' ', ':')
    data.dec = star['DEC'].item().strip().replace(' ', ':')
    data.par = star['PLX_VALUE'].item()
    data_cache[starname] = data
    return data
Exemplo n.º 7
0
def fetch_v_r_from_simbad(object_name):
    """
    Fetch an observed radial velocity from SIMBAD
    
    Parameters
    ----------
    object_name: str
        Name of the object to query SIMBAD for

    Returns
    -------
    v_r: float
        Observed radial velocity, in km/s
    v_r_err: float
        Error in observed radial velocity, in km/s
    """
    try:
        Simbad.add_votable_fields("rvz_radvel", "rvz_error")
    except KeyError:
        pass # already present in query
    res = Simbad.query_object(object_name)
    if res is None:
        raise Exception("Cannot fetch radial velocity from SIMBAD for object {0}".format(object_name))
    v_r, v_r_err = res["RVZ_RADVEL"][0], res["RVZ_ERROR"][0]
    return v_r, v_r_err
Exemplo n.º 8
0
def get_random_object(max_star_fraction=0.1):
	"""
	Choose random RA/DEC and select nearest SIMBAD source, 
	biasing against boring-looking stars.
	Returns a human-readable txt string and object RA/DEC.
	"""
	customSimbad = Simbad()
	customSimbad.add_votable_fields('otype(V)','coo(d)')

	coo = coord.SkyCoord(random()*360,random()*180-90,unit='deg')
	results = customSimbad.query_region(coo,radius='1 deg')
	
	for res in results:
		obj_name = ' '.join(res['MAIN_ID'].split())
		obj_type = res['OTYPE_V']
		if 'star' in obj_type.lower() and random() > max_star_fraction:
			continue
		a_an = 'an' if obj_type[0].upper() in ('X','A','E','I','O','U') else 'a'
		obj_coo = coord.SkyCoord(res['RA_d'],res['DEC_d'],unit='deg')		
		constellation = coord.get_constellation(obj_coo)
		greeting = greetings[randint(0,len(greetings)-1)]
		txt_str =  greeting + " %s is %s %s in the constellation %s. More: %s%s" % \
		(obj_name,a_an,obj_type,constellation,more_url,urlencode({'Ident':obj_name}))
		
		return obj_name,txt_str,res['RA_d'],res['DEC_d']
Exemplo n.º 9
0
def editCol(table):
    table['RA'] = None
    table['DEC'] = None
    for s in ['Teff', 'logg', 'Fe_H']:
        for i in table.index:
            try:
                a = table.loc[i, s].split('±')[0]
                table.loc[i, s] = float(a)
            except:
                print('Error in: ', table.loc[i, :])

            if table.loc[i, 'Fe_H'] == 999:
                print('999 Error: ', table.Name[i])
                customSimbad = Simbad()
                customSimbad.add_votable_fields('fe_h')
                try:
                    res = customSimbad.query_object(table.Name[i]).to_pandas()
                    table.at[i, 'Fe_H'] = float(res['Fe_H_Fe_H'])
                    print('Found Fe_H = ', table.Fe_H[i])
                    if table.Fe_H[i] < 3:
                        pass
                    else:
                        print('Nan error, drop: ', table.Name[i])
                        table.drop(i, inplace=True)
                except:
                    print('Error finding Fe_H, Drop : ', table.Name[i],
                          table.Fe_H[i])
                    table.drop(i, inplace=True)
Exemplo n.º 10
0
class SimbadHarvester(AbstractHarvester):
    name = 'Simbad'

    def __init__(self, *args, **kwargs):
        self.simbad = Simbad()
        self.simbad.add_votable_fields('pmra', 'pmdec', 'ra(d)', 'dec(d)',
                                       'id', 'parallax', 'distance')

    def query(self, term):
        self.catalog_data = self.simbad.query_object(term)

    def to_target(self):
        target = super().to_target()
        votable_fields = [
            'RA_d', 'DEC_d', 'PMRA', 'PMDEC', 'ID', 'Distance_distance'
        ]
        result = {}
        for key in votable_fields:
            if str(self.catalog_data[key][0]) not in ['--', '']:
                result[key] = self.catalog_data[key][0]
        target.type = 'SIDEREAL'
        target.ra = result.get('RA_d')
        target.dec = result.get('DEC_d')
        target.pm_ra = result.get('PMRA')
        target.pm_dec = result.get('PMDEC')
        target.distance = result.get('Distance_distance')
        target.identifier = result.get(
            'ID', b'').decode('UTF-8').split(',')[0].replace(' ', '')
        return target
Exemplo n.º 11
0
    def load(self):
        """Load the coordinates of the target.

        Examples
        --------
        >>> s = Star('3C273')
        >>> print(s.radec_position.dec)
        2d03m08.598s

        """
        # currently (pending a new release) astroquery has a race
        # condition at import time, so putting here rather than at the
        # module level so that multiple test runners don't run the race
        from astroquery.simbad import Simbad
        Simbad.add_votable_fields('flux(U)', 'flux(B)', 'flux(V)', 'flux(R)',
                                  'flux(I)', 'flux(J)', 'sptype', 'parallax',
                                  'pm', 'z_value')
        simbad = Simbad.query_object(self.label)
        self.simbad = simbad
        if simbad is not None:
            if self.verbose or True:
                self.my_logger.info(f'\n\tSimbad:\n{simbad}')
            self.radec_position = SkyCoord(simbad['RA'][0] + ' ' +
                                           simbad['DEC'][0],
                                           unit=(u.hourangle, u.deg))
        else:
            self.my_logger.warning(f'Target {self.label} not found in Simbad')
        self.get_radec_position_after_pm(date_obs="J2000")
        if not np.ma.is_masked(simbad['Z_VALUE']):
            self.redshift = float(simbad['Z_VALUE'])
        else:
            self.redshift = 0
        self.load_spectra()
Exemplo n.º 12
0
def query_from_simbad(targetName: str):
    limitedSimbad = Simbad()
    limitedSimbad.ROW_LIMIT = 5

    result_table = limitedSimbad.query_object(targetName)

    if result_table:
        ra = result_table[0][1]
        dec = result_table[0][2]

        ra_split = ra.split(" ")
        dec_split = dec.split(" ")

        len_ra = len(ra_split)
        len_dec = len(dec_split)

        # transfer the unit of ra/dec from hms/dms to degrees
        if len_ra == 1:
            ra_degree = float(ra_split[0]) * 15
        elif len_ra == 2:
            ra_degree = (float(ra_split[0]) + float(ra_split[1]) / 60) * 15
        else:
            ra_degree = (float(ra_split[0]) + float(ra_split[1]) / 60 +
                         float(ra_split[2]) / 3600) * 15

        if len_dec == 1:
            dec_degree = float(dec_split[0])
        elif len_dec == 2:
            dec_degree = float(dec_split[0]) + float(dec_split[1]) / 60
        else:
            dec_degree = float(dec_split[0]) + float(
                dec_split[1]) / 60 + float(dec_split[2]) / 3600

        webbrowser.open("https://simbad.u-strasbg.fr/simbad/sim-basic?Ident=" +
                        targetName + "&submit=SIMBAD+search")

        # check if the target exist in target table
        if (not get_targetDetails(targetName)):
            # create the target
            count = graph.run(
                "MATCH (t:target) return t.TID  order by t.TID DESC limit 1 "
            ).data()

            target = Target()
            if len(count) == 0:
                target.TID = 0
            else:
                target.TID = count[0]['t.TID'] + 1
            target.name = targetName
            target.longitude = ra_degree
            target.latitude = dec_degree
            graph.create(target)
            print("NAME", target.name)

            return [{'name': target.name}]
        else:
            print("Target is already in the target table")
            return [{'name': targetName}]
    else:
        print("Target doesn't exist.")
Exemplo n.º 13
0
class SimbadQuery(_BaseCatalogQuery):
    id_column = 'MAIN_ID'
    type_column = 'OTYPE'
    period_column = 'V__period'
    _table_ra = 'RA'
    _ra_unit = 'hour'
    _table_dec = 'DEC'
    columns = {
        '__link': 'MAIN_ID',
        'separation': 'Separation, arcsec',
        'OTYPE': 'Main type',
        'OTYPES': 'Other types',
        'V__vartyp': 'Variable type',
        'V__period': 'Period',
        'Distance_distance': 'Distance',
        'Distance_unit': 'Distance unit',
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._query = Simbad()
        self._query.add_votable_fields('distance', 'fluxdata(R)',
                                       'fluxdata(V)', 'otype', 'otypes', 'v*')
        self._query_region = self._query.query_region

    def get_url(self, id):
        qid = urllib.parse.quote(id)
        return f'//simbad.u-strasbg.fr/simbad/sim-id?Ident={qid}'

    def add_distance_column(self, table):
        table['__distance'] = table['Distance_distance'] * [
            units.Unit(u) for u in table['Distance_unit']
        ]
Exemplo n.º 14
0
    def test_query_object_ids(self, temp_dir):
        simbad = Simbad()
        simbad.cache_location = temp_dir
        result = simbad.query_objectids("Polaris")

        # Today, there are 42 names.  There could be more in the future
        assert len(result) >= 42
Exemplo n.º 15
0
    def set_simbad_fields(self, simbad_id, out_dir, overwrite=False,
                          votable_fields=('ra(d)', 'dec(d)', 'pmdec', 'pmra', 'parallax', 'sptype', 'ids')):
        """Retrieve source information from Simbad.

        Parameters
        ----------
        simbad_id
        out_dir
        overwrite
        votable_fields

        Returns
        -------

        """

        out_file = os.path.join(out_dir, '{}_simbad_parameters.txt'.format(self.identifier))
        if (not (os.path.isfile(out_file))) | overwrite:
            if os.path.isdir(out_dir) is False:
                os.makedirs(out_dir)
            simb = Simbad()
            if votable_fields is not None:
                simb.add_votable_fields(*votable_fields)
            pt = simb.query_object(simbad_id)
            pt.write(out_file, format='ascii.basic', delimiter=',')
        else:
            pt = Table.read(out_file, format='ascii.basic', delimiter=',')

        for c in pt.colnames:
            try:
                setattr(self, c, pt[c][0])
            except:
                setattr(self, c, None)
Exemplo n.º 16
0
def astroquery_skycoord(center, simbad=None):
    """Translate center coordinates to SkyCoord object.

    Notes
    -----
    - The supported formats are:
        - `str` or `bytes`: can be an object  name or
          `~astropy.coordinates.SkyCoord` compatible RA/DEC string.
        - `list`, `tuple` or `~numpy.array`: pair (RA, DEC) coordinates.
          Must be `~astropy.coordinates.SkyCoord` compatible.
        - `~astropy.coordinates.SkyCoord` object it self.
    """
    if isinstance(center, (str, bytes)):
        try:
            return SkyCoord(center)
        except (ValueError):
            if simbad is None:
                simbad = Simbad()
            t = simbad.query_object(center)
            if t is None:
                raise ValueError(f'Coordinates {center} could not be'
                                 ' resolved.')
            return guess_coordinates(t['RA'][0], t['DEC'][0], skycoord=True)
    elif isinstance(center, (tuple, list, np.ndarray)) and len(center) == 2:
        return guess_coordinates(center[0], center[1], skycoord=True)
    elif isinstance(center, SkyCoord):
        return center

    raise ValueError(f'Center coordinates {center} not undertood.')
Exemplo n.º 17
0
def querySIMBAD(objnames, formatGaia=False):
    """
    Returns SIMBAD catalog info for one or more object names
    Arguments:
        objnames: str (single name), list of strs (multiple names) or dict (names from key values)
    """
    if isinstance(objnames,str):
        ids = [ objnames ]
    elif isinstance(objnames, list):
        ids = objnames
    elif isinstance(objnames, dict):
        ids = list(objnames.keys())
    else:
        raise TypeError(f'Invalid argument type; Valid types are str, list and dict')


    #set up simbad search
    sim = Simbad()
    sim.add_votable_fields('parallax', 'pm','velocity','typed_id')
    #make table of data queried from given cluster name
    sim_table = vstack([sim.query_object(id) for id in ids], join_type = 'exact')
    #turn into usable table
    cluster_data = Table(sim_table['TYPED_ID', 'PLX_VALUE', 'PLX_PREC','RA', 'RA_PREC', 'DEC', 'DEC_PREC', 
                                   'PMRA', 'PMDEC', 'RVZ_RADVEL', 'RVZ_ERROR'])
    if formatGaia:
        name_mapper = objnames if isinstance(objnames, dict) else None
        return formatSIMBADtoGAIA(cluster_data, name_mapper=name_mapper)
    return(cluster_data)
Exemplo n.º 18
0
 def test_query_bibobj(self, temp_dir):
     simbad = Simbad()
     simbad.ROW_LIMIT = 5
     simbad.cache_location = temp_dir
     result = simbad.query_bibobj('2005A&A.430.165F')
     assert isinstance(result, Table)
     assert len(result) == 5
Exemplo n.º 19
0
 def test_query_zero_sized_region(self, temp_dir):
     simbad = Simbad()
     simbad.cache_location = temp_dir
     result = simbad.query_region(SkyCoord("20h54m05.6889s 37d01m17.380s"), radius="1s",
                                  equinox=2000.0, epoch='J2000')
     # This should find a single star, BD+36 4308
     assert len(result) == 1
Exemplo n.º 20
0
def get_data(start=None, stop=None, names=None, all=False):
    data_dir_path = get_data_dir_path()
    saved_names = os.listdir(data_dir_path)
    data = {}
    Simbad.add_votable_fields('flux(V)', 'flux(K)')
    if names is None:
        names = pd.read_csv("TYCHOII_targs.txt",
                            sep='|',
                            names=['blank', 'name'],
                            usecols=['blank', 'name'],
                            skiprows=1)
        names = names.name
        if not all:
            names = names[start:stop]
    elif type(names) is str:
        # you can specify names as a string separated
        # by commas, spaces, or semicolons
        names = re.split('\s+|,\s*|;\s*')
    for name in names:
        name = name.strip()
        file_path = os.path.join(data_dir_path, name)
        datum = None
        if name in saved_names:
            datum = get_datum_from_file(file_path)
        if datum is None:
            datum = get_datum_from_simbad(name, file_path)
        if datum is not None:
            data[name] = datum
    return data
Exemplo n.º 21
0
def get_ra_dec_pmra_pmdec(name, epoch=2018.07):
    """
    Get RA, DEC, PMRA and PMDEC from SIMBAD using astroquery

    INPUT:
    - name of the star
    - epoch - the epoch of the observation, assumes J2018.07 (Jan 2018), and assumes equinox = 2000

    OUTPUT:
    - astropy table with the columns:
    -- MAIN_ID
    -- RA
    -- DEC
    -- PMRA (mas/yr)
    -- PMDEC (mas/yr)
    -- RA_2_A_ICRS_J2018_07_2000
    -- DEC_2_D_ICRS_J2018_07_2000
    """
    customSimbad = Simbad()
    ra_epoch_string = "ra(2;A;ICRS;J" + str(epoch) + ";2000)"
    dec_epoch_string = "dec(2;D;ICRS;J" + str(epoch) + ";2000)"
    fields = ("pmra", "pmdec", ra_epoch_string, dec_epoch_string)
    customSimbad.add_votable_fields(*fields)
    table = customSimbad.query_object(name)
    #table[["RA","DEC","RA_2_A_ICRS_J2018_07_2000","DEC_2_D_ICRS_2018_07_2000","PMRA","PMDEC"]]
    return table
Exemplo n.º 22
0
def query_for_spectral_type(identifier, only_first_two_characters=True,
                            default_sptype='G0'):
    """
    Search SIMBAD for the spectral type of a star.

    If no spectral type is found, the default return value is ``"G0"``.

    Parameters
    ----------
    identifier : str
        Name of target
    only_first_two_characters : bool
        Return only first two characters of spectral type?
    default_sptype : str
        Spectral type returned when none is found on SIMBAD

    Returns
    -------
    sptype : str
        Spectral type of the star.
    """
    customSimbad = Simbad()
    customSimbad.SIMBAD_URL = 'http://simbad.harvard.edu/simbad/sim-script'
    customSimbad.add_votable_fields('sptype')
    result = customSimbad.query_object(identifier)

    if len(result['SP_TYPE']) > 0:

        if only_first_two_characters:
            return result['SP_TYPE'][0][:2].strip().decode()
        else:
            return result['SP_TYPE'][0].decode()
    else:
        return default_sptype.decode()
Exemplo n.º 23
0
def construct_standard_star_table(stars, write_to=results_dir):

    mwo_dict = dict()
    apo_dict = dict()
    for star in stars:
        mwo_dict[star.name.upper()] = []
        apo_dict[star.name.upper()] = []

    names = list(mwo_dict.keys())

    for star_name in names:
        all_obs_this_star = [star for star in stars if star.name.upper() == star_name]
        mwo_dict[star_name] = combine_measurements([s.s_mwo for s in all_obs_this_star])
        apo_dict[star_name] = combine_measurements([s.s_apo for s in all_obs_this_star])

    sp_types = []
    s_mwo = []
    s_apo = []
    n_obs = []

    for star in names:
        s_mwo.append(mwo_dict[star].to_latex())
        s_apo.append(apo_dict[star].to_latex())

        n_obs.append(apo_dict[star].meta)

        customSimbad = Simbad()
        customSimbad.add_votable_fields('sptype')
        sp_type = customSimbad.query_object(star)['SP_TYPE'][0]
        sp_types.append(sp_type)

    print('N_stars = {0}'.format(len(names)))
    print('N_spectra = {0}'.format(sum(n_obs)))
    print('N_sptype=G = {0}'.format(len([spt for spt in sp_types if spt.startswith(b'G')])))
    print('N_sptype=K = {0}'.format(len([spt for spt in sp_types if spt.startswith(b'K')])))
    print('N_sptype=M = {0}'.format(len([spt for spt in sp_types if spt.startswith(b'M')])))
    # for star in stars:
    #     names.append(star.name.upper())
    #     customSimbad = Simbad()
    #     customSimbad.add_votable_fields('sptype')
    #     sp_type = customSimbad.query_object(star.name)['SP_TYPE'][0]
    #     sp_types.append(sp_type)
    #
    #     s_mwo.append(star.s_mwo.to_latex())
    #     s_apo.append(star.s_apo.to_latex())

    standard_table = Table([names, sp_types, s_mwo, s_apo, n_obs],
                           names=['Star', 'Sp.~Type', '$S_{MWO}$', '$S_{APO}$', '$N$'])

    standard_table.sort(keys='$S_{MWO}$')

    latexdict = dict(col_align='l l c c c', preamble=r'\begin{center}',
                     tablefoot=r'\end{center}',
                     caption=r'Stars observed to calibrate the $S$-index '
                             r'(see Section~\ref{sec:def_s_index}). \label{tab:cals}',
                     data_start=r'\hline')

    # output_path,
    ascii.write(standard_table, format='latex', latexdict=latexdict,
                output='cal_stars.tex')
Exemplo n.º 24
0
def qu(obj):

    obj_str = obj

    #result_table = Simbad.query_object(obj_str)
    #print(result_table)

    #Simbad.list_votable_fields()

    customSimbad = Simbad()
    customSimbad.add_votable_fields('main_id', 'coordinates', 'propermotions',
                                    'flux(V)')
    #customSimbad.get_votable_fields()

    obj = customSimbad.query_object(obj_str)
    #print(obj.keys())

    ra, dec, pm_ra, pm_dec = obj['RA'][0].split(), obj['DEC'][0].split(
    ), obj['PMRA'], obj['PMDEC']
    flux_v = obj['FLUX_V']

    ra_str = str(ra[0]) + ':' + str(ra[1]) + ':' + str(ra[2])
    dec_str = str(dec[0]) + ':' + str(dec[1]) + ':' + str(dec[2])

    print str(ra_str) + ", " + str(dec_str) + ", " + str(
        pm_ra[0]) + ", " + str(pm_dec[0]) + ", " + str(flux_v[0])
Exemplo n.º 25
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Exemplo n.º 26
0
    def load(self):
        """Load the coordinates of the target.

        Examples
        --------
        >>> s = Star('3C273')
        >>> print(s.radec_position.dec)
        2d03m08.598s

        """
        Simbad.add_votable_fields('flux(U)', 'flux(B)', 'flux(V)', 'flux(R)',
                                  'flux(I)', 'flux(J)', 'sptype', 'parallax',
                                  'pm', 'z_value')
        simbad = Simbad.query_object(self.label)
        self.simbad = simbad
        if simbad is not None:
            if self.verbose or True:
                self.my_logger.info(f'\n\tSimbad:\n{simbad}')
            self.radec_position = SkyCoord(simbad['RA'][0] + ' ' +
                                           simbad['DEC'][0],
                                           unit=(u.hourangle, u.deg))
        else:
            self.my_logger.warning('Target {} not found in Simbad'.format(
                self.label))
        self.get_radec_position_after_pm(date_obs="J2000")
        self.redshift = float(simbad['Z_VALUE'])
        self.load_spectra()
Exemplo n.º 27
0
 def test_query_region(self, temp_dir):
     simbad = Simbad()
     # TODO: rewise once ROW_LIMIT is working
     simbad.TIMEOUT = 100
     simbad.cache_location = temp_dir
     result = simbad.query_region(ICRS_COORDS_M42, radius=2 * u.deg,
                                  equinox=2000.0, epoch='J2000')
     assert isinstance(result, Table)
Exemplo n.º 28
0
 def test_query_small_region_null(self, temp_dir):
     simbad = Simbad()
     simbad.cache_location = temp_dir
     result = simbad.query_region(SkyCoord("00h01m0.0s 00h00m0.0s"),
                                  radius=1.0 * u.marcsec,
                                  equinox=2000.0,
                                  epoch='J2000')
     assert result is None
Exemplo n.º 29
0
 def test_query_regions(self, temp_dir):
     simbad = Simbad()
     simbad.cache_location = temp_dir
     result = simbad.query_region(multicoords,
                                  radius=1 * u.arcmin,
                                  equinox=2000.0,
                                  epoch='J2000')
     assert isinstance(result, Table)
Exemplo n.º 30
0
def getSimbadCoordinates(name):
    from astroquery.simbad import Simbad
    s = Simbad()
    r = s.query_object(name)
    # print(r.info())
    ra = r['RA'][0]
    dec = r['DEC'][0]
    return str(ra), str(dec)
Exemplo n.º 31
0
def get_parallax():
    species_db = database.Database()
    species_db.add_photometry('vlm-plx')

    with h5py.File(species_db.database, 'a') as hdf_file:
        name = np.asarray(hdf_file['photometry/vlm-plx/name'])
        ra_coord = np.asarray(hdf_file['photometry/vlm-plx/ra'])
        dec_coord = np.asarray(hdf_file['photometry/vlm-plx/dec'])
        distance = np.asarray(hdf_file['photometry/vlm-plx/distance'])
        distance_error = np.asarray(
            hdf_file['photometry/vlm-plx/distance_error'])

        simbad_id = []

        print('Querying SIMBAD...', end='', flush=True)

        for i, item in enumerate(name):
            target_coord = SkyCoord(ra_coord[i],
                                    dec_coord[i],
                                    unit=(u.deg, u.deg),
                                    frame='icrs')

            result_table = Simbad.query_region(target_coord, radius='0d0m2s')

            if result_table is None:
                result_table = Simbad.query_region(target_coord,
                                                   radius='0d0m5s')

            if result_table is None:
                result_table = Simbad.query_region(target_coord,
                                                   radius='0d0m20s')

            if result_table is None:
                result_table = Simbad.query_region(target_coord,
                                                   radius='0d1m0s')

            if item == 'HIP38939B':
                simbad_id.append(get_simbad('HIP38939').decode('utf-8'))
            else:
                simbad_id.append(result_table['MAIN_ID'][0].decode('utf-8'))

        print(' [DONE]')

        simbad_id = np.asarray(simbad_id)

        dtype = h5py.special_dtype(vlen=str)

        dset = hdf_file.create_dataset('photometry/vlm-plx/simbad',
                                       (np.size(simbad_id), ),
                                       dtype=dtype)

        dset[...] = simbad_id

        np.savetxt(
            'parallax.dat',
            np.column_stack([name, simbad_id, distance, distance_error]),
            header='VLM-PLX name - SIMBAD name - Distance (pc) - Error (pc)',
            fmt='%35s, %35s, %8.2f, %8.2f')
Exemplo n.º 32
0
    def test_query_region_async(self, temp_dir):
        simbad = Simbad()
        # TODO: rewise once ROW_LIMIT is working
        simbad.TIMEOUT = 100
        simbad.cache_location = temp_dir
        response = simbad.query_region_async(
            ICRS_COORDS_M42, radius=2 * u.deg, equinox=2000.0, epoch='J2000')

        assert response is not None
Exemplo n.º 33
0
def get_named_source_coord(name):
    r = Simbad.query_object(name)  # and also IREFCAT name?
    print("found this", r)

    cat = Simbad.query_catalog("INTREF")

    print("cat", cat)

    return SkyCoord(r[0]['RA'], r[0]['DEC'], unit=("hourangle", "deg"))
Exemplo n.º 34
0
def label_guide_stars(filename, catalog, guide_stars):
    stars = np.array(guide_stars)
    # Get unique guide_stars
    unique = np.unique(stars[:, :-1])
    hip_names = []
    checked = 0
    labeled = 0
    # Need a tuple of [HIP_number, ra, dec] for all guide stars
    for hip_star in catalog:
        # Stop earlier if all guide stars are already labeled.
        if checked == len(unique):
            break
        if hip_star.starnumber in unique:
            # Query Simbad for its object, then name
            c = SkyCoord(ra=hip_star.ra, dec=hip_star.dec, unit=u.deg)
            print(c)
            while True:
                try:
                    reg = Simbad.query_region(c, radius=0.01 * u.deg)
                except:
                    time.sleep(5)
                    continue
                break
            name = ""
            if len(reg[0]) > 0:
                while True:
                    try:
                        objs = Simbad.query_objectids(reg[0][0])
                    except:
                        time.sleep(5)
                        continue
                    break
                if len(objs) > 0:
                    noname = True
                    for name in objs:
                        if "NAME" in name[0]:
                            name = name[0].replace("NAME", "").strip().lower()
                            noname = False
                            labeled += 1
                            print(name)
                            break
                    if noname:
                        name = str(hip_star.starnumber)

            time.sleep(0.2)
            hip_names.append([hip_star.starnumber, name])
            checked += 1
            print(f'{checked=} {labeled=}')

    with open(filename, mode='w') as csv_file:
        fieldnames = ['HIP_number', 'Name']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        for star in hip_names:
            writer.writerow({'HIP_number': star[0], 'Name': star[1]})
Exemplo n.º 35
0
def read_simbad_data(star_name):
    '''
    Query SIMBAD for a given star parallax, vsini, bump and references.

    :param star_name: star's name (string)
    :return: txt file with star's parallax, vsini, bump, the respective
    errors and references for vsini and E(B-V)
    '''

    customSimbad = Simbad()
    # customSimbad.list_votable_fields() #  to list all avaiable fields
    customSimbad.get_votable_fields()
    customSimbad.add_votable_fields('plx', 'plx_error', 'rot', 'sptype')
    customSimbad.get_votable_fields()
    result_table = customSimbad.query_object(star_name)
    # star = result_table['MAIN_ID']
    star = np.copy(star_name)
    plx = result_table['PLX_VALUE'][0]
    plx_error = result_table['PLX_ERROR'][0]
    vsini = result_table['ROT_Vsini'][0]
    vsini_err = result_table['ROT_err'].item()
    rot_bibcode = result_table['ROT_bibcode']
    sptype = result_table['SP_TYPE']
    sptype_ref = sptype.item()
    bump = True
    ebmv_ref = 0.0

    return star.item(), plx, plx_error, vsini, vsini_err, bump,\
        rot_bibcode.item(), ebmv_ref, sptype_ref
Exemplo n.º 36
0
    def update_window(self, *event):

        if not event:
            pass

        if self.update_object_list.get():

            try:
                result_table = Simbad.query_object(self.object_search.get(),
                                                   wildcard=True)

                if result_table:
                    self.object_entry['values'] = tuple(
                        [str(ff['MAIN_ID'])[2:-1] for ff in result_table])
                else:
                    self.object_entry['values'] = tuple([])

                if len(self.object_entry['values']) == 1:
                    self.skyobject.set(self.object_entry['values'][0])
                    self.update_object.set(True)
                else:
                    self.skyobject.set('Choose Object')

            except requests.exceptions.ConnectionError:
                self.skyobject.set('No connection')

            self.update_object_list.set(False)

        if self.update_object.get():

            try:
                result_table = Simbad.query_object(self.skyobject.get())[0]
                self.target_ra.set(str(result_table['RA']))
                self.target_dec.set(str(result_table['DEC']))

            except:
                self.target_ra.set('Import manually')
                self.target_dec.set('Import manually')
                self.skyobject.set('Not found or no connection')

            self.update_object.set(False)

        self.object_entry.selection_clear()

        check_ra_dec = test_coordinates2(self.target_ra_entry.get(),
                                         self.target_dec_entry.get())
        self.target_ra_dec_test.configure(text=check_ra_dec[1])
        check_year_month = test_date(self.obs_year_month_entry.get())
        self.obs_year_month_test.configure(text=check_year_month[1])

        if check_ra_dec[0] and check_year_month[0]:
            self.plot_button['state'] = NORMAL
        else:
            self.plot_button['state'] = DISABLED
Exemplo n.º 37
0
 def parallax(self, parallax):
     if isinstance(parallax, str):
         if parallax.lower() == 'auto':
             Simbad.add_votable_fields('parallax')
             plxplxerr = Simbad.query_object(self.sname)['PLX_VALUE',
                                                         'PLX_ERROR']
             self._parallax = plxplxerr['PLX_VALUE'].to('mas')[0]
             self.parallaxerr = plxplxerr['PLX_ERROR'].to('mas')[0]
             Simbad.reset_votable_fields()
     else:
         self._parallax = parallax.to('mas')
Exemplo n.º 38
0
    def test_query_target_error(self):
        jwst = JwstClass(show_messages=False)
        simbad = Simbad()
        ned = Ned()
        vizier = Vizier()
        # Testing default parameters
        with pytest.raises(ValueError) as err:
            jwst.query_target(target_name="M1", target_resolver="")
        assert "This target resolver is not allowed" in err.value.args[0]
        with pytest.raises(ValueError) as err:
            jwst.query_target("TEST")
        assert "This target name cannot be determined with this resolver: ALL" in err.value.args[
            0]
        with pytest.raises(ValueError) as err:
            jwst.query_target(target_name="M1", target_resolver="ALL")
        assert err.value.args[0] in [
            f"This target name cannot be determined "
            f"with this resolver: ALL", "Missing "
            f"required argument: 'width'"
        ]

        # Testing no valid coordinates from resolvers
        simbad_file = data_path(
            'test_query_by_target_name_simbad_ned_error.vot')
        simbad_table = Table.read(simbad_file)
        simbad.query_object = MagicMock(return_value=simbad_table)
        ned_file = data_path('test_query_by_target_name_simbad_ned_error.vot')
        ned_table = Table.read(ned_file)
        ned.query_object = MagicMock(return_value=ned_table)
        vizier_file = data_path('test_query_by_target_name_vizier_error.vot')
        vizier_table = Table.read(vizier_file)
        vizier.query_object = MagicMock(return_value=vizier_table)

        # coordinate_error = 'coordinate must be either a string or astropy.coordinates'
        with pytest.raises(ValueError) as err:
            jwst.query_target(target_name="test",
                              target_resolver="SIMBAD",
                              radius=units.Quantity(5, units.deg))
        assert 'This target name cannot be determined with this resolver: SIMBAD' in err.value.args[
            0]

        with pytest.raises(ValueError) as err:
            jwst.query_target(target_name="test",
                              target_resolver="NED",
                              radius=units.Quantity(5, units.deg))
        assert 'This target name cannot be determined with this resolver: NED' in err.value.args[
            0]

        with pytest.raises(ValueError) as err:
            jwst.query_target(target_name="test",
                              target_resolver="VIZIER",
                              radius=units.Quantity(5, units.deg))
        assert 'This target name cannot be determined with this resolver: VIZIER' in err.value.args[
            0]
Exemplo n.º 39
0
    def __init__(self, targ_name):

        simbad_info = Simbad()
        self.filters = ['B', 'V', 'J', 'H', 'K']
        f = ['flux({0})'.format(x) for x in self.filters]
        fe = ['flux_error({0})'.format(y) for y in self.filters]
        fields = f + fe
        [simbad_info.add_votable_fields(f) for f in fields]
        self.results = simbad_info.query_object(targ_name)
        for col in self.results.colnames:
            if self.results[col][0] is np.ma.masked:
                self.results[col][0] = np.nan
Exemplo n.º 40
0
def run_starlight(object_id,object_name,ob_id):
	SLdir=os.getenv("HOME")+"/STARLIGHT"
	scifile=SLdir+"/spectra/"+object_id+"_"+str(ob_id)+".fits"
	outfile=SLdir+"/spectra/"+object_id+"_"+str(ob_id)+".txt"
	##
	## get redshift of object
	Simbad.add_votable_fields("rv_value")
	q=Simbad.query_object(object_name)
	rv=q['RV_VALUE'].quantity.data[0]*1000 ## rv in m/s
	z=rv/constants.c
	print("Redshift of {object_id} is {z:7.5f}".format(object_id=object_id, z=z))
	##
	## get spectrum from FITS file, interpolate bad pixels, convolve to BC03 resolution for STARLIGHT
	write_spec_starlight(scifile,outfile,z,[6000,9500])
def get_stellar_params(star_name):
    """ Astro query search """

    #return Magnitudes, parralax, Temp
    customSimbad = Simbad()
    # Can add more fluxes here if need to extend to more flux ranges. although K is the limit for simbad.
    # if want higher need to search for Wise band in VISIER probably.
    customSimbad.add_votable_fields('parallax', 'sp', 'fluxdata(B)', 'fluxdata(V)', 'fluxdata(J)', 'fluxdata(K)', 'fe_h')
   
    result_table =  customSimbad.query_object(star_name)

    #print("Table colums", result_table.colnames)
    
    return result_table
Exemplo n.º 42
0
  def get_source_coordinates(self,catalog):
    verbose("-> Identifying the source")
    verbose("-> Solve source name %s with the Fermi-LAT catalog" %(self.name))
    try:
      source = catalog.find_source(self.name)
      self.RA  = source["raj2000"]
      self.DEC = source["decj2000"]
      return(1)
    except:
      verbose("-> Failed to locate source in the Fermi catalog")

    try:
      verbose("-> Solve source name %s with SIMBAD")
      from astroquery.simbad import Simbad
      object = Simbad.query_object(self.name)
      RA  = np.array(str(object["RA"].data.data[0]).split(" "),dtype=float)
      DEC = np.array(str(object["DEC"].data.data[0]).split(" "),dtype=float)
      self.RA  = 15.*(RA[0]+RA[1]/60.+RA[2]/3600.)
      self.DEC = (DEC[0]+DEC[1]/60.+DEC[2]/3600.)
      return(1)
    except:
      verbose("--> Failed to solve source name with simbad")

    verbose("Trying name, RA, DEC")
    try:
      self.name, self.RA, self.DEC = np.array(self.name.split(","))
      self.RA  = float(self.RA)
      self.DEC = float(self.DEC)
    except:
      verbose("--> Something went wrong while processing %s" %self.name)

    printc("-> Couldn't identify the source, check %s" %self.name)
    sys.exit(1)
Exemplo n.º 43
0
 def simbad_query(self):
     search_name = self.ui.name.currentText()
     try:
         result = Simbad.query_object(search_name)
         if not result:
             QMessageBox.warning(self, 'Not Found', 'Identifier {} not recognized by Simbad'.format(search_name))
             return
     except Exception as e:
         QMessageBox.critical(self, 'Query Error', 'Error running Simbad query: {}'.format(e))
         return
     row = result[0] # todo: handle more than one results
     main_id = row['MAIN_ID'].decode()
     names = [(name[0].decode(), re.sub('\s{2,}', ' ', re.sub('^\*+', '', name[0].decode())).replace('NAME ', '').strip()) for name in Simbad.query_objectids(main_id)]
     names = [(n[0],n[1].title()) if n[0][0:4]=='NAME' else n for n in names]
     self.ui.name.clear()
     plain_names = [n[1] for n in names]
     self.ui.names.setText(', '.join(plain_names))
     self.ui.name.addItems(plain_names)
     self.ui.name.setCurrentText([name[1] for name in names if main_id == name[0]][0])
     searched_name = [n for n in plain_names if n.lower() == search_name.lower()]
     if len(searched_name):
         self.ui.name.setCurrentText(searched_name[0])
     self.ui.ra.setText(row['RA'])
     self.ui.dec.setText(row['DEC'])
     self.ui.sptype.setText(row['SP_TYPE'].decode())
     self.ui.type.setText(row['OTYPE_V'].decode())
def classify_file(filename, astroquery=True):
    """
    This function uses the fits header information and the Simbad database to classify the object
    :param filename: The filename of the observation to be classified
    :return:
    """
    # Read in the header and get the object name
    header = fits.getheader(filename)
    object = header['object']
    print object

    # Default values if I can't get it any other way
    plx = 30.0

    MS = SpectralTypeRelations.MainSequence()

    # Make a Simbad object
    if astroquery:
        sim = Simbad()
        sim.add_votable_fields('plx', 'sp', 'flux(V)')
        data = sim.query_object(object)
        spt_full = data['SP_TYPE'].item()
        # spt = spt_full[0] + re.search(r'\d*\.?\d*', spt_full[1:]).group()
        spt = spt_full
        if data['PLX_VALUE'].mask:
            if not data['FLUX_V'].mask:
                # Fall back to photometric parallax
                Vmag_obs = data['FLUX_V'].item()
                Vmag_abs = MS.GetAbsoluteMagnitude(spt, color='V')
                plx = 10 ** (3.0 + (Vmag_abs - Vmag_obs - 5.0) / 5.0)
        else:
            plx = data['PLX_VALUE'].item()
    else:
        link = pySIMBAD.buildLink(object)
        data = pySIMBAD.simbad(link)
        plx = data.Parallax()
        spt_full = data.SpectralType().split()[0]
        spt = spt_full[0] + re.search(r'\d*\.?\d*', spt_full[1:]).group()

    if 'exptime' not in header.keys():
        header['exptime'] = 30.0
    d = {'Object': object,
         'plx': plx,
         'SpT': spt,
         'exptime': header['exptime']}
    return d
Exemplo n.º 45
0
def coord2objs(ra, dec, radius=2, extras = False):
    """Get objects within given radius of given ra/dec as decimal degrees.
    If object type given, restrict to that"""
    
    sk = coordinates.SkyCoord(ra=ra, dec=dec, unit=u.deg)
    rad = radius * u.arcmin
    sb = Simbad()
    sb.add_votable_fields('id', 'otype')
    sres = sb.query_region(sk, radius=rad)
    if sres is None: return []
    ids = [id for id in sres['MAIN_ID']]
    if not extras: return ids
    otypes = [ot for ot in sres['OTYPE']]
    idas = [string.split(oid, ', ') for oid in sres['ID']]
    resids = []
    for n in zip(ids, idas, otypes):
        resids.append(n)
    return resids
Exemplo n.º 46
0
Arquivo: u_sofa.py Projeto: RTS2/rts2
 def __init__(self, lg=None,obs=None,refraction_method=None):
   #
   self.lg=lg
   self.name='SF SOFA'
   self.refraction_method=refraction_method
   self.obs_astropy=obs
   longitude,latitude,height=self.obs_astropy.to_geodetic()
   self.elong=longitude
   self.phi=latitude
   self.hm=float(str(height).replace('m','').replace('meter',''))
   self.smbd=Simbad()
   self.smbd.add_votable_fields('propermotions','rv_value','parallax','flux(V)')
Exemplo n.º 47
0
 def get_data(self):
     result_table = Simbad()
     # Extended timeout to search for 1000 rows
     result_table.TIMEOUT = 120
     result_table.ROW_LIMIT = 1000
     result_table.add_votable_fields(
         "flux(V)",
         "mt",
         "otype",
         "ra",
         "dec",
         "dim",
         "flux(U)",
         "flux(B)",
         "flux(R)",
         "flux(I)",
         "flux(J)",
         "flux(H)",
         "flux(K)",
         "flux(u)",
         "flux(g)",
         "flux(r)",
         "flux(i)",
         "flux(z)",
         *self.args
     )
     result_table = result_table.query_object(self.name, **self.kwargs)
     return result_table
Exemplo n.º 48
0
def app_simbad():
    app.vars['name'] = request.form['name']

    # Get the relevant information from Simbad
    customSimbad = Simbad()
    customSimbad.remove_votable_fields('coordinates')
    customSimbad.add_votable_fields('ra(d)', 'dec(d)', 'pmra', 'pmdec', 'rv_value', 'plx')
    simbad_query = customSimbad.query_object(app.vars['name'])

    try:
        df = simbad_query.to_pandas()
    except AttributeError: # no result
        return render_template('error.html', headermessage='Error',
                                   errmess='<p>Error querying Simbad for: ' + app.vars['name'] + '</p>')

    # Clear and set values
    clear_values()
    app.vars['ra'] = df['RA_d'][0]
    app.vars['dec'] = df['DEC_d'][0]
    app.vars['pmra'] = df['PMRA'][0]
    app.vars['pmdec'] = df['PMDEC'][0]
    app.vars['rv'] = df['RV_VALUE'][0]
    app.vars['dist'] = 1000./df['PLX_VALUE'][0]

    return redirect('/query')
Exemplo n.º 49
0
def do_simbad_novae(catalog):
	task_str = catalog.get_current_task_str()	
	simbad_mirrors = ['http://simbad.harvard.edu/simbad/sim-script',
					'http://simbad.u-strasbg.fr/simbad/sim-script']

	customSimbad = Simbad()
	customSimbad.ROW_LIMIT = -1
	customSimbad.TIMEOUT = 120

	for mirror in simbad_mirrors:
		customSimbad.SIMBAD_URL = mirror
		try:
			table = customSimbad.query_criteria('maintype=No* | maintype="No?"')
		except:
			continue
		else:
			break

	if not table:
		catalog.log.warning('SIMBAD unable to load, probably offline.')

	
	
	for name in pbar(catalog.entries, task_str):
		try:
			nova_name = "V* " + get_nova_name(name)
			aliases = customSimbad.query_objectids(nova_name)
		except:
			#THROW WARNING HERE
			tprint("Could not find " + nova_name)
			continue
		
		table = customSimbad.query_object(nova_name)
		
		name = catalog.add_entry(name)
		
		bibcode = table[0]['COO_BIBCODE'].decode()
		ra = str(table[0]['RA'])
		dec = str(table[0]['DEC'])
		
		source = catalog.entries[name].add_source(name='SIMBAD astronomical database',
													bibcode=bibcode,
													url="http://simbad.u-strasbg.fr/",
                              						secondary=True)
		catalog.entries[name].add_quantity(NOVA.RA, ra, source)
		catalog.entries[name].add_quantity(NOVA.DEC, dec, source)

		for i in range(len(aliases)):
			try: alias = aliases[i][0].decode()
			except:	alias = str(aliases[i][0])
						
			catalog.entries[name].add_quantity(NOVA.ALIAS, alias, source)
		
		catalog.journal_entries()
Exemplo n.º 50
0
    def search_objects(self, params):

        Simbad.reset_votable_fields()
        fields = self.config.find_by_path("configuration.providers.Simbad.search_fields")

        for field in fields:
            Simbad.add_votable_fields(field)

        cel_objects = []
        wildcard = not params.exact

        try:
            if params.exact:
                result = Simbad.query_object(params.term, wildcard=wildcard)
            else:
                Simbad.ROW_LIMIT = 20
                if params.coordinates:
                    if params.epoch and params.equinox:
                        result = Simbad.query_region(params.coordinates,
                                                     radius=params.radius,
                                                     epoch=params.epoch,
                                                     equinox=params.equinox)
                    else:
                        result = Simbad.query_region(params.coordinates, radius=params.radius)
                else:
                    result = Simbad.query_region(params.term, radius=params.radius)

            if result:
                for entry in result:
                    identifiers = Simbad.query_objectids(entry["MAIN_ID"])
                    celestial_obj = CelestialObject(entry, identifiers)
                    cel_objects.append(celestial_obj)
            else:
                self.logger.info("Nothing found for '{0}'".format(params))

            obj_collection = CelestialObjectCollection(cel_objects)

            json_result = dumper(obj_collection, cls=CelestialObjectEncoder)
            self.logger.info("Result from Simbad for '{0}' \n {1}".format(params, json_result))
            return json_result
        except:
            self.logger.error("Error in SimbadProvider", exc_info=True)
            raise ProviderException("error", "something")
Exemplo n.º 51
0
def objcurrcoord(obj, twhen = None):
    """Get current coordinates of object of at time if given"""
    sb = Simbad()
    sb.add_votable_fields('pmra', 'pmdec', 'velocity', 'distance')
    qo = sb.query_object(obj)
    if qo is None: return None
    ra = coordinates.Angle(qo['RA'][0], unit=u.hour)
    dec = coordinates.Angle(qo['DEC'][0], unit=u.deg)
    distc = qo['distance_distance'][0]
    if type(distc) is np.float64:
        dist = u.Quantity(distc, unit=qo['distance_unit'][0])
    else:
        dist = u.Quantity(10.0, unit=u.pc)
    pmra = qo['PMRA'][0] * u.mas / u.yr
    pmdec = qo['PMDEC'][0] * u.mas / u.yr
    rvelc = qo['RVZ_RADVEL']
    radvel = u.Quantity(rvelc[0], unit=rvelc.unit)
    sk = coordinates.SkyCoord(ra=ra, dec=dec, pm_ra_cosdec=pmra, pm_dec=pmdec, obstime=Time('J2000.0'), distance=dist, radial_velocity=radvel)
    if twhen is None:
        t = Time(datetime.datetime.now())
    else:
        t = Time(twhen)
    sk2 = sk.apply_space_motion(new_obstime = t)
    return (sk2.ra.deg, sk2.dec.deg)
Exemplo n.º 52
0
def get_name(entry):
    """Get proper name for star given it's name."""
    # if 'hd' not in entry[:3].lower() and ' ' not in entry and len(entry) > 5:
    #     entry = entry[:3] + ' ' + entry[3:]

    try:
        result = Simbad.query_object(entry, verbose=False)
        if result is not None:
            obj_name = filter(lambda x: x != '*', result[0][0].split())
            prop_name = (' ').join(map(lambda x: x.capitalize(), obj_name))
            # if a hd name capitalize hd
            if prop_name[:2].lower() == 'hd':
                prop_name = 'HD' + prop_name[2:]
        else:
            print "Not Found"
            prop_name = None
        return prop_name
    except:
        print "ERROR"
        return None
Exemplo n.º 53
0
def name_query(target_name):
    # target_name is a variable containing a source name, such as M31, Alpha Centauri, Sag A*, etc
    if astroquery_import:
        data = Simbad.query_object(target_name)
        ra = data['RA'].item()
        dec = data['DEC'].item()
        return coords(ra, dec)

    else:
        # Just use urllib if astroquery is not available
        # This is the string with the URL to query the Sesame service,
        # using a 'name' parameter.
        # sesameQueryUrl = 'http://cdsws.u-strasbg.fr/axis/services/Sesame?'  +\
        #                  'method=sesame&resultType=p&all=true&service=NSVA' +\
        #                  '&name=%(name)s'
        # use the updated CDS REST endpoint
        sesameQueryUrl = 'http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/-op/NSV?%(name)s'
        # Build the query from the sesameQueryUrl and the dictionary
        # We have to use urllib.quote to make it safe to include in a URL
        sesameQuery = sesameQueryUrl % {
            'name': urllib.quote(target_name)
        }
        # Read the lines of the response from the final URL
        sesameResponse = urllib.urlopen(sesameQuery).readlines()
        # Parse the sesameResponse to get RA, Dec
        # oneliner: ra, dec = filter(lambda x: x.find('%J') == 0, sesameResponse)[0].split(' ')[1:3]
        # The coordinates are in the lines starting with %J
        coordinateList = filter(lambda x: x.find('%J') == 0, sesameResponse)
        # As filter returns a list, get the first line
        print target_name
        print coordinateList
        coordinates = coordinateList[0]
        # Split the coordinates between the spaces, and drop de first item (%J) (so, start from the second on)
        coordinates = coordinates.split(' ')[1:]
        ra = float(coordinates[0])
        dec = float(coordinates[1])
        print ra, dec
        print target_name
        return coords(ra, dec)  #Return a coordinate object
Exemplo n.º 54
0
def querySIMBAD(name):
    """
    querySIMBAD(): Return information on a galaxy from a simbad query

    Note: This is now simply a wrapper around astroquery.ned.

    Arguments
    name: galaxy name

    Returns:
    dictionary with:
        - ICRS coordinates (J2000)
        - redshift
        - angular size
    """

    from astroquery.simbad import Simbad

    out = {'RA': _np.nan*_u.deg,
           'Dec': _np.nan*_u.deg,
           'z': _np.nan,
           'angsize': {'major': _np.nan*_u.arcmin,
                       'minor': _np.nan*_u.arcmin,
                       'PA': _np.nan*_u.deg}}

    try:
        res = Simbad.query_object(name)[0]
    except UserWarning:
        _sys.stderr.write(name + " not found in SIMBAD.\n")
        return out

    try:
        out['RA'] = res['RA)'] * u.deg
        out['Dec'] = res['DEC'] * u.deg
    except:
        _sys.stderr.write('Error: coordinates not available for ' + name + "\n")

    return out
Exemplo n.º 55
0
def find_spectra(starname, cps_list, specdir=""):
    """Checks the CPS database for the star with the provided identifier.
    If not found, queries SIMBAD database for alternative idenitifiers to
    check.

    Args:
        starname (str): an identifier for the star
        cps_list (pd.DataFrame): Pandas dataframe with list of stars with
            spectra

    Returns:
        pd.DataFrame: Subset of cps_list corresponding to the observations for
        the given star.
    """
    specdir = "/Users/samuel/Dropbox/SpecMatch-Emp/spectra/iodfitsdb/"
    result = check_cps_database(starname, cps_list)

    if result.empty:
        # ignore warnings from Simbad query - we check if there are any results
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            s_query_result = Simbad.query_objectids(starname)
            if s_query_result is not None:
                for r in s_query_result:
                    result = check_cps_database(r['ID'].decode('ascii'),
                                                cps_list)
                    if not result.empty:
                        break

    # Check SNR for each spectrum and rank results
    if not result.empty:
        if len(specdir) == 0:
            specdir = os.path.join(SPECMATCHDIR, 'spectra')

        result.loc[:, 'snr'] = result.obs.apply(calc_snr, args=(specdir, ))
        result.sort_values(by='snr', ascending=False, inplace=True)

    return result
Exemplo n.º 56
0
Arquivo: VLSR.py Projeto: teuben/admit
 def vlsr2(self, name):
     """ experimental Simbad/NED
     """
     if have_SB:
         print "Trying SIMBAD..."
         try:
             t1 = Simbad.query_object(name)
             print t1.colnames
             print t1
         except:
             pass
     else:
         print "No SIMBAD"
     if have_NED:
         print "Trying NED..."
         try:
             t2 = Ned.query_object(name)
             print t2.colnames
             print t2
             print 'VLSR=',t2['Velocity'].item()
         except:
             pass
     else:
         print "No NED"
Exemplo n.º 57
0
def query_name(name, verbose=False, print_header=False):
    """
    Query SIMBAD by name.
    """
    try:
        q = Simbad.query_object(name)
        main_id  = str(q['MAIN_ID'][0], encoding='utf-8')
        otype    = str(q['OTYPE'][0], encoding='utf-8')
        rv       = q['RV_VALUE'][0]
        z        = q['Z_VALUE'][0]
        rvz_qual = q['RVZ_QUAL'][0]
        rvz_type = q['RVZ_TYPE'][0]
    except RemoteServiceError:
        main_id  = None
        otype    = None
        rv       = None
        z        = None
        rvz_qual = None
        rvz_type = None
        if verbose:
            print('*** %s: not found ***' % name, file=sys.stderr)
    #
    results = OrderedDict([
        ("Name",         name),
        ("SIMBAD_ID",    main_id),
        ("Type",         otype),
        ("RV",           rv),
        ("z",            z),
        ("RV/z_Quality", rvz_qual),
        ("RV/z_Type",    rvz_type),
    ])
    if verbose:
        if print_header:
            print(",".join(results.keys()))
        print(",".join([str(v) for v in results.values()]))
    return results
Exemplo n.º 58
0
from astropy.utils.exceptions import AstropyWarning
warnings.simplefilter('ignore', category=AstropyWarning)

def create_cutout(hdulist, ra, dec, fov):

    for i, ext in enumerate(hdulist):
        data = ext.data
        if (type(data) != numpy.ndarray):
            continue
        if (data.ndim != 2):
            continue

        wcs = astWCS.WCS(ext.header, mode='pyfits')
        xy = wcs.sky2pix(ra, dec)

        print xy



if __name__ == "__main__":

    print sys.argv[1]
    objname = sys.argv[1]

    results = Simbad.query_object(objname)

    coords = astropy.coordinates.SkyCoord(results[0][1], results[0][2], frame='icrs',
                                          unit=(astropy.units.hourangle, astropy.units.deg))
    print(coords)
    print float(coords.ra)
Exemplo n.º 59
0
from astropy import coordinates
from astroquery.simbad import Simbad

customSimbad = Simbad()

# We've seen errors where ra_prec was NAN, but it's an int: that's a problem
# this is a workaround we adapted
customSimbad.add_votable_fields('ra(d)', 'dec(d)')
customSimbad.remove_votable_fields('coordinates')

C = coordinates.SkyCoord(0, 0, unit=('deg', 'deg'), frame='icrs')

result = customSimbad.query_region(C, radius='2 degrees')

result[:5].pprint()
"""
    MAIN_ID        RA_d       DEC_d
 ------------- ----------- ------------
 ALFALFA 5-186  0.00000000   0.00000000
 ALFALFA 5-188  0.00000000   0.00000000
 ALFALFA 5-206  0.00000000   0.00000000
 ALFALFA 5-241  0.00000000   0.00000000
 ALFALFA 5-293  0.00000000   0.00000000
"""
Exemplo n.º 60
0
Arquivo: star.py Projeto: zkbt/zachopy
	def fromSimbad(self, name, **attributes):
		'''search for a star name in Simbad, and pull down its data'''

		# add a few extra pieces of information to the search
		Simbad.reset_votable_fields()
		Simbad.add_votable_fields('pm')
		Simbad.add_votable_fields('sptype')
		Simbad.add_votable_fields('flux(V)')
		Simbad.add_votable_fields('flux(K)')

		# send the query to Simbad
		self.table = Simbad.query_object(name)

		# pull out the official Simbad name
		self.name = name
		self.simbadname = self.table['MAIN_ID'].data[0]
		if len(self.simbadname) < len(self.name):
			self.speak( "renaming {1} to {0}".format(self.simbadname, self.name))
			self.name = self.simbadname

		ra = self.table['RA'].data[0]
		dec = self.table['DEC'].data[0]
		obstime = astropy.time.Time(2000.0, format='decimalyear')
		self.icrs = astropy.coordinates.SkyCoord(ra, dec,
												unit=(u.hourangle, u.deg),
												frame='icrs', obstime=obstime)

		self.pmra = self.table['PMRA'].data[0] 		# in (projected) mas/yr
		self.pmdec = self.table['PMDEC'].data[0]	# in mas/yr

		self.attributes = {}
		self.attributes['V'] = float(self.table['FLUX_V'].data[0])
		self.attributes['comment'] = self.table['SP_TYPE'].data[0]
		for k, v in attributes.items():
			self.attributes[k] = v
		self.speak('made {0} from SIMBAD'.format(self))