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
def query(self): ''' Example ------- >>> coords = SkyCoord([100, 90],[30, 20], unit=(u.deg, u.deg)) >>> r = 10 * u.arcmin >>> test = QueryVizier(coords, catalog='UCAC4', radius=r) >>> tq = test.query() ''' viz = Vizier(columns=self.columns, column_filters=self.column_filters) viz.ROW_LIMIT = -1 # query up to infinitely many rows. By default, this is 50. result = viz.query_region(self.coordinates, radius=self.radius, inner_radius=self.inner_radius, width=self.width, height=self.height, catalog=self.catalog) self.queried = result return self.queried
def panstarrs_query_pos(ra, dec, width): v = Vizier(columns=[ 'RAJ2000', 'DEJ2000', 'imag', 'e_imag', 'rmag', 'e_rmag', 'gmag', 'e_gmag', 'zmag', 'e_zmag', 'ymag', 'e_ymag' ]) #setting Vizier for specific columns v.ROW_LIMIT = -1 #no limits on the table length table_pre = v.query_region(astropy.coordinates.ICRS(ra=ra * u.deg, dec=dec * u.deg), width=width * u.arcmin, catalog='pan-STARRS') #the real query #selection of lines with determined in magnitudes in I, R, G, Z if len(table_pre) != 0: index = [] for i in range(0, len(table_pre[0]['RAJ2000'].data)): index.append(i) #rename the columns to fit my standard table = table_pre[0][index] table.rename_column('RAJ2000', 'raMean') table.rename_column('DEJ2000', 'decMean') table.rename_column('imag', 'i') table.rename_column('e_imag', 'i_err') table.rename_column('rmag', 'r') table.rename_column('e_rmag', 'r_err') table.rename_column('gmag', 'g') table.rename_column('e_gmag', 'g_err') table.rename_column('zmag', 'z') table.rename_column('e_zmag', 'z_err') table.rename_column('ymag', 'y') table.rename_column('e_ymag', 'y_err') return table else: return table_pre
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)
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
def cross_match(): """ Nothing but test query data and cross match. """ twomass = Irsa.query_region(coord.SkyCoord(28.2, -0.049, unit=(u.deg, u.deg), frame='galactic'), catalog='fp_psc', radius='1d0m0s') v = Vizier(columns=["**", "RAJ2000", "DEJ2000"]) v.ROW_LIMIT = 9000000 result = v.query_region(coord.SkyCoord(ra=280.7421273, dec=-4.2326516,\ unit=(u.deg, u.deg), frame='icrs'),radius=0.05*u.deg, catalog=["GAIA DR2"]) gaia_data = result[4] coo_wise = coord.SkyCoord(twomass['ra'], twomass['dec']) coo_twomass = coord.SkyCoord(gaia_data['RAJ2000'], gaia_data['DEJ2000']) idx_twomass, d2d_twomass, d3d_twomass = coo_wise.match_to_catalog_sky( coo_twomass) YSO = gaia_data[:0].copy() for k in idx_twomass: YSO.add_row(gaia_data[k]) return YSO
def OS_from_viz(viz_ID, file_name, extraCols=['default'], GUI_name='default', GUI_path='default', use_redshift='OFF'): from astroquery.vizier import Vizier v = Vizier() v.ROW_LIMIT = -1 Cats = v.get_catalogs(viz_ID) grbCat = Cats[0] grbAstroCat = Table(grbCat) global colNames colNames = ["RAJ2000", "DEJ2000"] if extraCols == ['default']: otherCols(grbAstroCat) else: for i in range(len(extraCols)): colNames.append(extraCols[i]) hasDistance(grbAstroCat, use_redshift) deleteCols(grbAstroCat) # global viz_key viz_key = 1996 global vizID vizID = viz_ID #guiforasset = GUI_name files2ops.createFiles(grbAstroCat, file_name, GUI_name, GUI_path, "Vizier:" + viz_ID)
def make_tess_query(self, mag_range=(1, 6), ra_range=(0, 360), dec_range=(-90, 90)): """ Query the TESS input catalog using VizieR :param mag_range: the magnitude range you wish to constrain the query by :param ra_range: the RA range you wish to constrain the query by :param dec_range: The DEC range you wish to constrain the query by :return: appends results to the catalogs results array """ print("Retrieving Catalogue") columns = ['RAJ2000','DEJ2000','TIC','2MASS','Tessmag','Teff','R*','M*','logg','Dist','Gmag','Vmag'] v = Vizier(columns=columns) v.ROW_LIMIT = -1 result = v.query_constraints(catalog="J/AJ/156/102", Vmag='>%s & <%s' %(mag_range[0], mag_range[1]), RAJ2000=">%s & <%s"%(ra_range[0], ra_range[1]), DEJ2000='>%s & <%s'%(dec_range[0], dec_range[1])) if result: good_val = np.where(~np.isnan(result[0]['R_']) & ~np.isnan(result[0]['Dist'])) self.tess = result[0][good_val] self.catalogs.append(self.tess) self.cat_names.append("TESS")
def from_sky(cls, magnitudelimit=None): ''' Create a Constellation from a criteria search of the whole sky. Parameters ---------- magnitudelimit : float Maximum magnitude (for Ve = "estimated V"). ''' # define a query for cone search surrounding this center criteria = {} if magnitudelimit is not None: criteria[cls.defaultfilter + 'mag'] = '<{}'.format(magnitudelimit) v = Vizier(columns=cls.columns, column_filters=criteria) v.ROW_LIMIT = -1 # run the query print('querying Vizier for {}, for {}<{}'.format( cls.name, cls.defaultfilter, magnitudelimit)) table = v.query_constraints(catalog=cls.catalog, **criteria)[0] # store the search parameters in this object c = cls(cls.standardize_table(table)) c.standardized.meta['catalog'] = cls.catalog c.standardized.meta['criteria'] = criteria c.standardized.meta[ 'magnitudelimit'] = magnitudelimit or c.magnitudelimit #c.magnitudelimit = magnitudelimit or c.magnitudelimit return c
def get_inclination(self): """ This function ... :return: """ # Inform the user log.info( "Querying the catalog of radial profiles for 161 face-on spirals ..." ) # The Vizier querying object vizier = Vizier() vizier.ROW_LIMIT = -1 # Radial profiles for 161 face-on spirals (Munoz-Mateos+, 2007) radial_profiles_result = vizier.query_object(self.galaxy_name, catalog="J/ApJ/658/1006") # Catalog doesnt contain data for a lot of galaxies # If it doesnt, use DustPedia galaxy info as a backup solution if len(radial_profiles_result) == 0 or len( radial_profiles_result[0]) == 0: inclination = Angle(self.info["Inclination"][0], "deg") # We have a table and it is not empty else: table = radial_profiles_result[0] # distance = float(table[0]["Dist"]) inclination = Angle(float(table[0]["i"]), "deg") # Set the inclination self.properties.inclination = inclination
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
def get_catalogue(self, catalogue, boundary_value="nan"): cat_ids={"SUMSS":"VIII/81B/sumss212", "NVSS":"VIII/65/nvss", "MGPS2":"VIII/82/mgpscat" } if catalogue not in cat_ids: self.logger.error("Requested catalogue not recongised.") return elif catalogue=="SUMSS": search_cat=[cat_ids["SUMSS"], cat_ids["MGPS2"]] elif catalogue=="NVSS": search_cat=[cat_ids["NVSS"],] else: search_cat=[cat_ids["MGPS2"],] if not self.wcs: self.load_wcs() if not self.header: self.load_header() if not self.centre: self.load_position_dimensions() if np.abs(self.size_x-self.size_y) > max([self.size_x,self.size_y])*0.05: self.logger.warning("Non square image detected! Will pad the Vizier search area by 2.0 (default 1.5).") pad=2.5 else: pad=2.0 # if not self.data: # self.load_data() v = Vizier(columns=["_r", "_RAJ2000","_DEJ2000", "**"]) v.ROW_LIMIT=-1 self.logger.info("Querying {} using Vizier...".format(catalogue)) result=v.query_region(self.centre, radius=self.radius*pad, catalog=search_cat) if catalogue=="SUMSS": catalogs_returned=result.keys() #Searching the galactic plane survey as well, check if there are any found in that one if len(catalogs_returned) == 2: #Here we have to merge them together, MGPS2 has two extra columns: 'MGPS' and 'E' pandas can just merge them df_result=result[cat_ids["SUMSS"]].to_pandas() mgps2_result=result[cat_ids["MGPS2"]].to_pandas() # mgps2_result.drop(["MGPS", "E"]) #And just append the mgps2 sources to the sumss result df_result=df_result.append(mgps2_result) else: df_result=result[0].to_pandas() else: df_result=result[0].to_pandas() if catalogue=="NVSS": df_result["PA"].fillna(0.0, inplace=True) self.raw_nvss_sources=df_result self.logger.info("{} sources obtained.".format(catalogue)) self.logger.info("Filtering {} sources to only those within the image area...".format(catalogue)) self.nvss_sources=self._filter_catalogue(self.raw_nvss_sources, boundary_value=boundary_value) return self.nvss_sources else: self.raw_sumss_sources=df_result self.logger.info("{} sources obtained.".format(catalogue)) self.logger.info("Filtering {} sources to only those within the image area...".format(catalogue)) self.sumss_sources=self._filter_catalogue(self.raw_sumss_sources, boundary_value=boundary_value) return self.sumss_sources
def catalogue_call(avgCoord, opt, cat_name): data = namedtuple(typename='data', field_names=['ra', 'dec', 'mag', 'emag', 'cat_name']) TABLES = { 'APASS': '******', 'SDSS': 'V/147/sdss12', 'PanSTARRS': 'II/349/ps1', 'SkyMapper': 'II/358/smss' } tbname = TABLES.get(cat_name, None) kwargs = {'radius': '0.33 deg'} kwargs['catalog'] = cat_name try: v = Vizier(columns=[ 'all' ]) # Skymapper by default does not report the error columns v.ROW_LIMIT = -1 query = v.query_region(avgCoord, **kwargs) except VOSError: raise AstrosourceException("Could not find RA {} Dec {} in {}".format( avgCoord.ra.value, avgCoord.dec.value, cat_name)) if query.keys(): resp = query[tbname] else: raise AstrosourceException("Could not find RA {} Dec {} in {}".format( avgCoord.ra.value, avgCoord.dec.value, cat_name)) logger.debug(f'Looking for sources in {cat_name}') if cat_name in ['APASS', 'PanSTARRS']: radecname = {'ra': 'RAJ2000', 'dec': 'DEJ2000'} elif cat_name == 'SDSS': radecname = {'ra': 'RA_ICRS', 'dec': 'DE_ICRS'} elif cat_name == 'SkyMapper': radecname = {'ra': 'RAICRS', 'dec': 'DEICRS'} else: radecname = {'ra': 'raj2000', 'dec': 'dej2000'} # Filter out bad data from catalogues if cat_name == 'PanSTARRS': resp = resp[where((resp['Qual'] == 52) | (resp['Qual'] == 60) | (resp['Qual'] == 61))] elif cat_name == 'SDSS': resp = resp[resp['Q'] == 3] elif cat_name == 'SkyMapper': resp = resp[resp['flags'] == 0] data.cat_name = cat_name data.ra = array(resp[radecname['ra']].data) data.dec = array(resp[radecname['dec']].data) # extract RA, Dec, Mag and error as arrays data.mag = array(resp[opt['filter']].data) data.emag = array(resp[opt['error']].data) return data
def download_table(cdsname, name=None, ra=0, dec=0, sr=0.1, columns=[], limit=-1, conversions={}, extracols=[], verbose=False): if name is None: name = cdsname cols = ['**'] + extracols # v = Vizier(columns = cols, vizier_server='vizier.cfa.harvard.edu') v = Vizier(columns=cols) v.ROW_LIMIT = limit t = v.query_region(SkyCoord(ra, dec, frame='icrs', unit='deg'), radius='%g degrees' % sr, catalog=cdsname) if len(t): t = t[0] if conversions: for cfrom in conversions.keys(): cto = conversions[cfrom] if cfrom in t.colnames: t.rename_column(cfrom, cto) if columns: for _ in t.colnames: if _ in columns: pass else: t.remove_column(_) # Check column names for _ in columns: if _ not in t.colnames and _[0] != '*': print("Column", _, "is missing!") if verbose: print("Downloaded table", name, "from", cdsname, "at", ra, dec, sr, ":", len(t), "rows and", len(t.colnames), "columns") else: t = None if verbose: print("Can't download table", name, "from", cdsname, "at", ra, dec, sr) return t
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 result is None or 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
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
def aavso(self, string): """ Return AAVSO variable star Catalog Title: B/vsx/vsx """ v = Vizier(catalog='B/vsx/vsx', columns=['_RAJ2000', '_DEJ2000', '*']) v.ROW_LIMIT = 500000 result = v.query_constraints(Name=string) for table_name in result.keys(): table = result[table_name] return table
def GalInABox2(self, catalog): v = Vizier(columns = ['RAJ2000', 'DEJ2000', 'z', 'GWGC', 'Bmag', 'Jmag', 'Kmag', 'Hmag']) v.ROW_LIMIT = 99999999 center = SkyCoord(M.p_pos.means_[0][0], M.p_pos.means_[0][1], unit = (u.rad, u.rad)) raggio = np.sqrt(np.diag(M.p_pos.covariances_[0])).max() table = v.query_region(center, radius = 5*raggio*u.rad, catalog = catalog) # width = width, height = height, catalog = catalog) data = pd.DataFrame() # for tablei in table: # data = data.append(tablei.to_pandas(), ignore_index = True) data = data.append(table[1].to_pandas()) return data.dropna(subset = ['RAJ2000', 'DEJ2000', 'z'])
def get_catalog(): coo = SkyCoord.from_name('GJ3470') rad = 40*u.arcmin cat_id = 'I/284/out' v=Vizier(catalog=cat_id,columns=["RAJ2000","DEJ2000","Plx","RAJ2000","DEJ2000"],column_filters={'Imag':'>13'}) v.ROW_LIMIT = -1 tab = v.query_region(coo, radius=rad, catalog = cat_id)[0] x2 = tab['RAJ2000'] y2 = tab['DEJ2000'] print(coo.galactic) return(x2,y2)
def getVizierResults(name, radius): from astroquery.vizier import Vizier from astropy import units as u v = Vizier(columns=["all"], catalog='I/345/gaia2') v.ROW_LIMIT = 25000 results = v.query_object(name, catalog='I/345/gaia2', radius=radius * u.arcsec) keys = results[0].keys() objectList = gaiaClass.GAIAObjects(gaiaTable=results[0]) return objectList
def getRandomVizier(numResults): from astroquery.vizier import Vizier from astropy import units as u v = Vizier(columns=["all"], catalog='I/345/gaia2', column_filters={ "RandomI": "830339102..840339102", "e_Plx": "<0.1" }) v.ROW_LIMIT = numResults result = v.get_catalogs('I/345/gaia2') result[0].pprint() return result[0].keys(), result[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"))
def get_catalog(pattern): d = get_target_coords(pattern) cooEQ = d['target_coords'].fk5.transform_to(FK5(equinox="J2019.9")) rad = 40 * u.arcmin cat_id = 'I/284/out' v = Vizier(catalog=cat_id, columns=["RAJ2000", "DEJ2000", "Plx", "RAJ2000", "DEJ2000"], column_filters={'Imag': '>14'}) v.ROW_LIMIT = -1 tab = v.query_region(cooEQ, radius=rad, catalog=cat_id)[0] g = dict() g['ra_cat'] = tab['RAJ2000'] g['dec_cat'] = tab['DEJ2000'] return (g)
def regionincatalog(self, astre_ra, astre_dec, angle_width, angle_height, mag, catalog_name, field_ra, field_dec, field_mag): """ Returns the table of RA, DEC and markers Attributes: astre_ra (float) : RA astre_dec (float) : DEC angle_width (float) : Degrees angle_height (float) : Degrees mag (float) : Maximun magnitude catalog_name (str) : Catalog Vizier name field_ra (float) : field of RA field_dec (float) : Field of DEC, field_mag (float) : Field maximun magnitude """ table_ra = [] table_dec = [] table_marker = [] # Recherche dans le catalog # Field catalog : _RAJ2000, _DEJ2000, Vmag, r'mag, Gmag ... v = Vizier(columns=[field_ra, field_dec, field_mag]) # Nombre limite de recherche v.ROW_LIMIT = 500000 # Recherche et création de la table mag_format = '<' + str(mag) result = v.query_region(SkyCoord(ra=astre_ra, dec=astre_dec, unit=(u.deg, u.deg), frame='icrs'), width=Angle(angle_width, "deg"), height=Angle(angle_height, "deg"), catalog=catalog_name, column_filters={'Gmag': mag_format}) if mag <= 14: stars = constant.starslow else: stars = constant.starshight for table_name in result.keys(): table = result[table_name] for line in table: ra = float(line[0]) dec = float(line[1]) mv = float(line[2]) if mv != 'masked': marker_size = stars[int(mv) + stars[0]] table_ra.append(ra) table_dec.append(dec) table_marker.append(marker_size) return Table([table_ra, table_dec, table_marker], names=['RA', 'DEC', 'MARKER'])
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)
def get_catalog(target, xobj, yobj, pattern): o = get_obj(target, xobj, yobj, pattern) cooEQ = SkyCoord.from_name(o['obj']).fk5.transform_to( FK5(equinox='J2019.9')) rad = 40 * u.arcmin cat_id = 'I/284/out' v = Vizier(catalog=cat_id, columns=["RAJ2000", "DEJ2000", "Plx", "RAJ2000", "DEJ2000"], column_filters={'Imag': '>14'}) v.ROW_LIMIT = -1 tab = v.query_region(cooEQ, radius=rad, catalog=cat_id)[0] g = dict() g['ra_cat'] = tab['RAJ2000'] g['dec_cat'] = tab['DEJ2000'] return (g)
def __query_box(self, ra, dec, base, height, catalog): """Vizier.query_region in a square/rectangular FoV using astroquery module.""" base_str, height_str = str(base) + 'd', str(height) + 'd' catalog_constraints = Vizier(catalog=[self.catalog], columns=['*', '_RAJ2000', '_DEJ2000', self.column_1, self.column_2], column_filters={self.column_1 : self.filter_1, self.column_2 : self.filter_2}) catalog_constraints.ROW_LIMIT = -1 # completed catalog query_result = catalog_constraints.query_region(SkyCoord( ra = ra, dec = dec, unit = (u.deg, u.deg), frame='icrs'), width = height_str, height = base_str) return query_result
def __query_circle(self, ra, dec, radius, catalog): """Vizier.query_region in a circle FoV using astroquery module.""" radius_str = str(radius) + 'd' catalog_constraints = Vizier(catalog=[self.catalog], columns=['*', '_RAJ2000', '_DEJ2000', self.column_1, self.column_2], column_filters={self.column_1 : self.filter_1, self.column_2 : self.filter_2}) catalog_constraints.ROW_LIMIT = -1 # completed catalog query_result = catalog_constraints.query_region(SkyCoord( ra = ra, dec = dec, unit = (u.deg, u.deg), frame='icrs'), radius = radius_str) return query_result
def search_vizier_for_2mass_sources(ra, dec, radius): """Function to perform online query of the 2MASS catalogue and return a catalogue of known objects within the field of view""" v = Vizier(columns=['_RAJ2000', '_DEJ2000', 'Jmag', 'e_Jmag', \ 'Hmag', 'e_Hmag','Kmag', 'e_Kmag'],\ column_filters={'Jmag':'<20'}) v.ROW_LIMIT = 5000 c = coordinates.SkyCoord(ra + ' ' + dec, frame='icrs', unit=(units.deg, units.deg)) r = radius * units.arcminute result = v.query_region(c, radius=r, catalog=['2MASS']) return result[0]
def GalInABox(ra, dec, ra_unit, dec_unit, catalog='GLADE', all=False): """ Dati gli intervalli RA e DEC (pensati come gli estremi di una forma qualunque), la funzione restituisce un DataFrame contenente tutte le galassie contenute in CATALOG entro il rettangolo definito dagli intervalli Parameters ---------- ra, dec: list Intervalli di coordinate angolari entro le quali è interamente contenuta la regione desiderata ra_unit, dec_unit: astropy.units.core.Unit Unità di misura in cui sono espressi RA e DEC. Default: deg catalog: string, optional. Catalogo dal quale estrarre i dati. Default: GLADE2 (pensato per coll. LIGO-Virgo). all: boolean, optional Se all = True restituisce tutte le colonne scaricate dal catalogo. Se all = False, solamente quelle corrispondenti a RA, DEC e z. Returns ------- df: Pandas DataFrame DataFrame Pandas contenente gli oggetti selezionati dal catalogo. """ if all: v = Vizier() else: v = Vizier(columns=['RAJ2000', 'DEJ2000', 'z', 'Bmag']) v.ROW_LIMIT = -1 ra = np.array(ra) dec = np.array(dec) center = sc(ra.mean(), dec.mean(), unit=(ra_unit, dec_unit)) width = (ra.max() - ra.min()) / 2. * ra_unit height = (dec.max() - dec.min()) / 2. * dec_unit table = v.query_region(center, width=width, height=height, catalog=catalog) data = pd.DataFrame() for tablei in table: data = data.append(tablei.to_pandas(), ignore_index=True) return data.dropna()
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 get_catalog(target, pattern): '''Gets a catalog from target's name and gives his objects coordinates in RA and DEC''' d = get_target_coords(target, pattern) cooEQ = d['target_coords'] rad = 40 * u.arcmin cat_id = 'I/284/out' v = Vizier(catalog=cat_id, columns=["RAJ2000", "DEJ2000", "Plx", "RAJ2000", "DEJ2000"], column_filters={'Imag': '>14'}) v.ROW_LIMIT = -1 tab = v.query_region(cooEQ, radius=rad, catalog=cat_id)[0] g = dict() g['RA_catalog'] = tab['RAJ2000'] g['DEC_catalog'] = tab['DEJ2000'] return (g)
def query_circle(self, ra, dec, radius, catalog, column_1, filter_1): """Vizier.query_region in a circle FoV using astroquery module.""" radius_str = str(radius) + 'd' catalog_constraints = Vizier( catalog=[catalog], columns=['*', 'RAJ2000', 'DEJ2000', column_1], column_filters={column_1: filter_1}) catalog_constraints.ROW_LIMIT = -1 # completed catalog query_result = catalog_constraints.query_region(coord.SkyCoord( ra=ra, dec=dec, unit=(u.deg, u.deg), frame='icrs'), radius=radius_str) return query_result
def from_cone(cls, center, radius=3 * u.arcmin, magnitudelimit=None, **kw): ''' Create a Constellation from a cone search of the sky, characterized by a positional center and a radius from it. Parameters ---------- center : SkyCoord object The center around which the query will be made. radius : float, with units of angle The angular radius for the query. magnitudelimit : float The maximum magnitude to include in the download. (This is explicitly thinking UV/optical/IR, would need to change to flux to be able to include other wavelengths.) ''' # make sure the center is a SkyCoord center = parse_center(center) criteria = {} if magnitudelimit is not None: criteria[cls.defaultfilter + 'mag'] = '<{}'.format(magnitudelimit) v = Vizier(columns=cls.columns, column_filters=criteria) v.ROW_LIMIT = -1 # run the query print( 'querying Vizier for {}, centered on {} with radius {}, for G<{}'. format(cls.name, center, radius, magnitudelimit)) table = v.query_region(coordinates=center, radius=radius, catalog=cls.catalog)[0] # store the search parameters in this object c = cls(cls.standardize_table(table)) c.standardized.meta['catalog'] = cls.catalog c.standardized.meta['center'] = center c.standardized.meta['radius'] = radius c.standardized.meta['magnitudelimit'] = magnitudelimit c.center = center c.radius = radius #c.magnitudelimit = magnitudelimit or cls.magnitudelimit return c
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"))
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
def process_vdb(vdbname, gfields, sun, ind, ra_interest, dec_interest, print_coord = True, print_head = True): lcol = 12 fields = [] + gfields fields.append('RAJ2000') fields.append('DEJ2000') v = Vizier(columns = fields, catalog = vdbname) v.ROW_LIMIT = -1 result = v.query_constraints(catalog = vdbname, RAJ2000 = ra_interest, DEJ2000 = dec_interest) #result[result.keys()[0]].pprint() numobjs = len(result[0]) twelveoc = 12*60*60 tms = twelveoc*np.array([1., 3., 4.]) prline = '==========' + '=' + '============' prhead = 'Date ' + ' ' + ' Time ' l = len(fields) if not print_coord: l -= 2 for i in xrange(l): prline = prline + '=' + '='*lcol tmp = fields[i] if len(tmp) < lcol: tmp = tmp + ' '*(lcol - len(tmp)) prhead = prhead + ' ' + tmp prhead = prhead + ' ' + 'Dec distance' prline = prline + '=' + '============' if print_head: print prline print prhead print prline for i in xrange(numobjs): ri = result[0][i].as_void() ri= list(ri) ri=ri[:-2] [ra, dec] = [ri[-2], ri[-1]] ra = parse_coord( ra, 'ra', ' ') dec = parse_coord( dec, 'deg', ' ') t, num = comp_time(sun[ind-1][1], sun[ind][1], sun[ind+1][1], ra) t = t.f2s() if num > 0: t += 2*twelveoc tmp = tms - t sz = tmp[tmp > 0].size if sz == 1: idx = ind+1 elif sz == 2: idx = ind elif sz == 3: idx = ind-1 t = coord(0, 0, t + twelveoc, 1, 'ra') if idx == ind: curdate = sun[idx][0] tmp = str(curdate[0]) if len(tmp) < 2: tmp = ' ' + tmp date = '' + tmp + '/' tmp = str(curdate[1]) if len(tmp) < 2: tmp = ' ' + tmp date = date + tmp + '/' + str(curdate[2]) dist = comp_dist(curdate[0], curdate[1], t, dec) printer = '' + date + ' ' + str(t) stri = [str(x) for x in ri[:-2]] if print_coord: stri = stri + [str(ra), str(dec)] for x in stri: if len(x) < lcol: x = ' '*(lcol - len(x)) + x printer = printer + ' ' + x printer = printer + ' ' + str(dist) print printer
def load(self, ra=0.0, dec=90.0, radius=0.2, write=True, faintlimit=None): # select the columns that should be downloaded from UCAC catalog = 'UCAC4' ratag = '_RAJ2000' dectag = '_DEJ2000' if catalog == 'UCAC4': vcat = 'I/322A/out' rmagtag = 'f.mag' jmagtag = 'Jmag' vmagtag = 'Vmag' pmratag, pmdectag = 'pmRA', 'pmDE' columns = ['_RAJ2000', '_DECJ2000', 'pmRA', 'pmDE', 'f.mag', 'Jmag', 'Vmag', 'UCAC4'] # create a query through Vizier v = Vizier(catalog=vcat, columns=columns) v.ROW_LIMIT = -1 # either reload an existing catalog file or download to create a new one starsfilename = settings.intermediates + self.directory starsfilename += "{catalog}ra{ra:.4f}dec{dec:.4f}rad{radius:.4f}".format( catalog=catalog, ra=ra, dec=dec, radius=radius) + '.npy' try: # try to load a raw catalog file logger.info("loading a catalog of stars from {0}".format(starsfilename)) t = np.load(starsfilename) except IOError: logger.info('could not load stars') # otherwise, make a new query logger.info("querying {catalog} " "for ra = {ra}, dec = {dec}, radius = {radius}".format( catalog=catalog, ra=ra, dec=dec, radius=radius)) # load via astroquery t = v.query_region(astropy.coordinates.ICRS(ra=ra, dec=dec, unit=(astropy.units.deg, astropy.units.deg)), radius='{:f}d'.format(radius), verbose=True)[0] # save the queried table np.save(starsfilename, t) # define the table self.table = astropy.table.Table(t) ras = np.array(t[:][ratag]) decs = np.array(t[:][dectag]) pmra = np.array(t[:][pmratag]) pmdec = np.array(t[:][pmdectag]) rmag = np.array(t[:][rmagtag]) jmag = np.array(t[:][jmagtag]) vmag = np.array(t[:][vmagtag]) rbad = (np.isfinite(rmag) == False) * (np.isfinite(vmag)) rmag[rbad] = vmag[rbad] rbad = (np.isfinite(rmag) == False) * (np.isfinite(jmag)) rmag[rbad] = jmag[rbad] jbad = (np.isfinite(jmag) == False) * (np.isfinite(vmag)) jmag[jbad] = vmag[jbad] jbad = (np.isfinite(jmag) == False) * (np.isfinite(rmag)) jmag[jbad] = rmag[jbad] vbad = (np.isfinite(vmag) == False) * (np.isfinite(rmag)) vmag[vbad] = rmag[vbad] vbad = (np.isfinite(vmag) == False) * (np.isfinite(jmag)) vmag[vbad] = jmag[vbad] temperatures = relations.pickles(rmag - jmag) imag = rmag - relations.davenport(rmag - jmag) pmra[np.isfinite(pmra) == False] = 0.0 pmdec[np.isfinite(pmdec) == False] = 0.0 ok = np.isfinite(imag) if faintlimit is not None: ok *= imag <= faintlimit logger.info("found {0} stars with {1} < V < {2}".format(np.sum(ok), np.min(rmag[ok]), np.max(rmag[ok]))) self.ra = ras[ok] self.dec = decs[ok] self.pmra = pmra[ok] self.pmdec = pmdec[ok] self.tmag = imag[ok] self.temperature = temperatures[ok] self.epoch = 2000.0
st = (sra-rad) ntiles=0 while st <= sra+rad: st = st + step ntiles += 1 ########################################################## ### Hipparcos print('Querying Hipparcos') t0 = time.time() v = Vizier(columns=['_RAJ2000', '_DEJ2000','HIP', 'Plx', 'e_Plx', 'pmRA', 'e_pmRA', 'pmDE', 'e_pmDE', 'Hpmag', 'e_Hpmag']) # for some reason we need this first to get more than 50 entries Vizier.ROW_LIMIT = -1 v.ROW_LIMIT = -1 result = v.query_region(coord.ICRS(ra=sra, dec=sde, unit=(u.deg, u.deg)), radius=Angle(rad, "deg"), catalog='I/311') #print(result) #print(sra,sde,rad) #pdb.set_trace() table=result[0] #table.colnames #pdb.set_trace() #x=np.array(table[:]['Plx']) #y=np.array(table[:]['e_Plx']) ra = np.array(table[:]['_RAJ2000']) dec = np.array(table[:]['_DEJ2000'])
def create_star_catalog(frame, catalogs=None): """ This function ... :return: """ # Initialize empty lists for the table columns catalog_column = [] id_column = [] ra_column = [] dec_column = [] ra_error_column = [] dec_error_column = [] magnitude_columns = {} magnitude_error_columns = {} on_galaxy_column = [] confidence_level_column = [] # Get the range of right ascension and declination of this image center, ra_span, dec_span = frame.coordinate_range # Create a new Vizier object and set the row limit to -1 (unlimited) viz = Vizier(keywords=["stars", "optical"]) viz.ROW_LIMIT = -1 # Loop over the different catalogs for catalog in catalogs: # Initialize a list to specify which of the stars added to the columns from other catalogs is already # matched to a star of the current catalog encountered = [False] * len(catalog_column) # Inform the user log.debug("Querying the " + catalog + " catalog") # Query Vizier and obtain the resulting table result = viz.query_region(center.to_astropy(), width=ra_span, height=dec_span, catalog=catalog) table = result[0] number_of_stars = 0 number_of_stars_in_frame = 0 number_of_new_stars = 0 magnitudes = {} magnitude_errors = {} # Get the magnitude in different bands for name in table.colnames: # If this column name does not end with "mag", skip it if not name.endswith("mag"): continue # If the column name contains more than one character before "mag", skip it if len(name.split("mag")[0]) > 1: continue # Get the name of the band band = name.split("mag")[0] # Create empty lists for the magnitudes and errors magnitudes[band] = [] magnitude_errors[band] = [] # Loop over all entries in the table for i in range(len(table)): # -- General information -- # Get the ID of this star in the catalog if catalog == "UCAC4": star_id = table["UCAC4"][i] elif catalog == "NOMAD": star_id = table["NOMAD1"][i] elif catalog == "II/246": star_id = table["_2MASS"][i] else: raise ValueError("Catalogs other than 'UCAC4', 'NOMAD' or 'II/246' are currently not supported") # -- Positional information -- # Get the position of the star as a SkyCoord object and as pixel coordinate position = SkyCoordinate(ra=table["_RAJ2000"][i], dec=table["_DEJ2000"][i], unit="deg", frame="fk5") pixel_position = position.to_pixel(frame.wcs) # Get the right ascension and declination for the current star star_ra = table["_RAJ2000"][i] star_dec = table["_DEJ2000"][i] number_of_stars += 1 # If this star does not lie within the frame, skip it if not frame.contains(position): continue number_of_stars_in_frame += 1 # Get the mean error on the right ascension and declination if catalog == "UCAC4" or catalog == "NOMAD": ra_error = table["e_RAJ2000"][i] * Unit("mas") dec_error = table["e_DEJ2000"][i] * Unit("mas") elif catalog == "II/246": error_maj = table["errMaj"][i] * Unit("arcsec") error_min = table["errMin"][i] * Unit("arcsec") error_theta = Angle(table["errPA"][i], "deg") # Temporary: use only the major axis error (convert the error ellipse into a circle) ra_error = error_maj.to("mas") dec_error = error_maj.to("mas") else: raise ValueError("Catalogs other than 'UCAC4', 'NOMAD' or 'II/246' are currently not supported") # -- Magnitudes -- # Loop over the different bands for which a magnitude is defined for band in magnitudes: # Determine the column name column_name = band + "mag" value = table[column_name][i] if isinstance(value, np.ma.core.MaskedConstant): magnitudes[band].append(None) magnitude_errors[band].append(None) else: # Add the magnitude value magnitudes[band].append(Magnitude(value)) # Check for presence of error on magnitude error_column_name = "e_" + column_name if error_column_name in table.colnames: error = table[error_column_name][i] if isinstance(error, np.ma.core.MaskedConstant): magnitude_errors[band].append(None) else: magnitude_errors[band].append(Magnitude(error)) else: magnitude_errors[band].append(None) # -- Cross-referencing with previous catalogs -- # If there are already stars in the list, check for correspondences with the current stars for index in range(len(encountered)): # Skip stars that are already encountered as matches with the current catalog (we assume there can only # be one match of a star of one catalog with the star of another catalog, within the radius of 3 pixels) if encountered[index]: continue saved_star_position = SkyCoordinate(ra=ra_column[index], dec=dec_column[index], unit="deg", frame="fk5") saved_star_pixel_position = saved_star_position.to_pixel(frame.wcs) # Calculate the distance between the star already in the list and the new star difference = saved_star_pixel_position - pixel_position # Check whether the distance is less then 3 pixels if difference.norm < 3.0: # Inform the user log.debug("Star " + star_id + " could be identified with star " + id_column[index] + " from the " + catalog_column[index] + " catalog") # Increment the confidence level for the 'saved' star confidence_level_column[index] += 1 # Set the 'encountered' flag to True for the 'saved' star encountered[index] = True # Break, because the current star does not have to be saved again (it is already in the lists) break # If no other stars are in the list yet or no corresponding star was found (no break was # encountered), just add all stars of the current catalog else: number_of_new_stars += 1 # Inform the user #print("DEBUG: Adding star " + star_id + " at " + str(position.to_string("hmsdms"))) # Fill in the column lists catalog_column.append(catalog) id_column.append(star_id) ra_column.append(star_ra) dec_column.append(star_dec) ra_error_column.append(ra_error.value) dec_error_column.append(dec_error.value) confidence_level_column.append(1) # Debug messages log.debug("Number of stars that were in the catalog: " + str(number_of_stars)) log.debug("Number of stars that fell within the frame: " + str(number_of_stars_in_frame)) log.debug("Number of stars that were only present in this catalog: " + str(number_of_new_stars)) # Create and return the table data = [catalog_column, id_column, ra_column, dec_column, ra_error_column, dec_error_column, confidence_level_column] names = ['Catalog', 'Id', 'Right ascension', 'Declination', 'Right ascension error', 'Declination error', 'Confidence level'] # TODO: add magnitudes to the table ? #magnitude_column_names = [] #for band in magnitudes: # Values ##column = MaskedColumn(magnitudes[band], mask=[mag is None for mag in magnitudes[band]]) ##data.append(column) #data.append(magnitudes[band]) #column_name = band + " magnitude" #names.append(column_name) #magnitude_column_names.append(column_name) # Errors ##column = MaskedColumn(magnitude_errors[band], mask=[mag is None for mag in magnitude_errors[band]]) ##data.append(column) #data.append(magnitude_errors[band]) #column_name = band + " magnitude error" #names.append(column_name) #magnitude_column_names.append(column_name) # Create the catalog meta = {'name': 'stars'} catalog = tables.new(data, names, meta) # Set units catalog["Right ascension"].unit = "deg" catalog["Declination"].unit = "deg" catalog["Right ascension error"].unit = "mas" catalog["Declination error"].unit = "mas" #for name in magnitude_column_names: # self.catalog[name].unit = "mag" # Return the catalog return catalog
def get_galaxy_info(name, position): """ This function ... :param name: :param position: :return: """ # Obtain more information about this galaxy try: ned_result = Ned.query_object(name) ned_entry = ned_result[0] # Get a more common name for this galaxy (sometimes, the name obtained from NED is one starting with 2MASX .., use the PGC name in this case) if ned_entry["Object Name"].startswith("2MASX "): gal_name = name else: gal_name = ned_entry["Object Name"] # Get the redshift gal_redshift = ned_entry["Redshift"] if isinstance(gal_redshift, np.ma.core.MaskedConstant): gal_redshift = None # Get the type (G=galaxy, HII ...) gal_type = ned_entry["Type"] if isinstance(gal_type, np.ma.core.MaskedConstant): gal_type = None except astroquery.exceptions.RemoteServiceError: # Set attributes gal_name = name gal_redshift = None gal_type = None except astroquery.exceptions.TimeoutError: # Set attributes gal_name = name gal_redshift = None gal_type = None except: # Set attributes gal_name = name gal_redshift = None gal_type = None # Create a new Vizier object and set the row limit to -1 (unlimited) viz = Vizier(keywords=["galaxies", "optical"]) viz.ROW_LIMIT = -1 # Query Vizier and obtain the resulting table result = viz.query_object(name.replace(" ", ""), catalog=["VII/237"]) # Not found ... TODO: fix this ... this object was in the first query output if len(result) == 0: return name, position, None, None, [], None, None, None, None, None, None table = result[0] # Get the correct entry (sometimes, for example for mergers, querying with the name of one galaxy gives two hits! We have to obtain the right one each time!) if len(table) == 0: raise ValueError("The galaxy could not be found under this name") elif len(table) == 1: entry = table[0] else: entry = None # Some rows don't have names, if no match is found based on the name just take the row that has other names defined rows_with_names = [] for row in table: if row["ANames"]: rows_with_names.append(row) # If only one row remains, take that one for the galaxy we are looking for if len(rows_with_names) == 1: entry = rows_with_names[0] # Else, loop over the rows where names are defined and look for a match else: for row in rows_with_names: names = row["ANames"] if name.replace(" ", "") in names or gal_name.replace(" ", "") in names: entry = row break # If no matches are found, look for the table entry for which the coordinate matches the given position (if any) if entry is None and position is not None: for row in table: if np.isclose(row["_RAJ2000"], position.ra.value) and np.isclose(row["_DEJ2000"], position.dec.value): entry = row break # Note: another temporary fix if entry is None: return name, position, None, None, [], None, None, None, None, None, None # Get the right ascension and the declination position = SkyCoordinate(ra=entry["_RAJ2000"], dec=entry["_DEJ2000"], unit="deg", frame="fk5") # Get the names given to this galaxy gal_names = entry["ANames"].split() if entry["ANames"] else [] # Get the size of the galaxy ratio = np.power(10.0, entry["logR25"]) if entry["logR25"] else None diameter = np.power(10.0, entry["logD25"]) * 0.1 * Unit("arcmin") if entry["logD25"] else None #print(" D25_diameter = ", diameter) radial_profiles_result = viz.query_object(name, catalog="J/ApJ/658/1006") if len(radial_profiles_result) > 0: radial_profiles_entry = radial_profiles_result[0][0] gal_distance = radial_profiles_entry["Dist"] * Unit("Mpc") gal_inclination = Angle(radial_profiles_entry["i"], "deg") gal_d25 = radial_profiles_entry["D25"] * Unit("arcmin") else: gal_distance = None gal_inclination = None gal_d25 = None # Get the size of major and minor axes gal_major = diameter gal_minor = diameter / ratio if diameter is not None and ratio is not None else None # Get the position angle of the galaxy gal_pa = Angle(entry["PA"] - 90.0, "deg") if entry["PA"] else None # Create and return a new Galaxy instance return gal_name, position, gal_redshift, gal_type, gal_names, gal_distance, gal_inclination, gal_d25, gal_major, gal_minor, gal_pa