Esempio n. 1
0
def abs_m(m, z, **cosmo):
    """ Return the absolute magnitude
    m: apparent magnitude
    z: redshift

    >>> abs_m(17.7, 0.1)
    array([-20.61520457])
    """

    m = np.atleast_1d(m)
    z = np.atleast_1d(z)
    if cosmo == {}:
        cosmo_in = {
            'omega_M_0': 0.3,
            'omega_lambda_0': 0.7,
            'omega_k_0': 0.0,
            'h': 0.70
        }
    else:
        cosmo_in = cosmo

    lum_dist = cd.luminosity_distance(z, **cosmo_in)

    absm = -25. + m - 5.0 * np.log10(lum_dist)
    return absm
Esempio n. 2
0
def Get_SdV(z,frq_r,L_line,L_units):
    """ PURPOSE: 
                Computes the velocity-integrated line flux (SdV)
                for a given source redshift, rest-frame line frequency, 
                and line luminosity.
               
        INPUT:
                z            :       source redshift
                frq_r        :       rest-frame frequency [GHz]
                L_line       :       line luminosity
                L_units      :       'prime': [L_line] = K km/s pc^2 or 
                                     'solar': = [L_line] = Lsolar

		OUTPUT:
				SdV			 :		 Line flux [Jy km/s]
                
        HISTORY: Feb 2015   :       created by [email protected]        
    """
    
    #Calculate luminosity distance in [Mpc]
    d_L = cd.luminosity_distance(z, **cosmo) 

    #calculate observed frequency
    frq_o = frq_r/(1.0+z)
    
    if L_units == 'prime':
		SdV = (L_line/3.25E7)*(frq_o**2)*((1.0+z)**3)/(d_L**2)
    elif L_units == 'solar':
        SdV = (((L_line/1.04E-3)*(1.+z))/(d_L*d_L))/frq_r
    else:
        print 'Wrong input'
        return -1
    
    return SdV
Esempio n. 3
0
def modelTheo(z, omegam, omegal):
    tab = []
    cosmo = {'omega_M_0': omegam, 'omega_lambda_0': omegal, 'h': 0.70}
    cosmo = cd.set_omega_k_0(cosmo)
    for i in range(0, len(z)):
        tab.append(cd.luminosity_distance(z[i], **cosmo) * 10**5)
    return tab
Esempio n. 4
0
 def zdistance(self, clus_z, H0=100.0):
     """
     Finds the angular diameter distance for an array of cluster center redshifts.
     Instead, use angular distance file precalculated and upload.
     """
     cosmo = {'omega_M_0': 0.3, 'omega_lambda_0': 0.7, 'h': H0 / 100.0}
     cosmo = cd.set_omega_k_0(cosmo)
     ang_d = cd.angular_diameter_distance(clus_z, **cosmo)
     lum_d = cd.luminosity_distance(clus_z, **cosmo)
     return ang_d, lum_d
Esempio n. 5
0
 def zdistance(self,clus_z,H0=100.0):
     """
     Finds the angular diameter distance for an array of cluster center redshifts.
     Instead, use angular distance file precalculated and upload.
     """
     cosmo = {'omega_M_0':0.3,'omega_lambda_0':0.7,'h':H0/100.0}
     cosmo = cd.set_omega_k_0(cosmo)
     ang_d = cd.angular_diameter_distance(clus_z,**cosmo)
     lum_d = cd.luminosity_distance(clus_z,**cosmo)
     return ang_d,lum_d
Esempio n. 6
0
def get_column(zin, z_r=6.0):
    #
    # Returns : HI column density in IGM.
    #
    delz = 0.1
    z = np.arange(z_r, zin, delz)
    try:
        nH = np.zeros(len(z), dtype='float32')
    except:
        nH = 0

    # From Cen & Haiman 2000
    nH = 8.5e-5 * ((1. + z) / 8)**3  # in cm^-3
    NH = 0
    for zz in range(len(z)):
        d1 = cd.luminosity_distance(z[zz] - delz, **cosmo)
        d2 = cd.luminosity_distance(z[zz] + delz, **cosmo)
        dx = (d2 - d1) * Mpc_cm
        NH += nH[zz] * dx / (1. + z[zz])

    return NH
def test_distances(threshold = 1e-3):
    """Compare distance measures with calculations from http://icosmo.org/"""
    cosmo = cosmo_wmap_5()

    print "Comparing distances with calculations from http://icosmo.org/"

    # load external distance calculations
    # z  DA(z)   DT(z)   DL(z) 
    distance_file = os.path.dirname(os.path.abspath(__file__))
    distance_file = os.path.join(distance_file, 'icosmo_testdata', 
                                 'distances.txt')
    ic_dists = numpy.loadtxt(distance_file)

    z = ic_dists[:,0]

    cd_da = cd.angular_diameter_distance(z, **cosmo)
    cd_dt = cd.light_travel_distance(z, **cosmo)
    cd_dl = cd.luminosity_distance(z, **cosmo)
    cd_dm = cd.comoving_distance_transverse(z, **cosmo)
    
    cd_dists = numpy.vstack((cd_dm, cd_da, cd_dt, cd_dl))

    labels = [ r'$D_M$', r'$D_A$', r'$D_T$', r'$D_L$']
    threshold = [1e-7,    1e-7,     1e-3,    1e-7    ]  

    # print ic_dists[-1].transpose()
    # print cd_dists[:,-1]
    pylab.figure()
    for i in range(len(labels)):
        pylab.plot(ic_dists[:,0], ic_dists[:,i+1], 
                   label=labels[i] +' IC', ls=':')
        pylab.plot(z, cd_dists[i], label=labels[i] +' distance.py', ls='-')
        pylab.legend(loc='best')

    pylab.figure()

    for i in range(len(labels)):
        diff = (cd_dists[i] - ic_dists[:,i+1]) / ic_dists[:,i+1]
        maxdiff = numpy.max(numpy.abs(diff[ic_dists[:,i+1] > 0]))
        print "Maximum fraction difference in %s is %e." % (labels[i],
                                                            maxdiff)
        assert(numpy.all(maxdiff < threshold[i]))
        pylab.plot(ic_dists[:,0], 
                   diff, 
                   label=labels[i], ls='-')

    #pylab.plot(z, err2, label=labels[1] + ' err.', ls=':')
    #pylab.plot(z, err3, label=labels[2] + ' err.', ls=':')
    #pylab.plot(z, err5, label=labels[3] + ' err.', ls=':')
    #pylab.plot(z, err6, label=labels[0] + ' err.', ls=':')

    pylab.legend(loc='best')
Esempio n. 8
0
def test_distances(threshold = 1e-3):
    """Compare distance measures with calculations from http://icosmo.org/"""
    cosmo = cosmo_wmap_5()

    print("Comparing distances with calculations from http://icosmo.org/")

    # load external distance calculations
    # z  DA(z)   DT(z)   DL(z) 
    distance_file = os.path.dirname(os.path.abspath(__file__))
    distance_file = os.path.join(distance_file, 'icosmo_testdata', 
                                 'distances.txt')
    ic_dists = numpy.loadtxt(distance_file)

    z = ic_dists[:,0]

    cd_da = cd.angular_diameter_distance(z, **cosmo)
    cd_dt = cd.light_travel_distance(z, **cosmo)
    cd_dl = cd.luminosity_distance(z, **cosmo)
    cd_dm = cd.comoving_distance_transverse(z, **cosmo)
    
    cd_dists = numpy.vstack((cd_dm, cd_da, cd_dt, cd_dl))

    labels = [ r'$D_M$', r'$D_A$', r'$D_T$', r'$D_L$']
    threshold = [1e-7,    1e-7,     1e-3,    1e-7    ]  

    # print ic_dists[-1].transpose()
    # print cd_dists[:,-1]
    pylab.figure()
    for i in range(len(labels)):
        pylab.plot(ic_dists[:,0], ic_dists[:,i+1], 
                   label=labels[i] +' IC', ls=':')
        pylab.plot(z, cd_dists[i], label=labels[i] +' distance.py', ls='-')
        pylab.legend(loc='best')

    pylab.figure()

    for i in range(len(labels)):
        diff = (cd_dists[i] - ic_dists[:,i+1]) / ic_dists[:,i+1]
        maxdiff = numpy.max(numpy.abs(diff[ic_dists[:,i+1] > 0]))
        print("Maximum fraction difference in %s is %e." % (labels[i],
                                                            maxdiff))
        assert(numpy.all(maxdiff < threshold[i]))
        pylab.plot(ic_dists[:,0], 
                   diff, 
                   label=labels[i], ls='-')

    #pylab.plot(z, err2, label=labels[1] + ' err.', ls=':')
    #pylab.plot(z, err3, label=labels[2] + ' err.', ls=':')
    #pylab.plot(z, err5, label=labels[3] + ' err.', ls=':')
    #pylab.plot(z, err6, label=labels[0] + ' err.', ls=':')

    pylab.legend(loc='best')
Esempio n. 9
0
    def __init__(self, redshift, limitingObsMag=27):
        self.cosmo = {'omega_M_0': 0.3, 'omega_lambda_0': 0.7, 'h': 0.7}
        self.cosmo = distance.set_omega_k_0(self.cosmo)

        distancePc = \
          distance.luminosity_distance(redshift, **self.cosmo)*1e6

        limitingAbsoluteMag = limitingObsMag - \
          5.*np.log10(distancePc) + 5

        self.magnitudes = np.linspace(-28, limitingAbsoluteMag, 10000)
        self.dMag = self.magnitudes[1] - self.magnitudes[0]
        self.redshift = redshift
        self.getLuminosityStar()
        self.getMagnitudeStar()
        self.getLuminosityFunction()
Esempio n. 10
0
    def get_lumdist(self, z):
        """Calculates the luminosity distance to redshift z.

        Uses :func:`cosmolopy.distance.luminosity_distance`, 
        which is based on David Hogg's `Distance measures in cosmology.
        <https://arxiv.org/abs/astro-ph/9905116>`_

        Args:
            z (float): Redshift 

        Returns:
            float: Luminosity distance in cm
        """
        # luminosity distance in Mpc
        dlum_mpc = cd.luminosity_distance(z, **self.cosmo) 
        return dlum_mpc * cc.Mpc_cm
Esempio n. 11
0
def Get_Line_Luminosity(z, SdV, transition, *unit):
	"""This function calculates the line luminosity for a given redshift (z), transition line
	flux density (sdv, in units of Jy km/s). The output luminosity is in units of K km/s pc^2 or
	Lsolar if 'Lsolar' keyword is set"""

	d_L = cd.luminosity_distance(z, **cosmo)   #[Mpc]

	f=open('../../frequencies/frequencies.dat','r')
	lines=f.readlines()
	f.close()

	trans=[]
	frq_r=[]
	for line in lines:
		p=line.split()
		if p != []:
			trans.append(p[0])
			frq_r.append(p[1])

	frq_r=[float(x) for x in frq_r]
	trans=np.array(trans)

	indices=[i for i,x in enumerate(trans) if transition in x]
	frq_r=[frq_r[i] for i in indices]
	frq_r=np.array(frq_r)/1.E3  #[GHz]
	frq_o=(frq_r/(1.+z))        #[GHz]

	L_transition=3.25E7*SdV*(1./(frq_o*frq_o))*d_L*d_L/((1.0+z)**3.)    #[K km/s pc^2]

	if unit == 'Lsolar':
		L_transition=3.18E4*((frq_r/100.)**3.)*(L_transition/1.E9)             #[Lsolar]

	#If SdV is undefined, then L_transition is undefined
	indices=[i for i, item in enumerate(SdV) if item == -999]
	if indices != []:
		for j in indices:
			L_transition[j]=-999
	#If SdV is upper limit, then L_transition is upper limit
	indices=[i for i, item in enumerate(SdV) if item == 99]
	if indices != []:
		for j in indices:
			L_transition[j]=99

	return L_transition
Esempio n. 12
0
def distance_modulus(z, **cosmo):
    """Distance modulus mu = m-M.

    The distance modulus is the difference between the apparent and
    absolute magnitudes,

      mu = 5 log(d/10 pc)

    Usage
    -----

    >>> from cosmolopy import fidcosmo, magnitudes
    >>> "mu(z=6) = %.4g" % magnitudes.distance_modulus(6.0, **fidcosmo)
    'mu(z=6) = 48.86'
    
    """
    dl = cd.luminosity_distance(z, **cosmo)
    mu = 5 * numpy.log10(dl / (10e-6))
    return mu
Esempio n. 13
0
def distance_modulus(z, **cosmo):
    """Distance modulus mu = m-M.

    The distance modulus is the difference between the apparent and
    absolute magnitudes,

      mu = 5 log(d/10 pc)

    Usage
    -----

    >>> from cosmolopy import fidcosmo, magnitudes
    >>> "mu(z=6) = %.4g" % magnitudes.distance_modulus(6.0, **fidcosmo)
    'mu(z=6) = 48.86'
    
    """
    dl = cd.luminosity_distance(z, **cosmo)
    mu = 5 * numpy.log10(dl/(10e-6))
    return mu
def test_figure3():
    """Plot Hogg fig. 3: The dimensionless luminosity distance DL/DH

    The three curves are for the three world models, 

    - Einstein-de Sitter (omega_M, omega_lambda) = (1, 0) [solid]
    
    : Low-density (0.05, 0) [dotted]

    -- High lambda, (0.2, 0.8) [dashed]

    Hubble distance DH = c / H0

    z from 0--5
    DL / DH from 0--16

    """

    z = numpy.arange(0, 5.05, 0.05)

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[1.0],[0.05],[0.2]])
    cosmo['omega_lambda_0'] = numpy.array([[0.0],[0.0],[0.8]])
    cosmo['h'] = 0.5
    cd.set_omega_k_0(cosmo)
    
    linestyle = ['-', ':', '--']

    dh = cd.hubble_distance_z(0, **cosmo)
    dl = cd.luminosity_distance(z, **cosmo)

    pylab.figure(figsize=(6,6))
    for i in range(len(linestyle)):
        pylab.plot(z, (dl/dh)[i], ls=linestyle[i])
    pylab.xlim(0,5)
    pylab.ylim(0,16)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"luminosity distance $D_L/D_H$")
    pylab.title("compare to " + inspect.stack()[0][3].replace('test_', '') + 
                " (astro-ph/9905116v4)")
Esempio n. 15
0
def test_figure3():
    """Plot Hogg fig. 3: The dimensionless luminosity distance DL/DH

    The three curves are for the three world models, 

    - Einstein-de Sitter (omega_M, omega_lambda) = (1, 0) [solid]
    
    : Low-density (0.05, 0) [dotted]

    -- High lambda, (0.2, 0.8) [dashed]

    Hubble distance DH = c / H0

    z from 0--5
    DL / DH from 0--16

    """

    z = numpy.arange(0, 5.05, 0.05)

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[1.0], [0.05], [0.2]])
    cosmo['omega_lambda_0'] = numpy.array([[0.0], [0.0], [0.8]])
    cosmo['h'] = 0.5
    cd.set_omega_k_0(cosmo)

    linestyle = ['-', ':', '--']

    dh = cd.hubble_distance_z(0, **cosmo)
    dl = cd.luminosity_distance(z, **cosmo)

    pylab.figure(figsize=(6, 6))
    for i in range(len(linestyle)):
        pylab.plot(z, (dl / dh)[i], ls=linestyle[i])
    pylab.xlim(0, 5)
    pylab.ylim(0, 16)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"luminosity distance $D_L/D_H$")
    pylab.title("compare to " + inspect.stack()[0][3].replace('test_', '') +
                " (astro-ph/9905116v4)")
Esempio n. 16
0
        ar = 0
    gal_vdisp3d = np.zeros(100)
    particle_vdisp3d = np.zeros(100)
    caustic_mass = np.zeros(100)
    for k in range(1):#HaloID.size): #loop over the halos
        i = ar+k
        #i = 0 #halo number to use
        mem_flag = 1 #This is a flag to alerting to (1) if members > 0 and (0) if not. Affects number output.
        HaloZ = Halo_Z[i]
        
        #Get current galaxy info
        print 'GETTING GALAXIES'
        
        gal_haloid,gal_z,gal_umag,gal_gmag,gal_rmag,gal_imag,gal_zmag,gal_xpos,gal_ypos,gal_zpos,gal_vx,gal_vy,gal_vz = G.get_galsbig(HaloID[i],H0,HaloZ)
        gal_mags = np.vstack((gal_umag,gal_gmag,gal_rmag,gal_imag,gal_zmag)).T
        lumdist = cd.luminosity_distance(gal_z,**cosmo)
        gal_abs_rmag = gal_rmag - 5*np.log10(lumdist*1e6/10.0)
        '''
        gal_haloid,gal_umag,gal_gmag,gal_rmag,gal_imag,gal_zmag,gal_xpos,gal_ypos,gal_zpos,gal_vx,gal_vy,gal_vz,gal_vdisp = G.get_galsbig2(HaloID[i],H0)
        gal_mags = np.vstack((gal_umag,gal_gmag,gal_rmag,gal_imag,gal_zmag)).T
        gal_abs_rmag = gal_rmag
        '''
        gal_p = np.array([gal_xpos,gal_ypos,gal_zpos])
        gal_v = np.array([gal_vx,gal_vy,gal_vz])
        gal_mem = np.zeros(gal_umag.size)+1

        #organize the current halo position and velocity
        Halo_P = np.array([Halo_PX[i],Halo_PY[i],Halo_PZ[i]]) #current halo position
        Halo_V = np.array([Halo_VX[i],Halo_VY[i],Halo_VZ[i]]) #current halo velocity
        HVD = HaloVD[i]
        HVD500 = HaloVD500[i]
def find_horizon_range(m1, m2, network, asdfile, pwfile, approx=ls.IMRPhenomD):

    fmin = 1.
    fref = 1.
    df = 1e-2

    ra, dec, psi, iota = genfromtxt('../data/horizon_coord_' + pwfile + '.txt',
                                    unpack=True)

    psdinterp_dict = {}
    minimum_freq = zeros(size(network))
    maximum_freq = zeros(size(network))
    for detector in range(0, size(network)):
        input_freq, strain = loadtxt(asdfile[detector],
                                     unpack=True,
                                     usecols=[0, 1])
        minimum_freq[detector] = maximum(min(input_freq), fmin)
        maximum_freq[detector] = minimum(max(input_freq), 5000.)
        psdinterp_dict[network[detector]] = interp1d(input_freq, strain**2)
    #initial guess of horizon redshift and luminosity distance
    z0 = 0.1
    input_dist = cd.luminosity_distance(z0, **cosmo)
    hplus_tilda, hcross_tilda, freqs = get_htildas((1. + z0) * m1,
                                                   (1. + z0) * m2,
                                                   input_dist,
                                                   iota=iota,
                                                   fmin=fmin,
                                                   fref=fref,
                                                   df=df,
                                                   approx=approx)

    fsel = list()
    psd_interp = list()
    for detector in range(0, size(network)):
        fsel.append(
            logical_and(freqs > minimum_freq[detector],
                        freqs < maximum_freq[detector]))
        psd_interp.append(psdinterp_dict[network[detector]](
            freqs[fsel[detector]]))
    input_snr = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra, dec,
                                   psi, psd_interp, fsel, df)

    input_redshift = z0
    guess_snr = 0
    njump = 0
    #evaluate the horizon recursively
    while abs(
            guess_snr - snr_th
    ) > snr_th * 0.001 and njump < 10:  #require the error within 0.1%
        try:
            guess_redshift, guess_dist = horizon_dist_eval(
                input_dist, input_snr,
                input_redshift)  #horizon guess based on the old SNR
            hplus_tilda, hcross_tilda, freqs = get_htildas(
                (1. + guess_redshift) * m1, (1. + guess_redshift) * m2,
                guess_dist,
                iota=iota,
                fmin=fmin,
                fref=fref,
                df=df,
                approx=approx)
        except:
            njump = 10
            print "Will try interpolation."
        fsel = list()
        psd_interp = list()
        for detector in range(0, size(network)):
            fsel.append(
                logical_and(freqs > minimum_freq[detector],
                            freqs < maximum_freq[detector]))
            psd_interp.append(psdinterp_dict[network[detector]](
                freqs[fsel[detector]]))
        guess_snr = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra,
                                       dec, psi, psd_interp, fsel,
                                       df)  #calculate the new SNR

        input_snr = guess_snr
        input_redshift = guess_redshift
        input_dist = guess_dist
        njump += 1
    horizon_redshift = guess_redshift

    #at high redshift the recursive jumps lead to too big a jump for each step, and the recursive loop converge slowly.
    #so I interpolate the z-SNR curve directly.
    if njump >= 10:
        print "Recursive search for the horizon failed. Interpolation instead."
        try:
            interp_z = linspace(0.001, 100, 200)
            interp_snr = zeros(size(interp_z))
            for i in range(0, size(interp_z)):
                hplus_tilda, hcross_tilda, freqs = get_htildas(
                    (1. + interp_z[i]) * m1, (1. + interp_z[i]) * m2,
                    cd.luminosity_distance(interp_z[i], **cosmo),
                    iota=iota,
                    fmin=fmin,
                    fref=fref,
                    df=df,
                    approx=approx)
                fsel = list()
                psd_interp = list()
                for detector in range(0, size(network)):
                    fsel.append(
                        logical_and(freqs > minimum_freq[detector],
                                    freqs < maximum_freq[detector]))
                    psd_interp.append(psdinterp_dict[network[detector]](
                        freqs[fsel[detector]]))
                interp_snr[i] = compute_horizonSNR(hplus_tilda, hcross_tilda,
                                                   network, ra, dec, psi,
                                                   psd_interp, fsel, df)
            interpolate_snr = interp1d(interp_snr[::-1], interp_z[::-1])
            horizon_redshift = interpolate_snr(snr_th)
        except RuntimeError:  #If the sources lie outside the given interpolating redshift the sources can not be observe, so I cut down the interpolation range.
            print "some of the SNR at the interpolated redshifts cannot be calculated."
            interpolate_snr = interp1d(interp_snr[::-1], interp_z[::-1])
            horizon_redshift = interpolate_snr(snr_th)
        except ValueError:  #horizon outside the interpolated redshifts. Can potentially modify the interpolation range, but we basically can not observe the type of source or the source has to be catastrophically close.
            print "Horizon further than z=100 or less than z=0.001. Need to modify the interpolated redshift range."
            return

    #sampled universal antenna power pattern for code sped up
    w_sample, P_sample = genfromtxt('../data/pw_' + pwfile + '.txt',
                                    unpack=True)
    P = interp1d(w_sample, P_sample, bounds_error=False, fill_value=0.0)
    n_zstep = 200

    z, dz = linspace(horizon_redshift,
                     0,
                     n_zstep,
                     endpoint=False,
                     retstep=True)
    dz = abs(dz)
    unit_volume = zeros(size(z))
    compensate_detect_frac = zeros(size(z))
    for i in range(0, size(z)):
        hplus_tilda, hcross_tilda, freqs = get_htildas(
            (1. + z[i]) * m1, (1. + z[i]) * m2,
            cd.luminosity_distance(z[i], **cosmo),
            iota=iota,
            fmin=fmin,
            fref=fref,
            df=df,
            approx=approx)
        for detector in range(0, size(network)):
            fsel.append(
                logical_and(freqs > minimum_freq[detector],
                            freqs < maximum_freq[detector]))
            psd_interp.append(psdinterp_dict[network[detector]](
                freqs[fsel[detector]]))
        optsnr_z = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra,
                                      dec, psi, psd_interp, fsel, df)
        w = snr_th / optsnr_z
        compensate_detect_frac[i] = P(w)
        unit_volume[i] = (cd.comoving_volume(z[i] + dz / 2., **cosmo) -
                          cd.comoving_volume(z[i] - dz / 2., **cosmo)) / (
                              1. + z[i]) * P(w)

    #Find out the redshift at which we detect 50%/90% of the sources at the redshift
    z_reach50 = max(z[where(compensate_detect_frac >= 0.5)])
    z_reach90 = max(z[where(compensate_detect_frac >= 0.1)])

    vol_sum = sum(unit_volume)
    #Find out the redshifts that 50%/90% of the sources lie within assuming constant-comoving-rate density
    z50 = max(z[where(cumsum(unit_volume) >= 0.5 * vol_sum)])
    z90 = max(z[where(cumsum(unit_volume) >= 0.1 * vol_sum)])

    #Find out the redshifts that 50%/90% of the sources lie within assuming star formation rate
    sfr_vol_sum = sum(unit_volume * sfr(z))
    sfr_z50 = max(z[where(cumsum(unit_volume * sfr(z)) >= 0.5 * sfr_vol_sum)])
    sfr_z90 = max(z[where(cumsum(unit_volume * sfr(z)) >= 0.1 * sfr_vol_sum)])

    #average redshift
    z_mean = sum(unit_volume * z) / vol_sum
    sfr_z_mean = sum(unit_volume * sfr(z) * z) / sfr_vol_sum

    return (3. * vol_sum / 4. / pi)**(
        1. / 3.
    ), z_reach50, z_reach90, horizon_redshift, vol_sum / 1E9, z50, z90, sfr_z50, sfr_z90, z_mean, sfr_z_mean
