Пример #1
0
def calc_mags_z(zarray=arange(3.0, 6.1, 0.1), bands=['b', 'v', 'i', 'z']):
    # calculate the B-V v.s. V-z color-color track for the fiducial LBG template SED
    # use E(B-V) = 0.0, 0.15, and 0.3 as the value for dust extinction
    sp_ext0 = S.FileSpectrum('mylbg_sfr10.sed')
    ext15 = S.Extinction(0.15, 'xgal')
    ext30 = S.Extinction(0.30, 'xgal')
    sp_ext15 = sp_ext0 * ext15
    sp_ext30 = sp_ext0 * ext30
    mag_meik = {}
    mag_mad = {}
    mag_meik['zarray'] = zarray
    mag_mad['zarray'] = zarray
    for b in bands:
        mag_meik[b] = {}
        mag_mad[b] = {}
    for b in bands:
        mag_meik[b]['ext0'] = zeros(len(zarray))
        mag_meik[b]['ext15'] = zeros(len(zarray))
        mag_meik[b]['ext30'] = zeros(len(zarray))
        mag_mad[b]['ext0'] = zeros(len(zarray))
        mag_mad[b]['ext15'] = zeros(len(zarray))
        mag_mad[b]['ext30'] = zeros(len(zarray))

    for i in range(len(zarray)):
        for b in bands:
            mag_meik[b]['ext0'][i] = magredshift.mag_redshift(
                sp_ext0, zarray[i], bandpasses[b],
                igmroutine=igmtrans.meiksin)[0]
            mag_meik[b]['ext15'][i] = magredshift.mag_redshift(
                sp_ext15,
                zarray[i],
                bandpasses[b],
                igmroutine=igmtrans.meiksin)[0]
            mag_meik[b]['ext30'][i] = magredshift.mag_redshift(
                sp_ext30,
                zarray[i],
                bandpasses[b],
                igmroutine=igmtrans.meiksin)[0]
            mag_mad[b]['ext0'][i] = magredshift.mag_redshift(
                sp_ext0, zarray[i], bandpasses[b],
                igmroutine=igmtrans.madau)[0]
            mag_mad[b]['ext15'][i] = magredshift.mag_redshift(
                sp_ext15, zarray[i], bandpasses[b],
                igmroutine=igmtrans.madau)[0]
            mag_mad[b]['ext30'][i] = magredshift.mag_redshift(
                sp_ext30, zarray[i], bandpasses[b],
                igmroutine=igmtrans.madau)[0]
    return mag_meik, mag_mad
Пример #2
0
def make_mconvert_1500_z(zlo, zhi, dz, mcfile, ebmv=0.15, H0=70., 
                         omega_m=0.3, omega_l=0.7):
   calz = S.Extinction(ebmv, 'xgal')  # dust obscuration
   sp_ext = sp10 * calz  # dust obscured SED
   mconvertfile(sp_ext, zlo, zhi, dz, mcfile, restband=uni1500, obsband=zband,
      H0=H0, omega_m=omega_m, omega_l=omega_l)
   return 0 
Пример #3
0
 def __init__(self,
              template,
              refband=VJohnson,
              refmag=-21.0,
              ebmv=0.,
              extlaw='xgal',
              filters=default_filters,
              cosmo=cosmo_def):
     self.template = template
     self.sp = S.FileSpectrum(template)
     if ebmv > 0:
         self.sp = self.sp * S.Extinction(ebmv, extlaw)
     if type(refband) == type(1500.):
         self.refband = S.Box(refband, 100.)
     else:
         self.refband = refband
     self.refmag = refmag
     self.filternames = [f.name for f in filters]
     self.kcorrs = {}
     for f in filters:
         self.kcorrs[f.name] = kcorr.KCorrect(self.sp, self.refband, f)
     if type(cosmo) == type([]):
         self.cosmo = cosmoclass.cosmoclass(H0=cosmo[0],
                                            omega_m=cosmo[1],
                                            omega_l=cosmo[2])
     else:
         self.cosmo = cosmo
