def query_for_source_coords(self, source_name): '''Queries NED or SIMBAD databases for coordinates using a source name. Args: source_name (str): source name to use for querying for coordinates ''' import astroquery from astroquery.ned import Ned try: coords = Ned.query_object(source_name) self.source_coords = SkyCoord('%s %s' % (coords['RA'][0], coords['DEC'][0]), unit=(u.deg, u.deg)) except astroquery.exceptions.RemoteServiceError: from astroquery.simbad import Simbad coords = Simbad.query_object(source_name) self.source_coords = SkyCoord('%s %s' % (coords['RA'][0], coords['DEC'][0]), unit=(u.hourangle, u.deg)) if not coords: raise astroquery.exceptions.RemoteServiceError( 'Both NED and SIMBAD queries failed for the provided source name. Maybe try supplying coordinates or selecting the source position interactively.' )
def get_ned_properties(self): """ This function ... :return: """ # Inform the user log.info("Querying the NASA/IPAC Extragalactic Database ...") # Search on NED ned_result = Ned.query_object(self.galaxy_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 = self.ngc_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 # Get the distance #ned_distance = ned_entry["Distance (arcmin)"] #if isinstance(ned_distance, np.ma.core.MaskedConstant): ned_distance = None # Set properties self.properties.common_name = gal_name self.properties.redshift = gal_redshift self.properties.galaxy_type = gal_type
def ned_query(ra, dec): # getting skycoordinate object co = coordinates.SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg), frame='icrs') search_radius = 0.01 * u.deg # this search radius is smaller than Fermi LAT resolution (please check) # get table with all objects inside the search radius result_table = Ned.query_region(co, radius=search_radius, equinox='J2000.0') result_table = Ned.query_object("NGC 224") print('names of the columns are ', result_table.colnames) print('to get an impression, here the whole table:') print(result_table) # get all the object names to get speific data object_names = result_table['Object Name'] print('identified objects = ', object_names) # get table with positions of the first object as an example: position_table = Ned.get_table(object_names[0], table='positions') # position table is something you normally don't need but might be interesting # This should always work' # print('position table: ', position_table) spectra = Ned.get_spectra("3c 273") return result_table, spectra
def fetch_object_by_name(name, radius): """ This function ... :param name: :param color: :param radius: :return: """ # Query the NED database for the object table = Ned.query_object(name) region_string = "# Region file format: DS9 version 3.0\n" region_string += "global color=green\n" # For every entry in the table for entry in table: # Get the right ascension and the declination ra = entry[2] dec = entry[3] #print coordinates.degrees_to_hms(ra=ra, dec=dec) # 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_size(gal): """ Search for largest size estimate on NED. """ try: result_table = Ned.query_object(gal) except: return 0 * u.arcsec ndiameters = result_table["Diameter Points"] if ndiameters > 0: diam = Ned.get_table(gal, table='diameters') try: units = [_ for _ in diam["Major Axis Unit"].data] except: units = [_.decode() for _ in diam["Major Axis Unit"].data] idx = [ i for i, un in enumerate(units) if un in ["arcmin", "arcsec", "degree"] ] if len(idx) > 0: diam = diam[idx] sizes = [ d["Major Axis"] * u.Unit(d["Major Axis Unit"]) for d in diam ] sizes = np.array([s.to("arcsec").value for s in sizes]) return np.nanmax(sizes) * u.arcsec return 0 * u.arcsec
def redshift_finder(objname): obj = objname[0] main_table = Ned.query_object(obj) redshift = main_table['Redshift'][0] NED_data.append(redshift) RA = main_table['RA(deg)'][0] NED_data.append(RA) DEC = main_table['DEC(deg)'][0] NED_data.append(DEC)
def find_NEDCoords(sourceNames, searchradius=1 * u.arcmin): Coords = [] for source in sourceNames: result_table = Ned.query_object(source) RA = result_table['RA'][0] * u.degree Dec = result_table['DEC'][0] * u.degree Coord = [SkyCoord(ra=RA, dec=Dec), searchradius] Coords.append(Coord) return Coords
def determine_redshift(self): if self.objectname!=None: try: table = Ned.query_object(self.objectname) self.z = table['Redshift'][0] except Exception as e: print "Could not determine redshift: ", e self.z = 0.0 if self.verbose: print "Using redshift z = ",self.z
def query_Simbad_NED(objname, z=np.nan): ''' Make use to astroquery to extract basic coordiantes/redshift information z: redshift. Normally NED query would give an answer. Provide z if NED answer is not satifying return: astropy SkyCoord object ''' import numpy as np from astroquery.simbad import Simbad from astroquery.ned import Ned from astropy.coordinates import SkyCoord import astropy.units as u from astropy.cosmology import Planck15 as cosmo sim = Simbad.query_object(objname) try: test1 = sim['RA'] except: print('Danger: %s cannot be recognized by Simbad, try other names.' % (objname)) return False try: ned = Ned.query_object(objname) except: print('Danger: %s cannot be recognized by NED, try other names.' % (objname)) return False galcoord = SkyCoord(ra=sim['RA'], dec=sim['DEC'], unit=(u.hour, u.deg), frame='icrs') if np.isfinite(z): gz = z else: gz = ned['Redshift'][0] scale_kpc_arcmin = cosmo.kpc_comoving_per_arcmin(gz) scale_pc_arcsec = scale_kpc_arcmin.to(u.pc / u.arcsec) print('Simbad: RA = %.4f deg ' % (galcoord.icrs.ra.deg), galcoord.icrs.ra) print('Simbad: DEC = %.4f deg ' % (galcoord.icrs.dec.deg), galcoord.icrs.dec) print('Simbad: l = %.4f deg, b = %.4f deg' % (galcoord.galactic.l.deg, galcoord.galactic.b.deg)) print('NED: z = %.4f; Input z = %.4f' % (ned['Redshift'], z)) print('Scale at z = %.4f: %.1f kpc/arcmin, %.1f pc/arcsec' % (gz, abs(scale_kpc_arcmin.value), abs(scale_pc_arcsec.value))) print('Returning astropy SkyCoord object...') return galcoord
def __init__(self, ob_name, object_name=""): self.ob_name = ob_name self.object_name = object_name if self.object_name == "": if self.ob_name[:-2] == "ESO137": self.object_name = "ESO137-G034" else: self.object_name = ob_name[:-2] ## ## TODO: need some error handling here! n=Ned.query_object(self.object_name) self.z=n['Redshift'].data.data[0] ## ## set some directories and files self.f_combined = os.getenv("XDIR")+'/combined/'+self.ob_name+'.fits' self.dir_starlight = os.getenv("HOME") + "/STARLIGHT" self.f_starlight_bc03 = self.dir_starlight + "/spectra/" + self.ob_name + ".txt" self.cfg_SL_infile=self.dir_starlight+"/infiles/"+self.ob_name+".in" self.dataset_definition = os.getenv("XDIR")+'/dataset_definition/'+self.ob_name+'.txt' d=ascii.read(self.dataset_definition) self.night=d['night'][0] ob_name_list=[d['object'][0],d['telluric'][0],d['flux'][0]] self.arms=["NIR","VIS","UVB"] self.dprlist=["SCI","TELL","FLUX"] self.dataset = Table(names=('dprtype', 'ob_name', 'arm', 'dpid'), dtype=(np.dtype((str,10)), np.dtype((str,20)), np.dtype((str,3)), np.dtype((str,29))), meta={'night': self.night}) conn=sqlite3.connect(os.getenv("OBSDB")) c=conn.cursor() for arm in self.arms: f_arm=self.dataset_definition.split('.txt')[0]+'_'+arm+'.txt' if os.path.isfile(f_arm): d_arm=ascii.read(f_arm,data_start=0,names=["ob","dpid"]) for ob,dpid,dpr in zip(d_arm["ob"],d_arm["dpid"],self.dprlist): self.dataset.add_row([dpr,ob,arm,dpid]) else: with open(f_arm,'w') as f: for ob,dpr in zip(ob_name_list,self.dprlist): query = "select arcfile from shoot where night=\"" + self.night + \ "\" and ob_name=\""+ ob + \ "\" and arm=\"" + arm + \ "\" and opti2_name=\"IFU\" limit 1;" c.execute(query) dpid=c.fetchone() self.dataset.add_row([dpr,ob,arm,dpid]) file_string=ob+" "+dpid[0]+"\n" f.write(file_string)
def from_query(cls, target, name=None): """Make SIMBAD data from an object query.""" from astroquery.ned import Ned if name is None: name = target.name t = Ned.query_object(name) r = t[0] ra = Angle(r['RA(deg)'], unit=u.deg).radian dec = Angle(r['DEC(deg)'], unit=u.deg).radian redshift = r['Redshift'] kind = r['Type'].decode("ascii") name = r['Object Name'].decode("ascii") return cls(target=target, ra=ra, dec=dec, name=name, kind=kind, redshift=redshift)
def query_ned_for_redshifts(name_dictionary, coordinate_dictionary): '''Query NED for redshifts based on target names''' print("\n\n =========== FINDING REDSHIFTS ========\n") # Instantiate an empty dictionary for redshifts redshift_dictionary = {} continued_failures = [] target_names = name_dictionary.values() for name in target_names: try: z = Ned.query_object(name)["Redshift"][0] redshift_dictionary["{}".format(name)] = z print("The NED redshift for {} is {}.".format(name, z)) except: print( "Cannot resolve redshift using NAME {}, trying coordinate search." .format(name)) z = Ned.query_region(coordinate_dictionary[name], radius=20 * u.arcsec, equinox='J2000.0')["Redshift"][0] # If this fails, it will silently set Z to a numpy.ma MaskedConstant (looks like '--') if np.ma.is_masked(z) is True: continued_failures.append(name) print( "Still cannot find a redshift for {}, skipping it.".format( name)) elif z < 1.0: # none of these sources are high redshift, this is a dumb sanity check: redshift_dictionary["{}".format(name)] = z print("{} is at RA={}, Dec={}. NED finds a redshift of {}.". format(name, coordinate_dictionary[name].ra, coordinate_dictionary[name].dec, z)) if len(continued_failures) > 0: print( "You need to manually fix these, which still cannot be resolved: ", continued_failures) print("In the meantime, they'll be skipped by the movie maker.") elif len(continued_failures) == 0: print("It SEEMS like all redshifts have successfully been found, ") print( "Here are your (hopefully) successful redshift identifications - check these!" ) print(" NAME = Z") for name, z in redshift_dictionary.items(): print(" {} = {}".format(name, z)) return redshift_dictionary
def redshift_ned(name): """Queries NED for heliocentric redshift if possible. `name` can be any string understood by Astroquery's NED module. """ try: from astroquery.ned import Ned except ImportError: raise try: z = Ned.query_object(name)['Redshift'] except: raise ValueError('Object not found') return z
def GC_Query(ObsID): #print "ObsID: ", ObsID Gname=Gname_Query(ObsID) #print "Gname: ", Gname #print "ObsID: ", ObsID if(Gname=="Error"): print "Error Gname: ", Gname #return "Error","Error" return np.nan,np.nan try: #print "NED Gname: ", Gname G_Data= Ned.query_object(Gname) #G_Data:-astropy.table.table.Table, Galaxy_Data, The Galaxy Data Table queried from NED except: Gname=Gname_Query(ObsID,NED_Resolved_Bool=True) #print "NED Gname: ", Gname G_Data= Ned.query_object(Gname) #G_Data:-astropy.table.table.Table, Galaxy_Data, The Galaxy Data Table queried from NED #print G_Data try: raGC=float(G_Data['RA(deg)']) decGC=float(G_Data['DEC(deg)']) except: raGC=float(G_Data['RA']) decGC=float(G_Data['DEC']) return raGC, decGC
def Known_Flux_Finder(gname,evtfname,PIMMSfname): G_Data = Ned.query_object(gname) #G_Data:-astropy.table.table.Table, Galaxy_Data, The queryed data of the galaxy from NED in the form of a astropy table #print G_Data #print type(G_Data) raGC=float(G_Data['RA(deg)']) #raGC:-float, Right Ascension of Galatic Center, The right ascension of the galatic center of the current galaxy in degrees. decGC=float(G_Data['DEC(deg)']) #decGC:-float, Declination of Galatic Center, The declination of the galatic center of the current galaxy in degrees. dmcoords(infile=str(evtfname),ra=str(raGC), dec=str(decGC), option='cel', verbose=0, celfmt='deg') # Runs the dmcoords CIAO tool, which converts coordinates like CHIP_ID to SKY, the tool is now being used to convert the RA and Dec of the GC to SKY coodinates in pixels (?) X_Phys=dmcoords.x #X_Phys:-float, X_Physical, The sky plane X pixel coordinate in units of pixels of the galatic center Y_Phys=dmcoords.y #Y_Phys:-float, Y_Physical, The sky plane Y pixel coordinate in units of pixels of the galatic center Chip_ID=dmcoords.chip_id #Chip_ID:-int, Chip_ID, The Chip ID number the GC is on hdulist = fits.open(evtfname) Obs_Date_Str=hdulist[1].header['DATE-OBS'] #print Obs_Date_Str #print type(Obs_Date_Str) Obs_Date_L=Obs_Date_Str.split("-") #print Obs_Date_L Obs_Year_Str=Obs_Date_L[0] Obs_Year=int(Obs_Year_Str) PIMMS_A=pd.read_csv('~/Desktop/PIMMS/'+PIMMSfname) #print PIMMS_A Cycle_A=PIMMS_A['Cycle'] #print Cycle_A Year_A=PIMMS_A['Year'] #print Year_A ACIS_I_A=PIMMS_A['ACIS-I(erg/cm**2/s)'] #print ACIS_I_A ACIS_S_A=PIMMS_A['ACIS-S(erg/cm**2/s)'] #print ACIS_S_A Year_L=list(Year_A) #print Year_L #Obs_Year=2006 #This is a test value for i in range(0,len(Year_L)): #print i if(Year_L[i]==Obs_Year): Row_Inx=i break #print Row_Inx #if((Chip_ID==3) or (Chip_ID==7)): #For Front illuminated? #Chip_ID=0 #This is a test value if(Chip_ID<4): Flux_A=ACIS_I_A if(Chip_ID>=4): Flux_A=ACIS_S_A #print Flux_A Flux=Flux_A[Row_Inx] return Flux
def query_name(name, verbose=False, print_header=False): """ Query NED by source name. """ try: q = Ned.query_object(name) objname = q["Object Name"][0] objtype = q["Type"][0].decode("utf-8") ra = q["RA(deg)"][0] dec = q["DEC(deg)"][0] velocity = q["Velocity"][0] z = q["Redshift"][0] z_flag = q["Redshift Flag"][0].decode("utf-8") refs = q["References"][0] notes = q["Notes"][0] except RemoteServiceError: objname = None objtype = None ra = None dec = None velocity = None z = None z_flag = None refs = None notes = None if verbose: print("*** %s: not found ***" % name, file=sys.stderr) # results = OrderedDict([ ("Name", name), ("NED_Name", objname), ("Type", objtype), ("RA", ra), ("DEC", dec), ("Velocity", velocity), ("z", z), ("z_Flag", z_flag), ("References", refs), ("Notes", notes), ]) if verbose: if print_header: print(",".join(results.keys())) print(",".join([str(v) for v in results.values()])) return results
def queryNED(name): """ queryNED(): Return information on a galaxy from a NED Query Note: This is now simply a wrapper around astroquery.ned. Arguments name: galaxy name Returns: dictionary with: - Cordinates (J2000) - redshift - nans for angular size (not provided in this short NED query) """ from astroquery.ned import Ned try: res = Ned.query_object(name)[0] except RemoteServiceError: _sys.stderr.write(name + " not found in NED.\n") return out 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: out['RA'] = res['Ra(deg)'] * u.deg out['Dec'] = res['Dec(deg)'] * u.deg except: _sys.stderr.write('Error: coordinates not available for ' + name + "\n") try: out['z'] = res['Redshift'] except: _sys.stderr.write('Error: redshift not available for ' + name + "\n") return out
def ned_query(ra, dec): # getting skycoordinate object co = coordinates.SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg), frame='icrs') search_radius = 0.01 * u.deg # this search radius is smaller than Fermi LAT resolution (please check) # get table with all objects inside the search radius result_table = Ned.query_region(co, radius=search_radius, equinox='J2000.0') result_table = Ned.query_object("NGC 224") print('names of the columns are ', result_table.colnames) print('to get an impression, here the whole table:') print(result_table) # get all the object names to get speific data object_names = result_table['Object Name'] print('identified objects = ', object_names) # get table with positions of the first object as an example: position_table = Ned.get_table(object_names[0], table='positions') # position table is something you normally don't need but might be interesting # This should always work' # print('position table: ', position_table) # now the redshift is for many sources not available,will give you an error # therefore we will use try and exept for specific_object in object_names: try: redshift_table = Ned.get_table(specific_object, table='redshifts') print('redshift found four ', specific_object) print(redshift_table) except: print('no redshift for ', specific_object) return result_table
def query_name(objname, verb=0): """ Query NED based on an object name (e.g., host galaxy name) Inputs: objname (str): name of object verb (int or bool, optional): vebrose output? default: False Outputs: ned_table: table of query results """ if verb: print('\tsending query for %s...' % objname) try: results = Ned.query_object(objname) if verb: print('\tcomplete') except: if verb: print('Object name query failed for object: %s' % objname) results = None sleep(1) return results
def queryNED(names,cat): ''' takes a list of names, queries them in NED and returns the 'Object Name' from the NED query results. ''' ned_names = [] if cat == 'bzb': failstr = '---bzcat---' elif cat == 'fermi': failstr = '---fermi---' else: failstr = '---' for name in names: try: ned_query = Ned.query_object(name) ned_names.append(ned_query["Object Name"][0]) except: ned_names.append(failstr) return ned_names
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"
def get_redshift(objname): """ Fetch redshift of the sample from the NED. Input ----- objname: str Name of the object (sample). Output ------ redshift: float64 The redshift. """ try: obj_table = Ned.query_object(objname) redshift = obj_table['Redshift'].data # get redshift redshift = float(redshift.data) except astroquery.exceptions.RemoteServiceError: print("Something wrong when feching %s." % objname) return -1 return redshift
dec = float(t[t.find(', Dec') + 7:t.find(')')]) if not cfg.quiet: print("Found LAT LC for {:20s}".format(name + ":"), end="") if cfg.no_ned: print() else: print("Now quering NED...", end="", flush=True) # Now query NED... if cfg.no_ned: z = 0 else: try: q = Ned.query_object(name) nedz = q['Redshift'] if nedz.mask: # True if invalid/data missing (i.e. redshift missing) z = 0.0 if not cfg.quiet: print("found! no z!, assigning 0.0") else: z = float(nedz) if not cfg.quiet: print("found! z=", z) except RemoteServiceError: # i.e. object not found if not cfg.quiet: print("not found! assigning z=-1") z = -1 except TimeoutError: if not cfg.quiet: print("timeout error contacting NED!") z = 0.0 # print("Filtering", name, end="")
def Area_Calc_Frac_B_2_Alt_2(gname,evtfname,polyfname,rchange=121.9512195,B=1): #NEED to finish this code, Check to see if the radius is increaing correctly and write outputs to a file """ gname:-str, Galaxy Name, The name of the galaxy in the form NGC #, For Example 'NGC 3077' evtfname:-str, Event File Name, The name of the event file of the observation, For Example 'acisf02076_repro_evt2.fits' ployfname:-str, PolyFileName, The filename of the simple_region_modifed file as a string rchange:-int(float?), Radius Change, The change in radius from one area cirlce to another area cirlce in pixels, must equal one arcminute in pixels B:-int, Binning, The binning on the regArea CIAO tool, It's standard value is 1 pixel """ inner_r=0.0 #inner_r:-float, Inner_Radius, The radius of the inner most circle #outer_r_gap=25.0 #outer_r_gap:-float, Outer_Radius_Gap, The addtional distance that needs to be added to the outer radius inorder to account for dithering #The addtional distance that needs to be added to the outer radius inorder to account for dithering outer_r_gap=40.0 #outer_r_gap:-float, Outer_Radius_Gap, The addtional distance that needs to be added to the outer radius inorder to account for dithering #The addtional distance that needs to be added to the outer radius inorder to account for dithering cur_r=inner_r #cur_r:-float?, Current_Radius, The current radius of the area circle in pixels n=1 #n:-int, n, the radius change multiplier, ie the the maximum n is the number of times the radius increases a_tot=0.0 #a_tot:-float, Area_Total, The total intersecting area of all the CCDs currently intersecting with the area circle a_L=[] #a_L:-list, Area_List, The list of Area Ratios for each n Evtfname_Reduced=evtfname.split(".")[0] #Evtfname_Reduced:-str, Event_Filename_Reduced, The filename of the event 2 file of the observation without the extention ".fits" at the end, for example "acisf02076_repro_evt2" Output_File=open(str(gname)+"_"+Evtfname_Reduced+"_Area_List.txt","w") #Output_File:-file, Output_File, The Area_List file, which is the file were the list of Area_Ratios one for each circle (ie. each n) are saved, in the form of one line per ratio polystring_L=[] #polystring_L:-list, Polygon String List, A list of all the CCD shape strings dir = os.path.dirname(__file__) #system('pwd') #system('cd ../..') #system('pwd') #path=os.path.realpath('../Polygons/'+str(polyfname)) path=os.path.realpath('../../Polygons/'+str(polyfname)) #path=os.path.realpath('../SQL_Standard_File/SQL_Sandard_File.csv') print "Path=",path #data = ascii.read(path) #polyfile=open("/home/asantini/Desktop/Polygons/"+str(polyfname),"r") #polyfile:-file, Polyfile, The polygon file that has the CCD shape strings in it #OLD polyfile=open(path,"r") #polyfile:-file, Polyfile, The polygon file that has the CCD shape strings in it #print type(polyfile) #print polyfile G_Data = Ned.query_object(gname) #G_Data:-astropy.table.table.Table, Galaxy_Data, The queryed data of the galaxy from NED in the form of a astropy table #print G_Data #print type(G_Data) raGC=float(G_Data['RA(deg)']) #raGC:-float, Right Ascension of Galatic Center, The right ascension of the galatic center of the current galaxy in degrees. decGC=float(G_Data['DEC(deg)']) #decGC:-float, Declination of Galatic Center, The declination of the galatic center of the current galaxy in degrees. dmcoords(infile=str(evtfname),ra=str(raGC), dec=str(decGC), option='cel', verbose=0, celfmt='deg') # Runs the dmcoords CIAO tool, which converts coordinates like CHIP_ID to SKY, the tool is now being used to convert the RA and Dec of the GC to SKY coodinates in pixels (?) X_Phys=dmcoords.x #X_Phys:-float, X_Physical, The sky plane X pixel coordinate in units of pixels of the galatic center Y_Phys=dmcoords.y #Y_Phys:-float, Y_Physical, The sky plane Y pixel coordinate in units of pixels of the galatic center Chip_ID=dmcoords.chip_id #Chip_ID:-int, Chip_ID, The Chip ID number the GC is on print "X_Phys ", X_Phys print "Y_Phys ", Y_Phys #Max_Min_Chip_Coord_L=[0,1024] #Max_Min_Chip_Coord_L=[1,1025] #dmkeypar acisf03931_repro_evt2.fits "DETNAM" #punlearn("dmkeypar") #This wipes the dmkeypar paramiter file #pset("dmkeypar",'hl') #This symtax is wrong #pset("dmkeypar", "mode", "hl") #pset("dmkeypar", "infile", str(evtfname)) #pset("dmkeypar", "keyword","DETNAM") """ pars = plist("dmkeypar") values = {} for p in pars: values[p] = pget( "dmkeypar", p ) print pars print values """ #dmkeypar(infile=str(evtfname), keyword="DETNAM") #Runs the dmkeypar tool which finds the data in the FITS header asscoiated with a certain header name, in this case dmkeypar is finding the "DETNAM" header info, which is a string containing what CCDs are used in the FOV1.fits file for the observation, For example "ACIS-356789" Chip_ID_String contains the chip IDs the string segment "356789" where each number in the list is its own CCD ID """ pars = plist("dmkeypar") values = {} for p in pars: values[p] = pget( "dmkeypar", p ) print pars print values """ """ This Par of the code finds what CCD's are used in the current observation by finding a string in the "DETNAM" header in the Event 2 file """ Header_String=dmlist(infile=str(evtfname),opt="header") #print Header_String Header_String_Reduced=Header_String.split("DETNAM")[1] #print Header_String_Reduced Header_String_Reduced_2=Header_String_Reduced.split("String")[0] #print Header_String_Reduced_2 Header_String_Reduced_3=Header_String_Reduced_2.replace(' ', '') print Header_String_Reduced_3 #dmkeypar(infile=str(evtfname), keyword="DETNAM") #pget(paramfile, paramname) #Chip_ID_String=pget(toolname="dmkeypar", parameter="value") #Chip_ID_String=pget("dmkeypar","value") #Chip_ID_String:-str, Chip_Idenifcation_String, Runs the pget tool to get the string containing what CCDs are used in the FOV1.fits file from the parameter file asscoiated with the dmkeypar tool and sets it equal to the Chip_ID_String (This) variable Chip_ID_String=Header_String_Reduced_3 #Chip_ID_String:-str, Chip_Idenifcation_String, Runs the pget tool to get the string containing what CCDs are used in the FOV1.fits file from the parameter file asscoiated with the dmkeypar tool and sets it equal to the Chip_ID_String (This) variable #Chip_ID_String=pget(toolname="dmkeypar", p_value="value") print "Chip_ID_String ", Chip_ID_String Chip_ID_String_L=Chip_ID_String.split('-') #Chip_ID_String_L:-List, Chip_Idenifcation_String_List, The resulting list from spliting the Chip_ID_String on "_", This list contains 2 elements, the first element is the string "ACIS" and the second element is the string segment in the form (Example) "356789" where each number in the list is its own CCD ID #print "Chip_ID_String_L ", Chip_ID_String_L Chip_ID_String_Reduced=Chip_ID_String_L[1] #Chip_ID_String_Reduced:-str, Chip_Idenifcation_String_Reduced, the string segment in the form (Example) "356789" where each number in the list is its own CCD ID print "Chip_ID_String_Reduced ", Chip_ID_String_Reduced Chip_ID_L=[] #Chip_ID_L:-List, Chip_Idenifcation_List, The list of all the int CCD IDs in FOV1.fits file for Cur_Chip_ID_Str in Chip_ID_String_Reduced: #Cur_Chip_ID_Str:-str, Current_Chip_Idenifcation_Str, The string vaule of the current string CCD ID in the Chip_ID_String_Reduced string, for example "3" Cur_Chip_ID=int(Cur_Chip_ID_Str) #Cur_Chip_ID:-int, Current_Chip_Idenifcation, The current chip ID number as an int, for example 3 Chip_ID_L.append(Cur_Chip_ID) #Appends The current chip ID number as an int to Chip_Idenifcation_List #print "Chip_ID_L ", Chip_ID_L """ This part of the code finds every distance between the Galatic Center and each corner of each CCD and puts them all into a list (Dist_L), The largest distance in Dist_L is the Outer_Radius """ #Max_Min_Chip_Coord_L=[0.0,1025.0] #Max_Min_Chip_Coord_L:-List, Maximum_Minimum_Chip_Coordinates_List, A list containing 2 elements the first of which is the lowest possble Chip value (X or Y) for the given Axis (in pixels) and the second is the largest possble Chip value (X or Y) for the given Axis. Since the CCDs on Chandra are square 1024 X 1024 pixel CCDs, the minimun and maximum Chip X values and Chip Y values are identical and therefore can be represented by this single list #Max_Min_Chip_Coord_L=[0,1025] #Max_Min_Chip_Coord_L:-List, Maximum_Minimum_Chip_Coordinates_List, A list containing 2 elements the first of which is the lowest possble Chip value (X or Y) for the given Axis (in pixels) and the second is the largest possble Chip value (X or Y) for the given Axis. Since the CCDs on Chandra are square 1024 X 1024 pixel CCDs, the minimun and maximum Chip X values and Chip Y values are identical and therefore can be represented by this single list Max_Min_Chip_Coord_L=[1,1024] #Max_Min_Chip_Coord_L:-List, Maximum_Minimum_Chip_Coordinates_List, A list containing 2 elements the first of which is the lowest possble Chip value (X or Y) for the given Axis (in pixels) and the second is the largest possble Chip value (X or Y) for the given Axis. Since the CCDs on Chandra are square 1024 X 1024 pixel CCDs, the minimun and maximum Chip X values and Chip Y values are identical and therefore can be represented by this single list #Max_Min_Chip_Coord_L=[0,1023] #Max_Min_Chip_Coord_L:-List, Maximum_Minimum_Chip_Coordinates_List, A list containing 2 elements the first of which is the lowest possble Chip value (X or Y) for the given Axis (in pixels) and the second is the largest possble Chip value (X or Y) for the given Axis. Since the CCDs on Chandra are square 1024 X 1024 pixel CCDs, the minimun and maximum Chip X values and Chip Y values are identical and therefore can be represented by this single list Dist_L=[] #Dist_L:-List, Distance_List, The list of every distance between the Galatic Center and each corner of each CCD for Chip_ID_Test in Chip_ID_L: #Chip_ID_Test:-int, Chip_Idenifcation_Test, The current test CCD were that four corners are being tested as the furthest point of the Galatic Center print "Chip_ID_Test ", Chip_ID_Test #print type(Chip_ID_Test) for Cur_Chip_X in Max_Min_Chip_Coord_L: #Cur_Chip_X:-float, Current_Chip_X, The chip X value of the current corner in pixels (Can be either 0.0 or 1025.0) #print type(Cur_Chip_X) for Cur_Chip_Y in Max_Min_Chip_Coord_L: #Cur_Chip_Y:-float, Current_Chip_Y, The chip Y value of the current corner in pixels (Can be either 0.0 or 1025.0) dmcoords(infile=str(evtfname),chipx=Cur_Chip_X, chipy=Cur_Chip_Y, chip_id=Chip_ID_Test, option='chip', verbose=0) #Runs dmcoords to convert the current CCD corner coordinates from CHIP coordinates to SKY coordinates #pars = plist("dmcoords") #values = {} #for p in pars: #values[p] = pget( "dmcoords", p ) #print pars #print values X_Phys_Test=dmcoords.x #X_Phys_Test:-float, X_Physical_Test, The X value current CCD corner being tested in SKY coordinates #print type(X_Phys_Test) Y_Phys_Test=dmcoords.y #Y_Phys_Test:-float, Y_Physical_Test, The Y value current CCD corner being tested in SKY coordinates print "Test Point CHIP ", [Cur_Chip_X,Cur_Chip_Y,Chip_ID_Test] print "Test Point SKY ", [X_Phys_Test,Y_Phys_Test] X_Phys_Diff=X_Phys-X_Phys_Test #X_Phys_Diff:-float, X_Physical_Difference, The differnce between the Galatic Center X value and the current chip corner X value Y_Phys_Diff=Y_Phys-Y_Phys_Test #Y_Phys_Diff:-float, Y_Physical_Difference, The differnce between the Galatic Center Y value and the current chip corner Y value Dist=np.sqrt(((X_Phys_Diff)**2)+((Y_Phys_Diff)**2)) #Dist:-numpy.float64, Distance, The distance between the Galatic Center and the current CCD Corner print "Dist ", Dist #print type(Dist) Dist_L.append(Dist) #Appends the current Distance to Distance_List #print "Dist_L ", Dist_L Dist_Max=max(Dist_L) #Dist_Max:-numpy.float64, Distance_Maximum, The distance between the Galatic Center and the furthest CCD Corner print "Dist_Max ", Dist_Max #print type(Dist_Max) outer_r=Dist_Max+outer_r_gap #outer_r:-numpy.float64, Outer_Radius, The largest radius of the area circle, this radius should just barely inclose the all the active CCDs for the observation (All the CCDs used in the FOV1.fits file) print "outer_r ", outer_r #print type(outer_r) polystring=polyfile.read() #polystring:-str, Polystring, The string containing the CCD shapes strings in it seperated by "\n" cur_polys_L=polystring.split("\n") #cur_polys_L:-List, Current_Polygons_List, The list of all the CCD Polygons (Simple Regions) strings for the observation, Since it is split on "\n" it is in the form ['Polystring_1','Polystring_2',...'Polystring_n',''], Example, ['box(4344.13761125,3924.99595875,5253.72685384,1088.14064223,-34.6522013895)', 'box(3728.26318125,2700.00581875,1086.83938437,1086.83938437,-34.6522013895)', ''], This has an extra element on the end that is a empty string needs to be removed from the list #print "cur_polys_L ", cur_polys_L del cur_polys_L[len(cur_polys_L)-1] #This deletes the last element containing the "" from the cur_polys_L #print "cur_polys_L ", cur_polys_L """ #This is for simple_region_no_header_modifed files for i in range(1,CCD_amt+1): #Splits up the polystring into the CCD shape strings cur_polys=polystring.split("\n")[i] #cur_polys:-str, Current Polystring, The current CCD shape string polystring_L.append(cur_polys) #polystring_L:-list, Polystring List, A list of all the CCD shape strings """ for cur_poly in cur_polys_L: #cur_poly:-str, Current_Polygon, The Current_Polygon string in Current_Polygons_List polystring_L.append(cur_poly) #Appends the Current_Polygon string to polystring_L while((cur_r)<=outer_r): #makes sure the largest area circle used is not larger then the outer radius outer_r cur_r=(n*rchange) + inner_r #increases the current radius by n times the change in radius shape1 ='circle(' + str(X_Phys) +','+ str(Y_Phys)+','+ str(cur_r)+')' #shape1:-str, shape1, The shape string of the current area circle r1 = regParse(shape1) #r1:-Region, Region 1, the region of the current area circle a_tot=0.0 #a_tot:-float, Area_Total, The total intersecting area of all the CCDs currently intersecting with the area circle a1_cur = regArea(r1,0,0,8192,8192,B) #a1_cur:-float, Area_1_Current, The area of the current area circle for s in polystring_L: #s:-str, String, the current CCD string shape2 =s #Renames "s" to "shape2" r2 = regParse(shape2) #r2:-region, Region 2, The region of the current CCD r3 = regParse(shape2 + "-" + shape1) #r3:-region, Region 3, The region of the current area circle that is NOT on the CCD cur_a= regArea(r2,0,0,8192,8192,B) - regArea(r3,0,0,8192,8192,B) #cur_a:-float, Current_Area, The area of the current CCD that is intersecting with the area circle (?) #print "Current Area is ", cur_a a_tot=a_tot+cur_a #Adds the intersecting area of the current CCD polygon to the total intersecting area of all previous the CCD polygons for the current radius (cur_r) #print "Area Total is ", a_tot #print "" #print "a_tot ", a_tot #When the previous area total is equal to the current area total the previous radius is greater then or equal to the maximum radius, this could be used to tell the code when to stop a_ratio=float(a_tot)/float(a1_cur) # a_ratio:-float, Area_Ratio, The ratio of the total intersecting area on the total area of the current area circle #print "Area Ratio is ", a_ratio a_L.append(a_ratio) #a_L:-list, Area_List, The list of Area Ratios for each n n=n+1 # Itterates n cur_r=(n*rchange) + inner_r #Increases the current radius by n times the change in radius for Current_Ratio in a_L: #Current_Ratio:-float, Current_Ratio, The Current_Ratio of the total intersecting area on the total area of the current area circle in a_L #print type(Current_Ratio) Current_Ratio_Str=str(Current_Ratio) #Current_Ratio_Str:-Str, Current_Ratio_String, The Current_Ratio as a string value Current_Ratio_Str_New_Line=Current_Ratio_Str+"\n" #Current_Ratio_Str_New_Line:-str, Current_Ratio_String_New_Line, The Current_Ratio_String with a "\n" at the end of the string to make sure that each line in the output file contains only one Area_Ratio Output_File.write(Current_Ratio_Str_New_Line) #Writes the Current_Ratio_String_New_Line to the Output_File return a_L #Returns the Area List #May not be nessary
def Source_Histogram_Plot(Gname, Fileout_B=True, Outpath=False): """ Gname: str- The name of the galaxy in the form NGC # Data: array- a table of data containg the coordinates of each object This fucntion takes the inputs for the name of the galaxy and returns a histrogram that plots the number of objects per bin by the area enclosed by the cirlce centered on the center of the galaxy that inculdes the objects in each bin in square degrees divided by the visible area of the galaxy in square degrees. This function plots the visible Major axis of the galaxy area enclosed by a circle that uses the Major axis as the diameter of the cirlce divided by itself to give 1 on histogram. This function uses astroquary to get data directly from NED #THIS IS THE CURRENT RUNNING VERSION OF THIS CODE """ Gname_Modifed = Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) import math from astropy.io import ascii import matplotlib.pyplot as plt #system('pwd') #system('cd ~/Desktop/SQL_Standard_File/') #import os dir = os.path.dirname(__file__) #filename= os.path.join(dir, '~','Desktop','SQL_Standard_File',) #filepath=os.path.abspath("~/Desktop/SQL_Standard_File") #print "Filepath =",filepath #path= os.path.join(dir,'~','Desktop','SQL_Standard_File',) #path=os.path.realpath('~/Desktop/SQL_Standard_File/SQL_Sandard_File.csv') #path=os.path.realpath('../SQL_Standard_File/SQL_Standard_File.csv') #path=os.path.realpath('../SQL_Standard_File/Source_Flux_Table.csv') #To Do: Update this path #path=os.path.realpath('../../../SQL_Standard_File/Source_Flux_Table.csv') #To Do: Update this path #path="/Volumes/xray/anthony/Research_Git/SQL_Standard_File/Source_Flux_Table.csv" #THIS CSC FILE DOES NOT HAVE ALL THE SOURCES ! ! ! IT IS WRONG ! ! ! #print "Path=",path #os.chdir(path) #os.chdir('~/Desktop/SQL_Standard_File/') #system('cd ~/Desktop/Big_Object_Regions/') #system('cd ../SQL_Standard_File/') #system('pwd') #system('ls') #data = ascii.read("SQL_Sandard_File.csv") #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data = ascii.read(filename) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data = ascii.read(filepath) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File Evt2_File_H_L = File_Query_Code_5.File_Query(Gname, "evt2") #print "Evt2_File_H_L : ", Evt2_File_H_L if (Evt2_File_H_L == False): print "Invalid Galaxy" return Galaxy_Obs_ID_L = [] for Evt2_File_L in Evt2_File_H_L: Cur_Galaxy_Obs_ID = Evt2_File_L[0] Galaxy_Obs_ID_L.append(Cur_Galaxy_Obs_ID) """ data = ascii.read(path) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data2=open("SQL_Sandard_File.csv","r") #print data2 #system('cd ~/Desktop/galaxies/out') RA_A=data['sourceRA'] #RA_A:-astropy.table.column.Column, Right_Ascension_Array, The array containing all Right Ascensions in the SQL Standard File #print type(RA_A) RA_L=list(RA_A) #RA_L:-list, Right_Ascension_List, The list containing all Right Ascensions in the SQL Standard File #print RA_L RA_A_Arcmin=RA_A*60.0 Dec_A=data['sourceDec'] #Dec_A:-astropy.table.column.Column, Declination_Array, The array containing all Declinations in the SQL Standard File Dec_L=list(Dec_A) #Dec_L:-List, Declination_List, The list containing all Declinations in the SQL Standard File Dec_A_Arcmin=Dec_A*60.0 #print Dec_L #Obs_ID_A=data["obsid"] #Obs_ID_A:-astropy.table.column.Column, Observation_Idenification_Array, The array containing all Observation IDs in the SQL_Standard_File (not indexable) #print type(Obs_ID_A) #Obs_ID_L=list(Obs_ID_A) #Obs_ID_L:-List, Observation_Idenification_List, The list containing all Observation IDs in the SQL_Standard_File (So it is indexable) Obs_ID_A=data["OBSID"] #Obs_ID_A:-astropy.table.column.Column, Observation_Idenification_Array, The array containing all Observation IDs in the SQL_Standard_File (not indexable) #print type(Obs_ID_A) Obs_ID_L=list(Obs_ID_A) #Obs_ID_L:-List, Observation_Idenification_List, The list containing all Observation IDs in the SQL_Standard_File (So it is indexable) #print "Obs_ID_L ", Obs_ID_L """ #for Obs_ID in Galaxy_Obs_ID_L: for Evt2_File_L in Evt2_File_H_L: Obs_ID = Evt2_File_L[0] Evtfpath = Evt2_File_L[1] Evtfname = Evtfpath.split("/")[-1] Evtfname_Reduced = Evtfname.split(".")[0] print "Evtfname_Reduced: ", Evtfname_Reduced Area_L_Path = "/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/" + Gname_Modifed + "/Area_Lists/" + str( Obs_ID ) + "/" + Gname_Modifed + "_" + Evtfname_Reduced + "_Area_List.txt" Area_File = open(Area_L_Path, "r") Area_Str = Area_File.read() Area_File.close() Area_L = Area_Str.split("\n") #print " Area_L Before: ", Area_L Area_L.pop() print "Area_L: ", Area_L Area_L_Float = [] for Area in Area_L: Area_Float = float(Area) Area_L_Float.append(Area_Float) Area_L = Area_L_Float #print type(Obs_ID_L) #print Obs_ID_A #FGname_A=data["foundName"] #FGname_L=list(FGname_A) #print FGname_A #QGname_A=data["queriedName"] #QGname_A:-Obs_ID_A:-astropy.table.column.Column, Query_Galaxy_Name_Array, The array containing all Query Galaxy Names in the SQL_Standard_File (not indexable) """ QGname_A=data["resolvedObject"] #QGname_A:-Obs_ID_A:-astropy.table.column.Column, Query_Galaxy_Name_Array, The array containing all Query Galaxy Names in the SQL_Standard_File (not indexable) QGname_L=list(QGname_A) #QGname_L:-List, Query_Galaxy_Name_Array, The list containing all Query Galaxy Names in the SQL_Standard_File (So it is indexable) #print type(QGname_A) #print QGname_A Matching_Index_List=[] #Matching_Index_List:-List, Matching_Index_List, The list of all indexes (ref. QGname_L) that corresepond to the input Galaxy Name, All arrays are of equal lenth, and "ith" value of an array is the correseponding value for any other arrays "ith" value, so for example Obs_ID_L[228]=794 and the Galaxy in the Observation is QGname_L[228]="NGC 891", Note both lists have the same index for i in range(0,len(QGname_L)): # i:-int, i, the "ith" index of QGname_L #print "i ", i QGname=QGname_L[i] #QGname:-string, Query_Galaxy_Name, The current test Galaxy Name, if this Galaxy name equals the input Galaxy Name (Gname) then this Matching_Index, i (ref. QGname_L) will be appended to the Matching_Index_List #QGname_Reduced=QGname.replace(" ", "") #print "QGname ", QGname #print "QGname_Reduced ", QGname_Reduced if(Gname==QGname): #Checks to see if the current test Galaxy Name is the same as the input Galaxy Name, if so it appends the current index (ref. QGname_L) to the Matching_Index_List #print "i ", i Matching_Index_List.append(i) #Appends the current index (ref. QGname_L) to the Matching_Index_List """ """ Matching_Index_List=[] #Matching_Index_List:-List, Matching_Index_List, The list of all indexes (ref. QGname_L) that corresepond to the input Galaxy Name, All arrays are of equal lenth, and "ith" value of an array is the correseponding value for any other arrays "ith" value, so for example Obs_ID_L[228]=794 and the Galaxy in the Observation is QGname_L[228]="NGC 891", Note both lists have the same index #Matching_Obs_ID_List=[] #Matching_Obs_ID_List:-List, Matching_Obs_ID_List, The list of all ob for i in range(0,len(Obs_ID_L)): # i:-int, i, the "ith" index of QGname_L #print "i ", i QObs_ID=Obs_ID_L[i] #QGname:-string, Query_Galaxy_Name, The current test Galaxy Name, if this Galaxy name equals the input Galaxy Name (Gname) then this Matching_Index, i (ref. QGname_L) will be appended to the Matching_Index_List #QGname_Reduced=QGname.replace(" ", "") #print "QGname ", QGname #print "QGname_Reduced ", QGname_Reduced if(Obs_ID==QObs_ID): #Checks to see if the current test Galaxy Name is the same as the input Galaxy Name, if so it appends the current index (ref. QGname_L) to the Matching_Index_List #print "i ", i Matching_Index_List.append(i) #Appends the current index (ref. QGname_L) to the Matching_Index_List RA_Match_L=[] #RA_Match_L:-List, Right_Ascension_Match_List, The list of all source RA's for the input Galaxy Name in decimal degrees Dec_Match_L=[] #Dec_Match_L:-List, Declination_Match_List, The list of all source Dec's for the input Galaxy Name in decimal degrees for Cur_Matching_Index in Matching_Index_List: #Cur_Matching_Index:-int, Current_Matching_Index, The current index (ref. QGname_L) in the list of matching indexes for the current input Galaxy Name (Matching_Index_List) Cur_Match_RA=RA_L[Cur_Matching_Index] #Cur_Match_RA:-numpy.float64, Current_Match_Right_Ascension, The RA of the current source in decimal degrees #print type(Cur_Match_RA) Cur_Match_Dec=Dec_L[Cur_Matching_Index] #Cur_Match_Dec:-numpy.float64, Current_Match_Declination, The Dec of the current source in decimal degrees RA_Match_L.append(Cur_Match_RA) #RA_Match_L:-list, Right_Ascension_Match_List, The list of all source RA's for the input Galaxy Name in decimal degrees Dec_Match_L.append(Cur_Match_Dec) #Dec_Match_L:-list, Declination_Match_List, The list of all source Dec's for the input Galaxy Name in decimal degrees """ #print RA_Match_L #print len(RA_Match_L) #print Dec_Match_L #print len(Dec_Match_L) #decA=Data['dec'] #raA=Data['ra'] #Maj=Maj/3600 #S_Maj=Maj/2 #area_T=((S_Maj)**2)*math.pi G_Data = Ned.query_object( Gname ) #G_Data:-astropy.table.table.Table, Galaxy_Data, The Galaxy Data Table queried from NED #print "G_Data : \n",G_Data #print type(G_Data) #/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/MESSIER_066/Coords_Lists/9548 #MESSIER_066_ObsID_9548_Coords.csv Coords_Path = "/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/" + Gname_Modifed + "/Coords_Lists/" + str( Obs_ID) + "/" + Gname_Modifed + "_ObsID_" + str( Obs_ID) + "_Coords.csv" Coords_Table = pd.read_csv(Coords_Path) #print "Coords_Table: \n",Coords_Table #Phys_X,Phys_Y,Chip_X,Chip_Y,Chip_ID,RA,DEC,Offaxis_Angle #Dec_Match_L,RA_Match_L RA_Match_Deg_DF = Coords_Table["RA"] #In decimal degrees RA_Match_Deg_L = list(RA_Match_Deg_DF) RA_Match_DF = RA_Match_Deg_DF * 60.0 #In units of arcmins #print "RA_Match_DF :\n", RA_Match_DF RA_Match_L = list(RA_Match_DF) #print "RA_Match_L :\n", RA_Match_L Dec_Match_Deg_DF = Coords_Table["DEC"] #In decimal degrees Dec_Match_Deg_L = list(Dec_Match_Deg_DF) Dec_Match_DF = Dec_Match_Deg_DF * 60.0 #In units of arcmins Dec_Match_L = list(Dec_Match_DF) #print "Dec_Match_L :\n", Dec_Match_L #return "STOPPING PROGRAM" """ Dia_Table = Ned.get_table(Gname, table='diameters') #Dia_Table:-astropy.table.table.Table, Diameter_Table, The Data table queried from NED that contains the infomation about the Major Axis of the input Galaxy Name #print type(Dia_Table) #print G_Data #print Dia_Table #print Dia_Table.colnames #print Dia_Table.meta #print Dia_Table.columns Dia_Table_Feq=Dia_Table['Frequency targeted'] #Dia_Table_Feq:-astropy.table.column.MaskedColumn, Diameter_Table_Fequency, The Array containing all named frequencies of light that are being used for the Major Axis Measurement #print Dia_Table['NED Frequency'] #print Dia_Table_Feq #print type(Dia_Table_Feq) Dia_Table_Feq_L=list(Dia_Table_Feq) #Dia_Table_Feq_L:-List, Diameter_Table_Fequency_List, The list containing all named frequencies of light that are being used for the Major Axis Measurement #print Dia_Table_Feq_L Dia_Table_Num=Dia_Table['No.'] #Dia_Table_Num:-astropy.table.column.MaskedColumn, Diameter_Table_Number, The number Ned assigns to #print Dia_Table_Num #print type(Dia_Table_Num) Dia_Table_Num_L=list(Dia_Table_Num) #print Dia_Table_Num_L for i in range(0,len(Dia_Table_Feq_L)-1): #There is a bug here with index matching, The matched index isn't that same index for the major axis Cur_Feq=Dia_Table_Feq_L[i] #print Cur_Feq if(Cur_Feq=="RC3 D_25, R_25 (blue)"): Match_inx=i Match_Feq=Dia_Table_Feq_L[Match_inx] Match_Num=Dia_Table_Num_L[Match_inx] #Match_Num #print "Match_Feq ", Match_Feq #print "Match_inx ", Match_inx #print "Match_Num ", Match_Num #Dia_Table_Maj=Dia_Table['Major Axis'] Dia_Table_Maj=Dia_Table['NED Major Axis'] #print Dia_Table_Maj Dia_Table_Maj_L=list(Dia_Table_Maj) #print Dia_Table_Maj_L Dia_Table_Maj_Units=Dia_Table['Major Axis Unit'] #print Dia_Table_Maj_Units Dia_Table_Maj_Units_L=list(Dia_Table_Maj_Units) #print Dia_Table_Maj_Units_L #print "i ", i D25_Maj=Dia_Table_Maj_L[Match_inx] #print "D25_Maj ", D25_Maj D25_Units=Dia_Table_Maj_Units[Match_inx] #print "D25_Units ", D25_Units #print type(Dia_Table) #print Dia_Table.info() #Dia_Table_2=Dia_Table[6] #print Dia_Table_2 #Maj=Dia_Table_2[18] #print "Maj, ! ! !", Maj D25_S_Maj=D25_Maj/2.0 D25_S_Maj_Deg=D25_S_Maj/3600.0 """ #print "Area Matching_Index_List : ", Matching_Index_List D25_S_Maj_Deg = D25_Finder.D25_Finder(Gname) D25_S_Maj_Arcmin = D25_S_Maj_Deg * 60.0 area_T = ((D25_S_Maj_Deg)**2) * math.pi try: raGC = float(G_Data['RA(deg)']) decGC = float(G_Data['DEC(deg)']) except: raGC = float(G_Data['RA']) decGC = float(G_Data['DEC']) #area_A=[((((((decGC-dec)**2)+((raGC-ra)**2)))*(math.pi))/area_T) for dec,ra in zip(decA,raA)] area_A = [ ((((((decGC - dec)**2) + ((raGC - ra)**2))) * (math.pi)) / area_T) for dec, ra in zip(Dec_Match_Deg_L, RA_Match_Deg_L) ] #REAL ONE #disA=[math.sqrt(((decGC-dec)**2)+((raGC-ra)**2)) for dec,ra in zip(decA,raA)] #REAL ONE #print area_A #area_max=max(area_A) #print area_max #plt.vlines(0.00001,0,10,color='red') #plt.vlines(1,0,10,color='red') #plt.hist(area_A) Hist_A = plt.hist(area_A) Bin_Hight_A = Hist_A[0] Bin_Hight_Max = max(Bin_Hight_A) #print Bin_Hight_Max plt.vlines(1, 0, Bin_Hight_Max, color='red') plt.xlabel('A') plt.ylabel('N') #Hist_Max=max(area_A) #print "Hist_Max ", Hist_Max Flux_90_Path = "/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/" + Gname_Modifed + "/Flux_90_Files/" + str( Obs_ID) + "/" + Gname_Modifed + "_ObsID_" + str( Obs_ID) + "_Flux_90.txt" BG_Source_HL = Background_Sources_Calc.Big_Background_Source_Calc( Flux_90_Path) if ( BG_Source_HL == False ): #Rejects current observation if it's liminiting flux was never calculated due to it's background being about of range of the 4D Graph Data interpolation continue #print "BG_Source_HL : ", BG_Source_HL BG_Source_Sum_Area_L = BG_Source_HL[4] BG_Source_Sum_Frac_L = [] for Sum_Area in BG_Source_Sum_Area_L: Sum_Frac = Sum_Area / area_T BG_Source_Sum_Frac_L.append(Sum_Frac) #BG_Source_Sum_N_L=BG_Source_HL[5] BG_Source_L = BG_Source_HL[3] #print "BG_Source_Sum_Frac_L : ", BG_Source_Sum_Frac_L #print "BG_Source_L : ", BG_Source_L plt.step(BG_Source_Sum_Frac_L, BG_Source_L) plt.plot() #plt.savefig('Test1.png') #path_2=os.path.realpath('../Master_Code/Master_Output/') #Goes to Master_Output folder, which will hold all the data calculated for the galaxies including the histogram pictures path_2 = os.path.realpath('./Source_Overdensity_Histograms/') if (Outpath != False): path_2 = Outpath #print "Path_2=", path_2 """ path_Hist=path_2+'/Histograms/' directory_Hist=os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=",path_Hist os.chdir(path_Hist) """ #system('mkdir '+Gname) #Creates Current Galaxy's Folder, Folder Named after Galaxy, Note: will have to remove space from "NGC #" to change to "NGC_#", I Don't know if this works """ Gname_L=Gname.split(" ") print "Gname_L: ", Gname_L if(len(Gname_L)>1): Gname_Modifed=Gname_L[0]+"_"+Gname_L[1] #Adds underscore to remove space from "NGC #" to change to "NGC_#" if there is a space in the name else: Gname_Modifed=Gname # Does nothing if the galaxy name has no space, ie. NGC#, For example NGC253 instead of NGC 253 or NGC_253 """ #Gname_Modifed=Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) #print Gname_Modifed path_3 = path_2 + '/' + Gname_Modifed + '/' directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) #os.chdir(path_3) #Goes to Current Galaxies Folder path_Hist = path_3 + 'Histograms/' directory_Hist = os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=", path_Hist #os.chdir(path_Hist) path_Obs_ID = path_Hist + str(Obs_ID) + '/' directory_Obs_ID = os.path.dirname(path_Obs_ID) if not os.path.exists(directory_Obs_ID): os.makedirs(directory_Obs_ID) plt.savefig(path_Obs_ID + Gname_Modifed + '_' + str(Obs_ID) + '_Frac.png') #Saves angluar histogram figure #system('pwd') #path_4=os.path.realpath('../../../../Histogram_Code/') #print "Path_4=",path_4 #os.chdir(path_4) #Goes back to where this code (the histogram code) is being run, ie. Desktop/GitHub plt.close() #plt.show() #For Area Histrograms raGC_Arcmin = raGC * 60.0 decGC_Arcmin = decGC * 60.0 ''' RA_A_Arcmin=RA_A*60.0 RA_L_Arcmin=list(RA_A_Arcmin) Dec_A_Arcmin=Dec_A*60.0 Dec_L_Arcmin=list(Dec_A_Arcmin) #print "Distance Matching_Index_List : ", Matching_Index_List RA_Match_L=[] Dec_Match_L=[] for Cur_Matching_Index in Matching_Index_List: #Cur_Matching_Index:-int, Current_Matching_Index, The current index (ref. QGname_L) in the list of matching indexes for the current input Galaxy Name (Matching_Index_List) """ Cur_Match_RA=RA_L[Cur_Matching_Index] #Cur_Match_RA:-numpy.float64, Current_Match_Right_Ascension, The RA of the current source in decimal degrees #print type(Cur_Match_RA) Cur_Match_Dec=Dec_L[Cur_Matching_Index] #Cur_Match_Dec:-numpy.float64, Current_Match_Declination, The Dec of the current source in decimal degrees """ Cur_Match_RA=RA_L_Arcmin[Cur_Matching_Index] #Cur_Match_RA:-numpy.float64, Current_Match_Right_Ascension, The RA of the current source in decimal degrees #print type(Cur_Match_RA) Cur_Match_Dec=Dec_L_Arcmin[Cur_Matching_Index] #Cur_Match_Dec:-numpy.float64, Current_Match_Declination, The Dec of the current source in decimal degrees RA_Match_L.append(Cur_Match_RA) #RA_Match_L:-list, Right_Ascension_Match_List, The list of all source RA's for the input Galaxy Name in decimal degrees Dec_Match_L.append(Cur_Match_Dec) #Dec_Match_L:-list, Declination_Match_List, The list of all source Dec's for the input Galaxy Name in decimal degrees #print "Dec_Match_L : ", Dec_Match_L #print "decGC_Arcmin : ", decGC_Arcmin ''' disA = [ math.sqrt(((decGC_Arcmin - dec)**2) + ((raGC_Arcmin - ra)**2)) for dec, ra in zip(Dec_Match_L, RA_Match_L) ] #REAL ONE in units of arcmins #print "disA : ", disA #dis_max=np.max(disA) #N_Bins_Float=dis_max/2.0 #N_Bins=int(round(N_Bins_Float)) #print "dis_max : ", dis_max #print area_A #area_max=max(area_A) #print area_max #plt.vlines(0.00001,0,10,color='red') #plt.vlines(1,0,10,color='red') #plt.hist(area_A) #Hist_A=plt.hist(disA,[0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0]) #Hist_A=plt.hist(disA,[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) #Hist_A=plt.hist(disA,[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) ##Hist_A=plt.hist(disA,range=(0.0,10.0)) #This is the correct plt.hist version used for the thesis Hist_A = np.histogram(disA, range=(0.0, 10.0)) #Hist_A=plt.hist(disA,N_Bins) #print "Angular Hist_A : ", Hist_A print "Hist_A : ", Hist_A Bin_Hight_A = Hist_A[0] Bin_Hight_A = np.array(Bin_Hight_A) print "Bin_Hight_A Before: ", Bin_Hight_A print "type(Bin_Hight_A) Before: ", type(Bin_Hight_A) print "type(Bin_Hight_A[0]) Before: ", type(Bin_Hight_A[0]) Bin_A = Hist_A[1] Area_A = np.array(Area_L) print "Area_A: ", Area_A print "type(Area_A): ", type(Area_A) print "type(Area_A[0]): ", type(Area_A[0]) Num_Observed_Sources_A = Bin_Hight_A Num_Missing_Sources_A = Num_Observed_Sources_A * ( (1.0 - Area_A) / Area_A) Bin_Hight_A = Bin_Hight_A * (1.0 + ((1.0 - Area_A) / Area_A)) print "Bin_Hight_A: ", Bin_Hight_A plt.bar([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], Num_Missing_Sources_A, align='edge', width=1.0, label='Missing', color='deepskyblue', bottom=Num_Observed_Sources_A) plt.bar([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], Num_Observed_Sources_A, align='edge', width=1.0, label='Observed', color='royalblue') ##Hist_Plot=plt.hist(Bin_Hight_A,range=(0.0,10.0)) ##plt.bar() Bin_Hight_Max = max(Bin_Hight_A) #print "Bin_Hight_Max : ", Bin_Hight_Max #/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/NGC_3631/Flux_90_Files/3951/NGC_3631_ObsID_3951_Flux_90.txt #Example Path #Flux_90_Path="/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/"+Gname_Modifed+"/Flux_90_Files/"+str(Obs_ID)+"/"+Gname_Modifed+"_ObsID_"+str(Obs_ID)+"_Flux_90.txt" #BG_Source_HL=Background_Sources_Calc.Big_Background_Source_Calc(Flux_90_Path) #print "BG_Source_HL : ", BG_Source_HL BG_Bins = BG_Source_HL[2] BG_Source_L = BG_Source_HL[3] #Hist_BG_A=plt.hist(BG_Source_L,[0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0],alpha=0.5) #Bar_BG_A=plt.bar([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L,color="red",alpha=0.5) #plt.plot([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L) #plt.step([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L) BG_Source_Plot_L = [0.0] for i in range(0, len(BG_Source_L) - 1): BG_Source_Plot_L.append(BG_Source_L[i]) print "BG_Source_L : ", BG_Source_L print "BG_Source_Plot_L : ", BG_Source_Plot_L #BG_Source_D25_Total_L=list(BG_Source_D25_Total_A) BG_Source_Plot_A = np.array(BG_Source_Plot_L) BG_Source_Sigificance_Plot_A = 3.0 * BG_Source_Plot_A BG_Source_Sigificance_Max = max(BG_Source_Sigificance_Plot_A) Plot_Max = max([Bin_Hight_Max, BG_Source_Sigificance_Max]) #plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_L) plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Plot_L, color="darkorange") ##plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_Plot_A,color="orange") #This version was used for the thesis plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_Plot_A, color="gold") #plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_Plot_A*3.0,color="gold") #This was used for the thesis but is not longer requried after the counts to flux bug fix as the number of sources are never this high #plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_Plot_A*3.0,color="goldenrod") #plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_Plot_A*5.0,color="gold") #BG_Bin_Hight= #print Bin_Hight_Max #plt.vlines(D25_S_Maj_Deg,0,Bin_Hight_Max,color='red') #Plots red line at D25 #plt.vlines(D25_S_Maj_Arcmin,0,Bin_Hight_Max,color='red') #Plots red line at D25 #Version used for thesis plt.vlines(D25_S_Maj_Arcmin, 0, Plot_Max, color='red') #Plots red line at D25 plt.xlabel('R (arcmin)') plt.ylabel('N') #print D25_S_Maj_Deg #Hist_Max=max(area_A) #print "Hist_Max ", Hist_Max plt.plot() #plt.savefig('Test2.png') #path_2=os.path.realpath('../Master_Code/Master_Output/') #Goes to Master_Output folder, which will hold all the data calculated for the galaxies including the histogram pictures, Quoted Out because path_2 is already defined #print "Path_2=", path_2 """ path_Hist=path_2+'/Histograms/' directory_Hist=os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=",path_Hist os.chdir(path_Hist) """ #system('mkdir '+Gname) #Creates Current Galaxy's Folder, Folder Named after Galaxy, Note: will have to remove space from "NGC #" to change to "NGC_#", I Don't know if this works """ Gname_L=Gname.split(" ") print "Gname_L: ", Gname_L if(len(Gname_L)>1): Gname_Modifed=Gname_L[0]+"_"+Gname_L[1] #Adds underscore to remove space from "NGC #" to change to "NGC_#" if there is a space in the name else: Gname_Modifed=Gname # Does nothing if the galaxy name has no space, ie. NGC#, For example NGC253 instead of NGC 253 or NGC_253 """ Gname_Modifed = Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) #print Gname_Modifed path_3 = path_2 + '/' + Gname_Modifed + '/' directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) #os.chdir(path_3) #Goes to Current Galaxies Folder path_Hist = path_3 + 'Histograms/' directory_Hist = os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) #print "path_Hist=",path_Hist #os.chdir(path_Hist) path_Obs_ID = path_Hist + str(Obs_ID) + '/' print "path_Obs_ID : ", path_Obs_ID directory_Obs_ID = os.path.dirname(path_Obs_ID) if not os.path.exists(directory_Obs_ID): os.makedirs(directory_Obs_ID) plt.savefig(path_Obs_ID + Gname_Modifed + '_' + str(Obs_ID) + '_Ang.png') #Saves angluar histogram figure #BG_Source_A=np.array(BG_Source_L) #system('pwd') #path_4=os.path.realpath('../../../../Histogram_Code/') #print "Path_4=",path_4 #os.chdir(path_4) #Goes back to where this code (the histogram code) is being run, ie. Desktop/GitHub plt.close() if (Fileout_B): O_R_fname = path_Obs_ID + Gname_Modifed + '_' + str( Obs_ID) + '_Overdensity_Ratios.txt' file = open(O_R_fname, "w") print "O_R_fname:", O_R_fname D25_Line = "D25:" + str(D25_S_Maj_Arcmin) + "|\n" file.write(D25_Line) BG_Source_A = np.array(BG_Source_L) Bin_Hight_L = list(Bin_Hight_A) #print "Bin_Hight_A : ", Bin_Hight_A #print "BG_Source_A: ", BG_Source_A #BG_Source_L_Reduced=BG_Source_L[0:len(BG_Source_L)-2] BG_Source_L_Reduced = BG_Source_L[0:len(BG_Source_L) - 1] BG_Source_A_Reduced = np.array(BG_Source_L_Reduced) np.delete( BG_Source_A, -1 ) #Deletes right most value so that bins are [0,1),[1,)...[n-1,n] were the value of any bin [i,i+1] is the value of the left edge of the bin (ie. the ith value, so if the number of expected BG source at an offaxis of 0' is 2 souces and at 1' 3 sources then the value for the bin [0,1) is 2 not 3. This may be reversed to be 3 later) #print "BG_Source_A_Reduced: ", BG_Source_A_Reduced Overdensity_Ratio_A = (Bin_Hight_A / BG_Source_A_Reduced ) #Somthing Might be wrong here Overdensity_Ratio_L = list(Overdensity_Ratio_A) #for i in range(0,len(Overdensity_Ratio_L)-1): for i in range(0, len(Overdensity_Ratio_L)): Num_Sources = Bin_Hight_L[i] Overdensity_Ratio = Overdensity_Ratio_L[i] Num_Observed_Sources = Num_Observed_Sources_A[i] Num_Missing_Sources = Num_Missing_Sources_A[i] ##Cur_Line=str(Overdensity_Ratio)+","+str(Num_Sources)+"\n" #This version was used for the thesis Cur_Line = str(Overdensity_Ratio) + "," + str( Num_Sources) + "," + str(Num_Observed_Sources) + "," + str( Num_Missing_Sources) + "\n" file.write(Cur_Line)
def get_redshift(object_name): Q=Ned.query_object(object_name) z=Q['Redshift'][0] return(z)
## LB, 2015-03-12 ## Python script to get redshift for a galaxy ## and print redshifted wavelength of a given rest wavelength import sys import numpy as np from astropy import coordinates from astropy import units as u from astroquery.ned import Ned id = sys.argv[1] line = np.float(sys.argv[2]) Q = Ned.query_object(id) z = Q['Redshift'][0] zline = (1 + z) * line print("Redshift of {id} is {z}".format(id=id, z=z)) print("{line} is redshifted to {zline}".format(line=line, zline=zline))
def Area_GC_R_N(Gname): """ Gname: str- The name of the galaxy in the form NGC # Data: array- a table of data containg the coordinates of each object This fucntion takes the inputs for the name of the galaxy and returns a histrogram that plots the number of objects per bin by the area enclosed by the cirlce centered on the center of the galaxy that inculdes the objects in each bin in square degrees divided by the visible area of the galaxy in square degrees. This function plots the visible Major axis of the galaxy area enclosed by a circle that uses the Major axis as the diameter of the cirlce divided by itself to give 1 on histogram. This function uses astroquary to get data directly from NED #THIS IS THE CURRENT RUNNING VERSION OF THIS CODE """ import math from astropy.io import ascii import matplotlib.pyplot as plt system('pwd') #system('cd ~/Desktop/SQL_Standard_File/') #import os dir = os.path.dirname(__file__) #filename= os.path.join(dir, '~','Desktop','SQL_Standard_File',) #filepath=os.path.abspath("~/Desktop/SQL_Standard_File") #print "Filepath =",filepath #path= os.path.join(dir,'~','Desktop','SQL_Standard_File',) #path=os.path.realpath('~/Desktop/SQL_Standard_File/SQL_Sandard_File.csv') path = os.path.realpath('../SQL_Standard_File/SQL_Sandard_File.csv') print "Path=", path #os.chdir(path) #os.chdir('~/Desktop/SQL_Standard_File/') #system('cd ~/Desktop/Big_Object_Regions/') #system('cd ../SQL_Standard_File/') system('pwd') #system('ls') #data = ascii.read("SQL_Sandard_File.csv") #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data = ascii.read(filename) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data = ascii.read(filepath) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File data = ascii.read( path ) #data:-astropy.table.table.Table, data, The data from the SQL_Standard_File #data2=open("SQL_Sandard_File.csv","r") #print data2 #system('cd ~/Desktop/galaxies/out') RA_A = data[ 'sourceRA'] #RA_A:-astropy.table.column.Column, Right_Ascension_Array, The array containing all Right Ascensions in the SQL Standard File #print type(RA_A) RA_L = list( RA_A ) #RA_L:-list, Right_Ascension_List, The list containing all Right Ascensions in the SQL Standard File #print RA_L Dec_A = data[ 'sourceDec'] #Dec_A:-astropy.table.column.Column, Declination_Array, The array containing all Declinations in the SQL Standard File Dec_L = list( Dec_A ) #Dec_L:-List, Declination_List, The list containing all Declinations in the SQL Standard File #print Dec_L #Obs_ID_A=data["obsid"] #Obs_ID_A:-astropy.table.column.Column, Observation_Idenification_Array, The array containing all Observation IDs in the SQL_Standard_File (not indexable) #print type(Obs_ID_A) #Obs_ID_L=list(Obs_ID_A) #Obs_ID_L:-List, Observation_Idenification_List, The list containing all Observation IDs in the SQL_Standard_File (So it is indexable) #print "Obs_ID_L ", Obs_ID_L #print type(Obs_ID_L) #print Obs_ID_A #FGname_A=data["foundName"] #FGname_L=list(FGname_A) #print FGname_A QGname_A = data[ "queriedName"] #QGname_A:-Obs_ID_A:-astropy.table.column.Column, Query_Galaxy_Name_Array, The array containing all Query Galaxy Names in the SQL_Standard_File (not indexable) QGname_L = list( QGname_A ) #QGname_L:-List, Query_Galaxy_Name_Array, The list containing all Query Galaxy Names in the SQL_Standard_File (So it is indexable) #print type(QGname_A) #print QGname_A Matching_Index_List = [ ] #Matching_Index_List:-List, Matching_Index_List, The list of all indexes (ref. QGname_L) that corresepond to the input Galaxy Name, All arrays are of equal lenth, and "ith" value of an array is the correseponding value for any other arrays "ith" value, so for example Obs_ID_L[228]=794 and the Galaxy in the Observation is QGname_L[228]="NGC 891", Note both lists have the same index for i in range(0, len(QGname_L)): # i:-int, i, the "ith" index of QGname_L #print "i ", i QGname = QGname_L[ i] #QGname:-string, Query_Galaxy_Name, The current test Galaxy Name, if this Galaxy name equals the input Galaxy Name (Gname) then this Matching_Index, i (ref. QGname_L) will be appended to the Matching_Index_List #QGname_Reduced=QGname.replace(" ", "") #print "QGname ", QGname #print "QGname_Reduced ", QGname_Reduced if ( Gname == QGname ): #Checks to see if the current test Galaxy Name is the same as the input Galaxy Name, if so it appends the current index (ref. QGname_L) to the Matching_Index_List #print "i ", i Matching_Index_List.append( i ) #Appends the current index (ref. QGname_L) to the Matching_Index_List RA_Match_L = [ ] #RA_Match_L:-List, Right_Ascension_Match_List, The list of all source RA's for the input Galaxy Name in decimal degrees Dec_Match_L = [ ] #Dec_Match_L:-List, Declination_Match_List, The list of all source Dec's for the input Galaxy Name in decimal degrees for Cur_Matching_Index in Matching_Index_List: #Cur_Matching_Index:-int, Current_Matching_Index, The current index (ref. QGname_L) in the list of matching indexes for the current input Galaxy Name (Matching_Index_List) Cur_Match_RA = RA_L[ Cur_Matching_Index] #Cur_Match_RA:-numpy.float64, Current_Match_Right_Ascension, The RA of the current source in decimal degrees #print type(Cur_Match_RA) Cur_Match_Dec = Dec_L[ Cur_Matching_Index] #Cur_Match_Dec:-numpy.float64, Current_Match_Declination, The Dec of the current source in decimal degrees RA_Match_L.append( Cur_Match_RA ) #RA_Match_L:-list, Right_Ascension_Match_List, The list of all source RA's for the input Galaxy Name in decimal degrees Dec_Match_L.append( Cur_Match_Dec ) #Dec_Match_L:-list, Declination_Match_List, The list of all source Dec's for the input Galaxy Name in decimal degrees #print RA_Match_L #print len(RA_Match_L) #print Dec_Match_L #print len(Dec_Match_L) #decA=Data['dec'] #raA=Data['ra'] #Maj=Maj/3600 #S_Maj=Maj/2 #area_T=((S_Maj)**2)*math.pi G_Data = Ned.query_object( Gname ) #G_Data:-astropy.table.table.Table, Galaxy_Data, The Galaxy Data Table queried from NED #print type(G_Data) Dia_Table = Ned.get_table( Gname, table='diameters' ) #Dia_Table:-astropy.table.table.Table, Diameter_Table, The Data table queried from NED that contains the infomation about the Major Axis of the input Galaxy Name #print type(Dia_Table) #print G_Data #print Dia_Table #print Dia_Table.colnames #print Dia_Table.meta #print Dia_Table.columns Dia_Table_Feq = Dia_Table[ 'Frequency targeted'] #Dia_Table_Feq:-astropy.table.column.MaskedColumn, Diameter_Table_Fequency, The Array containing all named frequencies of light that are being used for the Major Axis Measurement #print Dia_Table['NED Frequency'] #print Dia_Table_Feq #print type(Dia_Table_Feq) Dia_Table_Feq_L = list( Dia_Table_Feq ) #Dia_Table_Feq_L:-List, Diameter_Table_Fequency_List, The list containing all named frequencies of light that are being used for the Major Axis Measurement #print Dia_Table_Feq_L Dia_Table_Num = Dia_Table[ 'No.'] #Dia_Table_Num:-astropy.table.column.MaskedColumn, Diameter_Table_Number, The number Ned assigns to #print Dia_Table_Num #print type(Dia_Table_Num) Dia_Table_Num_L = list(Dia_Table_Num) #print Dia_Table_Num_L for i in range( 0, len(Dia_Table_Feq_L) - 1 ): #There is a bug here with index matching, The matched index isn't that same index for the major axis Cur_Feq = Dia_Table_Feq_L[i] #print Cur_Feq if (Cur_Feq == "RC3 D_25, R_25 (blue)"): Match_inx = i Match_Feq = Dia_Table_Feq_L[Match_inx] Match_Num = Dia_Table_Num_L[Match_inx] #Match_Num #print "Match_Feq ", Match_Feq #print "Match_inx ", Match_inx #print "Match_Num ", Match_Num #Dia_Table_Maj=Dia_Table['Major Axis'] Dia_Table_Maj = Dia_Table['NED Major Axis'] #print Dia_Table_Maj Dia_Table_Maj_L = list(Dia_Table_Maj) #print Dia_Table_Maj_L Dia_Table_Maj_Units = Dia_Table['Major Axis Unit'] #print Dia_Table_Maj_Units Dia_Table_Maj_Units_L = list(Dia_Table_Maj_Units) #print Dia_Table_Maj_Units_L #print "i ", i D25_Maj = Dia_Table_Maj_L[Match_inx] #print "D25_Maj ", D25_Maj D25_Units = Dia_Table_Maj_Units[Match_inx] #print "D25_Units ", D25_Units #print type(Dia_Table) #print Dia_Table.info() #Dia_Table_2=Dia_Table[6] #print Dia_Table_2 #Maj=Dia_Table_2[18] #print "Maj, ! ! !", Maj D25_S_Maj = D25_Maj / 2.0 D25_S_Maj_Deg = D25_S_Maj / 3600.0 area_T = ((D25_S_Maj_Deg)**2) * math.pi raGC = float(G_Data['RA(deg)']) decGC = float(G_Data['DEC(deg)']) #area_A=[((((((decGC-dec)**2)+((raGC-ra)**2)))*(math.pi))/area_T) for dec,ra in zip(decA,raA)] #area_A=[((((((decGC-dec)**2)+((raGC-ra)**2)))*(math.pi))/area_T) for dec,ra in zip(Dec_Match_L,RA_Match_L)] #REAL ONE #disA=[math.sqrt(((decGC-dec)**2)+((raGC-ra)**2)) for dec,ra in zip(dec_A,raA)] #REAL ONE? disA = [ math.sqrt(((decGC - dec)**2) + ((raGC - ra)**2)) for dec, ra in zip(Dec_Match_L, RA_Match_L) ] #REAL ONE #print area_A #area_max=max(area_A) #print area_max #plt.vlines(0.00001,0,10,color='red') #plt.vlines(1,0,10,color='red') #plt.hist(area_A) Hist_A = plt.hist(disA) Bin_Hight_A = Hist_A[0] Bin_Hight_Max = max(Bin_Hight_A) #print Bin_Hight_Max plt.vlines(D25_S_Maj_Deg, 0, Bin_Hight_Max, color='red') #Plots red line at D25 print D25_S_Maj_Deg #Hist_Max=max(area_A) #print "Hist_Max ", Hist_Max plt.plot() #plt.savefig('Test2.png') path_2 = os.path.realpath( '../Master_Code/Master_Output/' ) #Goes to Master_Output folder, which will hold all the data calculated for the galaxies including the histogram pictures print "Path_2=", path_2 """ path_Hist=path_2+'/Histograms/' directory_Hist=os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=",path_Hist os.chdir(path_Hist) """ #system('mkdir '+Gname) #Creates Current Galaxy's Folder, Folder Named after Galaxy, Note: will have to remove space from "NGC #" to change to "NGC_#", I Don't know if this works Gname_L = Gname.split(" ") print "Gname_L: ", Gname_L if (len(Gname_L) > 1): Gname_Modifed = Gname_L[0] + "_" + Gname_L[ 1] #Adds underscore to remove space from "NGC #" to change to "NGC_#" if there is a space in the name else: Gname_Modifed = Gname # Does nothing if the galaxy name has no space, ie. NGC#, For example NGC253 instead of NGC 253 or NGC_253 print Gname_Modifed path_3 = path_2 + '/' + Gname_Modifed + '/' directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) os.chdir(path_3) #Goes to Current Galaxies Folder path_Hist = path_3 + '/Histograms/' directory_Hist = os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=", path_Hist os.chdir(path_Hist) plt.savefig(Gname_Modifed + '_Ang.png') #Saves angluar histogram figure #system('pwd') path_4 = os.path.realpath('../../../../Histogram_Code/') print "Path_4=", path_4 os.chdir( path_4 ) #Goes back to where this code (the histogram code) is being run, ie. Desktop/GitHub plt.close()
dir_data = "../proj_goals_" + data_suffix + "/" list_donwload_txt = "goals_" + data_suffix + "_" + time_stamp + ".txt" done = glob.glob(dir_data) if not done: os.system("mkdir " + dir_data) array_goals = np.loadtxt("goals_list_name.txt", delimiter=",", dtype="S20") loop = len(array_goals) list_donwload = [] #for i in range(loop): for i in range([0, 1]): result_table = Ned.query_object(array_goals[i]) print(array_goals[i] + ", z=" + str(result_table["Redshift"][0])) target = Alma.query_object(array_goals[i]) spws = target['Frequency support'].tolist() uids = target['Member ous id'].tolist() loop2 = len(spws) for j in range(loop2): print(uids[j]) for k in range(len(spws[j].split(" U "))): freq_cover = spws[j].split(" U ")[k].split(",")[0] edge_low = float(freq_cover.split("..")[0].replace("[", "")) edge_high = float(freq_cover.split("..")[1].replace("GHz", "")) redshift_plus_1 = 1 + result_table["Redshift"][0] obs_freq = search_freq / redshift_plus_1 if edge_low < obs_freq < edge_high: print(data_suffix + " is here!")
def test1(): result_table = Ned.query_object("NGC 224") print(result_table)
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 ('_RAJ2000' in row.colnames) and ('_DEJ2000' in row.colnames): ra_key, dec_key = '_RAJ2000', '_DEJ2000' elif ('RAJ2000' in row.colnames) and ('DEJ2000' in row.colnames): ra_key, dec_key = 'RAJ2000', 'DEJ2000' if np.isclose( astropy.coordinates.Angle(row[ra_key] + ' hours').deg, position.ra.value) and np.isclose( astropy.coordinates.Angle(row[dec_key] + ' degrees').deg, 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 if ('_RAJ2000' in entry.colnames) and ('_DEJ2000' in entry.colnames): ra_key, dec_key = '_RAJ2000', '_DEJ2000' elif ('RAJ2000' in entry.colnames) and ('DEJ2000' in entry.colnames): ra_key, dec_key = 'RAJ2000', 'DEJ2000' position = SkyCoordinate(ra=entry[ra_key], dec=entry[dec_key], 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
def query(self, term): try: self.catalog_data = Ned.query_object(term) except RemoteServiceError: self.catalog_data = {}
__author__ = 'Jakub Wojtanek, [email protected]' from astroquery.ned import Ned import unittest result_table = Ned.query_object("NGC 6720") result_table2 = Ned.get_table("NGC 6720", table='diameters') for k in result_table: print k print result_table.keys() print result_table2.keys() print result_table['RA(deg)'] print result_table['DEC(deg)'] print result_table['Magnitude and Filter'] print result_table['Distance (arcmin)'] print result_table['Diameter Points'] print result_table2['Major Axis'] print result_table2['Minor Axis']
flux_err += [all_fermi[1].data[ii][16]] flux_E += [all_fermi[1].data[ii][17] * 6.24e5] flux_E_err += [all_fermi[1].data[ii][18] * 6.24e5] PL_index += [all_fermi[1].data['PL_Index'][ii]] unc_PL_index += [all_fermi[1].data['Unc_PL_Index'][ii]] variability_index += [all_fermi[1].data['Variability_Index'][ii]] frac_variability += [all_fermi[1].data['Frac_Variability'][ii]] unc_frac_variability += [all_fermi[1].data['Unc_Frac_Variability'][ii]] TeVCat_Flag += [all_fermi[1].data['TeVCat_Flag'][ii]] alt_name_gamma += [all_fermi[1].data['ASSOC_FGL'][ii]] print(all_fermi[1].data[ii][0], all_fermi[1].data[ii][65]) try: result = Ned.query_object(all_fermi[1].data[ii][65]) redshift_temp = result['Redshift'][0] redshift_flag_temp = result['Redshift Flag'][0] except: redshift_temp = '--' redshift_flag_temp = '' redshift += [redshift_temp] redshift_flag += [redshift_flag_temp] try: result1 = Ned.get_table(all_fermi[1].data[ii][65]) # optical_fluxes = result1[['Observed Passband', 'Frequency', 'Photometry Measurement', 'Uncertainty', 'Units', 'Flux Density', 'Lower limit of uncertainty']][np.logical_and(result1['Frequency'] < 1e16, result1['Frequency'] > 1e14)] optical_fluxes = result1['Flux Density'][np.logical_and( result1['Frequency'] < 1e16, result1['Frequency'] > 1e14)] optical_fluxes = np.array(optical_fluxes) num_optical_flux_temp = len(optical_fluxes)
def load_spectra(self): """Load reference spectra from Pysynphot database or NED database. If the object redshift is >0.2, the LAMBDA_MIN and LAMBDA_MAX parameters are redshifted accordingly. Examples -------- >>> s = Star('3C273') >>> print(s.spectra[0][:4]) [0.0000000e+00 2.5048577e-14 2.4238061e-14 2.4088789e-14] >>> s = Star('HD111980') >>> print(s.spectra[0][:4]) [2.16890002e-13 2.66480010e-13 2.03540011e-13 2.38780004e-13] >>> s = Star('PKS1510-089') >>> print(s.redshift) 0.36 >>> print(f'{parameters.LAMBDA_MIN:.1f}, {parameters.LAMBDA_MAX:.1f}') 408.0, 1496.0 >>> print(s.spectra[0][:4]) [117.34012 139.27621 87.38032 143.0816 ] """ self.wavelengths = [] # in nm self.spectra = [] # first try with pysynphot file_names = [] is_calspec = False if os.getenv("PYSYN_CDBS") is not None: dirname = os.path.expandvars('$PYSYN_CDBS/calspec/') for fname in os.listdir(dirname): if os.path.isfile(dirname + fname): if self.label.lower() in fname.lower(): file_names.append(dirname + fname) if len(file_names) > 0: is_calspec = True self.emission_spectrum = False self.hydrogen_only = False self.lines = Lines(HYDROGEN_LINES + ATMOSPHERIC_LINES + STELLAR_LINES, redshift=self.redshift, emission_spectrum=self.emission_spectrum, hydrogen_only=self.hydrogen_only) for k, f in enumerate(file_names): if '_mod_' in f: continue if self.verbose: self.my_logger.info('\n\tLoading %s' % f) data = S.FileSpectrum(f, keepneg=True) if isinstance(data.waveunits, S.units.Angstrom): self.wavelengths.append(data.wave / 10.) self.spectra.append(data.flux * 10.) else: self.wavelengths.append(data.wave) self.spectra.append(data.flux) elif 'HD' in self.label or self.label in parameters.STAR_NAMES: # it is a star self.emission_spectrum = False self.hydrogen_only = False self.lines = Lines(ATMOSPHERIC_LINES + HYDROGEN_LINES + STELLAR_LINES, redshift=self.redshift, emission_spectrum=self.emission_spectrum, hydrogen_only=self.hydrogen_only) else: if 'PNG' not in self.label: # Try with NED query # print 'Loading target %s from NED...' % self.label ned = Ned.query_object(self.label) hdulists = Ned.get_spectra(self.label, show_progress=False) self.redshift = ned['Redshift'][0] self.emission_spectrum = True self.hydrogen_only = False if self.redshift > 0.2: self.hydrogen_only = True parameters.LAMBDA_MIN *= 1 + self.redshift parameters.LAMBDA_MAX *= 1 + self.redshift self.lines = Lines(ATMOSPHERIC_LINES + ISM_LINES + HYDROGEN_LINES, redshift=self.redshift, emission_spectrum=self.emission_spectrum, hydrogen_only=self.hydrogen_only) for k, h in enumerate(hdulists): if h[0].header['NAXIS'] == 1: self.spectra.append(h[0].data) else: for d in h[0].data: self.spectra.append(d) wave_n = len(h[0].data) if h[0].header['NAXIS'] == 2: wave_n = len(h[0].data.T) wave_step = h[0].header['CDELT1'] wave_start = h[0].header['CRVAL1'] - ( h[0].header['CRPIX1'] - 1) * wave_step wave_end = wave_start + wave_n * wave_step waves = np.linspace(wave_start, wave_end, wave_n) is_angstrom = False for key in list(h[0].header.keys()): if 'angstrom' in str(h[0].header[key]).lower(): is_angstrom = True if is_angstrom: waves *= 0.1 if h[0].header['NAXIS'] > 1: for i in range(h[0].header['NAXIS'] + 1): self.wavelengths.append(waves) else: self.wavelengths.append(waves) else: self.emission_spectrum = True self.lines = Lines(ATMOSPHERIC_LINES + ISM_LINES + HYDROGEN_LINES, redshift=self.redshift, emission_spectrum=self.emission_spectrum, hydrogen_only=self.hydrogen_only) self.build_sed() self.my_logger.debug( f"\n\tTarget label: {self.label}" f"\n\tCalspec? {is_calspec}" f"\n\tNumber of spectra: {len(self.spectra)}" f"\n\tRedshift: {self.redshift}" f"\n\tEmission spectrum ? {self.emission_spectrum}" f"\n\tLines: {[l.label for l in self.lines.lines]}")
def Source_Histogram_Sum_Plot(Gname_L, Fname_Key="", Fileout_B=True, Outpath=False, Bins=100): """ Gname: str- The name of the galaxy in the form NGC # Data: array- a table of data containg the coordinates of each object This fucntion takes the inputs for the name of the galaxy and returns a histrogram that plots the number of objects per bin by the area enclosed by the cirlce centered on the center of the galaxy that inculdes the objects in each bin in square degrees divided by the visible area of the galaxy in square degrees. This function plots the visible Major axis of the galaxy area enclosed by a circle that uses the Major axis as the diameter of the cirlce divided by itself to give 1 on histogram. This function uses astroquary to get data directly from NED #THIS IS THE CURRENT RUNNING VERSION OF THIS CODE """ Failed_Galaxy_List = [] dis_Total_L = [] #BG_Source_D25_Total_L=[0,0,0,0,0,0,0,0,0,0] BG_Source_D25_Total_L = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #Cheap Fix to binning problem will fix later #BG_Source_D25_Total_A=np.zeros(10) for Gname in Gname_L: try: Gname_Modifed = Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) dir = os.path.dirname(__file__) #Evt2_File_H_L=File_Query_Code_5.File_Query(Gname,"evt2") Evt2_File_H_L = File_Query_Code_5.File_Query(Gname, "evt2", Exp_Max_B=True) #print "Evt2_File_H_L : ", Evt2_File_H_L if (Evt2_File_H_L == False): print "Invalid Galaxy" return Galaxy_Obs_ID_L = [] for Evt2_File_L in Evt2_File_H_L: Cur_Galaxy_Obs_ID = Evt2_File_L[0] Galaxy_Obs_ID_L.append(Cur_Galaxy_Obs_ID) for Obs_ID in Galaxy_Obs_ID_L: G_Data = Ned.query_object( Gname ) #G_Data:-astropy.table.table.Table, Galaxy_Data, The Galaxy Data Table queried from NED #print "G_Data : \n",G_Data #print type(G_Data) #/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/MESSIER_066/Coords_Lists/9548 #MESSIER_066_ObsID_9548_Coords.csv Coords_Path = "/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/" + Gname_Modifed + "/Coords_Lists/" + str( Obs_ID) + "/" + Gname_Modifed + "_ObsID_" + str( Obs_ID) + "_Coords.csv" Coords_Table = pd.read_csv(Coords_Path) #print "Coords_Table: \n",Coords_Table #Phys_X,Phys_Y,Chip_X,Chip_Y,Chip_ID,RA,DEC,Offaxis_Angle #Dec_Match_L,RA_Match_L RA_Match_Deg_DF = Coords_Table["RA"] #In decimal degrees RA_Match_Deg_L = list(RA_Match_Deg_DF) RA_Match_DF = RA_Match_Deg_DF * 60.0 #In units of arcmins #print "RA_Match_DF :\n", RA_Match_DF RA_Match_L = list(RA_Match_DF) #print "RA_Match_L :\n", RA_Match_L Dec_Match_Deg_DF = Coords_Table["DEC"] #In decimal degrees Dec_Match_Deg_L = list(Dec_Match_Deg_DF) Dec_Match_DF = Dec_Match_Deg_DF * 60.0 #In units of arcmins Dec_Match_L = list(Dec_Match_DF) #print "Dec_Match_L :\n", Dec_Match_L #return "STOPPING PROGRAM" #print "Area Matching_Index_List : ", Matching_Index_List D25_S_Maj_Deg = D25_Finder.D25_Finder(Gname) D25_S_Maj_Arcmin = D25_S_Maj_Deg * 60.0 area_T = ((D25_S_Maj_Deg)**2) * math.pi try: raGC = float(G_Data['RA(deg)']) decGC = float(G_Data['DEC(deg)']) except: raGC = float(G_Data['RA']) decGC = float(G_Data['DEC']) #area_A=[((((((decGC-dec)**2)+((raGC-ra)**2)))*(math.pi))/area_T) for dec,ra in zip(decA,raA)] ##area_A=[((((((decGC-dec)**2)+((raGC-ra)**2)))*(math.pi))/area_T) for dec,ra in zip(Dec_Match_Deg_L,RA_Match_Deg_L)] #REAL ONE #disA=[math.sqrt(((decGC-dec)**2)+((raGC-ra)**2)) for dec,ra in zip(decA,raA)] #REAL ONE #print area_A #area_max=max(area_A) #print area_max #plt.vlines(0.00001,0,10,color='red') #plt.vlines(1,0,10,color='red') #plt.hist(area_A) ##Hist_A=plt.hist(area_A) ##Bin_Hight_A=Hist_A[0] ##Bin_Hight_Max=max(Bin_Hight_A) #print Bin_Hight_Max ##plt.vlines(1,0,Bin_Hight_Max,color='red') ##plt.xlabel('A') ##plt.ylabel('N') #Hist_Max=max(area_A) #print "Hist_Max ", Hist_Max Flux_90_Path = "/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/" + Gname_Modifed + "/Flux_90_Files/" + str( Obs_ID) + "/" + Gname_Modifed + "_ObsID_" + str( Obs_ID) + "_Flux_90.txt" BG_Source_HL = Background_Sources_Calc.Big_Background_Source_Calc( Flux_90_Path) #print "BG_Source_HL : ", BG_Source_HL """ BG_Source_Sum_Area_L=BG_Source_HL[4] BG_Source_Sum_Frac_L=[] for Sum_Area in BG_Source_Sum_Area_L: Sum_Frac=Sum_Area/area_T BG_Source_Sum_Frac_L.append(Sum_Frac) """ #BG_Source_Sum_N_L=BG_Source_HL[5] BG_Source_L = BG_Source_HL[3] """ BG_Source_L_Reduced=BG_Source_L[0:len(BG_Source_L)-1] #BG_Source_A_Reduced=np.array(BG_Source_L_Reduced) #np.delete(BG_Source_A, -1) #Deletes right most value so that bins are [0,1),[1,)...[n-1,n] were the value of any bin [i,i+1] is the value of the left edge of the bin (ie. the ith value, so if the number of expected BG source at an offaxis of 0' is 2 souces and at 1' 3 sources then the value for the bin [0,1) is 2 not 3. This may be reversed to be 3 later) """ #print "BG_Source_Sum_Frac_L : ", BG_Source_Sum_Frac_L #print "BG_Source_L : ", BG_Source_L print "D25_S_Maj_Arcmin : ", D25_S_Maj_Arcmin D25_S_Maj_Arcmin_Whole = round(D25_S_Maj_Arcmin) print "D25_S_Maj_Arcmin_Whole : ", D25_S_Maj_Arcmin_Whole D25_S_Maj_Arcmin_Whole_Int = int(D25_S_Maj_Arcmin_Whole) print "D25_S_Maj_Arcmin_Whole_Int : ", D25_S_Maj_Arcmin_Whole_Int Num_BG_Bins = 10.0 / D25_S_Maj_Arcmin #print "Num_BG_Bins : ", Num_BG_Bins Num_BG_Bins_Whole = round(Num_BG_Bins) #print "Num_BG_Bins_Whole : ", Num_BG_Bins_Whole Num_BG_Bins_Whole_Int = int(Num_BG_Bins_Whole) #print "Num_BG_Bins_Whole_Int : ", Num_BG_Bins_Whole_Int Remainder_BG_Bins = 10.0 % Num_BG_Bins_Whole #print "Remainder_BG_Bins : ",Remainder_BG_Bins #Subdivided_A_Len=10*Num_BG_Bins_Whole_Int Subdivided_A_Len = 11 * Num_BG_Bins_Whole_Int #Subdivided_A_Len=10*D25_S_Maj_Arcmin_Whole_Int Subdivided_A = np.zeros(Subdivided_A_Len) BG_Source_SD_HL = [] #for BG_Source in BG_Source_L_Reduced: for BG_Source in BG_Source_L: BG_Source_SD = BG_Source / Num_BG_Bins_Whole #BG_Source_SD=BG_Source/Num_BG_Bins_Whole Cur_BG_Source_SD_A = np.empty(Num_BG_Bins_Whole_Int) Cur_BG_Source_SD_A.fill(BG_Source_SD) Cur_BG_Source_SD_L = list(Cur_BG_Source_SD_A) BG_Source_SD_HL.append(Cur_BG_Source_SD_L) #print "BG_Source_L : ", BG_Source_L #print "len(BG_Source_L) : ", len(BG_Source_L) #print "BG_Source_SD_HL : ", BG_Source_SD_HL #print "len(BG_Source_SD_HL) : ", len(BG_Source_SD_HL) i = 0 for BG_Source_SD_L in BG_Source_SD_HL: for BG_Source in BG_Source_SD_L: Subdivided_A[i] = BG_Source i = i + 1 #print "Subdivided_A : ", Subdivided_A #print "len(Subdivided_A) : ", len(Subdivided_A) Subdivided_L = list(Subdivided_A) #print "Subdivided_L : ", Subdivided_L #[l[i:i + n] for i in xrange(0, len(l), n)] #Subdivided_HL=[Subdivided_L[j:j + Num_BG_Bins_Whole_Int] for j in xrange(0, len(Subdivided_L), Num_BG_Bins_Whole_Int)] #Subdivided_HL=[Subdivided_L[j:j + D25_S_Maj_Arcmin_Whole_Int] for j in xrange(0, len(Subdivided_L), D25_S_Maj_Arcmin_Whole_Int)] #Subdivided_HL=[Subdivided_L[j:j + 10] for j in xrange(0, len(Subdivided_L), 10)] Subdivided_HL = [ Subdivided_L[j:j + 11] for j in xrange(0, len(Subdivided_L), 11) ] #print "Subdivided_HL : ", Subdivided_HL #print "len(Subdivided_HL) : ", len(Subdivided_HL) Subdivided_D25_A = np.array(Subdivided_HL) D25_BG_Source_A = np.sum(Subdivided_D25_A, axis=1) #print "D25_BG_Source_A : ", D25_BG_Source_A D25_BG_Source_L = list(D25_BG_Source_A) #print "D25_BG_Source_L : ", D25_BG_Source_L #print "len(D25_BG_Source_L) : ", len(D25_BG_Source_L) #for k in range(0,len(D25_BG_Source_L)): #for k in range(1,len(D25_BG_Source_L)): # 1 instead of zero in order to get plt.step to work correctly #for k in range(0,len(D25_BG_Source_L)): for k in range(0, len(D25_BG_Source_L)): #BG_Source_D25_Total_L[k]=BG_Source_D25_Total_L[k]+D25_BG_Source_L[k] BG_Source_D25_Total_L[ k + 1] = BG_Source_D25_Total_L[k + 1] + D25_BG_Source_L[k] """ plt.step(BG_Source_Sum_Frac_L, BG_Source_L) plt.plot() #plt.savefig('Test1.png') #path_2=os.path.realpath('../Master_Code/Master_Output/') #Goes to Master_Output folder, which will hold all the data calculated for the galaxies including the histogram pictures path_2=os.path.realpath('./Source_Overdensity_Histograms/') if(Outpath!=False): path_2=Outpath #print "Path_2=", path_2 #Gname_Modifed=Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) #print Gname_Modifed path_3=path_2+'/'+Gname_Modifed+'/' directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) #os.chdir(path_3) #Goes to Current Galaxies Folder path_Hist=path_3+'Histograms/' directory_Hist=os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) print "path_Hist=",path_Hist #os.chdir(path_Hist) path_Obs_ID=path_Hist+str(Obs_ID)+'/' directory_Obs_ID=os.path.dirname(path_Obs_ID) if not os.path.exists(directory_Obs_ID): os.makedirs(directory_Obs_ID) plt.savefig(path_Obs_ID+Gname_Modifed+'_'+str(Obs_ID)+'_Frac.png') #Saves angluar histogram figure #system('pwd') #path_4=os.path.realpath('../../../../Histogram_Code/') #print "Path_4=",path_4 #os.chdir(path_4) #Goes back to where this code (the histogram code) is being run, ie. Desktop/GitHub plt.close() """ #plt.show() #For Area Histrograms raGC_Arcmin = raGC * 60.0 decGC_Arcmin = decGC * 60.0 disA = [ math.sqrt(((decGC_Arcmin - dec)**2) + ((raGC_Arcmin - ra)**2)) for dec, ra in zip(Dec_Match_L, RA_Match_L) ] #REAL ONE in units of arcmins #print "disA : ", disA #D25_S_Maj_Arcmin dis_D25_A = disA / D25_S_Maj_Arcmin #print "dis_D25_A : ", dis_D25_A dis_D25_L = list(dis_D25_A) for dis_D25 in dis_D25_L: Dist_Arcmin = dis_D25 * D25_S_Maj_Arcmin if ( Dist_Arcmin > 10.0 ): #Throws out all sources outside the reasonable Chandra FOV (Offaxis > 10') continue dis_Total_L.append(dis_D25) #dis_max=np.max(disA) #N_Bins_Float=dis_max/2.0 #N_Bins=int(round(N_Bins_Float)) #print "dis_max : ", dis_max #print area_A #area_max=max(area_A) #print area_max #plt.vlines(0.00001,0,10,color='red') #plt.vlines(1,0,10,color='red') #plt.hist(area_A) #Hist_A=plt.hist(disA,[0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0]) #Hist_A=plt.hist(disA,[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) #Hist_A=plt.hist(disA,[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) ##Hist_A=plt.hist(disA,range=(0.0,10.0)) except: Failed_Galaxy_List.append(Gname) print "Failed_Galaxy_List : ", Failed_Galaxy_List dis_Total_A = np.array(dis_Total_L) #Hist_A=plt.hist(disA,range=(0.0,10.0/D25_S_Maj_Arcmin)) #Hist_A=plt.hist(dis_Total_A,range=(0.0,20.0)) Hist_A = plt.hist(dis_Total_A, bins=Bins, range=(0.0, 10.0)) Bin_Hight_A = Hist_A[0] Bin_A = Hist_A[1] print "Bin_A : ", Bin_A Bin_Hight_Max = max(Bin_Hight_A) #Hist_A=plt.hist(disA,N_Bins) #print "Angular Hist_A : ", Hist_A #print "Hist_A : ", Hist_A print "BG_Source_D25_Total_L : ", BG_Source_D25_Total_L BG_Source_D25_Total_A = np.array(BG_Source_D25_Total_L) BG_Source_D25_Total_A = BG_Source_D25_Total_A * (10.0 / Bins) BG_Source_D25_Total_L = list(BG_Source_D25_Total_A) BG_Source_Sigificance_A = 3.0 * BG_Source_D25_Total_A """ Bin_Hight_A=Hist_A[0] Bin_Hight_Max=max(Bin_Hight_A) #print "Bin_Hight_Max : ", Bin_Hight_Max #/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/NGC_3631/Flux_90_Files/3951/NGC_3631_ObsID_3951_Flux_90.txt #Example Path #Flux_90_Path="/Volumes/xray/anthony/Research_Git/Master_Code/Master_Output/"+Gname_Modifed+"/Flux_90_Files/"+str(Obs_ID)+"/"+Gname_Modifed+"_ObsID_"+str(Obs_ID)+"_Flux_90.txt" #BG_Source_HL=Background_Sources_Calc.Big_Background_Source_Calc(Flux_90_Path) #print "BG_Source_HL : ", BG_Source_HL BG_Bins=BG_Source_HL[2] BG_Source_L=BG_Source_HL[3] #Hist_BG_A=plt.hist(BG_Source_L,[0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0],alpha=0.5) #Bar_BG_A=plt.bar([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L,color="red",alpha=0.5) #plt.plot([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L) #plt.step([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0], BG_Source_L) plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_L) ##plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]/D25_S_Maj_Arcmin, BG_Source_L) #BG_Bin_Hight= #print Bin_Hight_Max #plt.vlines(D25_S_Maj_Deg,0,Bin_Hight_Max,color='red') #Plots red line at D25 plt.vlines(D25_S_Maj_Arcmin,0,Bin_Hight_Max,color='red') #Plots red line at D25 """ plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_D25_Total_L) plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_A, color="orange") #plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_A*5.0,color="yellow") plt.step([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], BG_Source_Sigificance_A * 3.0, color="gold") plt.vlines(1, 0, Bin_Hight_Max, color='red') #Plots red line at D25 #plt.xlabel('R (arcmin)') plt.xlabel('R (D25)') plt.ylabel('N') #print D25_S_Maj_Deg #Hist_Max=max(area_A) #print "Hist_Max ", Hist_Max plt.plot() #plt.savefig('Test2.png') #path_2=os.path.realpath('../Master_Code/Master_Output/') #Goes to Master_Output folder, which will hold all the data calculated for the galaxies including the histogram pictures, Quoted Out because path_2 is already defined #print "Path_2=", path_2 """ Gname_Modifed=Galaxy_Name_Reducer.Galaxy_Name_Reducer(Gname) #print Gname_Modifed path_3=path_2+'/'+Gname_Modifed+'/' directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) #os.chdir(path_3) #Goes to Current Galaxies Folder path_Hist=path_3+'Histograms/' directory_Hist=os.path.dirname(path_Hist) if not os.path.exists(directory_Hist): os.makedirs(directory_Hist) #print "path_Hist=",path_Hist #os.chdir(path_Hist) path_Obs_ID=path_Hist+str(Obs_ID)+'/' print "path_Obs_ID : ",path_Obs_ID directory_Obs_ID=os.path.dirname(path_Obs_ID) if not os.path.exists(directory_Obs_ID): os.makedirs(directory_Obs_ID) plt.savefig(path_Obs_ID + Gname_Modifed+'_'+str(Obs_ID)+'_Ang.png') #Saves angluar histogram figure """ Path_Sum = "/Volumes/xray/anthony/Research_Git/Data_Processing/Source_Overdensity/Source_Overdensity_Sum_Plot/Sum_Histograms/" """ directory = os.path.dirname(path_3) if not os.path.exists(directory): os.makedirs(directory) """ plt.savefig(Path_Sum + 'Sum_D25_' + Fname_Key + '_Histogram.png') #Saves angluar histogram figure #BG_Source_A=np.array(BG_Source_L) #system('pwd') #path_4=os.path.realpath('../../../../Histogram_Code/') #print "Path_4=",path_4 #os.chdir(path_4) #Goes back to where this code (the histogram code) is being run, ie. Desktop/GitHub plt.close() """ if(Fileout_B): O_R_fname=path_Obs_ID + Gname_Modifed+'_'+str(Obs_ID)+'_Overdensity_Ratios.txt' file=open(O_R_fname,"w") print "O_R_fname:",O_R_fname D25_Line="D25:"+str(D25_S_Maj_Arcmin)+"|\n" file.write(D25_Line) BG_Source_A=np.array(BG_Source_L) Bin_Hight_L=list(Bin_Hight_A) #print "Bin_Hight_A : ", Bin_Hight_A #print "BG_Source_A: ", BG_Source_A #BG_Source_L_Reduced=BG_Source_L[0:len(BG_Source_L)-2] BG_Source_L_Reduced=BG_Source_L[0:len(BG_Source_L)-1] BG_Source_A_Reduced=np.array(BG_Source_L_Reduced) np.delete(BG_Source_A, -1) #Deletes right most value so that bins are [0,1),[1,)...[n-1,n] were the value of any bin [i,i+1] is the value of the left edge of the bin (ie. the ith value, so if the number of expected BG source at an offaxis of 0' is 2 souces and at 1' 3 sources then the value for the bin [0,1) is 2 not 3. This may be reversed to be 3 later) #print "BG_Source_A_Reduced: ", BG_Source_A_Reduced Overdensity_Ratio_A=(Bin_Hight_A/BG_Source_A_Reduced) #Somthing Might be wrong here Overdensity_Ratio_L=list(Overdensity_Ratio_A) #for i in range(0,len(Overdensity_Ratio_L)-1): for i in range(0,len(Overdensity_Ratio_L)): Num_Sources=Bin_Hight_L[i] Overdensity_Ratio=Overdensity_Ratio_L[i] Cur_Line=str(Overdensity_Ratio)+","+str(Num_Sources)+"\n" file.write(Cur_Line) """ if (Fileout_B): #O_R_fname=path_Obs_ID + Gname_Modifed+'_'+str(Obs_ID)+'_Overdensity_Ratios.txt' #file=open(Path_Sum+'Sum_D25_'+Fname_Key+'_Data.txt',"w") file = open(Path_Sum + 'Sum_D25_' + Fname_Key + '_Data.csv', "w") #print "O_R_fname:",O_R_fname #D25_Line="D25:"+str(D25_S_Maj_Arcmin)+"|\n" #file.write(D25_Line) #BG_Source_A=np.array(BG_Source_L) Bin_Hight_L = list(Bin_Hight_A) #print "Bin_Hight_A : ", Bin_Hight_A #print "BG_Source_A: ", BG_Source_A Bin_L = list(Bin_A) #print "Bin_L : ", Bin_L #BG_Source_L_Reduced=BG_Source_L[0:len(BG_Source_L)-2] BG_Source_L_Reduced = BG_Source_L[0:len(BG_Source_L) - 1] #BG_Source_A_Reduced=np.array(BG_Source_L_Reduced) #np.delete(BG_Source_A, -1) #Deletes right most value so that bins are [0,1),[1,)...[n-1,n] were the value of any bin [i,i+1] is the value of the left edge of the bin (ie. the ith value, so if the number of expected BG source at an offaxis of 0' is 2 souces and at 1' 3 sources then the value for the bin [0,1) is 2 not 3. This may be reversed to be 3 later) #print "BG_Source_A_Reduced: ", BG_Source_A_Reduced #Overdensity_Ratio_A=(Bin_Hight_A/BG_Source_A_Reduced) #Somthing Might be wrong here #Overdensity_Ratio_L=list(Overdensity_Ratio_A) #for i in range(0,len(Overdensity_Ratio_L)-1): Header_Line_1 = "BG_Source_D25_Total_L:" + str( BG_Source_D25_Total_L) + "\n" + "Diluted:" + str( (10.0 / Bins)) + "|\n" file.write(Header_Line_1) Header_Line_2 = "Bins,Num_Sources\n" file.write(Header_Line_2) for i in range(0, len(Bin_Hight_L)): Bin = Bin_L[i] Num_Sources = Bin_Hight_L[i] #BG_Source=BG_Source_L_Reduced[i] #Overdensity_Ratio=Overdensity_Ratio_L[i] #Cur_Line=str(Overdensity_Ratio)+","+str(Num_Sources)+"\n" #Cur_Line=str(Bin)+","+str(Num_Sources)+","+str(BG_Source)"\n" Cur_Line = str(Bin) + "," + str(Num_Sources) + "\n" file.write(Cur_Line)
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