Esempio n. 18
0
def calc_pdf(density=1e-7,
             L_nu=1e50,
             sigma=1,
             gamma=2.19,
             logMu_range=[-10, 6],
             N_Mu_bins=200,
             z_limits=[0.04, 10.],
             nzbins=120,
             Lum_limits=[1e45, 1e54],
             nLbins=120,
             flux_to_mu=10763342917.859608):
    """
    Parameter:
        - density in 1/Mpc^3
        - L_nu in erg/yr
        - sigma in dex
        - gamma
        - flux_to_mu

    Integration Parameters
        - logMu_range = [-10,6]      # expected range in log mu,
        - N_Mu_bins = 200            # number of bins for log nu histogram
        - z_limits = [0.04, 10.]     # Redshift limits
        - nzbins = 120               # number of z bins
        - Lum_limits = [1e45,1e54]   # Luminosity limits
        - nLbins = 120               # number of logLuminosity bins
    """
    # Conversion Factors
    Mpc_to_cm = 3.086e+24
    erg_to_GeV = 624.151
    year2sec = 365 * 24 * 3600

    cosmology = {'omega_M_0': 0.308, 'omega_lambda_0': 0.692, 'h': 0.678}
    cosmology = set_omega_k_0(cosmology)  # Flat universe

    ### Define the Redshift and Luminosity Evolution
    redshift_evolution = lambda z: HopkinsBeacom2006StarFormationRate(z)
    LF = lambda z, logL: redshift_evolution(z)*np.log(10)*10**logL * \
        lognorm.pdf(10**logL, np.log(10)*sigma,
                    scale=L_nu*np.exp(-0.5*(np.log(10)*sigma)**2))

    N_tot, int_norm = tot_num_src(redshift_evolution, cosmology, z_limits[-1],
                                  density)
    print "Total number of sources {:.0f} (All-Sky)".format(N_tot)

    # Setup Arrays
    logMu_array = np.linspace(logMu_range[0], logMu_range[1], N_Mu_bins)
    Flux_from_fixed_z = []

    zs = np.linspace(z_limits[0], z_limits[1], nzbins)
    deltaz = (float(z_limits[1]) - float(z_limits[0])) / nzbins

    Ls = np.linspace(np.log10(Lum_limits[0]), np.log10(Lum_limits[1]), nLbins)
    deltaL = (np.log10(Lum_limits[1]) - np.log10(Lum_limits[0])) / nLbins

    # Integration
    t0 = time.time()
    Count_array = np.zeros(N_Mu_bins)
    muError = []
    tot_bins = nLbins * nzbins
    print('Starting Integration...Going to evaluate {} bins'.format(tot_bins))
    N_sum = 0

    Flux_from_fixed_z.append([])
    print "-" * 20

    # Loop over redshift bins
    for z_count, z in enumerate(zs):
        # Conversion Factor for given z
        bz = calc_conversion_factor(z, gamma)
        dlz = luminosity_distance(z, **cosmology)
        tot_flux_from_z = 0.

        # Loop over Luminosity bins
        for l_count, lum in enumerate(Ls):
            run_id = z_count * nLbins + l_count
            if run_id % (tot_bins / 10) == 0.:
                print "{}%".format(100 * run_id / tot_bins)
            # Number of Sources in
            dN = calc_dN(LF, lum, z, deltaL, deltaz, N_tot, int_norm,
                         cosmology)
            N_sum += dN

            #Flux to Source Strength
            logmu = np.log10(flux_to_mu * erg_to_GeV * 10**lum / year2sec /
                             (4 * np.pi * (Mpc_to_cm * dlz)**2) * bz)

            # Add dN to Histogram
            if logmu < logMu_range[1] and logmu > logMu_range[0]:
                tot_flux_from_z += dN * 10**logmu
                idx = int((logmu - logMu_range[0]) * N_Mu_bins /
                          (logMu_range[1] - logMu_range[0]))
                Count_array[idx] += dN
            else:
                muError.append(logmu)

        Flux_from_fixed_z.append(tot_flux_from_z)

    print "Number of Mu out of Range: {}".format(len(muError))
    print "Num Sou {}".format(N_sum)
    t1 = time.time()

    print "-" * 20
    print "\n Time needed for {}x{} bins: {}s".format(nzbins, nLbins,
                                                      int(t1 - t0))

    return logMu_array, Count_array, zs, Flux_from_fixed_z
Esempio n. 19
0
    #print wavelength_micron_redshifted_cut[0:50]
    #print flux_mjy_redshifted_cut[0:50]

    #------Unit conversion------------(micron-->m-->Hz-->reverse; mJy-->Jy-->W*m-2*Hz-1-->reverse-->*4pi*luminosity_distance)
    wavelength_sed_aless = []
    flux_sed_aless = []
    for m in range(0, len(wavelength_micron_redshifted_cut_aless)):
        wavelength_sed_aless.append(
            scipy.constants.c /
            (wavelength_micron_redshifted_cut_aless[m] * 1e-6))  #now in Hz
        #flux_sed.append(1e-26*flux_mjy_redshifted_cut[m]*1e-3*4.0*math.pi*pow(1e6*3.0857e16*cosmo.luminosity_distance(z_want[i]).value, 2.0))  #now in W/Hz
        flux_sed_aless.append(
            1e-26 * flux_mjy_redshifted_cut_aless[m] * 1e-3 * 4.0 * math.pi *
            pow(
                1e6 * 3.0857e16 * cd.luminosity_distance(
                    z_want_aless[i], **cosmo), 2.0))  #now in W/Hz

    wavelength_sed_aless = wavelength_sed_aless[::
                                                -1]  #reverse so get increasing in Hz
    flux_sed_aless = flux_sed_aless[::-1]

    #print wavelength_sed[0:50]
    #print flux_sed[0:50]

    L_area_aless = np.trapz(flux_sed_aless, wavelength_sed_aless)
    L_area_solar_aless = L_area_aless / 3.828e26  #in unit of solar luminosity

    L_area_solar_aless = np.log10(
        L_area_solar_aless)  #make it log to plot in corner diagram

    #print L_area_solar
Esempio n. 20
0
 def updatelumdist(self):
     import cosmolopy.distance as cd
     self.dL28 = 3.08567758e-4 * cd.luminosity_distance(self.z, **cosmology)
Esempio n. 21
0
val = numpy.zeros(len(z))

for i in xrange(len(z)):
    #Hubble Distance
    dh = cd.hubble_distance_z(z[i], **Cosmology) * cd.e_z(z[i], **Cosmology)
    #In David Hogg's (arXiv:astro-ph/9905116v4) formalism, this is equivalent to D_H / E(z) = c / (H_0 E(z)) [see his eq. 14], which
    #appears in the definitions of many other distance measures.

    dm = cd.comoving_distance_transverse(z[i], **Cosmology)
    #See equation 16 of David Hogg's arXiv:astro-ph/9905116v4

    da = cd.angular_diameter_distance(z[i], **Cosmology)
    #See equations 18-19 of David Hogg's arXiv:astro-ph/9905116v4

    dl = cd.luminosity_distance(z[i], **Cosmology)
    #Units are Mpc

    dVc = cd.diff_comoving_volume(z[i], **Cosmology)
    #The differential comoving volume element dV_c/dz/dSolidAngle.
    #Dimensions are volume per unit redshift per unit solid angle.
    #Units are Mpc**3 Steradians^-1.
    #See David Hogg's arXiv:astro-ph/9905116v4, equation 28

    tl = cd.lookback_time(z[i], **Cosmology)
    #See equation 30 of David Hogg's arXiv:astro-ph/9905116v4. Units are s.

    agetl = cd.age(z[i], **Cosmology)
    #Age at z is lookback time at z'->Infinity minus lookback time at z.

    tH = 3.09e17 / Cosmology['h']
Esempio n. 22
0
	def getF(z,L):
		DL = luminosity_distance(z, **cosmo) # In MPc
		DL = DL * (10**6. * pc) * 10**2. # in cm
		return L / (4 * math.pi * DL**2.) # ergs/s/cm2
Esempio n. 23
0
      Lmax = Lstart * Lmult**(j+1) 

      # Compute comoving volume in Mpc-3
      dV = ( comoving_volume(zmax,**cosmo) - comoving_volume(zmin,**cosmo) ) * (Tel_Area / 41253.) # Mpc3

      # Get Phi in Mpc-3
      alpha,logLStar,logPhiStar = LF_Data.retrieve_LF(z,line)
      LStar,PhiStar = 10.**(logLStar),10.**(logPhiStar)
      
      n = scipy.integrate.quad(lambda L: schechterL(L,PhiStar, alpha, LStar),Lmin, Lmax)[0]  

      # Number = number density * volume
      N = n * dV

      # Compute flux
      DL = luminosity_distance(z, **cosmo) # In MPc
      DL = DL * (10**6. * pc) * 10**2. # in cm
      F = Lmin / (4 * math.pi * DL**2.) # ergs/s/cm2

      Dist.append([zmin,zmax,math.log10(Lmin),math.log10(Lmax), int(N), F])

# Plot L vs. z
x = [elem[0] + 0.5 * (elem[1] - elem[0]) for elem in Dist] # av z
y = [elem[2] + 0.5 * (elem[3] - elem[2]) for elem in Dist] # av log10
z = [elem[4] for elem in Dist] 

#DensityPlot(x,y,z)

# Make zLF distributions
total = np.sum(z)
_zLF = []
Esempio n. 24
0
def int_ensamble(name, dir1, dir3, dir4, fo, fi=0, pdf=1, fits_f=0, m_t=""):
    names = name.split("-")
    dir3 = dir3  #+"/"+names[1]+"/"+names[2]
    dir_map = dir3 + "/" + names[1] + "/" + names[2] + m_t
    DIRS = dir3.split("/")
    DRT = ""
    for DR in DIRS:
        DRT = DRT + DR + "/"
        call = "mkdir -p " + DRT
        sycall(call)
    DIRS = dir_map.split("/")
    DRT = ""
    for DR in DIRS:
        DRT = DRT + DR + "/"
        call = "mkdir -p " + DRT
        #sycall(call)
    call = "mkdir -p " + dir3 + '/Plots'
    sycall(call)
    speed_of_light = 299792.458
    #dir1=dir1+"/"+names[1]+"/stadi/"+names[2]+m_t
    dir1 = dir1 + "/" + names[1] + "/" + names[2] + m_t
    dir2 = dir1
    file1 = dir1 + "/coeffs_auto_ssp." + name + ".int.out"
    file2 = dir2 + "/auto_ssp." + name + ".int.out"
    pdl_cube = []
    pdl_cube_e = []
    ages = []
    cont = 0
    f1 = open(file1, "r")
    for line in f1:
        if not "#" in line:
            line = line.replace("\n", "")
            data = line.split(" ")
            data = filter(None, data)
            if (cont % 4) == 0:
                ages.extend([np.log10(float_(data[1])) + 9.0])
            pdl_cube.extend([float_(data[3])])
            pdl_cube_e.extend([float_(data[8])])
            cont = cont + 1
    f1.close()
    f2 = open(file2, "r")
    for line in f2:
        if not "#" in line:
            line = line.replace("\n", "")
            data = line.split(",")
            data = filter(None, data)
            pdl_flux = float_(data[13])
            pdl_flux_e = float_(data[14])
            pdl_Av = float_(data[5])
            pdl_Av_e = float_(data[6])
            redshift = float_(data[7])
    f2.close()
    ages = np.array(ages)
    ages = sorted(ages, reverse=True)
    #np.sor
    #sys.exit()
    pdl_cube = np.array(pdl_cube)
    pdl_cube_e = np.array(pdl_cube_e)

    #    f=open(dir4+"/BASE.gsd01","r")
    f = open(dir4 + "/BASE.bc17_salp_Agelin_Metlin_330", "r")
    yunk = f.readline()
    age_t = []
    met_t = []
    cor_t = []
    for line in f:
        if not "#" in line:
            data = line.split(" ")
            data = filter(None, data)
            age_t.extend([float_(data[1])])
            met_t.extend([float_(data[2])])
            cor_t.extend([float_(data[4])])
    n_t = len(age_t)
    age_t = np.array(age_t)
    met_t = np.array(met_t)
    cor_t = np.array(cor_t)
    age_t = np.around(age_t / 1e9, decimals=4)
    met_t = np.around(met_t, decimals=4)
    f.close()

    cosmo = {'omega_M_0': 0.27, 'omega_lambda_0': 0.73, 'h': 0.71}
    cosmo = cd.set_omega_k_0(cosmo)
    DL1 = cd.luminosity_distance(redshift, **cosmo)
    #print DL, redshift
    ratio = 3.08567758e24
    modz = 5.0 * np.log10(DL1) + 25.0
    DL = DL1 * ratio
    DA = DL1 / (1 + redshift)**2.0 * 1e6 * np.pi / 180. / 3600.
    L = 4.0 * np.pi * (DL**2.0)  #/(1+$redshift);
    Factor = (L * 1e-16) / 3.826e33
    filed = file1
    f2 = open(filed, "r")
    n = 0
    n_ini = 0
    ML = np.zeros(156)
    a_age = []
    a_met = []
    n_age = 0
    n_met = 0
    AGE = np.zeros(156)
    MET = np.zeros(156)
    COR = np.zeros(156)
    for line in f2:
        if n_ini < 156:
            if not "#" in line:
                data = line.split(" ")
                data = filter(None, data)
                n = int(data[0])
                AGE[n] = float_(data[1])
                MET[n] = float_(data[2])
                ML[n] = float_(data[5])
                diff_age = 1
                for i in range(0, n):
                    if AGE[n] == AGE[i]:
                        diff_age = 0
                if diff_age == 1:
                    a_age.extend([AGE[n]])
                    n_age = n_age + 1
                diff_met = 1
                for i in range(0, n):
                    if MET[n] == MET[i]:
                        diff_met = 0
                if diff_met == 1:
                    a_met.extend([MET[n]])
                    n_met = n_met + 1
                n_ini = n_ini + 1
                for jt in range(0, n_t):
                    if age_t[jt] == 0.02:
                        age_t[jt] = 0.0199
                    if AGE[n] == age_t[jt]:
                        if MET[n] == met_t[jt]:
                            COR[n] = cor_t[jt]
    f2.close()
    n = n + 1
    MassT = 0
    LighT = 0
    massN = 0
    massN_e = 0
    lightN = 0
    lightN_e = 0
    #mas1=0
    #mas2=0
    #mas3=0
    #mas4=0
    mass = np.zeros([n_age])
    mass_e = np.zeros([n_age])
    light = np.zeros([n_age])
    light_e = np.zeros([n_age])
    #ages=np.zeros([n_age])
    sfrt = np.zeros([n_age])
    sfdt = np.zeros([n_age])
    nz = len(pdl_cube)
    temp_a = 0
    mass_age = 0
    #    pdl_cube[np.isnan(pdl_cube)]=1

    #sys.exit()
    #for i in range(nt-1, 155, -1):
    #    label=hdr['FILE_'+str(i)]
    #    time=label.replace('_NORM_age.fits.gz','')
    #    time=float_(time.replace('map.CS.'+name+'_',''))
    #    ages[38-i+156]=np.log10(time)+9
    #print np.log10(time)+9, 38-i+156
    #temp=pdl_cube[i,:,:]
    #temp=temp*10.0**(ML[i-156])*pdl_flux*Factor
    #temp_a=temp+temp_a
    #    MassT=MassT+np.sum(temp)
    #    mas1=np.sum(temp[n1])+mas1
    #    mas2=np.sum(temp[n2][n2a])+mas2
    #    mas3=np.sum(temp[n3][n3a])+mas3
    #    mas4=np.sum(temp[n4][n4a])+mas4
    #    mass[38-i+156,0]=np.log10(mas1)
    #    mass[38-i+156,1]=np.log10(mas2)
    #    mass[38-i+156,2]=np.log10(mas3)
    #    mass[38-i+156,3]=np.log10(mas4)
    f2 = open(dir3 + "/" + name + m_t + "_Ensemble_int.csv", "w")
    f2.write(
        "#  LOG_AGE  N_MASSR_1  N_MASSR_2  N_MASSR_3  N_MASSR_4  LOG_MASSR_1  LOG_MASSR_2  LOG_MASSR_3  LOG_MASSR_4 \n"
    )
    fL2 = open(dir3 + "/" + name + m_t + "_Ensemble_int_L.csv", "w")
    fL2.write(
        "#  LOG_AGE  N_LIGHTR_1  N_LIGHTR_2  N_LIGHTR_3  N_LIGHTR_4  LOG_LIGHTR_1  LOG_LIGHTR_2  LOG_LIGHTR_3  LOG_LIGHTR_4 \n"
    )
    mass_age_t = np.zeros([n_age])
    mass_age_t_2 = np.zeros([n_age])
    mass_age_t_e = np.zeros([n_age])
    light_age_t = np.zeros([n_age])
    light_age_t_2 = np.zeros([n_age])
    light_age_t_e = np.zeros([n_age])
    for i in range(0, n_age):
        age_now = a_age[i]
        pdl_age = 0
        pdl_age_2 = 0
        pdl_age_e = 0
        pdl_ageL = 0
        pdl_age_2L = 0
        pdl_age_eL = 0
        for j in range(0, n):
            if age_now == AGE[j]:
                #if AGE[j] <= 2:
                pdl_age = pdl_age + pdl_cube[j] * 10.0**(
                    ML[j]) * pdl_flux * Factor * 10.0**(0.4 * pdl_Av
                                                        )  #*0.25/np.pi#/1.47
                pdl_age_e = pdl_age_e + (
                    (pdl_cube_e[j] / pdl_cube[j])**2.0 +
                    (pdl_flux_e / pdl_flux)**2.0 +
                    (np.log(10.0) * 0.4 * pdl_Av_e)**2.0
                ) * (pdl_cube[j] * 10.0**(ML[j]) * pdl_flux * Factor * 10.0**
                     (0.4 * pdl_Av))**2.0
                pdl_age_2 = pdl_age_2 + pdl_cube[j] * 10.0**(
                    ML[j]) * pdl_flux * Factor * 10.0**(0.4 * pdl_Av) / COR[j]
                pdl_age_2L = pdl_age_2L + pdl_cube[
                    j] * pdl_flux * Factor * 10.0**(0.4 * pdl_Av) / COR[j]
                pdl_ageL = pdl_ageL + pdl_cube[j] * pdl_flux * Factor * 10.0**(
                    0.4 * pdl_Av)
                pdl_age_eL = pdl_age_eL + (
                    (pdl_cube_e[j] / pdl_cube[j])**2.0 +
                    (pdl_flux_e / pdl_flux)**2.0 +
                    (np.log(10.0) * 0.4 * pdl_Av_e)**2.0) * (
                        pdl_cube[j] * pdl_flux * Factor * 10.0**
                        (0.4 * pdl_Av))**2.0
                #print age_now

        if np.isfinite(pdl_age) == False:
            pdl_age = 0
        if np.isfinite(pdl_age_2) == False:
            pdl_age_2 = 0
        if np.isfinite(pdl_age_e) == False:
            pdl_age_e = 0
        if np.isfinite(pdl_ageL) == False:
            pdl_ageL = 0
        if np.isfinite(pdl_age_2L) == False:
            pdl_age_2L = 0
        if np.isfinite(pdl_age_eL) == False:
            pdl_age_eL = 0
        #  pdl_age_e[np.isnan(pdl_age_e)]=0
        for k in range(0, n_age):
            if np.log10(age_now) + 9 == ages[k]:
                #print ages[k],np.log10(age_now)+9,age_now
                mass_age_t[k] = pdl_age
                mass_age_t_2[k] = pdl_age_2
                mass_age_t_e[k] = pdl_age_e
                light_age_t[k] = pdl_ageL
                light_age_t_2[k] = pdl_age_2L
                light_age_t_e[k] = pdl_age_eL
    #print mass_age_t

    mass_temp_total = 0
    light_temp_total = 0
    #sys.exit()
    for i in range(0, n_age):
        if i == 0:
            age_s = 10.0**((ages[i] + ages[i + 1]) / 2.0)
            age_i = 0.0
        elif i == n_age - 1:
            age_i = 10.0**((ages[i] + ages[i - 1]) / 2.0)
            age_s = 2.0 * 10.0**(ages[i]) - age_i
        else:
            age_i = 10.0**((ages[i] + ages[i - 1]) / 2.0)
            age_s = 10.0**((ages[i] + ages[i + 1]) / 2.0)
        Dt_age = np.abs(age_s - age_i)
        sfdt[i] = Dt_age / 1e6
        temp = mass_age_t[i]
        temp_2 = mass_age_t_2[i]
        temp_e = mass_age_t_e[i]
        tempL = light_age_t[i]
        temp_2L = light_age_t_2[i]
        temp_eL = light_age_t_e[i]
        #temp[np.where(np.isfinite(temp) == False)]=0
        #temp_e[np.where(np.isfinite(temp_e) == False)]=1
        #temp_2[np.where(np.isfinite(temp_2) == False)]=0
        if i == 0:
            if fits_f == 1:
                MASS_map_cube = np.zeros([n_age])
                MGH_map_cube = np.zeros([n_age])
                SFH_map_cube = np.zeros([n_age])
                LIGHT_map_cube = np.zeros([n_age])
                LGH_map_cube = np.zeros([n_age])
            temp1 = temp
            temp1L = tempL
        else:
            temp1 = temp1 + temp
            temp1L = temp1L + tempL
        if fits_f == 1:
            MASS_map_cube[i] = temp
            MGH_map_cube[i] = temp1
            SFH_map_cube[i] = temp_2 / Dt_age
            LIGHT_map_cube[i] = tempL
            LGH_map_cube[i] = temp1L
        #if pdf==1:
        #map_plot(temp1,ages[i],pdl_rad,dir=dir_map+"/",pdf=1,title=name,form='pdf',fname=name+'_smap_'+str(i),minval=lovalue,maxval=upvalue)
        MassT = MassT + np.sum(temp)
        LighT = LighT + np.sum(tempL)
        #            print temp[ind[ii]]
        #            print len(temp[ind[ii]]),np.amax(inda[ii])
        Dt_mass = temp
        Dt_mass_e = temp_e
        Dt_mass_2 = temp_2
        Dt_light = tempL
        Dt_light_e = temp_eL
        Dt_light_2 = temp_2L
        massN = Dt_mass + massN
        massN_e = Dt_mass_e + massN_e
        lightN = Dt_light + lightN
        lightN_e = Dt_light_e + lightN_e
        #mas2=np.sum(temp[n2][n2a])+mas2
        #mas3=np.sum(temp[n3][n3a])+mas3
        #mas4=np.sum(temp[n4][n4a])+mas4
        #            print temp[ind[ii]][inda[ii]]
        mass[i] = np.log10(massN)
        mass_e[i] = massN_e
        light[i] = np.log10(lightN)
        light_e[i] = lightN_e
        sfrt[
            i] = Dt_mass_2 / Dt_age  #/massN[ii]#/(np.pi*(rx[ii+1]**2.0-rx[ii]**2.0)*rad**2.0)#/(float_(len(temp[ind[ii]][inda[ii]]))*(0.5*DA)**2.0)
        #mass[i,1]=np.log10(mas2)
        #mass[i,2]=np.log10(mas3)
        #mass[i,3]=np.log10(mas4)
    # print mass[i],massN
    mass_temp_total = np.log10(np.sum(10**mass[n_age - 1]))
    light_temp_total = np.log10(np.sum(10**light[n_age - 1]))
    MassT = np.log10(MassT)
    MassT = mass_temp_total
    LighT = np.log10(LighT)
    LighT = light_temp_total
    if fits_f == 1:
        #if ptt.exists() == True:
        h1 = pyf.PrimaryHDU(MASS_map_cube)  #.header
        h2 = pyf.PrimaryHDU(SFH_map_cube)  #.header
        h3 = pyf.PrimaryHDU(MGH_map_cube)
        h4 = pyf.PrimaryHDU(LIGHT_map_cube)
        h5 = pyf.PrimaryHDU(LGH_map_cube)
        h = h1.header
        h["NAXIS"] = 2
        h["NAXIS1"] = n_age
        h["NAXIS2"] = 1
        hlist = pyf.HDUList([h1])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "MASS_maps_" + name + ".fits", hlist)
        #if ptt.exists() == True:
        h = h2.header
        h["NAXIS"] = 2
        h["NAXIS1"] = n_age
        h["NAXIS2"] = 1
        hlist = pyf.HDUList([h2])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "SFH_maps_" + name + ".fits", hlist)
        #if ptt.exists() == True:
        h = h3.header
        h["NAXIS"] = 2
        h["NAXIS1"] = n_age
        h["NAXIS2"] = 1
        hlist = pyf.HDUList([h3])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "MGH_maps_" + name + ".fits", hlist)
        h = h4.header
        h["NAXIS"] = 2
        h["NAXIS1"] = n_age
        h["NAXIS2"] = 1
        hlist = pyf.HDUList([h4])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "LIGHT_maps_" + name + ".fits", hlist)
        h = h5.header
        h["NAXIS"] = 2
        h["NAXIS1"] = n_age
        h["NAXIS2"] = 1
        hlist = pyf.HDUList([h5])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "LGH_maps_" + name + ".fits", hlist)
    #print MassT,name

    #print Ha,(L*1e-16)
    #sys.exit(0)
    mass_n = 10**(10**(mass - mass[n_age - 1]))
    mass_n_e = np.sqrt((10**(mass - mass[n_age - 1]))**2.0 *
                       ((mass_e / 10**(2.0 * mass)) +
                        (mass_e[n_age - 1] / 10**(2.0 * mass[n_age - 1]))))
    light_n = 10**(10**(light - light[n_age - 1]))
    light_n_e = np.sqrt((10**(light - light[n_age - 1]))**2.0 *
                        ((light_e / 10**(2.0 * light)) +
                         (light_e[n_age - 1] / 10**(2.0 * light[n_age - 1]))))
    #print mass_n
    #mass_n=10**(mass-mass[nt-156-1,:])
    #mass_n=(mass-mass[nt-156-1,:])
    for i in range(0, n_age):
        #print ages[i],a_age[i],"test_ages"
        line = ''
        line = line + str(ages[i])
        line = line + ';' + str(mass_n[i])
        line = line + ';' + str(mass[i])
        line = line + ';' + str(sfrt[i])
        line = line + ';' + str(mass_n_e[i])
        line = line + ';' + str(sfdt[i])
        #print line
        line = line + ' \n'
        f2.write(line)
        lineL = ''
        lineL = lineL + str(ages[i])
        lineL = lineL + ';' + str(light_n[i])
        lineL = lineL + ';' + str(light[i])
        lineL = lineL + ';' + str(sfrt[i])
        lineL = lineL + ';' + str(light_n_e[i])
        lineL = lineL + ';' + str(sfdt[i])
        lineL = lineL + ' \n'
        fL2.write(lineL)