Пример #4
0
    def __init__(self,
                 ebvRange,
                 wave,
                 enableDIB=False,
                 enableFlux=True,
                 extinctionLaw='gal3'):
        self.points = np.array(ebvRange)
        values = []
        for ebv in ebvRange:
            extinctFlux = np.ones(wave.shape)
            if enableFlux:
                extinct = pysynphot.Extinction(ebv, extinctionLaw)
                extinctThroughPut = extinct.GetThroughput()[::-1]
                f = interpolate.interp1d(extinct.wave[::-1], extinctThroughPut)
                extinctFlux *= f(wave)

            if enableDIB:
                extinctFlux *= pydib.makeSpectrum(wave, ebv).flux

            values.append(extinctFlux)
        self.values = np.array(values)
        self.interpGrid = interpolate.interp1d(self.points,
                                               self.values.transpose(),
                                               fill_value=1,
                                               bounds_error=False)
Пример #5
0
    def __init__(self,
                 ebvRange,
                 wave,
                 enableDIB=False,
                 enableFlux=True,
                 extinctionLaw='gal3',
                 normRange=None):
        self.points = np.array(ebvRange)
        values = []
        for ebv in ebvRange:
            extinctFlux = np.ones(wave.shape)
            if enableFlux:
                extinct = pysynphot.Extinction(ebv, extinctionLaw)
                extinctThroughPut = extinct.GetThroughput()[::-1]
                f = interpolate.interp1d(extinct.wave[::-1], extinctThroughPut)
                extinctFlux *= f(wave)

            if enableDIB:
                extinctFlux *= pydib.makeSpectrum(wave, ebv).flux
            if normRange != None:
                extinctFluxSpec = oned.onedspec(wave,
                                                extinctFlux,
                                                mode='waveflux')
                extinctFlux /= np.mean(extinctFluxSpec[slice(*normRange)].flux)
            values.append(extinctFlux)
        self.values = np.array(values)
        self.interpGrid = interpolate.interp1d(self.points,
                                               self.values.transpose(),
                                               fill_value=1,
                                               bounds_error=False,
                                               kind='cubic')
def calc_dict(reddenings):

    EBmV_dict = {}  # { 0.0 : [u-g, g-r, r-i], ... }

    for EBmV in reddenings:

        spectrum = S.ArraySpectrum(np.array(wl), np.array(flx), 'angstrom',
                                   'flam')
        spectrum = spectrum * S.Extinction(EBmV, 'mwavg')

        #calculate colours
        obs_u = S.Observation(spectrum, u_bp)
        obs_g = S.Observation(spectrum, g_bp)
        obs_r = S.Observation(spectrum, r_bp)
        obs_i = S.Observation(spectrum, i_bp)

        u_min_g = obs_u.effstim(magsystem) - obs_g.effstim(magsystem)
        g_min_r = obs_g.effstim(magsystem) - obs_r.effstim(magsystem)
        r_min_i = obs_r.effstim(magsystem) - obs_i.effstim(magsystem)

        #Add EBmV and colours to the dictionary
        colours = [u_min_g, g_min_r, r_min_i]
        EBmV_dict[EBmV] = colours

    return EBmV_dict
Пример #7
0
    def __call__(self, z_range, obsband, outputfile):
        # Because m(z) = M + DM(z) + K_QR(z) := M + dm,
        # so dm = DM + K_QR.
        dm = np.zeros(len(z_range))
        sp = S.FileSpectrum(self.sedfile)
        dust = S.Extinction(self.ebmv, self.extlaw)
        sp_ext = sp * dust
        K = kcorr.KCorrect(sp_ext, self.Q, obsband, mode='AB')
        for i in range(len(z_range)):
            z = z_range[i]
            ## Use my own (clumsy) way to compute dm
            # m = self.factory.redshift(z_range[i]).ABmag(obsband)
            # dm[i] = m - self.normmag
            # self.factory.reset()
            ## Use my implementation of Hogg et al. K-correction
            dm[i] = self.cosmo.distmod(z) + K(z)
            if i % 20 == 0:
                sys.stdout.write('z = %.3f  \r' % z_range[i])
                sys.stdout.flush()
        f = open(outputfile, 'wb')
        f.write('# 1 z \n')
        f.write('# 2 dm \n')
        for i in range(len(z_range)):
            f.write('%.4f   %.6f  \n' % (z_range[i], dm[i]))

        f.close()
        print "Done!"
