def pair_up(targ, qsos, sep, z_targ=None, silent=False): """ Given a list of targets, find all quasars within an angle or physical distance. Parameters: ---------- targ: array of SkyCoord qsos: array of SkyCoord for quasars sep: Angle or Quantity Separation to search for z_targ: array (None) Array of redshifts of the targets. Required if sep=Distance Calculations are done in physical Returns: ---------- idxt: Indices of targets that were hits idxqso: Indices of qsos that were hits d2d: Angular or physical separation between qso-targ pairs """ # Set angle if not z_targ is None: from astropy.cosmology import WMAP9 as cosmo medz = np.median(z_targ) pkpc_amin = cosmo.kpc_comoving_per_arcmin(medz) / ( 1 + medz) # physical kpc per arcmin ang_sep = 3. * (sep / pkpc_amin).to('arcsec') # Physical if not silent: print('z1qa.pair_up: Searching to {:g}'.format(ang_sep)) else: ang_sep = sep # Search about idxt, idxq, d2d, d3d = qsos.search_around_sky(targ, ang_sep) # Cut on physical distance? if not z_targ is None: pkpc_amin = cosmo.kpc_comoving_per_arcmin(z_targ[idxt]) / ( 1 + z_targ[idxt]) # physical kpc per arcmin phys_sep = d2d.to('arcmin') * pkpc_amin gdp = np.where(phys_sep < sep)[0] # Cut if len(gdp) > 0: idxt = idxt[gdp] idxq = idxq[gdp] d2d = phys_sep[gdp] if not silent: print('z1qa.pair_up: Found {:d} matches!'.format(len(gdp))) # Return return idxt, idxq, d2d
def __init__(self, ras='02 26 14.5', decs='+00 15 29.8', cosmo=None, g_ras='02 26 12.98', g_decs='+00 15 29.1', zgal=0.227, verbose=False): # Absorption system self.abs_sys = CGMAbs() self.abs_sys.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg)) # Name self.name = ('J' + self.abs_sys.coord.ra.to_string( unit=u.hour, sep='', pad=True) + self.abs_sys.coord.dec.to_string( sep='', pad=True, alwayssign=True)) # Galaxy self.galaxy = Galaxy(ra=g_ras, dec=g_decs) self.galaxy.z = zgal # Calcualte rho if cosmo is None: from astropy.cosmology import WMAP9 as cosmo if verbose is True: print('cgm.core: Using WMAP9 cosmology') ang_sep = self.abs_sys.coord.separation(self.galaxy.coord).to('arcmin') kpc_amin = cosmo.kpc_comoving_per_arcmin( self.galaxy.z) # kpc per arcmin self.rho = ang_sep * kpc_amin / (1 + self.galaxy.z) # Physical
def photometry(): filters=['I','B','V','R'] #filter names for f in filters: All_data=Table(names=('Count','Error','Time')) file=open('photometry_'+str(sn_name)+str(f)+'.txt','w') super_lotis_path='/Users/zeynepyaseminkalender/Documents/MyFiles_Pyhton/SuperLOTIS_final' date_search_path=os.path.join(super_lotis_path, '13*') search_str=os.path.join(date_search_path,str(sn_name)+str(f)+'.fits') for name in glob(search_str): date=extract_date_from_fullpath(name) final_date=convert_time(date) with fits.open(name) as analysis: z = .086 r = 1 * u.kpc / cosmo.kpc_comoving_per_arcmin(z) cordinate = SkyCoord('01:48:08.66 +37:33:29.22', unit = (u.hourangle, u.deg)) aperture = SkyCircularAperture(cordinate, r) exp_time= analysis[0].header['EXPTIME'] # error calculation data_error = np.sqrt(analysis[0].data*exp_time) / exp_time tbl=Table(aperture_photometry(analysis[0],aperture,error=data_error),names=('Count','Count_Error','x_center','y_center','center_input')) tbl.keep_columns(['Count','Count_Error']) count=tbl[0]['Count'] error=tbl[0]['Count_Error'] All_data.add_row((count,error,final_date)) print >> file , All_data file.close() plot(filters)
def __init__(self, gal_ra, gal_dec, gal_z, bg_ra, bg_dec, bg_z, cosmo=None, verbose=False): # Galaxy self.galaxy = Galaxy(gal_ra, gal_dec, z=gal_z) # Name self.name = ( 'CGM' + self.galaxy.coord.ra.to_string(unit=u.hour, sep='', pad=True) + self.galaxy.coord.dec.to_string(sep='', pad=True, alwayssign=True)) # Absorption system self.abs_sys = CGMAbs() self.abs_sys.coord = xra.to_coord((bg_ra, bg_dec)) # Background source self.abs_sys.zem = bg_z # Calcualte rho if cosmo is None: from astropy.cosmology import WMAP9 as cosmo if verbose is True: print('cgm.core: Using WMAP9 cosmology') ang_sep = self.abs_sys.coord.separation(self.galaxy.coord).to('arcmin') kpc_amin = cosmo.kpc_comoving_per_arcmin( self.galaxy.z) # kpc per arcmin self.rho = ang_sep * kpc_amin / (1 + self.galaxy.z) # Physical
def separation_radius(self, z_cm): """ Generate the separation characteristics for a given redshift grid. Parameters ---------- z_cm : array-like The log redshift grid of redshift values to be transformed to kpc comoving values per arc minute. Returns ------- dr_cm : array-like Transverse comoving kpc values corresponding to an arcminute at the provided redshift values. dr_sep : float Separation radius for an annulus of area (1 Mpc)**2 dr_area : float Area of a given separation radius. """ # Calculate the separation given an array of redshift values # if z_cm is None: # z_cm = utils.log_zgrid([0.1, 3.5], 0.01) dr_cm = WMAP9.kpc_comoving_per_arcmin(z_cm).to(u.Mpc / u.arcsec) # density # dz_thresh = 0.01 # separation threshold, dz*(1+z) # Separation radius dr_sep = np.sqrt(0.5 / np.pi) * u.Mpc dr_area = (np.pi * dr_sep.value**2) return dr_cm, dr_sep, dr_area
def photometry(): filters = ['I', 'B', 'V', 'R'] #filter names for f in filters: All_data = Table(names=('Count', 'Error', 'Time')) file = open('photometry_' + str(sn_name) + str(f) + '.txt', 'w') super_lotis_path = '/Users/zeynepyaseminkalender/Documents/MyFiles_Pyhton/SuperLOTIS_final' date_search_path = os.path.join(super_lotis_path, '13*') search_str = os.path.join(date_search_path, str(sn_name) + str(f) + '.fits') for name in glob(search_str): date = extract_date_from_fullpath(name) final_date = convert_time(date) with fits.open(name) as analysis: z = .086 r = 1 * u.kpc / cosmo.kpc_comoving_per_arcmin(z) cordinate = SkyCoord('01:48:08.66 +37:33:29.22', unit=(u.hourangle, u.deg)) aperture = SkyCircularAperture(cordinate, r) exp_time = analysis[0].header['EXPTIME'] # error calculation data_error = np.sqrt(analysis[0].data * exp_time) / exp_time tbl = Table(aperture_photometry(analysis[0], aperture, error=data_error), names=('Count', 'Count_Error', 'x_center', 'y_center', 'center_input')) tbl.keep_columns(['Count', 'Count_Error']) count = tbl[0]['Count'] error = tbl[0]['Count_Error'] All_data.add_row((count, error, final_date)) print >> file, All_data file.close() plot(filters)
def conv_error(self, val, err): ''' Use a black box error method to find the uncertanty in astropy.cosmology.WMAP9.kpc_comoving_per_arcmin(). Args: val (float): A redshift value err (float): Error in the redshift Returns: error (float): Error in the conversion factor ''' diff = (cosmo.kpc_comoving_per_arcmin(val + err)**2 - cosmo.kpc_comoving_per_arcmin(val - err)**2) error = abs(.5 * diff.value) return(error)
def angular_size(r, z, degrees=False): # z: average redshift in bin; can be a np array # r: physical size of aperture radius in Mpc; can be a np array # degrees: bool, if True results in in degrees; otherwise, they're in arcmin # returns: corresponding angular radius of aperture in degrees # convert to kpc r = r * 1000. # Separation in transverse comoving kpc corresponding to an arcminute at redshift z foo = WMAP9.kpc_comoving_per_arcmin(z) # theta in arcmin theta = (r / foo).value # theta in degrees if degrees: theta = theta * 0.0166667 return (theta)
def __init__(self, ras='02 26 14.5', decs='+00 15 29.8', cosmo=None, g_ras='02 26 12.98', g_decs='+00 15 29.1', zgal=0.227, verbose=False): # Absorption system self.abs_sys = CGM_Abs() self.abs_sys.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg)) # Name self.name = ('J'+ self.abs_sys.coord.ra.to_string(unit=u.hour,sep='',pad=True)+ self.abs_sys.coord.dec.to_string(sep='',pad=True,alwayssign=True)) # Galaxy self.galaxy = Galaxy(ra=g_ras, dec=g_decs) self.galaxy.z = zgal # Calcualte rho if cosmo is None: from astropy.cosmology import WMAP9 as cosmo if verbose is True: print('cgm.core: Using WMAP9 cosmology') ang_sep = self.abs_sys.coord.separation(self.galaxy.coord).to('arcmin') kpc_amin = cosmo.kpc_comoving_per_arcmin( self.galaxy.z ) # kpc per arcmin self.rho = ang_sep * kpc_amin / (1+self.galaxy.z) # Physical
def __init__(self, gal_ra, gal_dec, gal_z, bg_ra, bg_dec, bg_z, cosmo=None, verbose=False): # Galaxy self.galaxy = Galaxy(gal_ra, gal_dec, z=gal_z) # Name self.name = ('CGM'+ self.galaxy.coord.ra.to_string(unit=u.hour,sep='',pad=True)+ self.galaxy.coord.dec.to_string(sep='',pad=True,alwayssign=True)) # Absorption system self.abs_sys = CGMAbs() self.abs_sys.coord = xra.to_coord( (bg_ra,bg_dec) ) # Background source self.abs_sys.zem = bg_z # Calcualte rho if cosmo is None: from astropy.cosmology import WMAP9 as cosmo if verbose is True: print('cgm.core: Using WMAP9 cosmology') ang_sep = self.abs_sys.coord.separation(self.galaxy.coord).to('arcmin') kpc_amin = cosmo.kpc_comoving_per_arcmin( self.galaxy.z ) # kpc per arcmin self.rho = ang_sep * kpc_amin / (1+self.galaxy.z) # Physical
def create_tables(self, uv_type, directory, radius, print_progress = False): ''' Perform photometry on a directory of .fits files and create a list of two tables. The first table contains the redshift, exposure time, luminosity, and surface brightness for various supernova, along with the associated error values. The second table is a log outlining any files that do not contain a supernova or are missing checkfiles. If print_progress is set equal to true, the path each fits file will be printed before performing photometry on along with the number of remaining files. Args: uv_type (str) : Specifies which type of uv to create a table for. Use either "NUV" or "FUV". directory (str) : A directory containing .fits files radius (float): Radius of desired photometry aperture in kpc print_progress (bool) : Whether or not to print the file path of each fits file Returns: results (list): [Data table (Table), Log table (Table)] ''' #Make sure we have redshift and coordinates of each supernova if self.cord_dict.keys() != self.red_dict.keys(): raise ValueError('''Keys in coordinate and redshift dictionaries (self.cord_dict, self.red_dict) do not match''') label = uv_type + " " + str(radius) + "kpc " #Define the tables that will be returned by the function log = Table(names = ["File Path", "Issue"], dtype = [object, object]) out = Table(names = ["sn", "Redshift", "Redshift Error", label + "Exposure Time", "Flux", "Flux Error", label + "Luminosity", label + "Luminosity Error", label + "Surface Brightness", label + "Surface Brightness Error"], dtype = ("S70", "float64", "float64", "float64", "float64", "float64", "float64", "float64", "float64", "float64")) out["Redshift"].unit = u.dimensionless_unscaled out["Redshift Error"].unit = u.dimensionless_unscaled out[label + "Exposure Time"].unit = u.s out["Flux"].unit = u.erg / u.s / u.Angstrom / u.kpc / u.kpc / u.cm / u.cm / np.pi out["Flux Error"].unit = u.erg / u.s / u.Angstrom / u.kpc / u.kpc / u.cm / u.cm / np.pi out[label + "Luminosity"].unit = u.erg / u.s / u.Angstrom / u.kpc / u.kpc out[label + "Luminosity Error"].unit = u.erg / u.s / u.Angstrom / u.kpc / u.kpc out[label + "Surface Brightness"].unit = u.erg / u.s / u.Angstrom / u.arcsec / u.arcsec out[label + "Surface Brightness Error"].unit = u.erg / u.s / u.Angstrom / u.arcsec / u.arcsec #Set parameters that are specific to NUV or FUV observations if "N" in uv_type.upper(): file_key = "nd-int" #A string distinguing galex file types flux_conv = 2.06 * 1e-16 #A conversion factor from counts per second to flux elif "F" in uv_type.upper(): file_key = "fd-int" flux_conv = 1.40 * 1e-15 #Create a list of files to perform photometry on file_list = [] for path, subdirs, files in os.walk(directory): for name in files: if file_key in name and len(name.split(".")) < 3: file_list.append(os.path.join(path, name)) count = len(file_list) #Perform photometry on each .fits file for fits_file in file_list: if print_progress == True: print(count, ":", fits_file, flush = True) count -= 1 p = self.photometry(fits_file, radius) for elt in p: if elt[0] == "error": log.add_row([elt[1], elt[2]]) if print_progress == True: print("error", elt[2], "\n", flush = True) else: #We calculate the values to be entered in the table redshift = float(self.red_dict[elt[0]]) peculiar_redshift = np.sqrt((1 + (300 / 299792.458)) / (1 - (300 / 299792.458))) - 1 redshift_err = np.sqrt((redshift / 1000)**2 + (peculiar_redshift)**2) arcmin = cosmo.kpc_comoving_per_arcmin(redshift).value**2 #kpc^2 per arcmin^2 arcmin_err = self.conv_error(redshift, redshift_err) photom = elt[2] #The photometry value photom_err = elt[3] flux = flux_conv * photom #convert cps to flux using the conversion factor flux_err = self.flux_error(photom, photom_err, flux_conv) ldist = cosmo.luminosity_distance(redshift).cgs.value #Luminosity Distance (cm) ldist_err = self.lum_dist_error(redshift, redshift_err) lum = flux * 4 * np.pi * (ldist**2) #luminosity = flux*4*pi*r^2 lum_err = self.luminosity_error(flux, flux_err, ldist, ldist_err) sbrightness = lum * arcmin / 3600 sbrightness_err = self.surf_brightness_error(lum, lum_err, arcmin, arcmin_err) out.add_row([elt[0], redshift, redshift_err, elt[1], flux, flux_err, lum, lum_err, sbrightness, sbrightness_err]) out.sort(label + "Surface Brightness Error") out_unique = unique(out, keys = "sn") out_unique.sort("sn") return([out_unique, log])
def photometry(self, fits_file, radius): ''' Perform photometry on an int type .fits file. Args: fits_file (str) : File path of an int type .fits file radius (float): Unitless radius of the desired aperture in kpc Returns: results (list): [supernova name (str), exposure time (float) photometry value (float), photometry_error (float)] results (list): ["error" (str), fits file path (str), error description (str)] ''' results = [] if os.path.isfile(fits_file.replace("d-int", "d-skybg")): with fits.open(fits_file) as (int_file ), fits.open(fits_file.replace("d-int", "d-skybg")) as (skybg_file ): wcs = WCS(fits_file) for sn in self.cord_dict: #Define the SN location in pixels w = wcs.all_world2pix(self.cord_dict[sn].ra, self.cord_dict[sn].dec, 1) #Make sure the sn is located in the image if 0 < w[0] < 3600 and 0 < w[1] < 3600: #Find arcmin of a 1kpc radius region r = radius * u.kpc / cosmo.kpc_comoving_per_arcmin(float(self.red_dict[sn])) #Create an aperture aperture = SkyCircularAperture(self.cord_dict[sn], r) #create an array of the error in each pixel exp_time = int_file[0].header["EXPTIME"] int_error = np.sqrt(int_file[0].data / exp_time) skybg_error = np.sqrt(skybg_file[0].data / exp_time) #Perform photometry int_phot_table = aperture_photometry(int_file[0], aperture, error = int_error) if int_phot_table[0][0] == 0: check = self.zero_check(fits_file, self.cord_dict[sn], r) if check == 1: skybg_phot_table = aperture_photometry(skybg_file[0], aperture, error = skybg_error) photometry_sum = int_phot_table[0][0] - skybg_phot_table[0][0] photometry_error = np.sqrt(int_phot_table[0][1]**2 + skybg_phot_table[0][1]**2) results.append([sn, exp_time, photometry_sum, photometry_error]) elif check == 0: results.append(["error", fits_file, "no check file"]) else: skybg_phot_table = aperture_photometry(skybg_file[0], aperture, error = skybg_error) photometry_sum = int_phot_table[0][0] - skybg_phot_table[0][0] photometry_error = np.sqrt(int_phot_table[0][1]**2 + skybg_phot_table[0][1]**2) results.append([sn, exp_time, photometry_sum, photometry_error]) if results == []: results.append(["error", fits_file, "no supernova found"]) return(results) else: return(results) else: results.append(["error", fits_file, "no skybg file"]) return(results)