# print mass_n.shape,ages.shape
    if not pdf == 0:
        dev = dir3 + '/Plots/' + name + m_t + "_int_Relative_Mass2.pdf"
        #if pdf == 1:
        #    matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(figsize=(6, 5.5))
        ax.set_xlabel("$log_{10}(time/yr)$", fontsize=14)
        ax.set_ylabel("$M(t)/M_{0}$", fontsize=14)
        #MassT=10.32
        ax.set_title(name + ' $\log M_{tot}=' + ('%7.2f' % MassT) + '$',
                     fontsize=15)
        ax.set_xlim(8.6, 10.1)
        #ax.set_ylim(0,12)
        ax.set_ylim(func_plot(np.log10(1.78), ftype=1),
                    func_plot(np.log10(12), ftype=1))
        plt.plot(
            ages, func_plot(np.log10(mass_n), ftype=1)
        )  #,label='$'+('%6.1f' % rx[ii])+'R_e<R<'+('%6.1f' % rx[ii+1])+'R_e$'
        plt.legend(loc=3)
        plt.plot(np.arange(0, 20, .1),
                 np.ones(200) * func_plot(0.95, ftype=1),
                 '--',
                 color='black')
        plt.plot(np.arange(0, 20, .1),
                 np.ones(200) * func_plot(0.50, ftype=1),
                 '--',
                 color='green')
        fig.canvas.draw()
        labels = [item.get_text() for item in ax.get_yticklabels()]
        for i in range(0, len(labels)):
            labels[i] = labels[i].replace(u'\u2212', '-')
        for i in range(0, len(labels)):
            if labels[i] != u'':
                if float_(labels[i]) == 0:
                    labels[i] = u'%3.2f' % 10**(0)
                else:
                    labels[i] = u'%3.2f' % 10**(float_(labels[i]))
        ax.set_yticklabels(labels)
        if pdf == 1:
            fig.tight_layout()
            plt.savefig(dev)  #,dpi = 1000)
        else:
            plt.show()
        plt.close()
    f2.close()
    fL2.close()
    fo.write(name + " " + str(MassT) + " " + str(redshift) + " \n")
Esempio n. 25
0
def ensamble(name,
             dir1,
             dir3,
             dir4,
             fo,
             fi=0,
             fii=0,
             pdf=1,
             rx=[0, 0.5, 1.0, 1.5],
             fits_f=0):
    rad = 1.0
    names = name.split("-")
    dir3 = dir3  #+"/"+names[1]+"/"+names[2]
    dir_map = dir3 + "/" + names[1] + "/" + names[2]
    DIRS = dir3.split("/")
    DRT = ""
    for DR in DIRS:
        DRT = DRT + DR + "/"
        call = "mkdir -p " + DRT
        sycall(call)
    DIRS = dir_map.split("/")
    DRT = ""
    for DR in DIRS:
        DRT = DRT + DR + "/"
        call = "mkdir -p " + DRT
        sycall(call)
    speed_of_light = 299792.458
    dir1 = dir1 + "/" + names[1] + "/" + names[2]
    #    dir2=dir2+"/"+names[1]+"-"+names[2]
    file = dir1 + "/" + name + ".SFH.cube.fits.gz"
    file2 = dir1 + "/" + name + ".p_e.pdl_r.fits"
    #file2=dir2+"/"+name+".photo.r_Lc_rad.fits"
    #file3=dir1+"/"+'mask.'+name+'.V.fits.gz'
    file3 = dir1 + "/" + 'DMASK.' + name + '.fits.gz'
    [pdl_cube, hdr] = gdata(file, 0, header=True)
    [pdl_rad, hdr2] = gdata(file2, 0, header=True)
    [pdl_mask, hdr3] = gdata(file3, 0, header=True)
    pdl_mask = 1.0 - pdl_mask
    if np.sum(pdl_mask) == 0:
        pdl_mask[:, :] = 1.0
    ind = []
    inda = []
    nr = len(rx)
    for ii in range(0, nr - 1):
        nt = np.where(pdl_rad < rx[ii + 1] * rad)
        nta = np.where(pdl_rad[nt] >= rx[ii] * rad)
        ind.extend([nt])
        inda.extend([nta])
#    n2=np.where(pdl_rad< r2*rad)
#    n2a=np.where(pdl_rad[n2]>= r1*rad)
#    n3=np.where(pdl_rad< r3*rad)
#    n3a=np.where(pdl_rad[n3]>= r2*rad)
#    n4=np.where(pdl_rad< r4*rad)
#    n4a=np.where(pdl_rad[n4]>= r3*rad)
    SN_file = "norm_SN_" + name + ".CS.fits.gz"
    if ptt.exists(dir1 + "/" + SN_file) == True:
        [pdl_SN, hdr000] = gdata(dir1 + "/" + SN_file, 0, header=True)
    Ha_file = "map.CS." + name + "_flux_6562.fits.gz"
    if ptt.exists(dir1 + "/" + Ha_file) == True:
        [pdl_ha, hdr001] = gdata(dir1 + "/" + Ha_file, 0, header=True)
        pdl_ha = pdl_ha * pdl_mask  #[0,:,:]#-z_r*speed_of_light
        pdl_ha[np.isnan(pdl_ha)] = 0
    Av_file = "map.CS." + name + "_Av_ssp.fits.gz"
    [pdl_Av, hdr002] = gdata(dir1 + "/" + Av_file, 0, header=True)
    Av_file_e = "map.CS." + name + "_e_Av_ssp.fits.gz"
    if ptt.exists(dir1 + "/" + Av_file_e) == True:
        [pdl_Av_e, hdr002e] = gdata(dir1 + "/" + Av_file_e, 0, header=True)
        pdl_Av_e[np.isnan(pdl_Av_e)] = 0
    else:
        pdl_Av_e = np.zeros(Av_file.shape)
    nt = hdr['NAXIS3'] - 5  #5#4#n_met
    flux_file = "map.CS." + name + "_flux_ssp.fits.gz"
    [pdl_flux, hdr0] = gdata(dir1 + "/" + flux_file, 0, header=True)
    flux_file_e = "map.CS." + name + "_e_flux_ssp.fits.gz"
    if ptt.exists(dir1 + "/" + flux_file_e) == True:
        [pdl_flux_e, hdr0e] = gdata(dir1 + "/" + flux_file_e, 0, header=True)
        pdl_flux_e[np.isnan(pdl_flux_e)] = 0
    else:
        pdl_flux_e = np.zeros(pdl_flux.shape)
    mass_file = "map.CS." + name + "_Mass_dust_cor_ssp.fits.gz"  #dust_cor_
    [pdl_mass, hdr00] = gdata(dir1 + "/" + mass_file, 0, header=True)
    pdl_mass[np.isnan(pdl_mass)] = 1
    MassT2 = np.log10(np.sum(10.0**pdl_mass))
    #print MassT2, name

    f = open(dir4 + "/BASE.gsd01", "r")
    #f=open(dir4+"/BASE.bc17_salp_Agelin_Metlin_330","r")
    yunk = f.readline()
    age_t = []
    met_t = []
    cor_t = []
    for line in f:
        if not "#" in line:
            data = line.split(" ")
            data = filter(None, data)
            age_t.extend([float_(data[1])])
            met_t.extend([float_(data[2])])
            cor_t.extend([float_(data[4])])
    n_t = len(age_t)
    age_t = np.array(age_t)
    met_t = np.array(met_t)
    cor_t = np.array(cor_t)
    age_t = np.around(age_t / 1e9, decimals=4)
    met_t = np.around(met_t, decimals=4)
    f.close()
    a_redshift = []
    filet = "auto_ssp.CS." + name + ".rss.out"
    f = open(dir1 + "/" + filet, "r")
    for line in f:
        if not "#" in line:
            data = line.split(",")
            data = filter(None, data)
            #print data
            a_redshift.extend([float_(data[7])])
    f.close()
    a_redshift = np.array(a_redshift)
    redshift = np.median(a_redshift)
    cosmo = {'omega_M_0': 0.27, 'omega_lambda_0': 0.73, 'h': 0.71}
    cosmo = cd.set_omega_k_0(cosmo)
    DL1 = cd.luminosity_distance(redshift, **cosmo)
    #print DL, redshift
    ratio = 3.08567758e24
    modz = 5.0 * np.log10(DL1) + 25.0
    DL = DL1 * ratio
    DA = DL1 / (1 + redshift)**2.0 * 1e6 * np.pi / 180. / 3600.
    L = 4.0 * np.pi * (DL**2.0)  #/(1+$redshift);
    Factor = (L * 1e-16) / 3.826e33
    filed = "coeffs_auto_ssp.CS." + name + ".rss.out"
    f2 = open(dir1 + "/" + filed, "r")
    n = 0
    n_ini = 0
    n_ssp = 156  #330
    ML = np.zeros(n_ssp)
    a_age = []
    a_met = []
    n_age = 0
    n_met = 0
    AGE = np.zeros(n_ssp)
    MET = np.zeros(n_ssp)
    COR = np.zeros(n_ssp)
    for line in f2:
        if n_ini < n_ssp:
            if not "#" in line:
                data = line.split(" ")
                data = filter(None, data)
                n = int(data[0])
                AGE[n] = float_(data[1])
                MET[n] = float_(data[2])
                ML[n] = float_(data[5])
                diff_age = 1
                for i in range(0, n):
                    if AGE[n] == AGE[i]:
                        diff_age = 0
                if diff_age == 1:
                    a_age.extend([AGE[n]])
                    n_age = n_age + 1
                diff_met = 1
                for i in range(0, n):
                    if MET[n] == MET[i]:
                        diff_met = 0
                if diff_met == 1:
                    a_met.extend([MET[n]])
                    n_met = n_met + 1
                n_ini = n_ini + 1
                for jt in range(0, n_t):
                    if age_t[jt] == 0.02:
                        age_t[jt] = 0.0199
                    if AGE[n] == age_t[jt]:
                        if MET[n] == met_t[jt]:
                            COR[n] = cor_t[jt]
    f2.close()
    n = n + 1
    MassT = 0
    LighT = 0
    massN = np.zeros(nr)
    massN_e = np.zeros(nr)
    lightN = np.zeros(nr)
    lightN_e = np.zeros(nr)
    #mas1=0
    #mas2=0
    #mas3=0
    #mas4=0
    mass = np.zeros([n_age, nr])
    mass_e = np.zeros([n_age, nr])
    light = np.zeros([n_age, nr])
    light_e = np.zeros([n_age, nr])
    ages = np.zeros([n_age])
    sfrt = np.zeros([n_age, nr])
    sfdt = np.zeros([n_age])
    [nz, nx, ny] = pdl_cube.shape
    temp_a = np.zeros([nx, ny])
    mass_age = np.zeros([nx, ny])
    pdl_cube[np.isnan(pdl_cube)] = 1

    pdl_cube_e = np.zeros([n, nx, ny])
    #print name
    for i in range(0, n):
        norm_file = dir1 + "/" + "map.CS." + name + "_eNORM_" + str(
            i) + "_ssp.fits.gz"
        if ptt.exists(norm_file) == True:
            pdl_cube_e[i, :, :] = gdata(norm_file)
        else:
            pdl_cube_e[i, :, :] = np.zeros([nx, ny])
    pdl_cube_e[np.isnan(pdl_cube_e)] = 0
    #print AGE
    #sys.exit()
    for i in range(nt - 1, n_ssp - 1, -1):
        label = hdr['FILE_' + str(i)]
        #        print label,n_age,n_met,n_age-i+n_ssp-1,-i+n_ssp,i
        time = label.replace('_NORM_age.fits.gz', '')
        time = float_(time.replace('map.CS.' + name + '_', ''))
        ages[n_age - i + n_ssp - 1] = np.log10(time) + 9
    #print np.log10(time)+9, 38-i+156
    #temp=pdl_cube[i,:,:]
    #temp=temp*10.0**(ML[i-156])*pdl_flux*Factor
    #temp_a=temp+temp_a