Пример #8
0
def get_model_spectra(teff, mh, logg, model='ck04models', L=1, ebv=0):
    '''
    
    For example: Temperature Teff=10000K, [M/H] = +0.1 and gravity log=3.0.
    model is the stellar model: 
    Castelli-Kurucz - ck04models
    Kurucz 1993 Atlas - k93models
        
    Parameters
    ----------
    teff : float
            The effective temperature of the star (in K).
    mh : string
            The metallicity as [M/H].
    logg : float
            The log g of the stellar model.
    model : string
            Gride stellar models that can be used to retrieve the models for stellar spectra.
            See: https://pysynphot.readthedocs.io/en/latest/appendixa.html
            for a description.
            
            Castelli-Kurucz - ck04models
            Kurucz 1993 Atlas - k93models
            Phoenix (F. Allard et al.) - phoenix
    L : float
            The bolometric luminosity of the star (in Lsun). It will be used to normalize the spectrum.
    ebv : float, default: 0
            The reddening to be applied to the model spectrum.    
            
    Returns
    -------
    s: pysynphot ArraySpectrum 
        The spectrum corresponding to the stellar model, scaled to the luminosity.
    
    Examples
    --------
    Temperature Teff=10000K, [M/H] = +0.1 and gravity log=3.0 for a star of 1 Lsun
    and no extinction.
    
    s = get_model_spectra(10000, 0.1, 3.0, model='ck04models', L=1, ebv=0)
    
    '''
    
    sp = ps.Icat(model, teff, mh, logg)

    if ebv != 0:
        sp = sp * ps.Extinction(ebv, 'lmcavg')
    
    F_model = sp.trapezoidIntegration(sp.wave, sp.flux)*(u.erg/u.s/u.cm**2) #In erg / s / cm**2
    Lmodel = (4 * np.pi * ((10*u.pc).to(u.cm))**2 * F_model ).to(u.Lsun)
    norm = L/Lmodel

    newflux = sp.flux * norm
    
    s = ps.ArraySpectrum(sp.wave, newflux, fluxunits="flam")
    
    return s
Пример #9
0
def fit_beta_sed(sedfile, beta0, ebmv=0.):
    # a wrapper that takes an SED, read it with pysynphot, and find the best-fit beta
    sp = S.FileSpectrum(sedfile)
    if ebmv > 0.:
        sp = sp * S.Extinction(ebmv, 'xgal')
    wave = sp.wave[(sp.wave >= 1220.) &
                   (sp.wave <= 3200.)]  # the rest-frame wavelength range
    sedflux = sp.sample(wave)  # the flux from sp
    x = fit_beta(wave, sedflux, beta0=beta0)
    return x[0][0]
Пример #10
0
    def test_merge_wave_sets(self):
        bb = S.BlackBody(20000)
        ext = S.Extinction(0.04, 'gal1')

        new_wave = S.spectrum.MergeWaveSets(bb.wave, ext.wave)

        delta = new_wave[1:] - new_wave[:-1]

        self.assertTrue((delta > S.spectrum.MERGETHRESH).all(),
                        msg='Deltas should be < %g, min delta = %f' %
                        (S.spectrum.MERGETHRESH, delta.min()))
