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')
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.")
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
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
def test_multi_vo_fields(self): '''Regression test for issue 820''' request = Simbad() request.add_votable_fields("flux_qual(V)") request.add_votable_fields("flux_qual(R)") request.add_votable_fields("coo(s)") # sexagesimal coordinates request.add_votable_fields("coo(d)") # degree coordinates request.add_votable_fields("ra(:;A;ICRS;J2000)") request.add_votable_fields("ra(:;A;fk5;J2000)") request.add_votable_fields("bibcodelist(2000-2006)") request.add_votable_fields("bibcodelist(1990-2000)") request.add_votable_fields("otype(S)") request.add_votable_fields("otype(3)") request.add_votable_fields("id(1)") request.add_votable_fields("id(2mass)") request.add_votable_fields("id(s)") response = request.query_object('algol') assert("FLUX_QUAL_V" in response.keys()) assert("FLUX_QUAL_R" in response.keys()) assert("RA_d" in response.keys()) assert("RA_s" in response.keys()) assert("RA___A_ICRS_J2000" in response.keys()) assert("RA___A_fk5_J2000" in response.keys()) assert("OTYPE_S" in response.keys()) assert("OTYPE_3" in response.keys()) assert("ID_1" in response.keys()) assert("ID_2mass" in response.keys()) assert("ID_s" in response.keys())
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
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
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.')
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
def get_stellar_data(name=''): ''' Function to query Simbad for following stellar information RA, Dec, PMRA, PMDec, Parallax Epoch INPUTS: name = Name of source. Example ''' warning = [] customSimbad = Simbad() customSimbad.add_votable_fields('ra(2;A;ICRS;J2000)', 'dec(2;D;ICRS;J2000)', 'pm', 'plx', 'parallax', 'rv_value') #Simbad.list_votable_fields() customSimbad.remove_votable_fields('coordinates') #Simbad.get_field_description('orv') obj = customSimbad.query_object(name) if obj is None: raise ValueError( 'ERROR: {} target not found. Check target name or enter RA,Dec,PMRA,PMDec,Plx,RV,Epoch manually\n\n' .format(name)) else: warning += ['{} queried from SIMBAD.'.format(name)] # Check for masked values if all([not x for x in [obj.mask[0][i] for i in obj.colnames]]) == False: warning += ['Masked values present in queried dataset'] obj = obj.filled(None) pos = SkyCoord(ra=obj['RA_2_A_ICRS_J2000'], dec=obj['DEC_2_D_ICRS_J2000'], unit=(u.hourangle, u.deg)) ra = pos.ra.value[0] dec = pos.dec.value[0] pmra = obj['PMRA'][0] pmdec = obj['PMDEC'][0] plx = obj['PLX_VALUE'][0] rv = obj['RV_VALUE'][0] * 1000 #SIMBAD output is in km/s. Converting to m/s epoch = 2451545.0 star = { 'ra': ra, 'dec': dec, 'pmra': pmra, 'pmdec': pmdec, 'px': plx, 'rv': rv, 'epoch': epoch } # Fill Masked values with None. Again. for i in star: if star[i] > 1e10: star[i] = None warning += ['Values queried from SIMBAD are {}'.format(star)] return star, warning
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()
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)
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)
def simbad_object(): customSimbad=Simbad() customSimbad.TIMEOUT=5 customSimbad.add_votable_fields('ra(d)','dec(d)','flux(V)') customSimbad.remove_votable_fields('coordinates') result_table=customSimbad.query_object(request.form["Name"]) return result_table
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)
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])
def get_tic_name(name): with warnings.catch_warnings(): warnings.simplefilter('ignore') customSimbad = Simbad() customSimbad.add_votable_fields( 'ra(2;A;ICRS;J2000;2000)', 'dec(2;D;ICRS;J2000;2000)') customSimbad.remove_votable_fields('coordinates') result_table = customSimbad.query_object(name) if result_table is None: logger.error("Target name failed to resolve, please check") sys.exit(1) with warnings.catch_warnings(): warnings.simplefilter('ignore') ra_sex = result_table['RA_2_A_ICRS_J2000_2000'][0] dec_sex = result_table['DEC_2_D_ICRS_J2000_2000'][0] catalogData = Catalogs.query_region(SkyCoord (ra_sex, dec_sex, unit=(u.hour, u.deg)), catalog='Tic', radius=0.006) try: return catalogData['ID'][0] except IndexError: logger.error("No TIC target at those coordiantes") sys.exit(1)
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
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
def simbad_region(coord): customSimbad=Simbad() customSimbad.TIMEOUT=5 customSimbad.add_votable_fields('ra(d)','dec(d)','flux(V)') customSimbad.remove_votable_fields('coordinates') result_table = customSimbad.query_region(coord, radius='0d2m0s') return result_table
def test_simbad_catalog_get_simbad_copy(self): # always return a copy of the querier s = Simbad() # assign our simbad self.cat.simbad = s assert_is_not(self.cat.simbad, s) assert_equal(self.cat.simbad.ROW_LIMIT, 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)
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)
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)
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
def get_simbad_data(starnames): """ queries the coordinates, V mag, proper motion and spectral type from a list of stars outputs a table with Simbad ID, coordinates, Vmag, proper motion and spectral type """ sim_data = {} mSimbad = Simbad() # only simbad ID & coord mSimbad.add_votable_fields('flux(V)') # add flux in V to table mSimbad.add_votable_fields('pm') # add proper motion to table mSimbad.add_votable_fields('sp') # add spectral type to table table_heads = [ 'my_starname', 'SimbadID', 'ra', 'dec', 'm_v', 'spectra_type', 'pm_ra', 'pm_dec' ] table_dtype = ['S50' for i in range(len(table_heads))] stable = Table(names=table_heads, dtype=table_dtype) for sn in starnames: print('...getting data for ', sn) newrow = [sn.replace(' ', '_')] stardata = mSimbad.query_object(sn.replace('_', ' ')) #print sn, stardata if stardata == None: print(colored('could not get data for : %s' % sn, 'red')) else: print('newrow', newrow) #print('stardata', repr(stardata['MAIN_ID'])) #print('stardata', stardata['MAIN_ID'][0].decode('UTF-8').split() ) newrow.extend( [' '.join(stardata['MAIN_ID'][0].decode('UTF-8').split())]) ra = re.match('(\d\d) (\d\d) (\d\d\.\d+)$', stardata['RA'][0]).groups() try: dec = re.match('(-\d\d|\+\d\d) (\d\d) (\d\d\.\d+)$', stardata['DEC'][0]).groups() except: dec = re.match('(-\d\d|\+\d\d) (\d\d) (\d\d)$', stardata['DEC'][0]).groups() print(dec) m_ra = ra[0] + u'h' + ra[1] + u'm' + ra[2] + u's' m_dec = dec[0] + u'd' + dec[1] + u'm' + dec[2] + u's' newrow.extend([m_ra, m_dec]) newrow.extend([stardata['FLUX_V'][0]]) newrow.extend([stardata['SP_TYPE'][0]]) newrow.extend([stardata['PMRA'][0]]) newrow.extend([stardata['PMDEC'][0]]) stable.add_row(newrow) return stable
def print_results(tic=12350, simbad_search=False, data_search=False): target = Target(tic) catalogData = target.query()[0] catalogData['ra'] = catalogData['ra'].round(5) catalogData['dec'] = catalogData['dec'].round(5) catalogData['eclong'] = catalogData['eclong'].round(5) catalogData['eclat'] = catalogData['eclat'].round(5) catalogData['pmRA'] = catalogData['pmRA'].round(2) catalogData['pmDEC'] = catalogData['pmDEC'].round(2) catalogData['Tmag'] = catalogData['Tmag'].round(2) catalogData['Vmag'] = catalogData['Vmag'].round(2) catalogData['Kmag'] = catalogData['Kmag'].round(2) print(catalogData[['ID', 'ra', 'dec', 'pmRA', 'pmDEC', 'eclong', 'eclat', 'Tmag', 'Vmag', 'Kmag', 'Teff', 'rad', 'mass', 'd', ]]) if simbad_search: skobj = SkyCoord(ra=catalogData['ra'] * u.degree, dec=catalogData['dec'] * u.degree, frame='icrs') with warnings.catch_warnings(): warnings.simplefilter('ignore') customSimbad = Simbad() customSimbad.add_votable_fields( 'ra(2;A;ICRS;J2000;2000)', 'dec(2;D;ICRS;J2000;2000)') customSimbad.remove_votable_fields('coordinates') # try different search radii, be fast if possible for i in [5, 10, 20]: result_table = customSimbad.query_region( skobj, radius=i * u.arcsec) if result_table is None: continue else: break if result_table is None: logger.warning("No Simbad target resolved") else: print() print('Target name: {}'.format( result_table['MAIN_ID'][0])) print("The target is in constellation {}".format(get_constellation( skobj))) if data_search: obs_sectors = target.get_obs() obs2, obsffi, obs20 = obs_sectors print(f'FFI data at MAST for sectors: {sorted(list(set(obsffi)))}') print(f'2-min data at MAST for sectors: {sorted(list(set(obs2)))}') print(f'20-s data at MAST for sectors: {sorted(list(set(obs20)))}') print()
def test_query_multi_object(self, temp_dir): simbad = Simbad() simbad.cache_location = temp_dir result = simbad.query_objects(['M32', 'M81']) assert len(result) == 2 assert len(result.errors) == 0 result = simbad.query_objects(['M32', 'M81', 'gHer']) # 'gHer' is not a valid Simbad identifier - it should be 'g Her' to # get the star assert len(result) == 2 assert len(result.errors) == 1 # test async s = Simbad() response = s.query_objects_async(['M32', 'M81']) result = s._parse_result(response, SimbadVOTableResult) assert len(result) == 2
def test_simbad_catalog_set_simbad(self): s = Simbad() # ok for simbad self.cat.simbad = s # raise everything else for i in ['Simbad', 'simbad', 1.0, [], (), np.array([]), {}]: with pytest.raises(ValueError, match='is not a SimbadClass'): self.cat.simbad = i
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]