#    MassT=MassT+np.sum(temp)
#    mas1=np.sum(temp[n1])+mas1
#    mas2=np.sum(temp[n2][n2a])+mas2
#    mas3=np.sum(temp[n3][n3a])+mas3
#    mas4=np.sum(temp[n4][n4a])+mas4
#    mass[38-i+156,0]=np.log10(mas1)
#    mass[38-i+156,1]=np.log10(mas2)
#    mass[38-i+156,2]=np.log10(mas3)
#    mass[38-i+156,3]=np.log10(mas4)
    f2 = open(dir3 + "/" + name + "_Ensemble.csv", "w")
    f2.write(
        "#  LOG_AGE  N_MASSR_1  N_MASSR_2  N_MASSR_3  N_MASSR_4  LOG_MASSR_1  LOG_MASSR_2  LOG_MASSR_3  LOG_MASSR_4 \n"
    )
    fL2 = open(dir3 + "/" + name + "_Ensemble_L.csv", "w")
    fL2.write(
        "#  LOG_AGE  N_LIGHTR_1  N_LIGHTR_2  N_LIGHTR_3  N_LIGHTR_4  LOG_LIGHTR_1  LOG_LIGHTR_2  LOG_LIGHTR_3  LOG_LIGHTR_4 \n"
    )
    mass_age_t = np.zeros([n_age, nx, ny])
    mass_age_t_2 = np.zeros([n_age, nx, ny])
    mass_age_t_e = np.zeros([n_age, nx, ny])
    light_age_t = np.zeros([n_age, nx, ny])
    light_age_t_2 = np.zeros([n_age, nx, ny])
    light_age_t_e = np.zeros([n_age, nx, ny])
    for i in range(0, n_age):
        age_now = a_age[i]
        pdl_age = np.zeros([nx, ny])
        pdl_age_2 = np.zeros([nx, ny])
        pdl_age_e = np.zeros([nx, ny])
        pdl_ageL = np.zeros([nx, ny])
        pdl_age_2L = np.zeros([nx, ny])
        pdl_age_eL = np.zeros([nx, ny])
        for j in range(0, n):
            if age_now == AGE[j]:
                #if AGE[j] <= 2:
                pdl_age = pdl_age + pdl_cube[j, :, :] * 10.0**(
                    ML[j]) * pdl_flux * Factor * 10.0**(
                        0.4 * pdl_Av) * pdl_mask  #*0.25/np.pi#/1.47
                pdl_age_e = pdl_age_e + (
                    (pdl_cube_e[j, :, :] / pdl_cube[j, :, :])**2.0 +
                    (pdl_flux_e / pdl_flux)**2.0 +
                    (np.log(10.0) * 0.4 * pdl_Av_e)**2.0) * (
                        pdl_cube[j, :, :] * 10.0**(ML[j]) * pdl_flux * Factor *
                        pdl_mask * 10.0**(0.4 * pdl_Av))**2.0
                pdl_age_2 = pdl_age_2 + pdl_cube[j, :, :] * 10.0**(
                    ML[j]) * pdl_flux * Factor * pdl_mask * 10.0**(
                        0.4 * pdl_Av) / COR[j]
                pdl_age_2L = pdl_age_2L + pdl_cube[
                    j, :, :] * pdl_flux * Factor * pdl_mask * 10.0**(
                        0.4 * pdl_Av) / COR[j]
                pdl_ageL = pdl_ageL + pdl_cube[
                    j, :, :] * pdl_flux * Factor * 10.0**(0.4 *
                                                          pdl_Av) * pdl_mask
                pdl_age_eL = pdl_age_eL + (
                    (pdl_cube_e[j, :, :] / pdl_cube[j, :, :])**2.0 +
                    (pdl_flux_e / pdl_flux)**2.0 +
                    (np.log(10.0) * 0.4 * pdl_Av_e)**2.0
                ) * (pdl_cube[j, :, :] * pdl_flux * Factor * pdl_mask * 10.0**
                     (0.4 * pdl_Av))**2.0
                #else:
                #    pdl_age=pdl_age+pdl_cube[j,:,:]*10.0**(ML[j])*pdl_flux*Factor*pdl_mask*COR[j]
        pdl_age[np.where(np.isfinite(pdl_age) == False)] = 0
        pdl_age_2[np.where(np.isfinite(pdl_age_2) == False)] = 0
        pdl_age_e[np.where(np.isfinite(pdl_age_e) == False)] = 0
        pdl_ageL[np.where(np.isfinite(pdl_ageL) == False)] = 0
        pdl_age_2L[np.where(np.isfinite(pdl_age_2L) == False)] = 0
        pdl_age_eL[np.where(np.isfinite(pdl_age_eL) == False)] = 0
        #pdl_age_e[np.isnan(pdl_age_e)]=0
        for k in range(0, n_age):
            if np.log10(age_now) + 9 == ages[k]:
                mass_age_t[k, :, :] = pdl_age
                mass_age_t_2[k, :, :] = pdl_age_2
                mass_age_t_e[k, :, :] = pdl_age_e
                light_age_t[k, :, :] = pdl_ageL
                light_age_t_2[k, :, :] = pdl_age_2L
                light_age_t_e[k, :, :] = pdl_age_eL
    temp5 = np.sum(mass_age_t, axis=0) + 0.01
    #    temp6=np.log10(np.sum(mass_age_t,axis=0)+1.0)#QUITAR
    #    wfits(dir3+"/"+name+"mass_tot.fits",temp6,hdr001)#QUITAR
    upvalue = math.ceil(np.log10(np.amax(temp5)) / .05) * .05
    if np.isinf(upvalue):
        upvalue = 8
    if upvalue - 1 <= 6.5:
        lovalue = math.ceil(np.log10(np.amin(temp5)) / .05) * .05
        if upvalue - 2 > lovalue:
            lovalue = upvalue - 2
    else:
        lovalue = 6.5
    mass_temp_total = 0
    light_temp_total = 0
    for i in range(0, n_age):
        if i == 0:
            age_s = 10.0**((ages[i] + ages[i + 1]) / 2.0)
            age_i = 0.0
        elif i == n_age - 1:
            age_i = 10.0**((ages[i] + ages[i - 1]) / 2.0)
            age_s = 2.0 * 10.0**(ages[i]) - age_i
        else:
            age_i = 10.0**((ages[i] + ages[i - 1]) / 2.0)
            age_s = 10.0**((ages[i] + ages[i + 1]) / 2.0)
        Dt_age = np.abs(age_s - age_i)
        sfdt[i] = Dt_age / 1e6
        temp = mass_age_t[i, :, :]
        temp_2 = mass_age_t_2[i, :, :]
        temp_e = mass_age_t_e[i, :, :]
        tempL = light_age_t[i, :, :]
        temp_2L = light_age_t_2[i, :, :]
        temp_eL = light_age_t_e[i, :, :]
        #temp[np.where(np.isfinite(temp) == False)]=0
        #temp_e[np.where(np.isfinite(temp_e) == False)]=1
        #temp_2[np.where(np.isfinite(temp_2) == False)]=0
        if i == 0:
            if fits_f == 1:
                [nx, ny] = temp.shape
                MASS_map_cube = np.zeros([n_age, nx, ny])
                MGH_map_cube = np.zeros([n_age, nx, ny])
                SFH_map_cube = np.zeros([n_age, nx, ny])
                LIGHT_map_cube = np.zeros([n_age, nx, ny])
                LGH_map_cube = np.zeros([n_age, nx, ny])
            temp1 = temp
            temp1L = tempL
        else:
            temp1 = temp1 + temp
            temp1L = temp1L + tempL
        if fits_f == 1:
            MASS_map_cube[i, :, :] = temp
            MGH_map_cube[i, :, :] = temp1
            SFH_map_cube[i, :, :] = temp_2 / Dt_age
            LIGHT_map_cube[i, :, :] = tempL
            LGH_map_cube[i, :, :] = temp1L
        #if pdf==1:
        #map_plot(temp1,ages[i],pdl_rad,dir=dir_map+"/",pdf=1,title=name,form='pdf',fname=name+'_smap_'+str(i),minval=lovalue,maxval=upvalue)
        MassT = MassT + np.sum(temp)
        LighT = LighT + np.sum(tempL)
        for ii in range(0, nr - 1):
            # print ind[ii],inda[ii],ii
            #            print temp[ind[ii]]
            #            print len(temp[ind[ii]]),np.amax(inda[ii])
            Dt_mass = np.sum(temp[ind[ii]][inda[ii]])
            Dt_mass_e = np.sum(temp_e[ind[ii]][inda[ii]])
            Dt_mass_2 = np.sum(temp_2[ind[ii]][inda[ii]])
            Dt_light = np.sum(tempL[ind[ii]][inda[ii]])
            Dt_light_e = np.sum(temp_eL[ind[ii]][inda[ii]])
            Dt_light_2 = np.sum(temp_2L[ind[ii]][inda[ii]])
            massN[ii] = Dt_mass + massN[ii]
            massN_e[ii] = Dt_mass_e + massN_e[ii]
            lightN[ii] = Dt_light + lightN[ii]
            lightN_e[ii] = Dt_light_e + lightN_e[ii]
            #mas2=np.sum(temp[n2][n2a])+mas2
            #mas3=np.sum(temp[n3][n3a])+mas3
            #mas4=np.sum(temp[n4][n4a])+mas4
            #            print temp[ind[ii]][inda[ii]]
            mass[i, ii] = np.log10(massN[ii])
            mass_e[i, ii] = massN_e[ii]
            light[i, ii] = np.log10(lightN[ii])
            light_e[i, ii] = lightN_e[ii]
            sfrt[
                i,
                ii] = Dt_mass_2 / Dt_age  #/massN[ii]#/(np.pi*(rx[ii+1]**2.0-rx[ii]**2.0)*rad**2.0)#/(float_(len(temp[ind[ii]][inda[ii]]))*(0.5*DA)**2.0)
        #mass[i,1]=np.log10(mas2)
        #mass[i,2]=np.log10(mas3)
        #mass[i,3]=np.log10(mas4)
    mass_temp_total = np.log10(np.sum(10**mass[nt - n_ssp - 1, :]))
    light_temp_total = np.log10(np.sum(10**light[nt - n_ssp - 1, :]))
    MassT = np.log10(MassT)
    MassT = mass_temp_total
    LighT = np.log10(LighT)
    LighT = light_temp_total
    if fits_f == 1:
        #if ptt.exists() == True:
        h1 = pyf.PrimaryHDU(MASS_map_cube)  #.header
        h2 = pyf.PrimaryHDU(SFH_map_cube)  #.header
        h3 = pyf.PrimaryHDU(MGH_map_cube)
        h4 = pyf.PrimaryHDU(LIGHT_map_cube)
        h5 = pyf.PrimaryHDU(LGH_map_cube)
        h = h1.header
        h["NAXIS"] = 3
        h["NAXIS3"] = n_age
        h["NAXIS1"] = nx
        h["NAXIS2"] = ny
        hlist = pyf.HDUList([h1])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "MASS_maps_" + name + ".fits", hlist)
        #if ptt.exists() == True:
        h = h2.header
        h["NAXIS"] = 3
        h["NAXIS3"] = n_age
        h["NAXIS1"] = nx
        h["NAXIS2"] = ny
        hlist = pyf.HDUList([h2])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "SFH_maps_" + name + ".fits", hlist)
        #if ptt.exists() == True:
        h = h3.header
        h["NAXIS"] = 3
        h["NAXIS3"] = n_age
        h["NAXIS1"] = nx
        h["NAXIS2"] = ny
        hlist = pyf.HDUList([h3])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "MGH_maps_" + name + ".fits", hlist)
        h = h4.header
        h["NAXIS"] = 3
        h["NAXIS3"] = n_age
        h["NAXIS1"] = nx
        h["NAXIS2"] = ny
        hlist = pyf.HDUList([h4])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "LIGHT_maps_" + name + ".fits", hlist)
        h = h5.header
        h["NAXIS"] = 3
        h["NAXIS3"] = n_age
        h["NAXIS1"] = nx
        h["NAXIS2"] = ny
        hlist = pyf.HDUList([h5])
        hlist.update_extend()
        wfits_ext(dir_map + "/" + "LGH_maps_" + name + ".fits", hlist)
    #print MassT,name
    if ptt.exists(dir1 + "/" + SN_file) == True:
        SN = np.zeros(nr - 1)
        sn_l = ''
        for ii in range(0, nr - 1):
            SN[ii] = np.average(pdl_SN[ind[ii]][inda[ii]])
            sn_l = sn_l + ' , ' + str(SN[ii])
        if fi != 0:
            fi.write(name + sn_l + ' \n')
    if ptt.exists(dir1 + "/" + Ha_file) == True:
        Ha = np.zeros(nr - 1)
        ha_l = ''
        for ii in range(0, nr - 1):
            Ha[ii] = np.sum(pdl_ha[ind[ii]][inda[ii]] * 10.0**
                            (0.4 * pdl_Av[ind[ii]][inda[ii]])) * (L * 1e-16)
            ha_l = ha_l + ' , ' + str(Ha[ii])
        if fii != 0:
            fii.write(name + ha_l + ' \n')
    else:
        ha_l = ''
        for ii in range(0, nr - 1):
            ha_l = ha_l + ' , ' + str(-100)
        if fii != 0:
            fii.write(name + ha_l + ' \n')
    #print Ha,(L*1e-16)
    #sys.exit(0)
    mass_n = 10**(10**(mass - mass[nt - n_ssp - 1, :]))
    mass_n_e = np.sqrt(
        (10**(mass - mass[nt - n_ssp - 1, :]))**2.0 *
        ((mass_e / 10**(2.0 * mass)) +
         (mass_e[nt - n_ssp - 1, :] / 10**(2.0 * mass[nt - n_ssp - 1, :]))))
    light_n = 10**(10**(light - light[nt - n_ssp - 1, :]))
    light_n_e = np.sqrt(
        (10**(light - light[nt - n_ssp - 1, :]))**2.0 *
        ((light_e / 10**(2.0 * light)) +
         (light_e[nt - n_ssp - 1, :] / 10**(2.0 * light[nt - n_ssp - 1, :]))))
    #mass_n=10**(mass-mass[nt-156-1,:])
    #mass_n=(mass-mass[nt-156-1,:])
    for i in range(0, n_age):
        #print ages[i],a_age[i],"test_ages"
        line = ''
        line = line + str(ages[i])
        for ii in range(0, nr - 1):
            line = line + ';' + str(mass_n[i, ii])
        for ii in range(0, nr - 1):
            line = line + ';' + str(mass[i, ii])
        for ii in range(0, nr - 1):
            line = line + ';' + str(sfrt[i, ii])
        for ii in range(0, nr - 1):
            line = line + ';' + str(mass_n_e[i, ii])
        line = line + ';' + str(sfdt[i])
        line = line + ' \n'
        f2.write(line)
        lineL = ''
        lineL = lineL + str(ages[i])
        for ii in range(0, nr - 1):
            lineL = lineL + ';' + str(light_n[i, ii])
        for ii in range(0, nr - 1):
            lineL = lineL + ';' + str(light[i, ii])
        for ii in range(0, nr - 1):
            lineL = lineL + ';' + str(sfrt[i, ii])
        for ii in range(0, nr - 1):
            lineL = lineL + ';' + str(light_n_e[i, ii])
        lineL = lineL + ';' + str(sfdt[i])
        lineL = lineL + ' \n'
        fL2.write(lineL)
    #if not pdf == 0:
    #dev=dir3+"/"+name+"_Relative_Mass.pdf"
    ##if pdf == 1:
    #    #matplotlib.use('Agg')
    #import matplotlib.pyplot as plt
    ##plt.axis([8, 10.5, 0, 10])
    #plt.xlabel("$log_{10}(time/yr)$",fontsize=14)
    #plt.ylabel("$10^{M(t)/M_{0}}$",fontsize=14)
    #plt.title(name+' $\log M_{tot}='+('%7.2f' % MassT)+'$',fontsize=15)
    ##plt.semilogx('log')
    #for ii in range(0, nr-1):
    #    plt.plot(ages,mass_n[:,ii],label='$'+('%6.1f' % rx[ii])+'R_e<R<'+('%6.1f' % rx[ii+1])+'R_e$')
    ##plt.plot(ages,mass_n[:,1],label='$'+('%6.1f' % r1)+'<R<'+('%6.1f' % r2)+'R_e$')
    ##plt.plot(ages,mass_n[:,2],label='$'+('%6.1f' % r2)+'<R<'+('%6.1f' % r3)+'R_e$')
    ##plt.plot(ages,mass_n[:,3],label='$'+('%6.1f' % r3)+'<R<'+('%6.1f' % r4)+'R_e$')
    #plt.legend(loc=3)
    #if pdf == 1:
    #    plt.savefig(dev,dpi = 1000)
    #else:
    #    plt.show()
    #plt.close()
    if not pdf == 0:
        dev = dir3 + '/' + name + "_Relative_Mass2.pdf"
        #if pdf == 1:
        #    matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(figsize=(6, 5.5))
        ax.set_xlabel("$log_{10}(time/yr)$", fontsize=14)
        ax.set_ylabel("$M(t)/M_{0}$", fontsize=14)
        #MassT=10.32
        ax.set_title(name + ' $\log M_{tot}=' + ('%7.2f' % MassT) + '$',
                     fontsize=15)
        ax.set_xlim(8.6, 10.1)
        #ax.set_ylim(0,12)
        ax.set_ylim(func_plot(np.log10(1.78), ftype=1),
                    func_plot(np.log10(12), ftype=1))
        for ii in range(0, nr - 1):
            plt.plot(ages,
                     func_plot(np.log10(mass_n[:, ii]), ftype=1),
                     label='$' + ('%6.1f' % rx[ii]) + 'R_e<R<' +
                     ('%6.1f' % rx[ii + 1]) + 'R_e$')
        plt.legend(loc=3)
        plt.plot(np.arange(0, 20, .1),
                 np.ones(200) * func_plot(0.95, ftype=1),
                 '--',
                 color='black')
        plt.plot(np.arange(0, 20, .1),
                 np.ones(200) * func_plot(0.50, ftype=1),
                 '--',
                 color='green')
        fig.canvas.draw()
        labels = [item.get_text() for item in ax.get_yticklabels()]
        for i in range(0, len(labels)):
            labels[i] = labels[i].replace(u'\u2212', '-')
        for i in range(0, len(labels)):
            if labels[i] != u'':
                if float_(labels[i]) == 0:
                    labels[i] = u'%3.2f' % 10**(0)
                else:
                    labels[i] = u'%3.2f' % 10**(float_(labels[i]))
        ax.set_yticklabels(labels)
        if pdf == 1:
            fig.tight_layout()
            plt.savefig(dev)  #,dpi = 1000)
        else:
            plt.show()
        plt.close()
    f2.close()
    fL2.close()
    fo.write(name + " " + str(MassT) + " " + str(redshift) + " ")
Esempio n. 26
0
def get_evolv(ID0, PA, Z=np.arange(-1.2,0.4249,0.05), age=[0.01, 0.1, 0.3, 0.7, 1.0, 3.0], f_comp = 0, fil_path = './FILT/', inputs=None, dust_model=0, DIR_TMP='./templates/', delt_sfh = 0.01):
    #
    # delt_sfh (float): delta t of input SFH in Gyr.
    #
    # Returns: SED as function of age, based on SF and Z histories;
    #
    print('This function may take a while.')
    flim = 0.01
    lsfrl = -1 # log SFR low limit
    mmax  = 1000
    Txmax = 4 # Max x value
    lmmin = 10.3

    nage = np.arange(0,len(age),1)
    fnc  = Func(Z, nage, dust_model=dust_model) # Set up the number of Age/ZZ
    bfnc = Basic(Z)
    age = np.asarray(age)

    ################
    # RF colors.
    import os.path
    home = os.path.expanduser('~')
    c      = 3.e18 # A/s
    chimax = 1.
    mag0   = 25.0
    d      = 10**(73.6/2.5) * 1e-18 # From [ergs/s/cm2/A] to [ergs/s/cm2/Hz]

    ###########################
    # Open result file
    ###########################
    file = 'summary_' + ID0 + '_PA' + PA + '.fits'
    hdul = fits.open(file) # open a FITS file
    zbes = hdul[0].header['z']
    chinu= hdul[1].data['chi']

    uv= hdul[1].data['uv']
    vj= hdul[1].data['vj']

    RA   = 0
    DEC  = 0
    rek  = 0
    erekl= 0
    ereku= 0
    mu = 1.0
    nn = 0
    qq = 0
    enn = 0
    eqq = 0
    try:
        RA   = hdul[0].header['RA']
        DEC  = hdul[0].header['DEC']
    except:
        RA  = 0
        DEC = 0

    try:
        SN = hdul[0].header['SN']
    except:
        ###########################
        # Get SN of Spectra
        ###########################
        file = 'templates/spec_obs_' + ID0 + '_PA' + PA + '.cat'
        fds  = np.loadtxt(file, comments='#')
        nrs  = fds[:,0]
        lams = fds[:,1]
        fsp  = fds[:,2]
        esp  = fds[:,3]

        consp = (nrs<10000) & (lams/(1.+zbes)>3600) & (lams/(1.+zbes)<4200)
        if len((fsp/esp)[consp]>10):
            SN = np.median((fsp/esp)[consp])
        else:
            SN = 1


    Asum = 0
    A50 = np.arange(len(age), dtype='float32')
    for aa in range(len(A50)):
        A50[aa] = hdul[1].data['A'+str(aa)][1]
        Asum += A50[aa]

    ####################
    # For cosmology
    ####################
    DL = cd.luminosity_distance(zbes, **cosmo) * Mpc_cm # Luminositydistance in cm
    Cons = (4.*np.pi*DL**2/(1.+zbes))

    Tuni = cd.age(zbes, use_flat=True, **cosmo)
    Tuni0 = (Tuni/cc.Gyr_s - age[:])

    delT  = np.zeros(len(age),dtype='float32')
    delTl = np.zeros(len(age),dtype='float32')
    delTu = np.zeros(len(age),dtype='float32')
    for aa in range(len(age)):
        if aa == 0:
            delTl[aa] = age[aa]
            delTu[aa] = (age[aa+1]-age[aa])/2.
            delT[aa]  = delTu[aa] + delTl[aa]
        elif Tuni/cc.Gyr_s < age[aa]:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = delTl[aa] #10.
            delT[aa]  = delTu[aa] + delTl[aa]
        elif aa == len(age)-1:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = Tuni/cc.Gyr_s - age[aa]
            delT[aa]  = delTu[aa] + delTl[aa]
        else:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = (age[aa+1]-age[aa])/2.
            delT[aa]  = delTu[aa] + delTl[aa]

    delT[:]  *= 1e9 # Gyr to yr
    delTl[:] *= 1e9 # Gyr to yr
    delTu[:] *= 1e9 # Gyr to yr
    ##############################
    # Load Pickle
    ##############################
    samplepath = './'
    pfile = 'chain_' + ID0 + '_PA' + PA + '_corner.cpkl'

    niter = 0
    data = loadcpkl(os.path.join(samplepath+'/'+pfile))
    try:
        ndim   = data['ndim']     # By default, use ndim and burnin values contained in the cpkl file, if present.
        burnin = data['burnin']
        nmc    = data['niter']
        nwalk  = data['nwalkers']
        Nburn  = burnin #* nwalk/10/2 # I think this takes 3/4 of samples
        #if nmc>1000:
        #    Nburn  = 500
        samples = data['chain'][:]
    except:
        print(' =   >   NO keys of ndim and burnin found in cpkl, use input keyword values')
        return -1

    ######################
    # Mass-to-Light ratio.
    ######################
    AM = np.zeros((len(age), mmax), dtype='float32') # Mass in each bin.
    AC = np.zeros((len(age), mmax), dtype='float32') # Cumulative mass in each bin.
    AL = np.zeros((len(age), mmax), dtype='float32') # Cumulative light in each bin.
    ZM = np.zeros((len(age), mmax), dtype='float32') # Z.
    ZC = np.zeros((len(age), mmax), dtype='float32') # Cumulative Z.
    ZL = np.zeros((len(age), mmax), dtype='float32') # Light weighted cumulative Z.
    TC = np.zeros((len(age), mmax), dtype='float32') # Mass weighted T.
    TL = np.zeros((len(age), mmax), dtype='float32') # Light weighted T.
    ZMM= np.zeros((len(age), mmax), dtype='float32') # Mass weighted Z.
    ZML= np.zeros((len(age), mmax), dtype='float32') # Light weighted Z.
    SF = np.zeros((len(age), mmax), dtype='float32') # SFR
    Av = np.zeros(mmax, dtype='float32') # SFR

    # ##############################
    # Add simulated scatter in quad
    # if files are available.
    # ##############################
    if inputs:
        f_zev = int(inputs['ZEVOL'])
    else:
        f_zev = 1

    eZ_mean = 0
    try:
        meanfile = './sim_SFH_mean.cat'
        dfile    = np.loadtxt(meanfile, comments='#')
        eA = dfile[:,2]
        eZ = dfile[:,4]
        eAv= np.mean(dfile[:,6])
        if f_zev == 0:
            eZ_mean = np.mean(eZ[:])
            eZ[:]   = age * 0 #+ eZ_mean
        else:
            try:
                f_zev = int(prihdr['ZEVOL'])
                if f_zev == 0:
                    eZ_mean = np.mean(eZ[:])
                    eZ = age * 0
            except:
                pass
    except:
        print('No simulation file (%s).\nError may be underestimated.' % meanfile)
        eA = age * 0
        eZ = age * 0
        eAv= 0

    mm = 0
    #mmax = 10
    #print('mmax is set to 10')
    for mm in range(mmax):
        mtmp  = np.random.randint(len(samples))# + Nburn
        AAtmp = np.zeros(len(age), dtype='float32')
        ZZtmp = np.zeros(len(age), dtype='float32')
        mslist= np.zeros(len(age), dtype='float32')

        Av_tmp = samples['Av'][mtmp]

        f0     = fits.open(DIR_TMP + 'ms_' + ID0 + '_PA' + PA + '.fits')
        sedpar = f0[1]
        f1     = fits.open(DIR_TMP + 'ms.fits')
        mloss  = f1[1].data

        Avrand = np.random.uniform(-eAv, eAv)
        if Av_tmp + Avrand<0:
            Av[mm] = 0
        else:
            Av[mm] = Av_tmp + Avrand

        for aa in range(len(age)):
            AAtmp[aa] = samples['A'+str(aa)][mtmp]/mu
            try:
                ZZtmp[aa] = samples['Z'+str(aa)][mtmp]
            except:
                ZZtmp[aa] = samples['Z0'][mtmp]

            nZtmp      = bfnc.Z2NZ(ZZtmp[aa])
            mslist[aa] = sedpar.data['ML_'+str(nZtmp)][aa]

            ml = mloss['ms_'+str(nZtmp)][aa]

            Arand = np.random.uniform(-eA[aa],eA[aa])
            Zrand = np.random.uniform(-eZ[aa],eZ[aa])
            AM[aa, mm] = AAtmp[aa] * mslist[aa] * 10**Arand
            AL[aa, mm] = AM[aa, mm] / mslist[aa]
            SF[aa, mm] = AAtmp[aa] * mslist[aa] / delT[aa] / ml * 10**Arand
            ZM[aa, mm] = ZZtmp[aa] + Zrand
            ZMM[aa, mm]= (10 ** ZZtmp[aa]) * AAtmp[aa] * mslist[aa] * 10**Zrand
            ZML[aa, mm]= ZMM[aa, mm] / mslist[aa]

        for aa in range(len(age)):
            AC[aa, mm] = np.sum(AM[aa:, mm])
            ZC[aa, mm] = np.log10(np.sum(ZMM[aa:, mm])/AC[aa, mm])
            ZL[aa, mm] = np.log10(np.sum(ZML[aa:, mm])/np.sum(AL[aa:, mm]))
            if f_zev == 0: # To avoid random fluctuation in A.
                ZC[aa, mm] = ZM[aa, mm]

            ACs = 0
            ALs = 0
            for bb in range(aa, len(age), 1):
                tmpAA       = 10**np.random.uniform(-eA[bb],eA[bb])
                tmpTT       = np.random.uniform(-delT[bb]/1e9,delT[bb]/1e9)
                TC[aa, mm] += (age[bb]+tmpTT) * AAtmp[bb] * mslist[bb] * tmpAA
                TL[aa, mm] += (age[bb]+tmpTT) * AAtmp[bb] * tmpAA
                ACs        += AAtmp[bb] * mslist[bb] * tmpAA
                ALs        += AAtmp[bb] * tmpAA

            TC[aa, mm] /= ACs
            TL[aa, mm] /= ALs

    Avtmp  = np.percentile(Av[:],[16,50,84])

    #############
    # Plot
    #############
    AMp = np.zeros((len(age),3), dtype='float32')
    ACp = np.zeros((len(age),3), dtype='float32')
    ZMp = np.zeros((len(age),3), dtype='float32')
    ZCp = np.zeros((len(age),3), dtype='float32')
    SFp = np.zeros((len(age),3), dtype='float32')
    for aa in range(len(age)):
       AMp[aa,:] = np.percentile(AM[aa,:], [16,50,84])
       ACp[aa,:] = np.percentile(AC[aa,:], [16,50,84])
       ZMp[aa,:] = np.percentile(ZM[aa,:], [16,50,84])
       ZCp[aa,:] = np.percentile(ZC[aa,:], [16,50,84])
       SFp[aa,:] = np.percentile(SF[aa,:], [16,50,84])

    ###################
    msize = np.zeros(len(age), dtype='float32')
    for aa in range(len(age)):
        if A50[aa]/Asum>flim: # if >1%
            msize[aa] = 150 * A50[aa]/Asum

    conA = (msize>=0)
    # Make template;
    tbegin = np.min(Tuni/cc.Gyr_s-age)
    tuniv_hr = np.arange(tbegin,Tuni/cc.Gyr_s,delt_sfh) # in Gyr
    sfh_hr_in= np.interp(tuniv_hr,(Tuni/cc.Gyr_s-age)[::-1],SFp[:,1][::-1])
    zh_hr_in = np.interp(tuniv_hr,(Tuni/cc.Gyr_s-age)[::-1],ZCp[:,1][::-1])

    # FSPS
    con_sfh = (tuniv_hr>0)
    import fsps
    nimf = int(inputs['NIMF'])
    try:
        fneb = int(inputs['ADD_NEBULAE'])
    except:
        fneb = 0

    if fneb == 1:
        print('Metallicity is set to logZ/Zsun=%.2f'%(np.max(zh_hr_in)))
        sp = fsps.StellarPopulation(compute_vega_mags=False, zcontinuous=1, imf_type=nimf, logzsol=np.max(zh_hr_in), sfh=3, dust_type=2, dust2=0.0, add_neb_emission=True)
        sp.set_tabular_sfh(tuniv_hr[con_sfh], sfh_hr_in[con_sfh])
    else:
        sp = fsps.StellarPopulation(compute_vega_mags=False, zcontinuous=3, imf_type=nimf, sfh=3, dust_type=2, dust2=0.0, add_neb_emission=False)
        sp.set_tabular_sfh(tuniv_hr[con_sfh], sfh_hr_in[con_sfh], Z=10**zh_hr_in[con_sfh])

    col01 = []
    t_get = tuniv_hr[con_sfh]
    #con_tget = ((Tuni/cc.Gyr_s-age)>0)
    #t_get = (Tuni/cc.Gyr_s-age)[con_tget][::-1]
    for ss in range(len(t_get)):
        wave0, flux0 = sp.get_spectrum(tage=t_get[ss], peraa=True) # if peraa=True, in unit of L/AA
        if ss == 0:
            spec_mul_nu_conv = np.zeros((len(t_get),len(wave0)),dtype='float32')
        #ax2.plot(wave0, flux0, linestyle='-', color='b')
        #plt.show()
        print('Template %d is done.'%(ss))
        wavetmp  = wave0*(1.+zbes)
        spec_mul_nu = flamtonu(wavetmp, flux0) # Conversion from Flambda to Fnu.
        Lsun = 3.839 * 1e33 #erg s-1
        stmp_common = 1e10 # 1 tmp is in 1e10Lsun

        spec_mul_nu_conv[ss,:] = spec_mul_nu[:]
        spec_mul_nu_conv[ss,:] *= Lsun/(4.*np.pi*DL**2/(1.+zbes))
        Ls = 10**sp.log_lbol
        spec_mul_nu_conv[ss,:] *= (1./Ls)*stmp_common # in unit of erg/s/Hz/cm2/ms[ss].

        consave = (wavetmp/(1.+zbes)<20000) # AA
        if ss == 0:
            nd_ap  = np.arange(0,len(wave0),1)
            col1   = fits.Column(name='wavelength', format='E', unit='AA', disp='obs', array=wavetmp[consave])
            col2   = fits.Column(name='colnum', format='K', unit='', array=nd_ap[consave])
            col00  = [col1, col2]
            col3   = fits.Column(name='age', format='E', unit='Gyr', array=t_get)
            col4   = fits.Column(name='sfh', format='E', unit='Msun/yr', array=sfh_hr_in[con_sfh])
            col5   = fits.Column(name='zh', format='E', unit='Zsun', array=zh_hr_in[con_sfh])
            col01  = [col3,col4,col5]

        colspec_all = fits.Column(name='fspec_'+str(ss), format='E', unit='Fnu', disp='%s'%(t_get[ss]), array=spec_mul_nu_conv[ss,:][consave])
        col00.append(colspec_all)

    coldefs_spec = fits.ColDefs(col00)
    hdu = fits.BinTableHDU.from_columns(coldefs_spec)
    hdu.writeto(DIR_TMP + 'obsspec_' + ID0 + '_PA' + PA + '.fits', overwrite=True)

    coldefs_spec = fits.ColDefs(col01)
    hdu = fits.BinTableHDU.from_columns(coldefs_spec)
    hdu.writeto(DIR_TMP + 'obshist_' + ID0 + '_PA' + PA + '.fits', overwrite=True)