Пример #11
0
def get_synthetic_mag_file(filename, filt_out, system_out, filt_in=None, mag_in=None, system_in=None, ebv=0, force=None):
    '''
    Scales the input spectrum (read from the filename file) to the magnitude 
    provided in the filter_in band, and obtains the synthetic photometry in the filter_out band.
    If no scaling magnitude is provided, the original spectrum is used to compute the synthetic mangitude.
    
    Parameters
    ----------
    filename : string
            The name of the file which contains the spectrum.
    filt_out : string
            The name of the filter the system will compute the output of.
    system_out : string
            The system in which the output magntiudes are measured. "abmag" or "vegamag" or "stmag"
    filt_in : string
            The name of the filter we want to scale the spectrum.
    mag_in : float
            The mangtude of the object in the filter_in band.
    system_in : string
            The system in which the input magntiude is measured. "abmag" or "vegamag" or "stmag"
    ebv : float, default: 0
            The reddening to be applied to the model spectrum.    
    force : string, default: None
            Whether the magnitude should be extrapolated in case the filter and the spectrum wavelengths do not
            completely overlap. You may use force=[extrap|taper] to force this Observation anyway.
            
    Returns
    -------
    
    mag_out : float
                The synthetic photometry magnitude of the input spectrum once 
                scaled to its mag_in value in filter_out band.
    '''
    sp = ps.FileSpectrum(filename)
    sp_ext = sp * ps.Extinction(ebv, 'mwavg')
    
    if not( filt_in is None or mag_in is None or system_in is None):
        sp_norm = sp_ext.renorm(mag_in, system_in, ps.ObsBandpass(filt_in))
    else:
        sp_norm = sp_ext
        
    try:
        obs = ps.Observation(sp_norm, ps.ObsBandpass(filt_out), binset=sp_norm.wave, force=force)
    except ValueError:
        bp = ps.FileBandpass(banddic[filt_out])
        obs = ps.Observation(sp_norm, bp, binset=sp.wave)
        
    mag_out = obs.effstim(system_out)
    
    return mag_out
Пример #12
0
def get_grid_phoenixmodels_extinct(extvalue):

    index = 1
    for temp in Temperature_range:
        for logg in Set_Log_G:
            for logz in Set_Log_Z:
                data[index, index_temp] = temp
                data[index, index_logg] = logg
                data[index, index_logz] = logz

                sed = S.Icat('phoenix', temp, logz, logg) * S.Extinction(
                    extvalue, 'mwavg')
                sed.convert(
                    'flam')  # to be sure every spectrum is in flam unit
                if (max(sed.flux) >
                        0):  # remove empty fluxes because of bad parameters
                    data[index, index_val] = 1
                    func = interp1d(sed.wave, sed.flux, kind='cubic')
                    flux = func(WL)
                    data[index, index_spec:] = flux
                index += 1
Пример #13
0
def create_stellar_atmosphere_grid(BPs = ['acs,wfc1,f475w'], ZPs = [26.168e0], ebv = 0.01, Z = 0.01):
	import pysynphot as S
	BPs = [S.ObsBandpass(BP) for BP in BPs]
	spectra = glob.glob('./data/grp/hst/cdbs/grid/ck04models/ckm{Z}/ckm{Z}*.fits'.format(Z = int(Z*1000)))
	logg_range = np.arange(0,5.5,0.5)

	filter_mag_grids = {}

	for BP in range(len(BPs)):
		magnitudes = np.zeros([len(logg_range)*len(spectra),3])
		for ii in range(len(spectra)):
			spec_file = spectra[ii]
			Teff = file.split('_')[1].split('.')[0]
			for logg in logg_range:
				gg = 'g{0:02d}'.format(10*logg)
				base_spec = S.FileSpectrum(spec_file,fluxname = gg)
				base_spec = base_spec * (6.957e8 / 3.0857e19)**2.e0
				if sum(base_spec.flux) != 0:
					spec = base_spec * S.Extinction(ebv,'gal3')
					obs = S.Observation(spec,BPs[BP])
					count = obs_475.countrate()
					mag = -2.5e0 * np.log10(count) + ZPs[BP]
				else:
					mag = np.nan

				magnitudes[0] = logg
				magnitdues[1] = Teff
				magnitudes[2] = mag
			
				print('done {}'.format(gg))
			print('done {}'.format(Teff))

		filter_mag_grids[BPs[BP]] = magnitues

	f = open('model_atmosphere_ebv{ebv:.3f}_Z{Z:.3f}.dat'.format(ebf=ebv,Z=Z),'w')
	f.write(str(filter_mags))
	f.close()
Пример #14
0
 def test4(self):
     self.xt = S.Extinction(0.2, S.Cache.RedLaws['smcbar'])
     self.assertTrue(isinstance(self.xt, spectrum.SpectralElement))
Пример #15
0
def calc_reddened_colours(temp):

    magsystem = 'vegamag'

    #read in transmission tables describing the VPHAS+ filter curves
    fpaths = glob.glob(
        '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/vphas_atmosphere_included_filters/*.dat'
    )
    for fpath in fpaths:
        bandpass = S.FileBandpass(fpath)
        with open(fpath, 'r') as f:
            tab = [line.strip().split() for line in f]
        #if 'u_SDSS' in fpath:
        #	u_bp = bandpass
        #elif 'g_SDSS' in fpath:
        #	g_bp = bandpass

        #use the filtercurved emailed by Janet Drew that contain the known u
        # and g band red leak
        if 'u-transmission' in fpath:
            bandpass = S.FileBandpass(fpath)
            u_bp = bandpass
        elif 'g-transmission' in fpath:
            bandpass = S.FileBandpass(fpath)
            g_bp = bandpass

        elif 'r_SDSS' in fpath:
            r_bp = bandpass
        elif 'i_SDSS' in fpath:
            i_bp = bandpass

    #read in PN model spectra from the TMAP models
    tmap_paths = glob.glob(
        '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/TubingenModels/'
        + str(temp) + 'kK_7.0_solar/*.txt')
    if len(tmap_paths) == 0:
        print 'File does not exist'
        print '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/TubingenModels/' + str(
            temp) + 'kK_7.0_solar/*.txt'
        sys.exit()
    fpath = tmap_paths[0]

    #read the spectrum into a table
    colnames = ['lambda', 'F_lambda']
    wl = []
    flx = []
    with open(fpath, 'r') as f:
        for line in f:
            line = line.split()
            wl.append(float(line[0]))  #A
            #convert flux from erg/cm**2/s/cm to erg/s/cm**2/A
            flx_cgs = float(line[1]) * 1e-8
            flx.append(flx_cgs)

    #E(B-V) values to calculate
    reddenings = np.arange(0, 31, 1)  #0, 0.1, 0.2, ...., 2.9, 3.0
    reddenings = [round(line / 10., 3) for line in reddenings]

    EBmV_dict = {}  # { 0.0 : [u-g, g-r, r-i], ... }
    for EBmV in reddenings:

        #construct spectrum for pysynphot
        spectrum = S.ArraySpectrum(np.array(wl), np.array(flx), 'angstrom',
                                   'flam')

        #convert from flam to photons, as colours need to be calculatated in photon counts
        spectrum.convert('counts')

        #redden the spectrum using cardelli1989 and Rv=3.1
        spectrum = spectrum * S.Extinction(EBmV, 'mwavg')

        obs_u = S.Observation(spectrum, u_bp)
        obs_g = S.Observation(spectrum, g_bp)
        obs_r = S.Observation(spectrum, r_bp)
        obs_i = S.Observation(spectrum, i_bp)

        #calculate colours
        u_min_g = obs_u.effstim(magsystem) - obs_g.effstim(magsystem)
        g_min_r = obs_g.effstim(magsystem) - obs_r.effstim(magsystem)
        r_min_i = obs_r.effstim(magsystem) - obs_i.effstim(magsystem)

        #Add EBmV and colours to the dictionary
        colours = [u_min_g, g_min_r, r_min_i]
        EBmV_dict[EBmV] = colours

    return EBmV_dict
Пример #16
0
              ('pickles_uk_40', 'M2V'), ('pickles_uk_43',
                                         'M4V'), ('pickles_uk_44', 'M5V'))

# Lightpath data
instrument = 'ucam'
telescope = 'ntt'
filt = 'super'

# Apply extinction to that spectrum
a_g = 0.561
# a_g = 0.0

# Convert from Gaia Ag to EBV
a_v = a_g / 0.789
ebv = a_v / 3.1
ext = S.Extinction(ebv, 'gal3')

# SDSS filters
sdss_filters = ['u', 'g', 'r', 'i', 'z']
# Super SDSS filters
super_filters = ['u_s', 'g_s', 'r_s', 'i_s', 'z_s']

cam_filters = super_filters if filt == 'super' else sdss_filters