Esempio n. 27
0
def plot_mz(ID0,
            PA,
            Z=np.arange(-1.2, 0.4249, 0.05),
            age=[0.01, 0.1, 0.3, 0.7, 1.0, 3.0]):

    #col = ['darkred', 'r', 'coral','orange','g','lightgreen', 'lightblue', 'b','indigo','violet','k']
    import matplotlib.cm as cm

    flim = 0.01

    lsfrl = -1  # log SFR low limit
    mmax = 500

    Txmax = 4  # Max x value

    lmmin = 10.3

    nage = np.arange(0, len(age), 1)
    fnc = Func(Z, nage)  # Set up the number of Age/ZZ
    bfnc = Basic(Z)

    age = np.asarray(age)

    ################
    # RF colors.
    import os.path
    home = os.path.expanduser('~')
    #fil_path = '/Users/tmorishita/eazy-v1.01/PROG/FILT/'
    fil_path = home + '/Dropbox/FILT/'
    fil_u = fil_path + 'u.fil'
    fil_b = fil_path + 'b.fil'
    fil_v = fil_path + "v.fil"
    fil_j = fil_path + "j.fil"
    fil_k = fil_path + "k.fil"
    fil_f125w = fil_path + "f125w.fil"
    fil_f160w = fil_path + "f160w.fil"
    fil_36 = fil_path + "3.6.fil"
    fil_45 = fil_path + "4.5.fil"

    du = np.loadtxt(fil_u, comments="#")
    lu = du[:, 1]
    fu = du[:, 2]

    db = np.loadtxt(fil_b, comments="#")
    lb = db[:, 1]
    fb = db[:, 2]

    dv = np.loadtxt(fil_v, comments="#")
    lv = dv[:, 1]
    fv = dv[:, 2]

    dj = np.loadtxt(fil_j, comments="#")
    lj = dj[:, 1]
    fj = dj[:, 2]

    c = 3.e18  # A/s
    chimax = 1.
    mag0 = 25.0
    d = 10**(73.6 / 2.5) * 1e-18  # From [ergs/s/cm2/A] to [ergs/s/cm2/Hz]
    #d = 10**(-73.6/2.5) # From [ergs/s/cm2/Hz] to [ergs/s/cm2/A]

    #############
    # Plot.
    #############
    fig = plt.figure(figsize=(6, 6))
    fig.subplots_adjust(top=0.98,
                        bottom=0.08,
                        left=0.1,
                        right=0.99,
                        hspace=0.18,
                        wspace=0.25)
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)

    #ax3t = ax3.twiny()
    #ax4t = ax4.twiny()

    ##################
    # Fitting Results
    ##################
    DIR_TMP = './templates/'
    SNlim = 3  # avobe which SN line is shown.

    ###########################
    # Open result file
    ###########################
    file = 'summary_' + ID0 + '_PA' + PA + '.fits'
    hdul = fits.open(file)  # open a FITS file
    zbes = hdul[0].header['z']

    Asum = 0
    A50 = np.arange(len(age), dtype='float32')
    for aa in range(len(A50)):
        A50[aa] = hdul[1].data['A' + str(aa)][1]
        Asum += A50[aa]

    # Cosmo;
    DL = cd.luminosity_distance(zbes, **
                                cosmo) * Mpc_cm  # Luminositydistance in cm
    Cons = (4. * np.pi * DL**2 / (1. + zbes))

    Tuni = cd.age(zbes, use_flat=True, **cosmo)  # age at zobs.
    Tuni0 = (Tuni / cc.Gyr_s - age[:])

    delT = np.zeros(len(age), dtype='float32')
    delTl = np.zeros(len(age), dtype='float32')
    delTu = np.zeros(len(age), dtype='float32')

    col = np.zeros((len(age), 4), dtype='float32')
    for aa in range(len(age)):
        col[aa, :] = cm.nipy_spectral_r((aa + 0.1) / (len(age)))

    for aa in range(len(age)):
        if aa == 0:
            delTl[aa] = age[aa]
            delTu[aa] = (age[aa + 1] - age[aa]) / 2.
            delT[aa] = delTu[aa] + delTl[aa]
        elif Tuni / cc.Gyr_s < age[aa]:
            delTl[aa] = (age[aa] - age[aa - 1]) / 2.
            delTu[aa] = 10.
            delT[aa] = delTu[aa] + delTl[aa]
        elif aa == len(age) - 1:
            delTl[aa] = (age[aa] - age[aa - 1]) / 2.
            delTu[aa] = Tuni / cc.Gyr_s - age[aa]
            delT[aa] = delTu[aa] + delTl[aa]
        else:
            delTl[aa] = (age[aa] - age[aa - 1]) / 2.
            delTu[aa] = (age[aa + 1] - age[aa]) / 2.
            delT[aa] = delTu[aa] + delTl[aa]

    delT[:] *= 1e9  # Gyr to yr
    delTl[:] *= 1e9  # Gyr to yr
    delTu[:] *= 1e9  # Gyr to yr
    #print(age, delT, delTu, delTl)
    ##############################
    # Load Pickle
    ##############################
    samplepath = './'
    pfile = 'chain_' + ID0 + '_PA' + PA + '_corner.cpkl'

    niter = 0
    data = loadcpkl(os.path.join(samplepath + '/' + pfile))
    try:
        #if 1>0:
        ndim = data[
            'ndim']  # By default, use ndim and burnin values contained in the cpkl file, if present.
        burnin = data['burnin']
        nmc = data['niter']
        nwalk = data['nwalkers']
        Nburn = burnin  #* nwalk/10/2 # I think this takes 3/4 of samples
        #if nmc>1000:
        #    Nburn  = 500
        samples = data['chain'][:]
    except:
        print(
            ' =   >   NO keys of ndim and burnin found in cpkl, use input keyword values'
        )
        return -1

    ######################
    # Mass-to-Light ratio.
    ######################
    # Wht do you want from MCMC sampler?
    AM = np.zeros((len(age), mmax), dtype='float32')  # Mass in each bin.
    AC = np.zeros((len(age), mmax),
                  dtype='float32')  # Cumulative mass in each bin.
    ZM = np.zeros((len(age), mmax), dtype='float32')  # Z.
    ZC = np.zeros((len(age), mmax), dtype='float32')  # Cumulative Z.
    TC = np.zeros((len(age), mmax), dtype='float32')  # Mass weighted T.
    ZMM = np.zeros((len(age), mmax), dtype='float32')  # Mass weighted Z.

    SF = np.zeros((len(age), mmax), dtype='float32')  # SFR

    mm = 0
    while mm < mmax:
        mtmp = np.random.randint(len(samples))  # + Nburn

        AAtmp = np.zeros(len(age), dtype='float32')
        ZZtmp = np.zeros(len(age), dtype='float32')
        mslist = np.zeros(len(age), dtype='float32')

        Av_tmp = samples['Av'][mtmp]

        f0 = fits.open(DIR_TMP + 'ms_' + ID0 + '_PA' + PA + '.fits')
        sedpar = f0[1]

        for aa in range(len(age)):
            AAtmp[aa] = samples['A' + str(aa)][mtmp]
            ZZtmp[aa] = samples['Z' + str(aa)][mtmp]

            nZtmp = bfnc.Z2NZ(ZZtmp[aa])
            mslist[aa] = sedpar.data['ML_' + str(nZtmp)][aa]

            AM[aa, mm] = AAtmp[aa] * mslist[aa]
            SF[aa, mm] = AAtmp[aa] * mslist[aa] / delT[aa]
            ZM[aa, mm] = ZZtmp[aa]  # AAtmp[aa] * mslist[aa]
            ZMM[aa, mm] = (10**ZZtmp[aa]) * AAtmp[aa] * mslist[aa]

        for aa in range(len(age)):
            AC[aa, mm] = np.sum(AM[aa:, mm])
            ZC[aa, mm] = np.log10(np.sum((ZMM)[aa:, mm]) / AC[aa, mm])

            ACs = 0
            for bb in range(aa, len(age), 1):
                TC[aa, mm] += age[bb] * AAtmp[bb] * mslist[bb]
                ACs += AAtmp[bb] * mslist[bb]

            TC[aa, mm] /= ACs

        mm += 1

    #############
    # Plot
    #############
    AMp = np.zeros((len(age), 3), dtype='float32')
    ACp = np.zeros((len(age), 3), dtype='float32')
    ZMp = np.zeros((len(age), 3), dtype='float32')
    ZCp = np.zeros((len(age), 3), dtype='float32')
    SFp = np.zeros((len(age), 3), dtype='float32')
    for aa in range(len(age)):
        AMp[aa, :] = np.percentile(AM[aa, :], [16, 50, 84])
        ACp[aa, :] = np.percentile(AC[aa, :], [16, 50, 84])
        ZMp[aa, :] = np.percentile(ZM[aa, :], [16, 50, 84])
        ZCp[aa, :] = np.percentile(ZC[aa, :], [16, 50, 84])
        SFp[aa, :] = np.percentile(SF[aa, :], [16, 50, 84])

    ###################
    msize = np.zeros(len(age), dtype='float32')
    for aa in range(len(age)):
        if A50[aa] / Asum > flim:  # if >1%
            msize[aa] = 10 + 150 * A50[aa] / Asum

    conA = (msize >= 0)

    #
    # M-SFR
    #
    #ax1.fill_between(age[conA], np.log10(SFp[:,0])[conA], np.log10(SFp[:,2])[conA], linestyle='-', color='k', alpha=0.3)
    ax1.scatter(np.log10(ACp[:, 1])[conA],
                np.log10(SFp[:, 1])[conA],
                marker='o',
                c=col[:],
                s=msize[conA],
                edgecolors='k',
                zorder=2)
    ax1.errorbar(np.log10(ACp[:, 1])[conA],
                 np.log10(SFp[:, 1])[conA],
                 linestyle='--',
                 color='k',
                 lw=1.,
                 marker='',
                 zorder=0,
                 alpha=1.)

    lM = np.arange(9, 13, 0.1)
    delSFR = np.zeros(len(age), dtype='float32')
    delSFRl = np.zeros(len(age), dtype='float32')
    delSFRu = np.zeros(len(age), dtype='float32')
    for ii in range(len(Tuni0)):
        lSFR = (0.84 - 0.026 * Tuni0[ii]) * (lM - 0.19) - (6.51 -
                                                           0.11 * Tuni0[ii])
        ax1.fill_between(lM,
                         lSFR - 0.1,
                         lSFR + 0.1,
                         linestyle='None',
                         lw=0.5,
                         zorder=-5,
                         alpha=0.5,
                         color=col[ii])  # 0.19 is for Kroupa to Salpeter.

        lSFRtmp = (0.84 - 0.026 * Tuni0[ii]) * np.log10(ACp[ii, 1]) - (
            6.51 - 0.11 * Tuni0[ii])
        delSFR[ii] = np.log10(SFp[ii, 1]) - lSFRtmp
        delSFRl[ii] = np.log10(SFp[ii, 0]) - lSFRtmp
        delSFRu[ii] = np.log10(SFp[ii, 2]) - lSFRtmp

    #
    # t - delta SRF relation (right top)
    #
    #ax2.plot(age[:][conA], delSFR[conA], marker='', c='k',zorder=1, lw=1, linestyle='-')
    ax2.scatter(age[:][conA],
                delSFR[conA],
                marker='o',
                c=col[:],
                s=msize[conA],
                edgecolors='k',
                zorder=2)
    ax2.errorbar(age[:][conA],
                 delSFR[:][conA],
                 linestyle='--',
                 fmt='--',
                 color='k',
                 lw=1.,
                 marker='',
                 zorder=0,
                 alpha=1.)

    #
    # Mass - Z relation (left bottom)
    #
    ax2label = ''
    #ax2.fill_between(age[conA], np.log10(ACp[:,0])[conA], np.log10(ACp[:,2])[conA], linestyle='-', color='k', alpha=0.3)
    ax3.errorbar(
        np.log10(ACp[:, 1])[conA],
        ZCp[:, 1][conA],
        linestyle='--',
        zorder=0,
        color='k',
        lw=1.,
        label=ax2label,
        alpha=1.
    )  #, xerr=[np.log10(ACp[:,1])[conA]-np.log10(ACp[:,0])[conA],np.log10(ACp[:,2])[conA]-np.log10(ACp[:,1])[conA]], yerr=[ZCp[:,1][conA]-ZCp[:,0][conA],ZCp[:,2][conA]-ZCp[:,1][conA]]
    ax3.scatter(np.log10(ACp[:, 1])[conA],
                ZCp[:, 1][conA],
                marker='o',
                c=col[:],
                s=msize,
                edgecolors='k',
                zorder=2)

    #
    # Mass-Z from Gallazzi+05
    #
    lM = [
        8.91, 9.11, 9.31, 9.51, 9.72, 9.91, 10.11, 10.31, 10.51, 10.72, 10.91,
        11.11, 11.31, 11.51, 11.72, 11.91
    ]
    lZ50 = [
        -0.6, -0.61, -0.65, -0.61, -.52, -.41, -.23, -.11, -.01, .04, .07, .10,
        .12, .13, .14, .15
    ]
    lZ16 = [
        -1.11, -1.07, -1.1, -1.03, -.97, -.90, -.8, -.65, -.41, -.24, -.14,
        -.09, -.06, -.04, -.03, -.03
    ]
    lZ84 = [
        -0., -0., -0.05, -0.01, .05, .09, .14, .17, .20, .22, .24, .25, .26,
        .28, .29, .30
    ]

    lM = np.asarray(lM)
    lZ50 = np.asarray(lZ50)
    lZ16 = np.asarray(lZ16)
    lZ84 = np.asarray(lZ84)

    ax3.errorbar(lM,
                 lZ50,
                 marker='',
                 color='gray',
                 ms=15,
                 linestyle='-',
                 lw=1,
                 zorder=-2)  #, yerr=[lZ50-lZ16, lZ84-lZ50]
    ax3.fill_between(lM,
                     lZ16,
                     lZ84,
                     color='gray',
                     linestyle='None',
                     lw=1,
                     alpha=0.4,
                     zorder=-2)

    #
    # Fundamental Metal
    #
    bsfr = -0.32  # From Mannucci+10
    #ax4.fill_between(age[conA], ZCp[:,0][conA], ZCp[:,2][conA], linestyle='-', color='k', alpha=0.3)
    ax4.scatter((np.log10(ACp[:, 1]) + bsfr * np.log10(SFp[:, 1]))[conA],
                ZCp[:, 1][conA],
                marker='o',
                c=col[:],
                s=msize[conA],
                edgecolors='k',
                zorder=2)
    ax4.errorbar((np.log10(ACp[:, 1]) + bsfr * np.log10(SFp[:, 1]))[conA],
                 ZCp[:, 1][conA],
                 linestyle='--',
                 color='k',
                 lw=1.,
                 zorder=0,
                 alpha=1.)

    for iic in range(len(A50)):
        if msize[iic] > 10:
            lwe = 1.5
            ax1.errorbar(np.log10(ACp[iic, 1]),
                         np.log10(SFp[iic, 1]),
                         xerr=[[np.log10(ACp[iic, 1]) - np.log10(ACp[iic, 0])],
                               [np.log10(ACp[iic, 2]) - np.log10(ACp[iic, 1])]
                               ],
                         yerr=[[np.log10(SFp[iic, 1]) - np.log10(SFp[iic, 0])],
                               [np.log10(SFp[iic, 2]) - np.log10(SFp[iic, 1])]
                               ],
                         linestyle='-',
                         color=col[iic],
                         lw=lwe,
                         marker='',
                         zorder=1)
            ax2.errorbar(age[iic],
                         delSFR[iic],
                         xerr=[[delTl[iic] / 1e9], [delTu[iic] / 1e9]],
                         yerr=[[delSFR[iic] - delSFRl[iic]],
                               [delSFRu[iic] - delSFR[iic]]],
                         linestyle='-',
                         fmt='-',
                         color=col[iic],
                         lw=lwe,
                         marker='',
                         zorder=1)
            ax3.errorbar(np.log10(ACp[iic, 1]),
                         ZCp[iic, 1],
                         xerr=[[np.log10(ACp[iic, 1]) - np.log10(ACp[iic, 0])],
                               [np.log10(ACp[iic, 2]) - np.log10(ACp[iic, 1])]
                               ],
                         yerr=[[ZCp[iic, 1] - ZCp[iic, 0]],
                               [ZCp[iic, 2] - ZCp[iic, 1]]],
                         linestyle='-',
                         color=col[iic],
                         lw=lwe,
                         label=ax2label,
                         zorder=1)

            xerl_ax4 = np.sqrt(
                (np.log10(ACp[iic, 1]) - np.log10(ACp[iic, 0]))**2 + bsfr**2 *
                (np.log10(SFp[iic, 1]) - np.log10(SFp[iic, 0]))**2)
            xeru_ax4 = np.sqrt(
                (np.log10(ACp[iic, 2]) - np.log10(ACp[iic, 1]))**2 + bsfr**2 *
                (np.log10(SFp[iic, 2]) - np.log10(SFp[iic, 1]))**2)

            ax4.errorbar(
                (np.log10(ACp[iic, 1]) + bsfr * np.log10(SFp[iic, 1])),
                ZCp[iic, 1],
                xerr=[[xerl_ax4], [xeru_ax4]],
                yerr=[[ZCp[iic, 1] - ZCp[iic, 0]],
                      [ZCp[iic, 2] - ZCp[iic, 1]]],
                linestyle='-',
                color=col[iic],
                lw=lwe,
                label=ax2label,
                zorder=1)

    #########################
    # Title
    #########################
    #ax1.set_title('Each $t$-bin', fontsize=12)
    #ax2.set_title('Net system', fontsize=12)
    #ax3.set_title('Each $t$-bin', fontsize=12)
    #ax4.set_title('Net system', fontsize=12)

    #############
    # Axis
    #############
    #ax1.set_xlabel('$t$ (Gyr)', fontsize=12)
    ax1.set_ylabel('$\log \dot{M_*}/M_\odot$yr$^{-1}$', fontsize=12)
    #ax1.set_ylabel('$\log M_*/M_\odot$', fontsize=12)

    y3min, y3max = np.min(Z), np.max(Z)

    lsfru = 2.8
    if np.max(np.log10(SFp[:, 2])) > 2.8:
        lsfru = np.max(np.log10(SFp[:, 2])) + 0.1

    y2min, y2max = 9.5, 12.5
    ax1.set_xlim(y2min, y2max)
    ax1.set_ylim(lsfrl, lsfru)
    #ax1.set_xscale('log')
    ax1.set_xlabel('$\log M_*/M_\odot$', fontsize=12)

    #ax1.xaxis.labelpad = -3
    #ax1.yaxis.labelpad = -2
    #ax2t.set_yticklabels(())

    #ax2.set_xlabel('$t$ (Gyr)', fontsize=12)
    #ax2.set_ylabel('$\log M_*/M_\odot$', fontsize=12)
    ax2.set_xlabel('$t-t_\mathrm{obs.}$/Gyr', fontsize=12)
    ax2.set_ylabel('$\Delta_\mathrm{SFR}$', fontsize=12)

    #ax2.set_ylim(lsfrl, lsfru)
    ax2.set_ylim(-4, 2.5)
    ax2.set_xlim(0.008, 3.2)
    ax2.set_xscale('log')

    dely2 = 0.1
    while (y2max - y2min) / dely2 > 7:
        dely2 *= 2.

    #y2ticks = np.arange(y2min, y2max, dely2)
    #ax2.set_yticks(y2ticks)
    #ax2.set_yticklabels(np.arange(y2min, y2max, 0.1), minor=False)
    #ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))

    ax3.set_xlim(y2min, y2max)
    ax3.set_ylim(y3min, y3max)

    ax3.set_xlabel('$\log M_*/M_\odot$', fontsize=12)
    ax3.set_ylabel('$\log Z_*/Z_\odot$', fontsize=12)

    #ax3.set_xscale('log')
    #ax2.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

    # For redshift
    if zbes < 2:
        zred = [zbes, 2, 3, 6]
        #zredl = ['$z_\mathrm{obs.}$', 2, 3, 6]
        zredl = ['$z_\mathrm{obs.}$', 2, 3, 6]
    elif zbes < 2.5:
        zred = [zbes, 2.5, 3, 6]
        zredl = ['$z_\mathrm{obs.}$', 2.5, 3, 6]
    elif zbes < 3.:
        zred = [zbes, 3, 6]
        zredl = ['$z_\mathrm{obs.}$', 3, 6]
    elif zbes < 6:
        zred = [zbes, 6]
        zredl = ['$z_\mathrm{obs.}$', 6]

    Tzz = np.zeros(len(zred), dtype='float32')
    for zz in range(len(zred)):
        Tzz[zz] = (Tuni - cd.age(zred[zz], use_flat=True, **cosmo)) / cc.Gyr_s
        if Tzz[zz] < 0.01:
            Tzz[zz] = 0.01

    #ax3t.set_xscale('log')
    #ax3t.set_xlim(0.008, Txmax)

    ax4.set_xlabel('$\log M_*/M_\odot - 0.32 \log \dot{M_*}/M_\odot$yr$^{-1}$',
                   fontsize=12)
    ax4.set_ylabel('$\log Z_*/Z_\odot$', fontsize=12)

    #ax4t.set_xscale('log')
    #ax4t.set_xlim(0.008, Txmax)

    ax4.set_xlim(9, 12.3)
    ax4.set_ylim(y3min, y3max)
    #ax4.set_xscale('log')
    #ax4.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

    ax3.yaxis.labelpad = -2
    ax4.yaxis.labelpad = -2

    ####################
    ## Save
    ####################
    ax1.legend(loc=1, fontsize=11)
    ax2.legend(loc=3, fontsize=8)
    plt.savefig('MZ_' + ID0 + '_PA' + PA + '_pcl.pdf')
Esempio n. 28
0
def DensityPlot(x,y,z):
  # Create a density plot
	import numpy as np
	import matplotlib.pyplot as plt
	import scipy.interpolate
	
	x,y,z = np.array(x),np.array(y),np.array(z)
	
	for i in range(0,len(x)):
	   print x[i],y[i],z[i]
	
	# Set up a regular grid of interpolation points
	xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
	#xi, yi = np.meshgrid(xi, yi)
	
	# Interpolate
	#rbf = scipy.interpolate.Rbf(x, y, z, function = 'linear')
	densityfit = scipy.interpolate.interp2d(x, y, z, kind = 'linear')
	zi = densityfit(xi, yi)
	
	fig = plt.figure()
	ax = fig.add_subplot(111)
	
	# Plot labels
	for i in range(0,len(z)):
	   ax.annotate(
		  str(z[i]), 
		  xy = (x[i],y[i])
		  , xytext = (0, 0),
		  textcoords = 'offset points', ha = 'center', va = 'center', color='white',size=13, fontname='Times New Roman')
	
	
	# set your ticks manually
	#ax.xaxis.set_ticks([0.0,0.1,0.2,0.3,0.4,0.5])
	ax.xaxis.set_ticks([0.5,0.75,1.0,1.25,1.50])
	
	plt.xlabel('redshift',fontname='Times New Roman',size=16)
	plt.ylabel('log L [erg/s]', fontname='Times New Roman',size=16)
	
	plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
			   extent=[0.5, 1.5, 38, 45.], aspect='auto',cmap = 'jet')
	#plt.scatter(x, y, c=z)
	
	matplotlib.rcParams.update({'font.size': 13, 'font': 'Times New Roman'})
	
	ax.grid(color='#B0B0B0',linestyle='-',linewidth=1.)
	
	_F = [10**(-18.),10**(-17.),10**(-16.),10**(-15.),10**(-14.)]
	for F in _F:
		_z = np.linspace(0.001,1.5,100)
		_L = []
		for z in _z:
			DL = luminosity_distance(z, **cosmo) # In MPc
			DL = DL * (10**6. * pc) * 10**2. # in cm
			L = math.log10(4 * math.pi * DL**2. * F)
			_L.append(L)
		plt.plot(_z,_L,'w--')
          
	#plt.xlim(0.0,0.5)
	plt.xlim(0.5,1.5)
	plt.ylim(38,44)
	plt.savefig('LvsZ.png')