# Lets store it all in a pandas dataframe.
INFO = ['SpecType', 'PicklesName']
SDSS_COLOURS = ['u-g', 'g-r', 'r-i', 'i-z']
CORRECTIONS = ["{}-{}".format(a, b) for a, b in zip(cam_filters, sdss_filters)]

COLNAMES = INFO + SDSS_COLOURS + CORRECTIONS
table = pd.DataFrame(columns=COLNAMES)
Пример #17
0
    #expected flux per cm^2 at 1kpc
    F = L / (4 * math.pi * (distance**2))  #erg/s/cm^2 /ster?
    #Expected flux per sq cm of a CS  at the distance
    print 'Flux at ', distance_parsec, 'pc: ', F, 'erg/s/cm^2'

    #calcualte multiplication factor needed to convert the input spectum to one of an object at 1kpc
    m_factor = F / total_flux
    new_flux = [line['F_lambda'] * m_factor for line in spectrum]  #erg/s/cm^2

    #multiply by the star's surface area to get erg/s
    new_flux = [line * SA for line in new_flux]

    #redden the array using CCM1998, Rv=3.1
    spectrum = S.ArraySpectrum(np.array(wl), np.array(new_flux), 'angstrom',
                               'flam')
    spectrum = spectrum * S.Extinction(EBmV, 'mwavg')

    #calculate colours
    obs_u = S.Observation(spectrum, u_bp)
    obs_g = S.Observation(spectrum, g_bp)
    obs_r = S.Observation(spectrum, r_bp)
    obs_i = S.Observation(spectrum, i_bp)

    u_mag = obs_u.effstim(magsystem)
    g_mag = obs_g.effstim(magsystem)
    r_mag = obs_r.effstim(magsystem)
    i_mag = obs_i.effstim(magsystem)

    u_min_g = obs_u.effstim(magsystem) - obs_g.effstim(magsystem)
    g_min_r = obs_g.effstim(magsystem) - obs_r.effstim(magsystem)
    r_min_i = obs_r.effstim(magsystem) - obs_i.effstim(magsystem)
			#flux of whole star at Earth = BB_flux* 4*pi*/D^2
			#D=1kpc=3.086e16m = 3.086e18cm
			distance_parsec = distance #pc
			distance_m = distance_parsec * 3.086e16 #meters
			distance_cm = distance_m * 100 #cm

			F = expected_lum / (4*math.pi*(distance_cm**2)) #expected flux of the star at the distance
			factor = F / total_flux
			spect = [val * factor for val in spect]

			#convolve with the vphas bands
			spectrum=S.ArraySpectrum(np.array(wavelengths_AA), np.array(spect), waveunits='angstrom', fluxunits='flam')
	
	
			#redden the spectrum
			spectrum = spectrum * S.Extinction(reddening, 'mwavg')	
	
	
			#calculate magnitudes and colours using pysynphot
			obs_u = S.Observation(spectrum, u_bp)
			obs_g = S.Observation(spectrum, g_bp)
			obs_r = S.Observation(spectrum, r_bp)
			obs_i = S.Observation(spectrum, i_bp)

			u = obs_u.effstim(magsystem)
			g = obs_g.effstim(magsystem)
			r = obs_r.effstim(magsystem)
			i = obs_i.effstim(magsystem)
				
			parameters.append(u)
			parameters.append(g)
Пример #19
0
cs_factor = F_CS/CS_total_flux
CS = [val*cs_factor for val in CS]



#sum the flux of the CS and MS stars
spectra_sum = [line[0]+line[1] for line in zip(CS, MS)]


#convolve with the vphas bands
spectrum=S.ArraySpectrum(np.array(wavelengths_AA), np.array(spectra_sum), waveunits='angstrom', fluxunits='flam')

	
	
"""apply a reddening to the binary's spectrum"""
spectrum = spectrum * S.Extinction(EBmV_applied, 'mwavg')	
	
	
	