Esempio n. 29
0
def DensityPlot(x, y, z):
    # Create a density plot
    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.interpolate

    x, y, z = np.array(x), np.array(y), np.array(z)

    for i in range(0, len(x)):
        print x[i], y[i], z[i]

    # Set up a regular grid of interpolation points
    xi, yi = np.linspace(x.min(), x.max(),
                         100), np.linspace(y.min(), y.max(), 100)
    #xi, yi = np.meshgrid(xi, yi)

    # Interpolate
    #rbf = scipy.interpolate.Rbf(x, y, z, function = 'linear')
    densityfit = scipy.interpolate.interp2d(x, y, z, kind='linear')
    zi = densityfit(xi, yi)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    # Plot labels
    for i in range(0, len(z)):
        ax.annotate(str(z[i]),
                    xy=(x[i], y[i]),
                    xytext=(0, 0),
                    textcoords='offset points',
                    ha='center',
                    va='center',
                    color='white',
                    size=13,
                    fontname='Times New Roman')

    # set your ticks manually
    #ax.xaxis.set_ticks([0.0,0.1,0.2,0.3,0.4,0.5])
    ax.xaxis.set_ticks([0.5, 0.75, 1.0, 1.25, 1.50])

    plt.xlabel('redshift', fontname='Times New Roman', size=16)
    plt.ylabel('log L [erg/s]', fontname='Times New Roman', size=16)

    plt.imshow(zi,
               vmin=z.min(),
               vmax=z.max(),
               origin='lower',
               extent=[0.5, 1.5, 38, 45.],
               aspect='auto',
               cmap='jet')
    #plt.scatter(x, y, c=z)

    matplotlib.rcParams.update({'font.size': 13, 'font': 'Times New Roman'})

    ax.grid(color='#B0B0B0', linestyle='-', linewidth=1.)

    _F = [10**(-18.), 10**(-17.), 10**(-16.), 10**(-15.), 10**(-14.)]
    for F in _F:
        _z = np.linspace(0.001, 1.5, 100)
        _L = []
        for z in _z:
            DL = luminosity_distance(z, **cosmo)  # In MPc
            DL = DL * (10**6. * pc) * 10**2.  # in cm
            L = math.log10(4 * math.pi * DL**2. * F)
            _L.append(L)
        plt.plot(_z, _L, 'w--')

    #plt.xlim(0.0,0.5)
    plt.xlim(0.5, 1.5)
    plt.ylim(38, 44)
    plt.savefig('LvsZ.png')
Esempio n. 30
0
def maketemp(inputs,
             zbest,
             Z=np.arange(-1.2, 0.45, 0.1),
             age=[0.01, 0.1, 0.3, 0.7, 1.0, 3.0],
             fneb=0,
             DIR_TMP='./templates/'):
    #
    # inputs      : Configuration file.
    # zbest(float): Best redshift at this iteration. Templates are generated based on this reshift.
    # Z (array)   : Stellar phase metallicity in logZsun.
    # age (array) : Age, in Gyr.
    # fneb (int)  : flag for adding nebular emissionself.
    #
    nage = np.arange(0, len(age), 1)
    fnc = Func(Z, nage)  # Set up the number of Age/ZZ
    bfnc = Basic(Z)

    ID = inputs['ID']
    PA = inputs['PA']
    try:
        DIR_EXTR = inputs['DIR_EXTR']
        if len(DIR_EXTR) == 0:
            DIR_EXTR = False
    except:
        DIR_EXTR = False
    DIR_FILT = inputs['DIR_FILT']
    try:
        CAT_BB_IND = inputs['CAT_BB_IND']
    except:
        CAT_BB_IND = False
    try:
        CAT_BB = inputs['CAT_BB']
    except:
        CAT_BB = False

    SFILT = inputs['FILTER']  # filter band string.
    SFILT = [x.strip() for x in SFILT.split(',')]
    FWFILT = fil_fwhm(SFILT, DIR_FILT)

    # If FIR data;
    try:
        DFILT = inputs['FIR_FILTER']  # filter band string.
        DFILT = [x.strip() for x in DFILT.split(',')]
        DFWFILT = fil_fwhm(DFILT, DIR_FILT)
        CAT_BB_DUST = inputs['CAT_BB_DUST']
        DT0 = float(inputs['TDUST_LOW'])
        DT1 = float(inputs['TDUST_HIG'])
        dDT = float(inputs['TDUST_DEL'])
        f_dust = True
        print('FIR is implemented.')
    except:
        print('No FIR is implemented.')
        f_dust = False
        pass

    #
    # Tau for MCMC parameter; not as fitting parameters.
    #
    tau0 = inputs['TAU0']
    tau0 = [float(x.strip()) for x in tau0.split(',')]

    print('############################')
    print('Making templates at %.4f' % (zbest))
    print('############################')
    ####################################################
    # Get extracted spectra.
    ####################################################
    #
    # Get ascii data.
    #
    #ninp1 = 0
    #ninp2 = 0
    f_spec = False
    try:
        spec_files = inputs['SPEC_FILE'].replace('$ID', '%s' % (ID))
        spec_files = [x.strip() for x in spec_files.split(',')]
        ninp0 = np.zeros(len(spec_files), dtype='int')
        for ff, spec_file in enumerate(spec_files):
            try:
                fd0 = np.loadtxt(DIR_EXTR + spec_file, comments='#')
                lm0tmp = fd0[:, 0]
                fobs0 = fd0[:, 1]
                eobs0 = fd0[:, 2]
                ninp0[ff] = len(lm0tmp)  #[con_tmp])
            except Exception:
                print('File, %s, cannot be open.' % (spec_file))
                pass
        # Constructing arrays.
        lm = np.zeros(np.sum(ninp0[:]), dtype='float32')
        fobs = np.zeros(np.sum(ninp0[:]), dtype='float32')
        eobs = np.zeros(np.sum(ninp0[:]), dtype='float32')
        fgrs = np.zeros(np.sum(ninp0[:]), dtype='int')  # FLAG for G102/G141.
        for ff, spec_file in enumerate(spec_files):
            try:
                fd0 = np.loadtxt(DIR_EXTR + spec_file, comments='#')
                lm0tmp = fd0[:, 0]
                fobs0 = fd0[:, 1]
                eobs0 = fd0[:, 2]
                for ii1 in range(ninp0[ff]):
                    if ff == 0:
                        ii = ii1
                    else:
                        ii = ii1 + np.sum(ninp0[:ff])
                    fgrs[ii] = ff
                    lm[ii] = lm0tmp[ii1]
                    fobs[ii] = fobs0[ii1]
                    eobs[ii] = eobs0[ii1]
                f_spec = True
            except Exception:
                pass
    except:
        print('No spec file is provided.')
        pass

    #############################
    # Extracting BB photometry:
    #############################
    if CAT_BB:
        fd0 = np.loadtxt(CAT_BB, comments='#')
        try:
            id0 = fd0[:, 0]
            ii0 = np.argmin(np.abs(id0[:] - int(ID)))
            if int(id0[ii0]) != int(ID):
                return -1
            fd = fd0[ii0, :]
        except:
            id0 = fd0[0]
            if int(id0) != int(ID):
                return -1
            fd = fd0[:]
        id = fd[0]
        fbb = np.zeros(len(SFILT), dtype='float32')
        ebb = np.zeros(len(SFILT), dtype='float32')
        for ii in range(len(SFILT)):
            fbb[ii] = fd[ii * 2 + 1]
            ebb[ii] = fd[ii * 2 + 2]
    elif CAT_BB_IND:  # if individual photometric catalog; made in get_sdss.py
        fd0 = fits.open(DIR_EXTR + CAT_BB_IND)
        hd0 = fd0[1].header
        bunit_bb = float(hd0['bunit'][:5])
        lmbb0 = fd0[1].data['wavelength']
        fbb0 = fd0[1].data['flux'] * bunit_bb
        ebb0 = 1 / np.sqrt(fd0[1].data['inverse_variance']) * bunit_bb

        unit = 'nu'
        try:
            unit = inputs['UNIT_SPEC']
        except:
            print('No param for UNIT_SPEC is found.')
            print('BB flux unit is assumed to Fnu.')
            pass

        if unit == 'lambda':
            print('#########################')
            print('Changed BB from Flam to Fnu')
            snbb0 = fbb0 / ebb0
            fbb = flamtonu(lmbb0, fbb0)
            ebb = fbb / snbb0
        else:
            snbb0 = fbb0 / ebb0
            fbb = fbb0
            ebb = ebb0

    else:
        fbb = np.zeros(len(SFILT), dtype='float32')
        ebb = np.zeros(len(SFILT), dtype='float32')
        for ii in range(len(SFILT)):
            fbb[ii] = 0
            ebb[ii] = -99  #1000

    # Dust flux;
    if f_dust:
        fdd = np.loadtxt(CAT_BB_DUST, comments='#')
        try:
            id0 = fdd[:, 0]
            ii0 = np.argmin(np.abs(id0[:] - int(ID)))
            if int(id0[ii0]) != int(ID):
                return -1
            fd = fdd[ii0, :]
        except:
            id0 = fdd[0]
            if int(id0) != int(ID):
                return -1
            fd = fdd[:]
        id = fd[0]
        fbb_d = np.zeros(len(DFILT), dtype='float32')
        ebb_d = np.zeros(len(DFILT), dtype='float32')
        for ii in range(len(DFILT)):
            fbb_d[ii] = fd[ii * 2 + 1]
            ebb_d[ii] = fd[ii * 2 + 2]

    #############################
    # Getting Morphology params.
    #############################
    Amp = 0
    f_morp = False
    if f_spec:
        try:
            if inputs['MORP'] == 'moffat' or inputs['MORP'] == 'gauss':
                f_morp = True
                try:
                    mor_file = inputs['MORP_FILE'].replace('$ID', '%s' % (ID))
                    fm = np.loadtxt(DIR_EXTR + mor_file, comments='#')
                    #Amp   = fm[0]
                    #gamma = fm[1]
                    Amp = fm[2]
                    gamma = fm[4]
                    if inputs['MORP'] == 'moffat':
                        #alp   = fm[2]
                        alp = fm[5]
                    else:
                        alp = 0
                except Exception:
                    print('Error in reading morphology params.')
                    print('No morphology convolution.')
                    #return -1
                    pass
            else:
                print('MORP Keywords does not match.')
                print('No morphology convolution.')
        except:
            pass

        ############################
        # Template convolution;
        ############################
        try:
            sig_temp = float(inputs['SIG_TEMP'])
        except:
            sig_temp = 50.
            print('Template resolution is unknown.')
            print('Set to %.1f km/s.' % (sig_temp))
        dellam = lm[1] - lm[0]  # AA/pix
        R_temp = c / (sig_temp * 1e3 * 1e10)
        sig_temp_pix = np.median(lm) / R_temp / dellam  # delta v in pixel;

        #
        sig_inst = 0  #65 #km/s for Manga

        # If grism;
        if f_morp:
            print('Templates convolution (intrinsic morphology).')
            if gamma > sig_temp_pix:
                sig_conv = np.sqrt(gamma**2 - sig_temp_pix**2)
            else:
                sig_conv = 0
                print('Template resolution is broader than Morphology.')
                print('No convolution is applied to templates.')

            xMof = np.arange(-5, 5.1, .1)  # dimension must be even.
            if inputs['MORP'] == 'moffat' and Amp > 0 and alp > 0:
                LSF = moffat(xMof, Amp, 0, np.sqrt(gamma**2 - sig_temp_pix**2),
                             alp)
                #print(np.sqrt(gamma**2-sig_temp_pix**2))
                print('Template convolution with Moffat.')
                #print('params are;',Amp, 0, gamma, alp)
            elif inputs['MORP'] == 'gauss':
                sigma = gamma
                LSF = gauss(xMof, Amp, np.sqrt(sigma**2 - sig_temp_pix**2))
                print('Template convolution with Gaussian.')
                print('params is sigma;', sigma)
            else:
                print('Something is wrong.')
                return -1

        else:  # For slit spectroscopy. To be updated...
            print('Templates convolution (intrinsic velocity).')
            f_disp = False
            try:
                vdisp = float(inputs['VDISP'])
                dellam = lm[1] - lm[0]  # AA/pix
                #R_disp = c/(vdisp*1e3*1e10)
                R_disp = c / (np.sqrt(vdisp**2 - sig_inst**2) * 1e3 * 1e10)
                vdisp_pix = np.median(
                    lm) / R_disp / dellam  # delta v in pixel;
                print('Templates are convolved at %.2f km/s.' % (vdisp))
                if vdisp_pix - sig_temp_pix > 0:
                    sig_conv = np.sqrt(vdisp_pix**2 - sig_temp_pix**2)
                else:
                    sig_conv = 0
            except:
                vdisp = 0.
                print('Templates are not convolved.')
                sig_conv = 0  #np.sqrt(sig_temp_pix**2)
                pass
            xMof = np.arange(-5, 5.1, .1)  # dimension must be even.
            Amp = 1.
            LSF = gauss(xMof, Amp, sig_conv)
    else:
        lm = []

    ####################################
    # Start generating templates
    ####################################
    #DIR_TMP = './templates/'
    #DIR_TMP = inputs['DIR_TEMP']
    f0 = fits.open(DIR_TMP + 'ms.fits')
    mshdu = f0[1]
    col00 = []
    col01 = []
    col02 = []
    for zz in range(len(Z)):
        for pp in range(len(tau0)):
            f1 = fits.open(DIR_TMP + 'spec_all.fits')
            spechdu = f1[1]
            Zbest = Z[zz]

            Na = len(age)
            Nz = 1
            param = np.zeros((Na, 6), dtype='float32')
            param[:, 2] = 1e99
            Ntmp = 1
            chi2 = np.zeros(Ntmp) + 1e99
            snorm = np.zeros(Ntmp)
            agebest = np.zeros(Ntmp)
            avbest = np.zeros(Ntmp)
            age_univ = cd.age(zbest, use_flat=True, **cosmo)

            if zz == 0 and pp == 0:
                lm0 = spechdu.data['wavelength']
                if fneb == 1:
                    spec0 = spechdu.data['efspec_' + str(zz) + '_0_' + str(pp)]
                    #logU  = f1[0].header['logU']
                else:
                    spec0 = spechdu.data['fspec_' + str(zz) + '_0_' + str(pp)]

            lmbest = np.zeros((Ntmp, len(lm0)), dtype='float32')
            fbest = np.zeros((Ntmp, len(lm0)), dtype='float32')
            lmbestbb = np.zeros((Ntmp, len(SFILT)), dtype='float32')
            fbestbb = np.zeros((Ntmp, len(SFILT)), dtype='float32')

            A = np.zeros(Na, dtype='float32') + 1

            spec_mul = np.zeros((Na, len(lm0)), dtype='float32')
            spec_mul_nu = np.zeros((Na, len(lm0)), dtype='float32')
            spec_mul_nu_conv = np.zeros((Na, len(lm0)), dtype='float64')

            ftmpbb = np.zeros((Na, len(SFILT)), dtype='float32')
            ltmpbb = np.zeros((Na, len(SFILT)), dtype='float32')

            ftmp_nu_int = np.zeros((Na, len(lm)), dtype='float32')
            spec_av_tmp = np.zeros((Na, len(lm)), dtype='float32')

            ms = np.zeros(Na, dtype='float32')
            Ls = np.zeros(Na, dtype='float32')
            ms[:] = mshdu.data['ms_' + str(zz)][:]  # [:] is necessary.
            Ls[:] = mshdu.data['Ls_' + str(zz)][:]
            Fuv = np.zeros(Na, dtype='float32')

            for ss in range(Na):
                wave = spechdu.data['wavelength']
                if fneb == 1:
                    spec_mul[ss] = spechdu.data['efspec_' + str(zz) + '_' +
                                                str(ss) + '_' + str(pp)]
                else:
                    spec_mul[ss] = spechdu.data['fspec_' + str(zz) + '_' +
                                                str(ss) + '_' + str(pp)]

                ###################
                # IGM attenuation.
                ###################
                spec_av_tmp = madau_igm_abs(wave, spec_mul[ss, :], zbest)
                spec_mul_nu[ss, :] = flamtonu(wave, spec_av_tmp)
                if len(lm) > 0:
                    try:
                        spec_mul_nu_conv[ss, :] = convolve(spec_mul_nu[ss],
                                                           LSF,
                                                           boundary='extend')
                    except:
                        spec_mul_nu_conv[ss, :] = spec_mul_nu[ss]
                        if zz == 0 and ss == 0:
                            print('Kernel is too small. No convolution.')
                else:
                    spec_mul_nu_conv[ss, :] = spec_mul_nu[ss]

                spec_sum = 0 * spec_mul[0]  # This is dummy file.
                DL = cd.luminosity_distance(
                    zbest, **cosmo) * Mpc_cm  # Luminositydistance in cm
                wavetmp = wave * (1. + zbest)
                #spec_av  = flamtonu(wavetmp, spec_sum) # Conversion from Flambda to Fnu.
                #ftmp_int = data_int(lm, wavetmp, spec_av)

                Lsun = 3.839 * 1e33  #erg s-1
                stmp_common = 1e10  # 1 tmp is in 1e10Lsun
                #ftmpbb[ss,:]           *= Lsun/(4.*np.pi*DL**2/(1.+zbest))
                #ftmpbb[ss,:]      *= (1./Ls[ss])*stmp_common
                spec_mul_nu_conv[ss, :] *= Lsun / (4. * np.pi * DL**2 /
                                                   (1. + zbest))
                spec_mul_nu_conv[ss, :] *= (
                    1. /
                    Ls[ss]) * stmp_common  # in unit of erg/s/Hz/cm2/ms[ss].
                ms[ss] *= (
                    1. / Ls[ss]
                ) * stmp_common  # M/L; 1 unit template has this mass in [Msolar].
                if f_spec:
                    ftmp_nu_int[ss, :] = data_int(lm, wavetmp,
                                                  spec_mul_nu_conv[ss, :])
                ltmpbb[ss, :], ftmpbb[ss, :] = filconv(SFILT, wavetmp,
                                                       spec_mul_nu_conv[ss, :],
                                                       DIR_FILT)

                # UV magnitude;
                #print('%s AA is used as UV reference.'%(xm_tmp[iiuv]))
                #print(ms[ss], (Lsun/(4.*np.pi*DL**2/(1.+zbest))))
                #print('m-M=',5*np.log10(DL/Mpc_cm*1e6/10))

                ##########################################
                # Writing out the templates to fits table.
                ##########################################
                if ss == 0 and pp == 0 and zz == 0:
                    # First file
                    nd1 = np.arange(0, len(lm), 1)
                    nd3 = np.arange(10000, 10000 + len(ltmpbb[ss, :]), 1)
                    nd_ap = np.append(nd1, nd3)
                    lm_ap = np.append(lm, ltmpbb[ss, :])

                    col1 = fits.Column(name='wavelength',
                                       format='E',
                                       unit='AA',
                                       array=lm_ap)
                    col2 = fits.Column(name='colnum',
                                       format='K',
                                       unit='',
                                       array=nd_ap)
                    col00 = [col1, col2]

                    # Second file
                    col3 = fits.Column(name='wavelength',
                                       format='E',
                                       unit='AA',
                                       array=wavetmp)
                    nd = np.arange(0, len(wavetmp), 1)
                    col4 = fits.Column(name='colnum',
                                       format='K',
                                       unit='',
                                       array=nd)
                    col01 = [col3, col4]

                spec_ap = np.append(ftmp_nu_int[ss, :], ftmpbb[ss, :])
                colspec = fits.Column(name='fspec_' + str(zz) + '_' + str(ss) +
                                      '_' + str(pp),
                                      format='E',
                                      unit='Fnu',
                                      disp='%s' % (age[ss]),
                                      array=spec_ap)
                col00.append(colspec)
                colspec_all = fits.Column(name='fspec_' + str(zz) + '_' +
                                          str(ss) + '_' + str(pp),
                                          format='E',
                                          unit='Fnu',
                                          disp='%s' % (age[ss]),
                                          array=spec_mul_nu_conv[ss, :])
                col01.append(colspec_all)

            #########################
            # Summarize the ML
            #########################
            if pp == 0:
                colms = fits.Column(name='ML_' + str(zz),
                                    format='E',
                                    unit='Msun/1e10Lsun',
                                    array=ms)
                col02.append(colms)

    #########################
    # Summarize the templates
    #########################
    coldefs_spec = fits.ColDefs(col00)
    hdu = fits.BinTableHDU.from_columns(coldefs_spec)
    hdu.writeto(DIR_TMP + 'spec_' + ID + '_PA' + PA + '.fits', overwrite=True)

    coldefs_spec = fits.ColDefs(col01)
    hdu2 = fits.BinTableHDU.from_columns(coldefs_spec)
    hdu2.writeto(DIR_TMP + 'spec_all_' + ID + '_PA' + PA + '.fits',
                 overwrite=True)

    coldefs_ms = fits.ColDefs(col02)
    hdu3 = fits.BinTableHDU.from_columns(coldefs_ms)
    hdu3.writeto(DIR_TMP + 'ms_' + ID + '_PA' + PA + '.fits', overwrite=True)

    ######################
    # Add dust component;
    ######################
    if f_dust:
        Temp = np.arange(DT0, DT1, dDT)
        lambda_d = np.arange(
            1e4, 1e7,
            1e3)  # RF wavelength, in AA. #* (1.+zbest) # 1um to 1000um;
        #lambda_d = np.arange(4000,1e7,1e3) # RF wavelength, in AA. #* (1.+zbest) # 1um to 1000um;
        # c in AA/s.
        kb = 1.380649e-23  # Boltzmann constant, in J/K
        hp = 6.62607015e-34  # Planck constant, in J*s

        # from Eq.3 of Bianchi 13
        kabs0 = 4.0  # in cm2/g
        beta_d = 2.08  #
        lam0 = 250. * 1e4  # mu m to AA
        kappa = kabs0 * (lam0 / lambda_d)**beta_d  # cm2/g
        kappa *= (1e8)**2  # AA2/g
        for tt in range(len(Temp)):
            if tt == 0:
                # For full;
                nd_d = np.arange(0, len(lambda_d), 1)
                colspec_dw = fits.Column(name='wavelength',
                                         format='E',
                                         unit='AA',
                                         array=lambda_d * (1. + zbest))
                col_dw = fits.Column(name='colnum',
                                     format='K',
                                     unit='',
                                     array=nd_d)
                col03 = [colspec_dw, col_dw]
            nu_d = c / lambda_d  # 1/s = Hz
            BT_nu = 2 * hp * nu_d[:]**3 / c**2 / (
                np.exp(hp * nu_d[:] / (kb * Temp[tt])) - 1
            )  # J*s * (1/s)^3 / (AA/s)^2 / sr = J / AA^2 / sr = J/s/AA^2/Hz/sr.
            # in side exp: J*s * (1/s) / (J/K * K) = 1;

            # if optically thin;
            #kappa = nu_d ** beta_d
            fnu_d = 1.0 / (
                4. * np.pi * DL**2 / (1. + zbest)
            ) * kappa * BT_nu  # 1/cm2 * AA2/g * J/s/AA^2/Hz = J/s/cm^2/Hz/g
            #fnu_d = 1.0 / (4.*np.pi*DL**2/(1.+zbest)) * BT_nu # 1/cm2 * AA2/g * J/s/AA^2/Hz = J/s/cm^2/Hz/g
            fnu_d *= 1.989e+33  # J/s/cm^2/Hz/Msun; i.e. 1 flux is in 1Msun
            fnu_d *= 1e7  # erg/s/cm^2/Hz/Msun.
            #fnu_d *= 1e9 # Now 1 flux is in 1e9Msun
            print('Somehow, crazy scale is required for FIR normalization...')
            fnu_d *= 1e40
            colspec_d = fits.Column(name='fspec_' + str(tt),
                                    format='E',
                                    unit='Fnu(erg/s/cm^2/Hz/Msun)',
                                    disp='%.2f' % (Temp[tt]),
                                    array=fnu_d)
            col03.append(colspec_d)
            #print('At z=%.2f, luminosity surface is %.2e cm^2'%(zbest,4.*np.pi*DL**2/(1.+zbest)))

            # Convolution;
            #ltmpbb_d, ftmpbb_d = filconv(DFILT,lambda_d*(1.+zbest),fnu_d,DIR_FILT)
            ALLFILT = np.append(SFILT, DFILT)
            ltmpbb_d, ftmpbb_d = filconv(ALLFILT, lambda_d * (1. + zbest),
                                         fnu_d, DIR_FILT)
            if False:
                #plt.plot(nu_d/1e9/(1.+zbest),fnu_d)
                #nubb_d = c / ltmpbb_d
                #plt.plot(nubb_d/1e9, ftmpbb_d, 'x')
                plt.plot(lambda_d / 1e4, fnu_d)
                plt.plot(lambda_d * (1. + zbest) / 1e4, fnu_d)
                plt.plot(ltmpbb_d / 1e4, ftmpbb_d, 'x')
                plt.show()
            if tt == 0:
                # For conv;
                col3 = fits.Column(name='wavelength',
                                   format='E',
                                   unit='AA',
                                   array=ltmpbb_d)
                nd_db = np.arange(0, len(ltmpbb_d), 1)
                col4 = fits.Column(name='colnum',
                                   format='K',
                                   unit='',
                                   array=nd_db)
                col04 = [col3, col4]
            colspec_db = fits.Column(name='fspec_' + str(tt),
                                     format='E',
                                     unit='Fnu',
                                     disp='%.2f' % (Temp[tt]),
                                     array=ftmpbb_d)
            col04.append(colspec_db)

        coldefs_d = fits.ColDefs(col03)
        hdu4 = fits.BinTableHDU.from_columns(coldefs_d)
        hdu4.writeto(DIR_TMP + 'spec_dust_all_' + ID + '_PA' + PA + '.fits',
                     overwrite=True)

        coldefs_db = fits.ColDefs(col04)
        hdu5 = fits.BinTableHDU.from_columns(coldefs_db)
        hdu5.writeto(DIR_TMP + 'spec_dust_' + ID + '_PA' + PA + '.fits',
                     overwrite=True)

    ##########################################
    # For observation.
    # Write out for the Multi-component fitting.
    ##########################################
    lamliml = 0.
    lamlimu = 20000.
    ebblim = 1e5
    ncolbb = 10000
    fw = open(DIR_TMP + 'spec_obs_' + ID + '_PA' + PA + '.cat', 'w')
    fw.write('# BB data (>%d) in this file are not used in fitting.\n' %
             (ncolbb))
    for ii in range(len(lm)):
        if fgrs[ii] == 0:  # G102
            if lm[ii] / (1. + zbest) > lamliml and lm[ii] / (1. +
                                                             zbest) < lamlimu:
                fw.write('%d %.5f %.5e %.5e\n' %
                         (ii, lm[ii], fobs[ii], eobs[ii]))
            else:
                fw.write('%d %.5f 0 1000\n' % (ii, lm[ii]))
        elif fgrs[ii] == 1:  # G141
            if lm[ii] / (1. + zbest) > lamliml and lm[ii] / (1. +
                                                             zbest) < lamlimu:
                fw.write('%d %.5f %.5e %.5e\n' %
                         (ii + 1000, lm[ii], fobs[ii], eobs[ii]))
            else:
                fw.write('%d %.5f 0 1000\n' % (ii + 1000, lm[ii]))

    for ii in range(len(ltmpbb[0, :])):
        if ebb[ii] > ebblim:
            fw.write('%d %.5f 0 1000\n' % (ii + ncolbb, ltmpbb[0, ii]))
        else:
            fw.write('%d %.5f %.5e %.5e\n' %
                     (ii + ncolbb, ltmpbb[0, ii], fbb[ii], ebb[ii]))

    fw.close()
    fw = open(DIR_TMP + 'spec_dust_obs_' + ID + '_PA' + PA + '.cat', 'w')
    if f_dust:
        nbblast = len(ltmpbb[0, :])
        for ii in range(len(ebb_d[:])):
            if ebb_d[ii] > ebblim:
                fw.write('%d %.5f 0 1000\n' %
                         (ii + ncolbb + nbblast, ltmpbb_d[ii + nbblast]))
            else:
                fw.write('%d %.5f %.5e %.5e\n' %
                         (ii + ncolbb + nbblast, ltmpbb_d[ii + nbblast],
                          fbb_d[ii], ebb_d[ii]))
    fw.close()

    fw = open(DIR_TMP + 'bb_obs_' + ID + '_PA' + PA + '.cat', 'w')
    for ii in range(len(ltmpbb[0, :])):
        if ebb[ii] > ebblim:
            fw.write('%d %.5f 0 1000 %.1f\n' %
                     (ii + ncolbb, ltmpbb[0, ii], FWFILT[ii] / 2.))
        else:
            fw.write('%d %.5f %.5e %.5e %.1f\n' %
                     (ii + ncolbb, ltmpbb[0, ii], fbb[ii], ebb[ii],
                      FWFILT[ii] / 2.))

    fw.close()
    fw = open(DIR_TMP + 'bb_dust_obs_' + ID + '_PA' + PA + '.cat', 'w')
    if f_dust:
        for ii in range(len(ebb_d[:])):
            if ebb_d[ii] > ebblim:
                fw.write('%d %.5f 0 1000 %.1f\n' %
                         (ii + ncolbb + nbblast, ltmpbb_d[ii + nbblast],
                          DFWFILT[ii] / 2.))
            else:
                fw.write('%d %.5f %.5e %.5e %.1f\n' %
                         (ii + ncolbb + nbblast, ltmpbb_d[ii + nbblast],
                          fbb_d[ii], ebb_d[ii], DFWFILT[ii] / 2.))
    fw.close()
Esempio n. 31
0
        # Compute comoving volume in Mpc-3
        dV = (comoving_volume(zmax, **cosmo) -
              comoving_volume(zmin, **cosmo)) * (Tel_Area / 41253.)  # Mpc3

        # Get Phi in Mpc-3
        alpha, logLStar, logPhiStar = LF_Data.retrieve_LF(z, line)
        LStar, PhiStar = 10.**(logLStar), 10.**(logPhiStar)

        n = scipy.integrate.quad(
            lambda L: schechterL(L, PhiStar, alpha, LStar), Lmin, Lmax)[0]

        # Number = number density * volume
        N = n * dV

        # Compute flux
        DL = luminosity_distance(z, **cosmo)  # In MPc
        DL = DL * (10**6. * pc) * 10**2.  # in cm
        F = Lmin / (4 * math.pi * DL**2.)  # ergs/s/cm2

        Dist.append(
            [zmin, zmax,
             math.log10(Lmin),
             math.log10(Lmax),
             int(N), F])

# Plot L vs. z
x = [elem[0] + 0.5 * (elem[1] - elem[0]) for elem in Dist]  # av z
y = [elem[2] + 0.5 * (elem[3] - elem[2]) for elem in Dist]  # av log10
z = [elem[4] for elem in Dist]

#DensityPlot(x,y,z)
def findzfromDL(z, DL):
    return DL - cd.luminosity_distance(z, **cosmo)
Esempio n. 33
0
 def getF(z, L):
     DL = luminosity_distance(z, **cosmo)  # In MPc
     DL = DL * (10**6. * pc) * 10**2.  # in cm
     return L / (4 * math.pi * DL**2.)  # ergs/s/cm2
Esempio n. 34
0
def plot_evolv(ID0, PA, Z=np.arange(-1.2,0.4249,0.05), age=[0.01, 0.1, 0.3, 0.7, 1.0, 3.0], f_comp = 0, fil_path = './FILT/', inputs=None, dust_model=0, DIR_TMP='./templates/', delt_sfh = 0.01, nmc=300):
    #
    # delt_sfh (float): delta t of input SFH in Gyr.
    #
    # Returns: SED as function of age, based on SF and Z histories;
    #
    ################
    flim = 0.01
    lsfrl = -1 # log SFR low limit
    mmax  = 1000
    Txmax = 4 # Max x value
    lmmin = 10.3

    nage = np.arange(0,len(age),1)
    fnc  = Func(Z, nage, dust_model=dust_model) # Set up the number of Age/ZZ
    bfnc = Basic(Z)
    age = np.asarray(age)

    ################
    # RF colors.
    import os.path
    home = os.path.expanduser('~')
    c      = 3.e18 # A/s
    chimax = 1.
    mag0   = 25.0
    d      = 10**(73.6/2.5) * 1e-18 # From [ergs/s/cm2/A] to [ergs/s/cm2/Hz]

    #############
    # Plot.
    #############
    fig = plt.figure(figsize=(5,2.6))
    fig.subplots_adjust(top=0.96, bottom=0.16, left=0.12, right=0.99, hspace=0.15, wspace=0.15)
    #ax1 = fig.add_subplot(131)
    #ax2 = fig.add_subplot(132)
    #ax3 = fig.add_subplot(133)
    ax2 = fig.add_subplot(121)
    ax3 = fig.add_subplot(122)

    ###########################
    # Open result file
    ###########################
    file = 'summary_' + ID0 + '_PA' + PA + '.fits'
    hdul = fits.open(file) # open a FITS file
    zbes = hdul[0].header['z']
    chinu= hdul[1].data['chi']
    uv= hdul[1].data['uv']
    vj= hdul[1].data['vj']

    try:
        RA   = hdul[0].header['RA']
        DEC  = hdul[0].header['DEC']
    except:
        RA  = 0
        DEC = 0

    try:
        SN = hdul[0].header['SN']
    except:
        ###########################
        # Get SN of Spectra
        ###########################
        file = 'templates/spec_obs_' + ID0 + '_PA' + PA + '.cat'
        fds  = np.loadtxt(file, comments='#')
        nrs  = fds[:,0]
        lams = fds[:,1]
        fsp  = fds[:,2]
        esp  = fds[:,3]

        consp = (nrs<10000) & (lams/(1.+zbes)>3600) & (lams/(1.+zbes)<4200)
        if len((fsp/esp)[consp]>10):
            SN = np.median((fsp/esp)[consp])
        else:
            SN = 1

    Asum = 0
    A50 = np.arange(len(age), dtype='float32')
    for aa in range(len(A50)):
        A50[aa] = hdul[1].data['A'+str(aa)][1]
        Asum += A50[aa]

    # Cosmo;
    DL = cd.luminosity_distance(zbes, **cosmo) * Mpc_cm # Luminositydistance in cm
    Cons = (4.*np.pi*DL**2/(1.+zbes))
    Tuni = cd.age(zbes, use_flat=True, **cosmo)
    Tuni0 = (Tuni/cc.Gyr_s - age[:])

    # Open summary;
    file = 'summary_' + ID0 + '_PA' + PA + '.fits'
    fd   = fits.open(file)[1].data
    #print(fits.open(file)[1].header)
    Avtmp = fd['Av0']
    uvtmp = fd['uv']
    vjtmp = fd['vj']
    #ax2.plot(vj[1],uv[1],color='gray',marker='s',ms=3)

    # SFH
    file = DIR_TMP + 'obshist_' + ID0 + '_PA' + PA + '.fits'
    fd   = fits.open(file)[1].data
    age  = fd['age']
    sfh  = fd['sfh']
    zh   = fd['zh']

    # Open FSPS temp;
    file = DIR_TMP + 'obsspec_' + ID0 + '_PA' + PA + '.fits'
    fd   = fits.open(file)[1].data
    wave = fd['wavelength']
    nr   = fd['colnum']
    uvall= age * 0 - 99
    vjall= age * 0 - 99

    delp = -10
    flag = False
    flag2= False
    #for ii in range(1,len(age),10):
    for ii in range(len(age)-1,-1,delp):
        flux = fd['fspec_%d'%(ii)]
        flux_att = madau_igm_abs(wave/(1.+zbes), flux, zbes)
        flux_d, xxd, nrd = dust_calz(wave/(1.+zbes), flux_att, 0.0, nr)
        #ax1.plot(xxd,flux_d,linestyle='-',lw=0.3+0.1*ii/len(age))
        band0  = ['u','v','j']
        lmconv,fconv = filconv(band0, xxd, flux_d, fil_path) # flux in fnu
        uv = -2.5*np.log10(fconv[0]/fconv[1])
        vj = -2.5*np.log10(fconv[1]/fconv[2])
        uvall[ii] = uv
        vjall[ii] = vj
        #ax2.plot(vjall[ii],uvall[ii],marker='s',ms=5,linestyle='-',zorder=5)

        if flag and not flag2:
            flux_d, xxd, nrd = dust_calz(wave/(1.+zbes), flux_att, Avtmp[1], nr)
            lmconv,fconv = filconv(band0, xxd, flux_d, fil_path) # flux in fnu
            uv_av = -2.5*np.log10(fconv[0]/fconv[1])
            vj_av = -2.5*np.log10(fconv[1]/fconv[2])
            delvj, deluv = vj_av-vj, uv_av-uv
            flag2 = True
        flag = True

    #import matplotlib.colormaps as cm
    conuvj = (vjall>-90)&(uvall>-90)
    ax2.plot(vjall[conuvj],uvall[conuvj],marker='s',markeredgecolor='k',color='none',ms=5,zorder=4)
    ax2.scatter(vjall[conuvj],uvall[conuvj],marker='s',c=age[conuvj],cmap='jet',s=8,zorder=5)
    ax2.plot(vjall[conuvj],uvall[conuvj],marker='',color='k',ms=3,linestyle='-',zorder=3)
    ax3.plot(age,np.log10(sfh),color='b', linewidth=1, linestyle='-',label=r'$\log$SFR$/M_\odot$yr$^{-1}$')
    ax3.plot(age,zh,color='r', linewidth=1, linestyle='-',label=r'$\log Z_*/Z_\odot$')

    '''
    ax1.set_xlim(1000,40000)
    ax1.set_xscale('log')
    ax1.set_ylim(1e-2,1e2)
    ax1.set_yscale('log')
    ax1.set_xlabel('Wavelength')
    '''

    ax2.set_xlim(-0.3,2.3)
    ax2.set_ylim(-0.3,2.3)

    ax2.set_xlabel('$V-J\,$/ mag')
    ax2.set_ylabel('$U-V\,$/ mag')
    ax3.set_xlabel('age / Gyr')
    #ax3.set_ylabel('$\log$SFR$/M_\odot$yr$^{-1}$ or $\log Z_*/Z_\odot$')

    ##
    prog_path = '/Users/tmorishita/GitHub/gsf/gsf/example/misc/'
    data_uvj = np.loadtxt(prog_path+'f2.cat',comments='#')
    x=data_uvj[:,0]
    y=data_uvj[:,1]
    ax2.plot(x,y,color="gray",lw=1,ls="-")

    data_uvj = np.loadtxt(prog_path+'g2.cat',comments='#')
    x=data_uvj[:,0]
    y=data_uvj[:,1]
    ax2.plot(x,y,color="gray",lw=1,ls="-")

    data_uvj = np.loadtxt(prog_path+'h2.cat',comments='#')
    x=data_uvj[:,0]
    y=data_uvj[:,1]
    ax2.plot(x,y,color="gray",lw=1,ls="-")

    try:
        av=np.array([1.2,0.,delvj,deluv])
        X,Y,U,V=zip(av)
        ax2.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1,linewidth=1,color="k")
    except:
        pass

    ax2.text(-0.1,2.1,'Quiescent',fontsize=11,color='orangered')
    ax2.text(1.3,-0.2,'Starforming',fontsize=11,color='royalblue')

    ax3.legend(loc=3)
    #plt.show()
    plt.savefig('hist_' + ID0 + '_PA' + PA + '.pdf')