#calculate magnitudes and colours using pysynphot
obs_u = S.Observation(spectrum, u_bp)
obs_g = S.Observation(spectrum, g_bp)
obs_r = S.Observation(spectrum, r_bp)
obs_i = S.Observation(spectrum, i_bp)
obs_V = S.Observation(spectrum, S.ObsBandpass('V'))
obs_B = S.Observation(spectrum, S.ObsBandpass('B'))
obs_R = S.Observation(spectrum, S.ObsBandpass('R'))
obs_J = S.Observation(spectrum, S.ObsBandpass('J'))

u = obs_u.effstim(magsystem)
g = obs_g.effstim(magsystem)
Пример #20
0
            flx.append(float(line[1]) * 1e-8)  #convert to per angstrom

    spectrum = S.ArraySpectrum(np.array(wl), np.array(flx), 'angstrom', 'flam')

    #convert from flam to photons, as colours need to be calculatated in photon counts
    spectrum.convert('counts')

    #redden the spectrum  using Cardelli 1989, RV=3.1
    E_BmV = [
        0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3,
        1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7,
        2.8, 2.9
    ]

    for e in E_BmV:
        red_spectrum = spectrum * S.Extinction(e, 'mwavg')

        #calcuate colours
        obs_u = S.Observation(red_spectrum, u_bp)
        obs_g = S.Observation(red_spectrum, g_bp)
        obs_r = S.Observation(red_spectrum, r_bp)
        obs_i = S.Observation(red_spectrum, i_bp)
        obs_J = S.Observation(red_spectrum, J_bp)

        magsystem = 'vegamag'

        u_min_g = obs_u.effstim(magsystem) - obs_g.effstim(magsystem)
        g_min_r = obs_g.effstim(magsystem) - obs_r.effstim(magsystem)
        r_min_i = obs_r.effstim(magsystem) - obs_i.effstim(magsystem)
        #g_min_i = obs_g.effstim(magsystem) - obs_i.effstim(magsystem)
        #g_min_J = obs_g.effstim(magsystem) - obs_J.effstim(magsystem)
    distance = distance * 100  #cm
    F = L / (4 * math.pi * (distance**2))  #erg/s/cm^2
    print 'Flux at 10kpc: ', F, 'erg/s/cm^2'

    #calcualte multiplication factor needed to convert the input spectum to one of an object at 10kpc
    m_factor = F / total_flux
    new_flux = [line['F_lambda'] * m_factor for line in spectrum]

    #make recarray with new flux values
    #spectrum = make_recarray( zip(wl,new_flux), colnames)

    #redden the array using CCM1998
    EBmV = 1.0
    reddened_spectrum = S.ArraySpectrum(np.array(wl), np.array(new_flux),
                                        'angstrom', 'flam')
    reddened_spectrum = reddened_spectrum * S.Extinction(EBmV, 'mwavg')
    spectrum = make_recarray(
        zip(reddened_spectrum.wave, reddened_spectrum.flux), colnames)
    wl = list(reddened_spectrum.wave)

    spectrum = S.ArraySpectrum(np.array(wl), np.array(reddened_spectrum.flux),
                               'angstrom', 'flam')
    """			
	#interpolate the u filter so the spectrum can be convolved with it
	filter_interp = interp1d(u['wavelength'], u['transmission'], kind='linear')
	filter_new = []  # u filter with same wavelength spacing as the spectrum
	convolved = []
	for line in spectrum:
		if line['lambda']>min(u['wavelength']) and line['lambda']<max(u['wavelength']):
			flux_transmission = filter_interp(line['lambda'])
			convolved.append(flux_transmission * line['F_lambda'])
Пример #22
0
 def setUp(self):
     #Uses new extinction functionality
     self.oldsmc = S.Extinction(0.2, 'smc')
     self.newsmc = S.Extinction(0.2, 'smcbar')
Пример #23
0
def mkinput(ngal,
            Mlo,
            Mhi,
            Mdist,
            extpar,
            zlo,
            zhi,
            bands,
            igmroutine=meiksin.meiksin,
            spec=SED_LBG2,
            extdist='uniform',
            lyadist='Lya_EW_dist.txt',
            w0=0.,
            w1=20.,
            restwave=1500.):
    """
   Generate input catalog for LBG simulation
   Use randomly drawn values of E(B-V), z, absolute magnitude at the specified
   rest-frame wavelength, and Ly-alpha equivalent width.
   """
    sp = S.FileSpectrum(spec)
    random.seed()
    # randomly draw E(B-V), z, and M
    # use either a flat distribution ('uniform') or a Gaussian distribution ('gaussian')
    if extdist == 'uniform':
        ebmvr = draw_ebmv_uniform(extpar[0], extpar[1], size=ngal)
    elif extdist == 'gaussian':
        ebmvr = draw_ebmv_gaussian(extpar[0], extpar[1], size=ngal)
    elif extdist == 'lognormal':
        ebmvr = draw_ebmv_lognormal(extpar[0], extpar[1], size=ngal)
    zr = draw_z_uniform(
        zlo, zhi, size=ngal
    )  # draw a redshift from a flat distribution between zlo and zhi

    if Mdist == 'uniform':
        Mr = draw_M_uniform(Mlo, Mhi, size=ngal)
        # draw an M_1500 from a flat distribution between Mlo and Mhi
    elif Mdist == 'single':
        # Use a single value for input absolute magnitude M=-21.0, therefore
        # will ignore MLO and MHI.
        # This is useful if one is interested in colors only; apparent magnitudes
        # can be scaled later with respect to the reference absolute magnitude
        Mr = ones(ngal) * -21.0
    assert len(Mr) == ngal, "Input absolute magnitudes are not generated."
    #?? Should I draw from a reasonbly assumed LF??

    # draw equivalent width from Lya EW distribution at z~1-3 provided by Naveen Reddy
    if lyadist == 'uniform':
        lya_ew = random.uniform(w0, w1, size=ngal)
    elif len(lyadist) > 0:
        ld = sextractor(lyadist)
        lya_ew = draw_lya(ngal, ld.lya_ew, ld.pdf)
    else:
        lya_ew = zeros(ngal)
    if bands == 'highz_bands':
        bands = {}
        for b in highz_bands:
            bands[b] = filters[b]
    else:
        bandnames = copy.copy(bands)
        bands = {}
        for b in bandnames:
            bands[b] = filters[b]

    mags = zeros((len(bands), ngal))
    kc = zeros((len(bands), ngal))
    restband = S.Box(restwave, 100.)

    for i in range(ngal):
        if i % 500 == 0:
            print "%d done." % i
            sys.stdout.flush()
        ext = S.Extinction(ebmvr[i], 'xgal')
        spec_ext = sp * ext  # apply dust extinction to rest-frame SED
        # calculate observed magnitudes (normalized to M_1500 = Mr[i]) of each band, using the drawn redshift &
        # Lya EW
        for j in range(len(bands)):
            # b = bands[j]
            b = bands.keys()[j]
            mags[j][i], kc[j][i] = simkcorr.simkcorr(spec_ext, Mr[i], restband,
                                                     bands[b], zr[i],
                                                     lya_ew[i])
    results = []
    for i in range(len(bands)):
        results += [mags[i]]
    results += [zr, ebmvr, Mr, lya_ew]
    return array(results)
Пример #24
0
 def test1(self):
     self.xt = S.Extinction(0.3, 'mwdense')
     self.assertTrue(isinstance(self.xt, spectrum.SpectralElement))
Пример #25
0
 def test1(self):
     self.sp = S.Extinction(0.2, 'gal1')  #Make an extinction law
     self.sp.convert('1/um')  #convert to inverse microns
     refwave = extinction._buildDefaultWaveset()
     testwave = self.sp.wave
     self.assertApproxNumpy(testwave, refwave)
Пример #26
0
def make_mconvert_1500_z(zlo, zhi, dz, mcfile, ebmv=0.15):
   calz = S.Extinction(ebmv, 'xgal')  # dust obscuration
   sp_ext = sp10 * calz  # dust obscured SED
   mconvertfile(sp_ext, zlo, zhi, dz, mcfile, restband=uni1500, obsband=zband)
   return 0 
Пример #27
0
 def test6(self):
     self.xt = S.Extinction(0.3)
     self.assertTrue(isinstance(self.xt, spectrum.SpectralElement))
     self.assertTrue('mwavg' in self.xt.name.lower())