Esempio n. 35
0
def plot_sfh(ID0, PA, Z=np.arange(-1.2,0.4249,0.05), age=[0.01, 0.1, 0.3, 0.7, 1.0, 3.0], f_comp = 0, fil_path = './FILT/', inputs=None, dust_model=0, DIR_TMP='./templates/',f_SFMS=False):
    #
    #
    #
    flim = 0.01
    lsfrl = -1 # log SFR low limit
    mmax  = 1000
    Txmax = 4 # Max x value
    lmmin = 9.5 #10.3

    nage = np.arange(0,len(age),1)
    fnc  = Func(Z, nage, dust_model=dust_model) # Set up the number of Age/ZZ
    bfnc = Basic(Z)

    age = np.asarray(age)

    ################
    # RF colors.
    import os.path
    home = os.path.expanduser('~')
    c      = 3.e18 # A/s
    chimax = 1.
    mag0   = 25.0
    d      = 10**(73.6/2.5) * 1e-18 # From [ergs/s/cm2/A] to [ergs/s/cm2/Hz]
    #d = 10**(-73.6/2.5) # From [ergs/s/cm2/Hz] to [ergs/s/cm2/A]

    #############
    # Plot.
    #############
    fig = plt.figure(figsize=(8,2.8))
    fig.subplots_adjust(top=0.88, bottom=0.18, left=0.07, right=0.99, hspace=0.15, wspace=0.3)
    ax1 = fig.add_subplot(131)
    ax2 = fig.add_subplot(132)
    #ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(133)

    ax1t = ax1.twiny()
    ax2t = ax2.twiny()
    #ax3t = ax3.twiny()
    ax4t = ax4.twiny()

    ##################
    # Fitting Results
    ##################
    #DIR_TMP = './templates/'
    SNlim = 3 # avobe which SN line is shown.

    ###########################
    # Open result file
    ###########################
    file = 'summary_' + ID0 + '_PA' + PA + '.fits'
    hdul = fits.open(file) # open a FITS file
    zbes = hdul[0].header['z']
    chinu= hdul[1].data['chi']

    uv= hdul[1].data['uv']
    vj= hdul[1].data['vj']

    RA   = 0
    DEC  = 0
    rek  = 0
    erekl= 0
    ereku= 0
    mu = 1.0
    nn = 0
    qq = 0
    enn = 0
    eqq = 0
    try:
        RA   = hdul[0].header['RA']
        DEC  = hdul[0].header['DEC']
    except:
        RA  = 0
        DEC = 0

    try:
        SN = hdul[0].header['SN']
    except:
        ###########################
        # Get SN of Spectra
        ###########################
        file = 'templates/spec_obs_' + ID0 + '_PA' + PA + '.cat'
        fds  = np.loadtxt(file, comments='#')
        nrs  = fds[:,0]
        lams = fds[:,1]
        fsp  = fds[:,2]
        esp  = fds[:,3]

        consp = (nrs<10000) & (lams/(1.+zbes)>3600) & (lams/(1.+zbes)<4200)
        if len((fsp/esp)[consp]>10):
            SN = np.median((fsp/esp)[consp])
        else:
            SN = 1


    Asum = 0
    A50 = np.arange(len(age), dtype='float32')
    for aa in range(len(A50)):
        A50[aa] = hdul[1].data['A'+str(aa)][1]
        Asum += A50[aa]

    ####################
    # For cosmology
    ####################
    DL = cd.luminosity_distance(zbes, **cosmo) * Mpc_cm # Luminositydistance in cm
    Cons = (4.*np.pi*DL**2/(1.+zbes))

    Tuni = cd.age(zbes, use_flat=True, **cosmo)
    Tuni0 = (Tuni/cc.Gyr_s - age[:])

    delT  = np.zeros(len(age),dtype='float32')
    delTl = np.zeros(len(age),dtype='float32')
    delTu = np.zeros(len(age),dtype='float32')
    for aa in range(len(age)):
        if aa == 0:
            delTl[aa] = age[aa]
            delTu[aa] = (age[aa+1]-age[aa])/2.
            delT[aa]  = delTu[aa] + delTl[aa]
        elif Tuni/cc.Gyr_s < age[aa]:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = delTl[aa] #10.
            delT[aa]  = delTu[aa] + delTl[aa]
        elif aa == len(age)-1:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = Tuni/cc.Gyr_s - age[aa]
            delT[aa]  = delTu[aa] + delTl[aa]
        else:
            delTl[aa] = (age[aa]-age[aa-1])/2.
            delTu[aa] = (age[aa+1]-age[aa])/2.
            delT[aa]  = delTu[aa] + delTl[aa]


    delT[:]  *= 1e9 # Gyr to yr
    delTl[:] *= 1e9 # Gyr to yr
    delTu[:] *= 1e9 # Gyr to yr
    #print(age, delT, delTu, delTl)
    ##############################
    # Load Pickle
    ##############################
    samplepath = './'
    pfile = 'chain_' + ID0 + '_PA' + PA + '_corner.cpkl'

    niter = 0
    data = loadcpkl(os.path.join(samplepath+'/'+pfile))
    try:
    #if 1>0:
        ndim   = data['ndim']     # By default, use ndim and burnin values contained in the cpkl file, if present.
        burnin = data['burnin']
        nmc    = data['niter']
        nwalk  = data['nwalkers']
        Nburn  = burnin #* nwalk/10/2 # I think this takes 3/4 of samples
        #if nmc>1000:
        #    Nburn  = 500
        samples = data['chain'][:]
    except:
        print(' =   >   NO keys of ndim and burnin found in cpkl, use input keyword values')
        return -1

    ######################
    # Mass-to-Light ratio.
    ######################
    #ms     = np.zeros(len(age), dtype='float32')
    # Wht do you want from MCMC sampler?
    AM = np.zeros((len(age), mmax), dtype='float32') # Mass in each bin.
    AC = np.zeros((len(age), mmax), dtype='float32') # Cumulative mass in each bin.
    AL = np.zeros((len(age), mmax), dtype='float32') # Cumulative light in each bin.
    ZM = np.zeros((len(age), mmax), dtype='float32') # Z.
    ZC = np.zeros((len(age), mmax), dtype='float32') # Cumulative Z.
    ZL = np.zeros((len(age), mmax), dtype='float32') # Light weighted cumulative Z.
    TC = np.zeros((len(age), mmax), dtype='float32') # Mass weighted T.
    TL = np.zeros((len(age), mmax), dtype='float32') # Light weighted T.
    ZMM= np.zeros((len(age), mmax), dtype='float32') # Mass weighted Z.
    ZML= np.zeros((len(age), mmax), dtype='float32') # Light weighted Z.
    SF = np.zeros((len(age), mmax), dtype='float32') # SFR
    Av = np.zeros(mmax, dtype='float32') # SFR


    # ##############################
    # Add simulated scatter in quad
    # if files are available.
    # ##############################
    if inputs:
        f_zev = int(inputs['ZEVOL'])
    else:
        f_zev = 1

    eZ_mean = 0
    try:
        #meanfile = '/Users/tmorishita/Documents/Astronomy/sim_tran/sim_SFH_mean.cat'
        meanfile = './sim_SFH_mean.cat'
        dfile    = np.loadtxt(meanfile, comments='#')
        eA = dfile[:,2]
        eZ = dfile[:,4]
        eAv= np.mean(dfile[:,6])
        if f_zev == 0:
            eZ_mean = np.mean(eZ[:])
            eZ[:]   = age * 0 #+ eZ_mean
        else:
            try:
                f_zev = int(prihdr['ZEVOL'])
                if f_zev == 0:
                    eZ_mean = np.mean(eZ[:])
                    eZ = age * 0
            except:
                pass
    except:
        print('No simulation file (%s).\nError may be underestimated.' % meanfile)
        eA = age * 0
        eZ = age * 0
        eAv= 0

    mm = 0
    #while mm<mmax:
    for mm in range(mmax):
        mtmp  = np.random.randint(len(samples))# + Nburn

        AAtmp = np.zeros(len(age), dtype='float32')
        ZZtmp = np.zeros(len(age), dtype='float32')
        mslist= np.zeros(len(age), dtype='float32')

        Av_tmp = samples['Av'][mtmp]

        f0     = fits.open(DIR_TMP + 'ms_' + ID0 + '_PA' + PA + '.fits')
        sedpar = f0[1]
        f1     = fits.open(DIR_TMP + 'ms.fits')
        mloss  = f1[1].data

        Avrand = np.random.uniform(-eAv, eAv)
        if Av_tmp + Avrand<0:
            Av[mm] = 0
        else:
            Av[mm] = Av_tmp + Avrand

        for aa in range(len(age)):
            AAtmp[aa] = samples['A'+str(aa)][mtmp]/mu
            try:
                ZZtmp[aa] = samples['Z'+str(aa)][mtmp]
            except:
                ZZtmp[aa] = samples['Z0'][mtmp]

            nZtmp      = bfnc.Z2NZ(ZZtmp[aa])
            mslist[aa] = sedpar.data['ML_'+str(nZtmp)][aa]

            ml = mloss['ms_'+str(nZtmp)][aa]

            Arand = np.random.uniform(-eA[aa],eA[aa])
            Zrand = np.random.uniform(-eZ[aa],eZ[aa])
            AM[aa, mm] = AAtmp[aa] * mslist[aa] * 10**Arand
            AL[aa, mm] = AM[aa, mm] / mslist[aa]
            SF[aa, mm] = AAtmp[aa] * mslist[aa] / delT[aa] / ml * 10**Arand
            ZM[aa, mm] = ZZtmp[aa] + Zrand
            ZMM[aa, mm]= (10 ** ZZtmp[aa]) * AAtmp[aa] * mslist[aa] * 10**Zrand
            ZML[aa, mm]= ZMM[aa, mm] / mslist[aa]

        for aa in range(len(age)):
            AC[aa, mm] = np.sum(AM[aa:, mm])
            ZC[aa, mm] = np.log10(np.sum(ZMM[aa:, mm])/AC[aa, mm])
            ZL[aa, mm] = np.log10(np.sum(ZML[aa:, mm])/np.sum(AL[aa:, mm]))
            if f_zev == 0: # To avoid random fluctuation in A.
                ZC[aa, mm] = ZM[aa, mm]

            ACs = 0
            ALs = 0
            for bb in range(aa, len(age), 1):
                tmpAA       = 10**np.random.uniform(-eA[bb],eA[bb])
                tmpTT       = np.random.uniform(-delT[bb]/1e9,delT[bb]/1e9)
                TC[aa, mm] += (age[bb]+tmpTT) * AAtmp[bb] * mslist[bb] * tmpAA
                TL[aa, mm] += (age[bb]+tmpTT) * AAtmp[bb] * tmpAA
                ACs        += AAtmp[bb] * mslist[bb] * tmpAA
                ALs        += AAtmp[bb] * tmpAA

            TC[aa, mm] /= ACs
            TL[aa, mm] /= ALs

    #Avtmp  = np.percentile(samples['Av'][:],[16,50,84])
    Avtmp  = np.percentile(Av[:],[16,50,84])

    #############
    # Plot
    #############
    AMp = np.zeros((len(age),3), dtype='float32')
    ACp = np.zeros((len(age),3), dtype='float32')
    ZMp = np.zeros((len(age),3), dtype='float32')
    ZCp = np.zeros((len(age),3), dtype='float32')
    SFp = np.zeros((len(age),3), dtype='float32')
    for aa in range(len(age)):
       AMp[aa,:] = np.percentile(AM[aa,:], [16,50,84])
       ACp[aa,:] = np.percentile(AC[aa,:], [16,50,84])
       ZMp[aa,:] = np.percentile(ZM[aa,:], [16,50,84])
       ZCp[aa,:] = np.percentile(ZC[aa,:], [16,50,84])
       SFp[aa,:] = np.percentile(SF[aa,:], [16,50,84])

    ###################
    msize = np.zeros(len(age), dtype='float32')
    for aa in range(len(age)):
        if A50[aa]/Asum>flim: # if >1%
            msize[aa] = 150 * A50[aa]/Asum

    conA = (msize>=0)

    ax1.fill_between(age[conA], np.log10(SFp[:,0])[conA], np.log10(SFp[:,2])[conA], linestyle='-', color='k', alpha=0.3)
    #ax1.fill_between(age, np.log10(SFp[:,0]), np.log10(SFp[:,2]), linestyle='-', color='k', alpha=0.3)
    ax1.scatter(age[conA], np.log10(SFp[:,1])[conA], marker='.', c='k', s=msize[conA])
    ax1.errorbar(age[conA], np.log10(SFp[:,1])[conA], xerr=[delTl[:][conA]/1e9,delTu[:][conA]/1e9], yerr=[np.log10(SFp[:,1])[conA]-np.log10(SFp[:,0])[conA], np.log10(SFp[:,2])[conA]-np.log10(SFp[:,1])[conA]], linestyle='-', color='k', lw=0.5, marker='')

    # Get SFMS;
    IMF = int(inputs['NIMF'])
    SFMS_16 = get_SFMS(zbes,age,ACp[:,0],IMF=IMF)
    SFMS_50 = get_SFMS(zbes,age,ACp[:,1],IMF=IMF)
    SFMS_84 = get_SFMS(zbes,age,ACp[:,2],IMF=IMF)

    f_rejuv,t_quench,t_rejuv = check_rejuv(age,np.log10(SFp[:,:]),np.log10(ACp[:,:]),np.log10(SFMS_50))
    #print(f_rejuv,t_quench,t_rejuv)

    # Plot MS?
    if f_SFMS:
        #ax1.fill_between(age[conA], np.log10(SFMS_16)[conA], np.log10(SFMS_84)[conA], linestyle='-', color='b', alpha=0.3)
        ax1.fill_between(age[conA], np.log10(SFMS_50)[conA]-0.2, np.log10(SFMS_50)[conA]+0.2, linestyle='-', color='b', alpha=0.3)
        ax1.plot(age[conA], np.log10(SFMS_50)[conA], linestyle='--', color='b', alpha=0.5)

    #
    # Fit with delayed exponential??
    #
    minsfr = 1e-10
    if f_comp == 1:
        #
        # Plot exp model?
        #
        DIR_exp = '/Users/tmorishita/Documents/Astronomy/sedfitter_exp/'
        file = DIR_exp + 'summary_' + ID0 + '_PA' + PA + '.fits'
        hdul = fits.open(file) # open a FITS file

        t0  = 10**float(hdul[1].data['age'][1])
        tau = 10**float(hdul[1].data['tau'][1])
        A   = float(hdul[1].data['A'][1])
        Zexp= hdul[1].data['Z']
        Mexp= float(hdul[1].data['ms'][1])

        deltt0 = 0.01 # in Gyr
        tt0 = np.arange(0.01,10,deltt0)
        sfr = SFH_dec(np.max(age)-t0, tau, A, tt=tt0)
        mtmp = np.sum(sfr * deltt0 * 1e9)
        C_exp = Mexp/mtmp
        ax1.plot(np.max(age) - tt0, np.log10(sfr*C_exp), marker='', linestyle='--', color='r', lw=1.5, alpha=0.7, zorder=-4, label='')
        mctmp = tt0 * 0
        for ii in range(len(tt0)):
            mctmp[ii] = np.sum(sfr[:ii] * deltt0 * 1e9)
        ax2.plot(np.max(age) - tt0, np.log10(mctmp*C_exp), marker='', linestyle='--', color='r', lw=1.5, alpha=0.7, zorder=-4)
        ax4.errorbar(t0, Zexp[1], yerr=[[Zexp[1]-Zexp[0]], [Zexp[2]-Zexp[1]]], marker='s', color='r', alpha=0.7, zorder=-4, capsize=0)
        sfr_exp = sfr
        mc_exp = mctmp*C_exp
        '''
        #
        # Plot delay model?
        #
        DIR_exp = '/Users/tmorishita//Documents/Astronomy/sedfitter_del/'
        file = DIR_exp + 'summary_' + ID0 + '_PA' + PA + '.fits'
        hdul = fits.open(file) # open a FITS file

        t0  = 10**float(hdul[1].data['age'][0])
        tau = 10**float(hdul[1].data['tau'][0])
        A   = float(hdul[1].data['A'][0])
        Mdel= float(hdul[1].data['ms'][1])

        tt0 = np.arange(0.01,10,0.01)
        sfr = SFH_del(np.max(age)-t0, tau, A, tt=tt0)
        mtmp = np.sum(sfr * deltt0 * 1e9)
        C_del = Mdel/mtmp
        '''

    #
    # Mass in each bin
    #
    ax2label = ''
    ax2.fill_between(age[conA], np.log10(ACp[:,0])[conA], np.log10(ACp[:,2])[conA], linestyle='-', color='k', alpha=0.3)
    ax2.errorbar(age[conA], np.log10(ACp[:,1])[conA], xerr=[delTl[:][conA]/1e9,delTu[:][conA]/1e9], yerr=[np.log10(ACp[:,1])[conA]-np.log10(ACp[:,0])[conA],np.log10(ACp[:,2])[conA]-np.log10(ACp[:,1])[conA]], linestyle='-', color='k', lw=0.5, label=ax2label)
    ax2.scatter(age[conA], np.log10(ACp[:,1])[conA], marker='.', c='k', s=msize)

    y2min = np.max([lmmin,np.min(np.log10(ACp[:,0])[conA])])
    y2max = np.max(np.log10(ACp[:,2])[conA])+0.05

    if f_comp == 1:
        y2max = np.max([y2max, np.log10(np.max(mc_exp))+0.05])
        y2min = np.min([y2min, np.log10(np.max(mc_exp))-0.05])

    if (y2max-y2min)<0.2:
        y2min -= 0.2


    #
    # Total Metal
    #
    ax4.fill_between(age[conA], ZCp[:,0][conA], ZCp[:,2][conA], linestyle='-', color='k', alpha=0.3)
    ax4.scatter(age[conA], ZCp[:,1][conA], marker='.', c='k', s=msize[conA])
    ax4.errorbar(age[conA], ZCp[:,1][conA], yerr=[ZCp[:,1][conA]-ZCp[:,0][conA],ZCp[:,2][conA]-ZCp[:,1][conA]], linestyle='-', color='k', lw=0.5)


    fw_sfr = open('SFH_' + ID0 + '_PA' + PA + '.txt', 'w')
    fw_sfr.write('# time_l time_u SFR SFR16 SFR84\n')
    fw_sfr.write('# (Gyr)  (Gyr)  (M/yr) (M/yr) (M/yr)\n')

    fw_met = open('ZH_' + ID0 + '_PA' + PA + '.txt', 'w')
    fw_met.write('# time_l time_u logZ logZ16 logZ84\n')
    fw_met.write('# (Gyr)  (Gyr)  (logZsun) (logZsun) (logZsun)\n')

    for ii in range(len(age)-1,0-1,-1):
        t0 = Tuni/cc.Gyr_s - age[ii]
        fw_sfr.write('%.2f %.2f %.2f %.2f %.2f\n'%(t0-delTl[ii]/1e9, t0+delTl[ii]/1e9, SFp[ii,1], SFp[ii,0], SFp[ii,2]))
        fw_met.write('%.2f %.2f %.2f %.2f %.2f\n'%(t0-delTl[ii]/1e9, t0+delTl[ii]/1e9, ZCp[ii,1], ZCp[ii,0], ZCp[ii,2]))
    fw_sfr.close()
    fw_met.close()

    #########################
    # Title
    #########################
    #ax1.set_title('Each $t$-bin', fontsize=12)
    #ax2.set_title('Net system', fontsize=12)
    #ax3.set_title('Each $t$-bin', fontsize=12)
    #ax4.set_title('Net system', fontsize=12)


    #############
    # Axis
    #############
    #ax1.set_xlabel('$t$ (Gyr)', fontsize=12)
    ax1.set_ylabel('$\log \dot{M}_*/M_\odot$yr$^{-1}$', fontsize=12)
    #ax1.set_ylabel('$\log M_*/M_\odot$', fontsize=12)

    lsfru = 2.8
    if np.max(np.log10(SFp[:,2]))>2.8:
        lsfru = np.max(np.log10(SFp[:,2]))+0.1

    if f_comp == 1:
        lsfru = np.max([lsfru, np.log10(np.max(sfr_exp*C_exp))])


    ax1.set_xlim(0.008, Txmax)
    ax1.set_ylim(lsfrl, lsfru)
    ax1.set_xscale('log')

    #ax2.set_xlabel('$t$ (Gyr)', fontsize=12)
    ax2.set_ylabel('$\log M_*/M_\odot$', fontsize=12)

    ax2.set_xlim(0.008, Txmax)
    ax2.set_ylim(y2min, y2max)
    ax2.set_xscale('log')

    ax2.text(0.01, y2min + 0.07*(y2max-y2min), 'ID: %s\n$z_\mathrm{obs.}:%.2f$\n$\log M_\mathrm{*}/M_\odot:%.2f$\n$\log Z_\mathrm{*}/Z_\odot:%.2f$\n$\log T_\mathrm{*}$/Gyr$:%.2f$\n$A_V$/mag$:%.2f$'%(ID0, zbes, np.log10(ACp[0,1]), ZCp[0,1], np.log10(np.percentile(TC[0,:],50)), Avtmp[1]), fontsize=9)

    #
    # Brief Summary
    #
    # Writing SED param in a fits file;
    # Header
    prihdr = fits.Header()
    prihdr['ID']     = ID0
    prihdr['PA']     = PA
    prihdr['z']      = zbes
    prihdr['RA']     = RA
    prihdr['DEC']    = DEC
    prihdr['Re_kpc'] = rek
    prihdr['Ser_n']  = nn
    prihdr['Axis_q'] = qq
    prihdr['e_Re']   = (erekl+ereku)/2.
    prihdr['e_n']    = enn
    prihdr['e_q']    = eqq
    # Add rejuv properties;
    prihdr['f_rejuv']= f_rejuv
    prihdr['t_quen'] = t_quench
    prihdr['t_rejuv']= t_rejuv
    prihdu = fits.PrimaryHDU(header=prihdr)

    col01 = []
    # Redshift
    zmc = hdul[1].data['zmc']
    col50 = fits.Column(name='zmc', format='E', unit='', array=zmc[:])
    col01.append(col50)

    # Stellar mass
    ACP = [np.log10(ACp[0,0]), np.log10(ACp[0,1]), np.log10(ACp[0,2])]
    col50 = fits.Column(name='Mstel', format='E', unit='logMsun', array=ACP[:])
    col01.append(col50)

    # Metallicity_MW
    ZCP = [ZCp[0,0], ZCp[0,1], ZCp[0,2]]
    col50 = fits.Column(name='Z_MW', format='E', unit='logZsun', array=ZCP[:])
    col01.append(col50)

    # Age_mw
    para = [np.log10(np.percentile(TC[0,:],16)), np.log10(np.percentile(TC[0,:],50)), np.log10(np.percentile(TC[0,:],84))]
    col50 = fits.Column(name='T_MW', format='E', unit='logGyr', array=para[:])
    col01.append(col50)

    # Metallicity_LW
    ZCP = [ZL[0,0], ZL[0,1], ZL[0,2]]
    col50 = fits.Column(name='Z_LW', format='E', unit='logZsun', array=ZCP[:])
    col01.append(col50)

    # Age_lw
    para = [np.log10(np.percentile(TL[0,:],16)), np.log10(np.percentile(TL[0,:],50)), np.log10(np.percentile(TL[0,:],84))]
    col50 = fits.Column(name='T_LW', format='E', unit='logGyr', array=para[:])
    col01.append(col50)

    # Dust
    para = [Avtmp[0], Avtmp[1], Avtmp[2]]
    col50 = fits.Column(name='AV', format='E', unit='mag', array=para[:])
    col01.append(col50)

    # U-V
    para = [uv[0], uv[1], uv[2]]
    col50 = fits.Column(name='U-V', format='E', unit='mag', array=para[:])
    col01.append(col50)

    # V-J
    para = [vj[0], vj[1], vj[2]]
    col50 = fits.Column(name='V-J', format='E', unit='mag', array=para[:])
    col01.append(col50)

    colms  = fits.ColDefs(col01)
    dathdu = fits.BinTableHDU.from_columns(colms)
    hdu    = fits.HDUList([prihdu, dathdu])
    hdu.writeto('SFH_' + ID0 + '_PA' + PA + '_param.fits', overwrite=True)


    #
    # SFH
    #
    zzall = np.arange(1.,12,0.01)
    Tall  = cd.age(zzall, use_flat=True, **cosmo)/cc.Gyr_s

    fw = open('SFH_' + ID0 + '_PA' + PA + '_sfh.cat', 'w')
    fw.write('%s'%(ID0))
    for mm in range(len(age)):
        mmtmp = np.argmin(np.abs(Tall - Tuni0[mm]))
        zztmp = zzall[mmtmp]
        fw.write(' %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f'%(zztmp, Tuni0[mm], np.log10(ACp[mm,1]), (np.log10(ACp[mm,1])-np.log10(ACp[mm,0])), (np.log10(ACp[mm,2])-np.log10(ACp[mm,1])), ZCp[mm,1], ZCp[mm,1]-ZCp[mm,0], ZCp[mm,2]-ZCp[mm,1], SFp[mm,1], SFp[mm,1]-SFp[mm,0], SFp[mm,2]-SFp[mm,1]))
    fw.write('\n')
    fw.close()
    #print('%s & $%.5e$ & $%.5e$ & $%.3f$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.2f_{-%.2f}^{+%.2f}$ & $%.1f$ & $%.1f$ & $%.2f$\\\\'%(ID0, RA, DEC, zbes, np.log10(ACp[0,1]), (np.log10(ACp[0,1])-np.log10(ACp[0,0])), (np.log10(ACp[0,2])-np.log10(ACp[0,1])), ACp[7,1]/ACp[0,1], ACp[7,1]/ACp[0,1]-ACp[7,0]/ACp[0,1], ACp[7,2]/ACp[0,1]-ACp[7,1]/ACp[0,1], ZCp[0,1], ZCp[0,1]-ZCp[0,0], ZCp[0,2]-ZCp[0,1], np.percentile(TC[0,:],50), np.percentile(TC[0,:],50)-np.percentile(TC[0,:],16), np.percentile(TC[0,:],84)-np.percentile(TC[0,:],50), Avtmp[1], Avtmp[1]-Avtmp[0], Avtmp[2]-Avtmp[1], uv[1], uv[1]-uv[0], uv[2]-uv[1], vj[1], vj[1]-vj[0], vj[2]-vj[1], chinu[1], SN, rek))

    dely2 = 0.1
    while (y2max-y2min)/dely2>7:
        dely2 *= 2.

    y2ticks = np.arange(y2min, y2max, dely2)
    ax2.set_yticks(y2ticks)
    ax2.set_yticklabels(np.arange(y2min, y2max, 0.1), minor=False)

    ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    #ax2.yaxis.set_major_locator(plt.MaxNLocator(4))
    #ax3.set_xlabel('$t$ (Gyr)', fontsize=12)
    #ax3.set_ylabel('$\log Z_*/Z_\odot$', fontsize=12)
    y3min, y3max = np.min(Z), np.max(Z)
    #ax3.set_xlim(0.008, Txmax)
    #ax3.set_ylim(y3min, y3max)
    #ax3.set_xscale('log')
    #ax3.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

    fwt = open('T_' + ID0 + '_PA' + PA + '_sfh.cat', 'w')
    fwt.write('%s %.3f %.3f %.3f'%(ID0, np.percentile(TC[0,:],50), np.percentile(TC[0,:],16), np.percentile(TC[0,:],84)))
    fwt.close()

    # For redshift
    if zbes<4:
        if zbes<2:
            zred  = [zbes, 2, 3, 6]
            #zredl = ['$z_\mathrm{obs.}$', 2, 3, 6]
            zredl = ['$z_\mathrm{obs.}$', 2, 3, 6]
        elif zbes<2.5:
            zred  = [zbes, 2.5, 3, 6]
            zredl = ['$z_\mathrm{obs.}$', 2.5, 3, 6]
        elif zbes<3.:
            zred  = [zbes, 3, 6]
            zredl = ['$z_\mathrm{obs.}$', 3, 6]
        else:
            zred  = [zbes, 6]
            zredl = ['$z_\mathrm{obs.}$', 6]
    else:
        zred  = [zbes, 6, 7, 9]
        zredl = ['$z_\mathrm{obs.}$', 6, 7, 9]

    Tzz   = np.zeros(len(zred), dtype='float32')
    for zz in range(len(zred)):
        Tzz[zz] = (Tuni - cd.age(zred[zz], use_flat=True, **cosmo))/cc.Gyr_s
        if Tzz[zz] < 0.01:
            Tzz[zz] = 0.01

    #print(zred, Tzz)
    #ax3t.set_xscale('log')
    #ax3t.set_xlim(0.008, Txmax)

    ax1.set_xlabel('$t_\mathrm{lookback}$/Gyr', fontsize=12)
    ax2.set_xlabel('$t_\mathrm{lookback}$/Gyr', fontsize=12)
    ax4.set_xlabel('$t_\mathrm{lookback}$/Gyr', fontsize=12)
    ax4.set_ylabel('$\log Z_*/Z_\odot$', fontsize=12)

    ax1t.set_xscale('log')
    ax1t.set_xlim(0.008, Txmax)
    ax2t.set_xscale('log')
    ax2t.set_xlim(0.008, Txmax)
    ax4t.set_xscale('log')
    ax4t.set_xlim(0.008, Txmax)

    ax4.set_xlim(0.008, Txmax)
    ax4.set_ylim(y3min-0.05, y3max)
    ax4.set_xscale('log')

    ax4.set_yticks([-0.8, -0.4, 0., 0.4])
    ax4.set_yticklabels(['-0.8', '-0.4', '0', '0.4'])
    #ax4.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

    #ax3.yaxis.labelpad = -2
    ax4.yaxis.labelpad = -2


    ax1t.set_xticklabels(zredl[:])
    ax1t.set_xticks(Tzz[:])
    ax1t.tick_params(axis='x', labelcolor='k')
    ax1t.xaxis.set_ticks_position('none')
    #ax1t.plot(Tzz, Tzz*0+y3max+(y3max-y3min)*.00, marker='|', color='k', ms=3, linestyle='None')

    ax2t.set_xticklabels(zredl[:])
    ax2t.set_xticks(Tzz[:])
    ax2t.tick_params(axis='x', labelcolor='k')
    ax2t.xaxis.set_ticks_position('none')
    #ax2t.plot(Tzz, Tzz*0+y3max+(y3max-y3min)*.00, marker='|', color='k', ms=3, linestyle='None')

    ax4t.set_xticklabels(zredl[:])
    ax4t.set_xticks(Tzz[:])
    ax4t.tick_params(axis='x', labelcolor='k')
    ax4t.xaxis.set_ticks_position('none')
    ax4t.plot(Tzz, Tzz*0+y3max+(y3max-y3min)*.00, marker='|', color='k', ms=3, linestyle='None')

    ax1.plot(Tzz, Tzz*0+lsfru+(lsfru-lsfrl)*.00, marker='|', color='k', ms=3, linestyle='None')
    ax2.plot(Tzz, Tzz*0+y2max+(y2max-y2min)*.00, marker='|', color='k', ms=3, linestyle='None')

    ####################
    ## Save
    ####################
    #plt.show()
    #ax1.legend(loc=2, fontsize=8)
    #ax2.legend(loc=3, fontsize=8)
    plt.savefig('SFH_' + ID0 + '_PA' + PA + '_pcl.png')
Esempio n. 36
0
val = numpy.zeros(len(z))

for i in xrange(len(z)):
    #Hubble Distance
    dh = cd.hubble_distance_z(z[i],**Cosmology)*cd.e_z(z[i],**Cosmology)
    #In David Hogg's (arXiv:astro-ph/9905116v4) formalism, this is equivalent to D_H / E(z) = c / (H_0 E(z)) [see his eq. 14], which
        #appears in the definitions of many other distance measures.
    
    dm = cd.comoving_distance_transverse(z[i],**Cosmology)
    #See equation 16 of David Hogg's arXiv:astro-ph/9905116v4
    
    da = cd.angular_diameter_distance(z[i],**Cosmology)
    #See equations 18-19 of David Hogg's arXiv:astro-ph/9905116v4
    
    dl = cd.luminosity_distance(z[i],**Cosmology)
    #Units are Mpc
    
    dVc = cd.diff_comoving_volume(z[i], **Cosmology)
    #The differential comoving volume element dV_c/dz/dSolidAngle.
    #Dimensions are volume per unit redshift per unit solid angle.
    #Units are Mpc**3 Steradians^-1.
    #See David Hogg's arXiv:astro-ph/9905116v4, equation 28

    tl = cd.lookback_time(z[i],**Cosmology)
    #See equation 30 of David Hogg's arXiv:astro-ph/9905116v4. Units are s.
    
    agetl = cd.age(z[i],**Cosmology)
    #Age at z is lookback time at z'->Infinity minus lookback time at z.
    
    tH = 3.09e17/Cosmology['h']