def Dc2(z1,z2):
    Dcz1 = (p15.comoving_distance(z1).value*p15.h)
    Dcz2 = (p15.comoving_distance(z2).value*p15.h)
    res = Dcz2-Dcz1+1e-8
    return res
    """Dc2(z1,z2) returns comoving distance between two objects at different redshifts.  It accepts z1
	and z2 as input, which are redshifts of lens and source, respectively."""
    """Parameters
Ejemplo n.º 2
0
def get_cluster_properties(hdf_dir, snap, dist_cut, props):
    """ Load in filenames of available clusters and
    save desired properties into a pandas dataframe"""

    # Load filenames
    cluster_fnames = [f for f in listdir(
        hdf_dir) if isfile(join(hdf_dir, f))]

    # Initialise pandas dataframe
    ndex = np.arange(0, len(cluster_fnames))
    cluster_props = pd.DataFrame(index=ndex, columns=props)
    cluster_props['fname'] = cluster_fnames

    # Get cluster properties for each cluster.
    for i in ndex:
        cluster_data = pd.read_hdf(hdf_dir + cluster_props.loc[i, 'fname'],
                                   'cluster_evo', mode='r',
                                   where="""var in [redshift,hmass,rvir,\
                                   snapid,x_comov,y_comov,z_comov]""")
        halo_data = pd.read_hdf(hdf_dir + cluster_props.loc[i, 'fname'],
                                'halo_evo', mode='r',
                                where="""snap in [""" + str(snap) + """] and \
                                var in [snapid, host_id,x_comov,y_comov,z_comov,hmass]""")

        # Mass at snap.
        cluster_props.loc[i, 'mass'] = cluster_data.loc[snap, 'hmass']

        # Get number of subhalos for each cluster, find unique ones
        u, idx = np.unique(
            halo_data.loc[snap, :, 'snapid'], return_index=True)
        num_subs = np.sum(halo_data.loc[
            snap, :, 'host_id'][idx] == cluster_data.loc[snap, 'snapid'])
        cluster_props.loc[i, 'num_subs'] = num_subs

        # Find mass diff in time diff from snap.
        for time_req in range(1, 4):
            ages = (WMAP7.age(cluster_data.loc[
                snap, 'redshift']) - WMAP7.age(cluster_data.loc[:, 'redshift']))
            idx = (np.abs(ages.value - time_req)).argmin()
            snap_inq = idx + cluster_data.index.get_level_values('snap')[0]
            cluster_props.loc[i, 'mass_time_diff_' + str(time_req)] = (cluster_data.loc[
                snap, 'hmass'] -
                cluster_data.loc[snap_inq, 'hmass'])

        # Find number of groups
        halo_data = halo_data.drop_duplicates()
        rad_select = (np.sqrt((np.power(halo_data.loc[:, :, 'x_comov'].subtract(
            cluster_data.loc[:, 'x_comov']), 2) +
            np.power(halo_data.loc[:, :, 'y_comov'].subtract(
                cluster_data.loc[:, 'y_comov']), 2) +
            np.power(halo_data.loc[:, :, 'z_comov'].subtract(
                cluster_data.loc[:, 'z_comov']), 2))) < dist_cut)
        mass_select = halo_data.loc[:, :, 'hmass'] > 1e13
        num_grps = np.sum(mass_select & rad_select)
        cluster_props.loc[i, 'num_grps'] = num_grps

    return cluster_props, ndex
Ejemplo n.º 3
0
def convert_one_from_dir(file_name_base,ncc):
    mp=7.43e9
    zs = 1.0

    file_dir = "./15x15/"
    #file_name_base = "s97"
    file_in_base = file_dir+file_name_base

    zl_array = np.fromfile(file_in_base+"_redshift.bin",dtype = ">f")
    zl = 0.5*(zl_array.max()+zl_array.min())
    zD = cosmo.comoving_distance(zl)*cosmo.h
    zB = cosmo.comoving_distance(zl_array.max())-cosmo.comoving_distance(zl_array.min())

    x1 = np.fromfile(file_in_base+"_theta.bin",dtype = ">f")
    npp=len(x1) # total mass = 1e9*2e5 M_sun/h
    bsz = 15.0
    if ((npp/500000.0)<2):
        nsa = 1
    else:
        nsa = int(npp/500000.0)

    #nsa = 1

    xc1 = (x1.max()+x1.min())*0.5
    x1 = x1[::nsa]-xc1

    x2 = np.fromfile(file_in_base+"_phi.bin",dtype = ">f")
    xc2 = (x2.max()+x2.min())*0.5
    x2 = x2[::nsa]-xc2

    x3 = (np.random.random_sample((len(x1)))-0.5)*zB/zD*mm.apr/3600
    #print zB/zD*mm.apr/3600
    #x3 = np.linspace(-0.5,0.5,len(x1))*100.0/zD*mm.apr/3600

    #print nsa,len(x1),len(x2),len(x3)


    if npp > 100:
        sdens_angular = call_cic_sdens(x1,x2,bsz,ncc,len(x1))*mp/np.deg2rad(1.0)**2.0*npp/len(x1)
    else:
        sdens_angular = call_sph_sdens(x1,x2,x3,bsz,ncc,len(x1))*mp/np.deg2rad(1.0)**2.0*npp/len(x1)


    #sdens_angular_normal = (sdens_angular-sdens_angular.mean())
    sdens_angular_normal = sdens_angular
    Dcl = (cosmo.comoving_distance(zl).value*cosmo.h)
    Dcs = (cosmo.comoving_distance(zs).value*cosmo.h)
    Dcls = Dcs-Dcl
    kappa = 4.0*np.pi*mm.G/mm.vc**2*(1.0+zl)/Dcl*Dcls/Dcs*sdens_angular_normal

    ##----------------------------
    #sdens_normal = sdens_angular_normal/mm.Da(zl)**2.0/mm.sigma_crit(zl,zs)
    ##----------------------------
    #file_out ="./output_files/"+file_name_base+"_"+str(zl)+"_sdens_normal.bin"
    #sdens_normal.astype(np.float32).tofile(file_out)
    return kappa,zl
Ejemplo n.º 4
0
 def calculateAvgMassEinsteinRadius(gz, qz):
     avgMass = 0.247
     # avgMass = 0.20358470458734301
     dL = cosmo.angular_diameter_distance(gz).to('m')
     dS = cosmo.angular_diameter_distance(qz).to('m')
     dLS = cosmo.angular_diameter_distance_z1z2(gz, qz).to('m')
     thetaE = 4 * const.G * u.Quantity(
         avgMass, 'solMass').to('kg') * dLS / dL / dS / const.c / const.c
     thetaEUnit = u.def_unit('theta_E', math.sqrt(thetaE.value) * u.rad)
     return thetaEUnit
Ejemplo n.º 5
0
def projected_rho_mean(z1, z2):
    # return the mean density of the unvierse integrated across redshifts
    # z1 and z2, in comoving (M_sun/h)(Mpc/h)^-3
    pc0 = cosmo.critical_density(0).to(units.Msun / units.Mpc**3).value
    Om0 = cosmo.Om0
    rho_mean_0 = Om0 * pc0

    d1 = cosmo.comoving_distance(z1).value
    d2 = cosmo.comoving_distance(z2).value

    return rho_mean_0 * (d2 - d1) / cosmo.h
Ejemplo n.º 6
0
    def disterr(self):
        """
        Distance error (given WMAP7 cosmology/H0)
        """
        from astropy.cosmology import WMAP7

        dist = WMAP7.luminosity_distance(self.zdist)
        dp = abs(dist - WMAP7.luminosity_distance(self.zdist + self.zdisterr))
        dm = abs(dist - WMAP7.luminosity_distance(self.zdist - self.zdisterr))

        return (dp + dm) / 2
    def output_catalog(self,outfile):
        print("    Saving catalog: ", outfile)

        fobj = open(outfile,'w')

        fobj.write('## Lightcone Catalog File for input geometry: '+self.lightconefile+'\n')
        fobj.write('## Catalog source Directory: '+self.basedir+'\n')
        fobj.write('## Square FOV (arcmin): {:12.6f}'.format(self.delb_arcmin)+'\n')
        fobj.write('## Area (arcmin^2): {:12.6f}'.format(self.delb_arcmin**2)+'\n')
        fobj.write('## Baryonic Mass Lower Limit (Msun) : {:10.5e}'.format(self.mass_limit)+'\n')
        fobj.write('## Assumed Cosmology: '+WMAP7.__str__()+'\n')
        fobj.write('## Creator:  Greg Snyder (STScI) \n')
        fobj.write('## Catalog & Data Release Reference:  Nelson et al. (2015) \n')
        fobj.write('## Catalog & Data Release URL: illustris-project.org/data \n')
        fobj.write('## Column 01: Snapshot number \n')
        fobj.write('## Column 02: Subhalo Index \n')
        fobj.write('## Column 03: RA (degrees) \n')
        fobj.write('## Column 04: DEC (degrees) \n')
        fobj.write('## Column 05: RA (proper kpc at true z) \n')
        fobj.write('## Column 06: DEC (proper kpc at true z) \n')
        fobj.write('## Column 07: RA (proper kpc at inferred z) \n')
        fobj.write('## Column 08: DEC (proper kpc at inferred z) \n')
        fobj.write('## Column 09: True cosmological redshift \n')
        fobj.write('## Column 10: Inferred redshift (includes peculiar v) \n')
        fobj.write('## Column 11: Peculiar redshift; Peculiar Velocity / Speed of Light \n')
        fobj.write('## Column 12: True scale at cosmological z, in kpc/arcsec \n')
        fobj.write('## Column 13: [Mpc] Comoving X in Observer Coordinates \n')
        fobj.write('## Column 14: [Mpc] Comoving Y in Observer Coordinates \n')
        fobj.write('## Column 15: [Mpc] Comoving Z in Observer Coordinates \n')
        fobj.write('## Column 16: [Mpc] True Angular Diameter Distance to observer \n')
        fobj.write('## Column 17: [Mpc] Inferred Angular Diameter Distance to observer \n')
        fobj.write('## Column 18: Snapshot redshift \n')
        fobj.write('## Column 19: Geometrically appropriate redshift at center of this cylinder \n')
        fobj.write('## Column 20: Lightcone cylinder number \n')
        fobj.write('## Column 21: [Msun] Stellar mass within 2X stellar half mass radius\n')
        fobj.write('## Column 22: [Msun] Total gas mass within 2X stellar half mass radius\n')
        fobj.write('## Column 23: [Msun] Total mass of this subhalo (excludes children subhalos) \n')
        fobj.write('## Column 24: [Msun] Total BH mass within 2X stellar half mass radius\n')
        fobj.write('## Column 25: [Msun] Total baryon mass within 2X stellar half mass radius\n')
        fobj.write('## Column 26: [Msun/year] SFR within 2X stellar half mass radius\n')
        fobj.write('## Column 27: [(10^10 Msun/h) / (0.978 Gyr/h)] Total BH accretion rate within subhalo\n')
        fobj.write('## Column 28: [Mpc] Camera X in Observer Coordinates (Proper X at z; a transverse coordinate) \n')
        fobj.write('## Column 29: [Mpc] Camera Y in Observer Coordinates (Proper Y at z; a transverse coordinate)\n')
        fobj.write('## Column 30: [Mpc] Camera Z in Observer Coordinates (Proper Z at z; should be almost exactly Column 16)\n')
        fobj.write('## Column 31: [AB Mag] Intrinsic stellar g absolute magnitude (BC03) \n')
        fobj.write('## Column 32: [AB Mag] Intrinsic stellar r absolute magnitude (BC03) \n')
        fobj.write('## Column 33: [AB Mag] Intrinsic stellar i absolute magnitude (BC03) \n')
        fobj.write('## Column 34: [AB Mag] Intrinsic stellar z absolute magnitude (BC03) \n')
        fobj.write('## Column 35: [km/s] Galaxy motion in transverse Camera X direction \n')
        fobj.write('## Column 36: [km/s] Galaxy motion in transverse Camera Y direction \n')
        fobj.write('## Column 37: [km/s] Galaxy motion in line-of-sight Camera Z direction ; the Peculiar Velocity \n')
        fobj.write('## Column 38: [km/s] Cosmological expansion velocity at true z (Column 10 measures Column 37+38)\n')
        fobj.write('## Column 39: [AB Mag] Apparent total rest-frame g-band magnitude (BC03) \n')

        for cylobj in self.cylinder_object_list:
            if cylobj is not None:
                cylobj.print_cylinder(fobj)

        fobj.close()
        return
Ejemplo n.º 8
0
    def dist(self):
        """
        Distance to host (given WMAP7 cosmology/H0)
        """
        from astropy.cosmology import WMAP7

        return WMAP7.luminosity_distance(self.zdist)
Ejemplo n.º 9
0
def rho0(z):
    global _rho0_func
    if _critical_density_func is None:
        zs = np.linspace(0, 10, 1000)
        rho_0 = 2.77536627e11
        density = cosmo.critical_density(zs) / cosmo.critical_density0 * rho_0
        _critical_density_func = np.interp(z, density)
Ejemplo n.º 10
0
def generateSpecialUnits(qMass, qR, gR):
    linearRg = (qMass.to('kg') * const.G / const.c / const.c).to('m')
    angleRg = linearRg / cosmo.angular_diameter_distance(qR)
    rgUnit = u.def_unit('r_g', angleRg.value * u.rad)
    thetaE = 4 * const.G * u.Quantity(0.5, 'solMass').to('kg') * _scaleFactor(
        qR, gR) / const.c / const.c
    thetaEUnit = u.def_unit('theta_E', math.sqrt(thetaE.value) * u.rad)
    return [thetaEUnit, rgUnit]
Ejemplo n.º 11
0
def plot_evolution(plotlabel, galaxy_counts, num_members, num_members_std,
                   resultsdirs, colors, symbols, lbtimes, plot_lookback_times,
                   plot_redshifts, plotsdir, labels):
    #
    # Plot fractional number of galaxies in compact groups vs. redshift
    #

    figname = os.path.join(plotsdir,
                           '{0}_frac_galaxies_evolution.eps'.format(plotlabel))
    frac_galaxies = np.array([[
        df / galaxy_counts['num_galaxies'][snapnum]
        for snapnum, df in enumerate(num_members[result_ind])
    ] for result_ind in range(len(resultsdirs))])
    frac_galaxies_std = frac_galaxies * np.sqrt(
        np.array(
            [[(num_members_std / df)**2. +
              (galaxy_counts['std_galaxies'][snapnum] /
               galaxy_counts['num_galaxies'][snapnum])**2.
              for snapnum, (df, num_members_std) in enumerate(
                  zip(num_members[result_ind], num_members_std[result_ind]))]
             for result_ind in range(len(resultsdirs))]))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    for ind, (frac_galaxy, frac_galaxy_std) in enumerate(
            zip(frac_galaxies, frac_galaxies_std)):
        ax.plot(lbtimes,
                100. * frac_galaxy,
                color=colors[ind],
                marker=symbols[ind],
                label=labels[ind])
        ax.fill_between(lbtimes,
                        100. * (frac_galaxy - frac_galaxy_std),
                        100. * (frac_galaxy + frac_galaxy_std),
                        facecolor=colors[ind],
                        edgecolor='none',
                        alpha=0.6)
    ax.set_xlabel('Lookback Time (Gyr)')
    ax.set_ylabel(
        'Percent of non-dwarf Galaxies in that are currently in \nor have ever been in Compact Groups'
    )

    ax.legend(loc='best', fontsize=12, numpoints=1)
    ax.set_xlim(0, WMAP7.age(0).to('Gyr').value)
    m = np.max(frac_galaxies)
    ax.set_ylim(0, 10)
    #ax.set_yscale('log')
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(plot_lookback_times)
    ax2.set_xticklabels(plot_redshifts)
    ax2.set_xlabel('Redshift')
    ax2.grid(False)
    plt.savefig(figname)
    plt.close()
    return
Ejemplo n.º 12
0
def convert_physical_to_comoving_vol(end_z):
    z_bins = np.linspace(0, end_z, 1000)
    comov_vol = WMAP7.comoving_volume(z_bins)
    comov_shell = comov_vol[:-1] - comov_vol[1:]
    z_shell = (z_bins[:-1] + z_bins[1:]) / 2.0
    a_shell = 1.0 / (1.0 + z_shell)
    a3_shell = a_shell**3
    total_comov_vol = np.sum(comov_shell)
    total_phys_vol = np.sum(comov_shell * a3_shell)
    return total_phys_vol / total_comov_vol
Ejemplo n.º 13
0
    def _SFR_UV(self, z, fmag, nmag, rmag, f_flux):
        ''' calculate UV star formation rates based on Salim+(2007) Eq. 5, 7, 8. 
        
        :param z:
            redshift

        :param fmag: 
            FUV absolute magnitude

        :param nmag: 
            NUV absolute magnitude

        :param rmag: 
            r-band absolute magnitude

        :param f_flux: 
            FUV flux in Janskies. See `_jansky` method for conversion 
        '''
        from astropy.cosmology import WMAP7
        fn = fmag - nmag
        opt = nmag - rmag  # N-r

        #Luminosity Distance
        dist = WMAP7.comoving_distance(z)
        ldist = (1 + z) * dist.value

        #calculating Attenuation 'atten'
        atten = np.repeat(-999., len(fmag))

        case1 = np.where((opt > 4.) & (fn < 0.95))
        atten[case1] = 3.32 * fn[case1] + 0.22
        case2 = np.where((opt > 4.) & (fn >= 0.95))
        atten[case2] = 3.37
        case3 = np.where((opt <= 4.) & (fn < 0.9))
        atten[case3] = 2.99 * fn[case3] + 0.27
        case4 = np.where((opt <= 4.) & (fn >= 0.9))
        atten[case4] = 2.96

        #if opt >= 4.0:
        #    if fn < 0.95:
        #        atten = 3.32*fn + 0.22
        #    else:
        #        atten = 3.37
        #else:
        #    if fn < 0.90:
        #        atten = 2.99*fn +0.27
        #    else:
        #        atten = 2.96

        lum = 4. * np.pi * (ldist**2.0) * (3.087**2.0) * (10**(
            25.0 + (atten / 2.5))) * f_flux  #Luminosity
        sfr = 1.08 * (10**(-28.0)) * np.abs(lum)
        return sfr
Ejemplo n.º 14
0
def histograms(savefig=False):

    h = 0.70

    from matplotlib import pyplot as plt
    from astropy.io import fits

    metadata = fits.getdata('%s/gz_illustris_all_metadata.fits' % path,1)

    fig,axarr = plt.subplots(2,2,figsize=(10,10))
    axravel = np.ravel(axarr)
    histsubplot(axravel[0],metadata['mass_stars']/h * 10.,'Mass '+r'$[\log$'+' '+r'$(M/M_{\odot})]$',color="#377eb8",range=(6,14),bins=30)
    histsubplot(axravel[1],metadata['halfmassrad_stars'] * h,color="#e41a1c",range=(0,20),bins=30)
    histsubplot(axravel[2],metadata['sfr'],'SFR '+r'$[M_{\odot}/yr]$',color="#4daf4a",range=(0,10),bins=30)
    histsubplot(axravel[3],metadata['stellarphotometrics_r'],color="#984ea3",range=(-26,-15),bins=30)

    # Same plots for GZ2 Legacy data?
    #
    gz2data = fits.getdata('/Users/willettk/Astronomy/Research/GalaxyZoo/fits/mpajhu_gz2.fits',1)

    from astropy.cosmology import WMAP7
    from astropy import units as u
    r50_kpc = (gz2data['PETROR50_R'] * u.arcsec / WMAP7.arcsec_per_kpc_comoving(gz2data['REDSHIFT'])).value
    r90_kpc = (gz2data['PETROR90_R'] * u.arcsec / WMAP7.arcsec_per_kpc_comoving(gz2data['REDSHIFT'])).value
    r_e = re_from_petrosian(r50_kpc,r90_kpc)

    histsubplot(axravel[0],gz2data['MEDIAN_MASS'],'Stellar mass '+r'$[\log$'+' '+r'$(M/M_{\odot})]$',color="k",histtype='step',range=(6,14),bins=30)
    histsubplot(axravel[1],r50_kpc,'Stellar half-mass radius [kpc]',color="k",range=(0,20),histtype='step',bins=30)
    histsubplot(axravel[2],10**(gz2data['MEDIAN_SFR']),'SFR '+r'$[M_{\odot}/yr]$',color="k",range=(0,10),histtype='step',bins=30)
    histsubplot(axravel[3],gz2data['PETROMAG_MR'],r'$M_r$',color="k",histtype='step',range=(-26,-15),bins=30)


    fig.tight_layout()
    if savefig:
        plt.savefig('%s/hist_compare_gz2.pdf' % path)
    else:
        plt.show()

    return None
Ejemplo n.º 15
0
    def _init_code(self):
        """Compute the age of the Universe at a given redshift
        """
        self.redshift = float(self.parameters["redshift"])

        # Raise an error when applying a negative redshift. This module is
        # not for blue-shifting.
        if self.redshift < 0.:
            raise Exception("The redshift provided is negative <{}>."
                            .format(self.redshift))

        self.universe_age = cosmology.age(self.redshift).value * 1000.
        if self.redshift == 0.:
            self.luminosity_distance = 10. * parsec
        else:
            self.luminosity_distance = (
                cosmology.luminosity_distance(self.redshift).value * 1e6 *
                parsec)
        # We do not define the values of the IGM attenuation component yet.
        # This is because we need the wavelength grid for that first. This
        # will be assigned on the first call.
        self.igm_attenuation = {}
Ejemplo n.º 16
0
    def getFluxes(self, z, Lbol, Filter):
	    # Redshift to object's z
	    DLcm  = WMAP7.luminosity_distance(z).to_value(u.cm)
	    waveZ = self.QSOtemp['Wave']*(1.+z)
	    filtZ = np.interp(waveZ, Filter['lambda'], Filter['trans'])

	    # Normalise spectral densities
	    L5100 = Lbol / (9.*5100.)
	    lum   = L5100 * self.QSOtemp['FluxD']/self.QSOtemp['FluxD'][4300]
	    flux  = lum / (4*np.pi*DLcm*DLcm * (1.+z))

	    # Compute flux through filter
	    tempflux = igrt.trapz(waveZ * flux * filtZ, x=waveZ)
	    zeroflux = igrt.trapz(self.c/waveZ * self.AB * filtZ, x=waveZ)

	    return waveZ, lum, tempflux, zeroflux
Ejemplo n.º 17
0
    def getAbsMag(self, z, appmag, Lbol, Filter):
	    # Calculate value of fractions in K-correction
	    tempflux, zeroflux = self.getFluxes(z, Lbol, Filter)[2:]
	    frac1 = 10**(-0.4*appmag)
	    frac2 = zeroflux/tempflux

	    # Calculate K-correction
	    KQR = -2.5 * np.log10(frac1*frac2)

	    # Calculate distance modulus
	    DLpc = WMAP7.luminosity_distance(z).to_value(u.pc)
	    DM   = 5 * np.log10(0.1 * DLpc)

	    # Calculate apparent magnitude based on the apparent-absolute magnitude relationship
	    absMag = appmag - DM - KQR
	    return absMag
Ejemplo n.º 18
0
 def getQSOmag(self, Lbol, z, Filter):
     # Return apparent magnitude of QSO at redshift z in filter
     
     # Redshift the QSO to z
     waveZ = self.QSOTemplate['Wave'] * (1.0+z)
     
     # Normalise spectrum from relative to absolute flux units
     # Index 4300 is 5100.5 Angstroms
     L5100 = Lbol/(5100.0*9.0)
     lumZ  = self.QSOTemplate['FluxD'] * L5100 / self.QSOTemplate['FluxD'][4300]
     
     # Calculate fluxes based on luminosity distance DL in cm
     DL = WMAP7.luminosity_distance(z) * 1.0e6 * 3.0857e18   # cm
     fluxZ = lumZ / (4*np.pi*DL.value**2)                    # ergs/s/cm^2
     
     # Convolve with Filter and report flux in AB mag
     return self.QSOConv(waveZ, fluxZ, Filter)
Ejemplo n.º 19
0
def pecZ(x, y, z, vx, vy, vz, z_hubb, obs=np.zeros(3)):
    '''
    This function calculates peculiar z_hubbs for n-body simulation objects, given
    their comoving position and velocity, and returns some other useful products of the calculation. 

    :param x: x-position for each object, in form [x1, x2,... xn]
    :param y: y-position for each object, in form of param x
    :param z: z-position for each object, in form of param x
    :param vx: x-velocity for each object, in form [vx1, vx2,... vxn]
    :param vy: y-velocity for each object, in form of param vx
    :param vz: z-velocity for each object, in form of param vx
    :param z_hubb: cosmological redshifts for each object, in form [z1, z2,... zn]
    :param obs: The coordinates of the observer, in form [x, y, z]
    :return: - the peculair z_hubb in each object in form of param redshift
             - the total observed z_hubb (cosmological+peculiar)
             - the peculiar velocity of each object, in the form of param vx, where negative 
               velocities are toward the observer, in comoving km/s
             - the line-of-sight velocity, in proper km/s (peculiar velocity * a)
             - distance from observer to object in comoving Mpc
             - distance from observer to object in kpc proper (comoving dist * a)
             - distorted distance from observer to object in Mpc proper 
    '''

    # get relative position (r vector) of and position unit vector toward each object
    r_rel = np.array([x, y, z]).T - obs
    r_rel_mag = np.linalg.norm(r_rel, axis=1)
    r_rel_hat = np.divide(r_rel, np.array([r_rel_mag]).T)

    # dot velocity vectors with relative position unit vector to get peculiar velocity
    v = np.array([vx, vy, vz]).T
    v_mag = np.linalg.norm(v, axis=1)
    v_pec = npm.inner1d(v, r_rel_hat)

    # find total and peculiar z_hubb (full relativistic expression)
    c = const.c.value / 1000
    z_pec = np.sqrt((1 + v_pec / c) / (1 - v_pec / c)) - 1
    z_tot = (1 + z_hubb) * (1 + z_pec) - 1

    # find the distorted distance from appliying Hubble's law using the new z_tot z_hubbs
    a = 1 / (1 + z_hubb)
    r_dist = r_rel_mag + v_pec / 100. / cosmo.efunc(z_hubb) / a
    #pdb.set_trace()

    return z_pec, z_tot, v_pec, v_pec * a, r_rel_mag, r_rel_mag * a, r_dist
Ejemplo n.º 20
0
def UVsfr(z, fmag, nmag, rmag, f_flux):
    ''' Calculate UV star formation rates. 
    Inputs: NSAID,z,F-band magnitude, N-band magnitude, r-band magnitude, F-band flux in Janskies
    '''
    fn = fmag - nmag
    opt = nmag - rmag  # N-r

    #Luminosity Distance
    dist = WMAP7.comoving_distance(z)
    ldist = (1 + z) * dist

    #calculating Attenuation 'atten'
    atten = np.repeat(-999., len(fmag))

    case1 = np.where((opt > 4.) & (fn < 0.95))
    atten[case1] = 3.32 * fn[case1] + 0.22
    case2 = np.where((opt > 4.) & (fn >= 0.95))
    atten[case2] = 3.37
    case3 = np.where((opt <= 4.) & (fn < 0.9))
    atten[case3] = 2.99 * fn[case3] + 0.27
    case4 = np.where((opt <= 4.) & (fn >= 0.9))
    atten[case4] = 2.96

    #if opt >= 4.0:
    #    if fn < 0.95:
    #        atten = 3.32*fn + 0.22
    #    else:
    #        atten = 3.37
    #else:
    #    if fn < 0.90:
    #        atten = 2.99*fn +0.27
    #    else:
    #        atten = 2.96

    lum = 4. * np.pi * (ldist**2.0) * (3.087**2.0) * (10**(
        25.0 + (atten / 2.5))) * f_flux  #Luminosity
    sfr = 1.08 * (10**(-28.0)) * np.abs(lum)
    return sfr
Ejemplo n.º 21
0
def update_plot(i):
    sim = simlist[i]
    host, subs = load_elvis(sim=sim, processed=True)
    # subs = subs[subs.nadler2018 > 0.5]
    bind = -subs.pot_mltr.values - 0.5*(subs.v_r.values**2 + subs.v_t.values**2)
    z = WMAP7.lookback_time(1/subs.a_acc.values - 1)[bind>0].value
    r = subs.r[bind>0]
    bind = bind[bind>0]

    # calculate linear regression
    infallcut = z > 2
    bindcut = bind > 0
    bind_ = bind[infallcut & bindcut]
    infall_ = z[infallcut & bindcut]
    slope, intercept, r_value, p_value, std_err = linregress(infall_, np.log10(bind_))

    # update plot
    offset = [[infall, np.log10(E)] for E,infall in zip(bind,z)]
    scat.set_offsets(offset)        # positions
    scat.set_array(r)               # colors
    line.set_data(z[bindcut], intercept + slope*z[bindcut])
    sim_text.set_text(sim)
    sortprop_text.set_text("Mvir = "'%.2E' % sortprop[i])
    return scat,sim_text,sortprop_text,line
Ejemplo n.º 22
0
def uvsfr(id, z, fmag, nmag, rmag, f_flux):
    fn = fmag - nmag
    opt = nmag - rmag  # N-r

    #Luminosity Distance
    dist = WMAP7.comoving_distance(z)
    ldist = (1 + z) * dist

    #calculating Attenuation 'a'
    if opt >= 4.0:
        if fn < 0.95:
            a = 3.32 * float(fn) + 0.22
        else:
            a = 3.37
    else:
        if fn < 0.90:
            a = 2.99 * float(fn) + 0.27
        else:
            a = 2.96

    lum = 4 * 3.14159 * (ldist**2.0) * (3.087**2.0) * (10**(
        25.0 + (a / 2.5))) * f_flux  #Luminosity
    sfr = 1.08 * (10**(-28.0)) * abs(lum)
    return sfr
Ejemplo n.º 23
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import h5py
import dtk
import sys

from astropy.cosmology import WMAP7 as cosmo
import time
from scipy.interpolate import interp1d

h = 0.702
stepz = dtk.StepZ(200, 0, 500)
zs = np.linspace(0, 1.5, 1000)
z_to_dl = interp1d(zs, cosmo.luminosity_distance(zs))
step2nan_str_z = {}

param = dtk.Param(sys.argv[1])
output = param.get_string('output')
output_mod = output.replace('.hdf5', '_mod.hdf5')

hfile = h5py.File(output_mod, 'a')

redshift = hfile['galaxyProperties/redshiftHubble'].value
dl = z_to_dl(redshift)
print "done getting the luminosity distance..."
adjust = -2.5 * np.log10(1 + redshift) + 5 * np.log10(dl) + 25.0


def recal_obs(hgroup):
Ejemplo n.º 24
0
 def angDiamDist(self):
     return cosmo.angular_diameter_distance(self.__redshift).to('lyr')
Ejemplo n.º 25
0
def dLum(z):
    return cosmo.luminosity_distance(z).value * h  #in Mpc/h
Ejemplo n.º 26
0
def dcomv(z):
    return cosmo.comoving_distance(z).value * h  #in Mpc/h
Ejemplo n.º 27
0
def getcoords(a,d,z):                                                          
    comdis = WMAP7.comoving_distance(z)                                        
    i = (comdis)*(math.cos(math.radians(d)))*(math.cos(math.radians(a)))       
    j = (comdis)*(math.cos(math.radians(d)))*(math.sin(math.radians(a)))       
    k = (comdis)*(math.sin(math.radians(d)))                                   
    return(i,j,k,z)                                                            
Ejemplo n.º 28
0
def tdyn_nsnap(nsnap): 
    z_t = z_nsnap(nsnap)
    rho_m = WMAP7.Om(z_t) * WMAP7.critical_density(z_t)
    return ((4./3. * np.pi * 200. * rho_m * Const.G)**-0.5).to(U.Gyr).value
            i = np.random.randint(len(objs[div]))
            print(objs[div][i])
        if i % tenpct == 0:
            print(i, 'of', len(objs[div]))

        #Loop over the simulation projections
        for p in projection:
            #Load data, has to be reloaded for reasons (IDK)
            f = h5py.File(objs[div][i], 'r')

            px = 1.0
            #get redshift and determine effective resolution of EAGLE
            if high_z:
                while px / 3600 > 0.00011:
                    rand_idx = np.random.randint(len(table))
                    kpc_as = cosmo.kpc_proper_per_arcmin(
                        table[z_col][rand_idx]).to(u.kpc / u.arcsec)
                    px = (((60 * u.kpc) / kpc_as) /
                          256).value  #calculate pixel size at redshift
            else:
                rand_idx = np.random.randint(len(table))
                kpc_as = cosmo.kpc_proper_per_arcmin(
                    table[z_col][rand_idx]).to(u.kpc / u.arcsec)
                px = (((60 * u.kpc) / kpc_as) /
                      256).value  #calculate pixel size at redshift
            wcs_egl.wcs.cdelt = np.array([px / 3600,
                                          px / 3600])  #update eagle WCS

            obj_name.append(objs[div][i][len(path) + len(div) + 1:-len(extn)] +
                            p)
            obj_zsft.append(table[z_col][rand_idx])
Ejemplo n.º 30
0
                    def rhs(t, n):
                        """
                        Calculate the RHS of the radiative transfer equations.

                        RHS of the coupled nHII, n_HeII, n_HeIII and T equations. The equations are labelled as A,B,C,
                        and D and the rest of the variables are the terms contained in the respective equations.

                        Parameters
                        ----------
                        t : float
                         Time of evaluation in s.
                        n : array-like
                         1-D array containing the variables nHII, nHeII, nHeIII, T for evaluating the RHS.

                        Returns
                        -------
                        array_like
                         The RHS of the radiative transfer equations.
                        """

                        if isnan(n[0]) or isnan(n[1]) or isnan(n[2]) or isnan(n[3]):
                            print('Warning: calculations contain nan values, check the rhs')

                        n_HIIx = n[0]
                        n_HIx = n_H(zstar, C) - n[0]
                        if isnan(n_HIIx):
                            n_HIIx = n_H(zstar, C)
                            n_HIx = 0
                        if n_HIIx > n_H(zstar, C):
                            n_HIIx = n_H(zstar, C)
                            n_HIx = 0
                        if n_HIIx < 0:
                            n_HIIx = 0
                            n_HIx = n_H(zstar, C)

                        n_HeIIx = n[1]
                        n_HeIIIx = n[2]
                        n_HeIx = n_He(zstar, C) - n[1] - n[2]
                        if isnan(n_HeIIIx):
                            n_HeIIIx = n_He(zstar, C)
                            n_HeIIx = 0
                            n_HeIx = 0

                        if n_HeIIIx > n_He(zstar, C):
                            n_HeIIIx = n_He(zstar, C)
                            n_HeIIx = 0
                            n_HeIx = 0

                        if n_HeIIIx < 0:
                            n_HeIIIx = 0
                            n_HeIIx = 0
                            n_HeIx = n_He(zstar, C)

                        Tx = n[3]

                        if isnan(Tx):
                            print('Tx is nan')
                        if (Tx < T_gamma.value * (1 + zstar) ** 1 / (1 + 250)):
                            Tx = T_gamma.value * (1 + zstar) ** 1 / (1 + 250)

                        n_ee = n_HIIx + n_HeIIx + 2 * n_HeIIIx

                        mu = (n_H(zstar, C) + 4 * n_He(zstar, C)) / (
                                    n_H(zstar, C) + n_He(zstar, C) + n_ee)
                        n_B = n_H(zstar, C) + n_He(zstar, C) + n_ee

                        A1_HI = xi_HI(Tx) * n_HIx * n_ee
                        A1_HeI = xi_HeI(Tx) * n_HeIx * n_ee
                        A1_HeII = xi_HeII(Tx) * n_HeIIx * n_ee
                        A2_HII = eta_HII(Tx) * n_HIIx * n_ee
                        A2_HeII = eta_HeII(Tx) * n_HeIIx * n_ee
                        A2_HeIII = eta_HeIII(Tx) * n_HeIIIx * n_ee

                        A3 = omega_HeII(Tx) * n_ee * n_HeIIIx

                        A4_HI = psi_HI(Tx) * n_HIx * n_ee
                        A4_HeI = psi_HeI(Tx, n_ee, n_HeIIx) * n_ee
                        A4_HeII = psi_HeII(Tx) * n_HeIIx * n_ee

                        A5 = theta_ff(Tx) * (n_HIIx + n_HeIIx + 4 * n_HeIIIx) * n_ee

                        H = pl.H(zstar)
                        H = H.to(u.s ** -1)

                        A6 = (2 * H * kb * Tx * n_B / mu).value

                        A = gamma_HI(n_HIIx, n_HeIx, n_HeIIx, n_HeIIIx, Tx, I1_HI, I2_HI, I3_HI, zstar,C,  gamma_2c) * n_HIx - alpha_HII(
                            Tx) * n_HIIx * n_ee
                        B = gamma_HeI(n_HIIx, n_HeIx, n_HeIIx, n_HeIIIx, I1_HeI, I2_HeI, I3_HeI, zstar, C) * n_HeIx + beta_HeI(
                            Tx) * n_ee * n_HeIx - beta_HeII(Tx) * n_ee * n_HeIIx - alpha_HeII(
                            Tx) * n_ee * n_HeIIx + alpha_HeIII(Tx) * n_ee * n_HeIIIx - zeta_HeII(
                            Tx) * n_ee * n_HeIIx
                        Cc = gamma_HeII(I1_HeII) * n_HeIIx + beta_HeII(
                            Tx) * n_ee * n_HeIIx - alpha_HeIII(Tx) * n_ee * n_HeIIIx
                        Dd = (Tx / mu) * (-mu / (n_H(zstar, C) + n_He(zstar, C) + n_ee)) * (A + B + 2 * Cc)
                        D = (2 / 3) * mu / (kb.value * n_B) * (
                                    f_Heat(n_HIIx/n_H(zstar,C), zstar) * n_HIx * I1_T_HI + f_Heat(n_HIIx/n_H(zstar,C),
                                                                                       zstar) * n_HeIx * I1_T_HeI + f_Heat(
                                n_HIIx/n_H(zstar,C), zstar) * n_HeIIx * I1_T_HeII + sigma_s.value * n_ee / (m_e * c ** 2).value * (
                                            I2_Ta + Tx * I2_Tb) - (
                                            A1_HI + A1_HeI + A1_HeII + A2_HII + A2_HeII + A2_HeIII + A3 + A4_HI + A4_HeI + A4_HeII + A5 + A6)) + Dd
Ejemplo n.º 31
0
    def solve(self,param):
        """
        Solves the radiative transfer equation for the given source and the parameters.

        The solver calls grid parameters and initializes the starting grid with the initial conditions for the densities
        and the temperature. Using the time step, the radiative transfer equations are used to update the k-th cell from
        the radial grid for a certain time step dt_init. Then the solver moves on to the (k+1)-th cell, and uses the
        values calculated from the k-th cell in order to calculate the optical depth, which requires information of the
        densities from all prior cells. For each cell, we sum up the three densities from the starting cell up to the
        current cell and use these values to evaluate the 12 integrals in the equations, which is done by interpolation
        of the tables we generated previously. After each cell is updated for some time dt_init, we start again with the
        first cell and use the calculation from the previous time step as the initial condition and repeat the same
        process until the radial cells are updated l times such that l*dt_init has reached the evolution time. After the
        solver is finished we compare the ionization fronts of two consecutive runs and require an accuracy of 5% in
        order to finish the calculations. If the accuracy is not reached we store the values from the run and start
        again with time step size dt_init/2 and a radial grid with half the step size from the previous run.
        This process is repeated until the desired accuracy is reached.
        """
        print('Solving the radiative equations...')
        t_start_solver = datetime.datetime.now()
        self.initialise_grid_param()
        z_reion = self.grid_param['z_reion']
        gamma_2c = self.grid_param['gamma_2c']
        T_gamma = self.grid_param['T_gamma']
        C = self.grid_param['C']

        dt_init = self.grid_param['dt_init']
        dn = self.grid_param['dn']

        r_grid0 =  linspace(self.grid_param['r_start'], self.grid_param['r_end'], dn)
        r_grid = linspace(self.grid_param['r_start'], self.grid_param['r_end'], dn)




        n_HII_grid = zeros_like(r_grid0)
        n_HeII_grid = zeros_like(r_grid0)
        n_HeIII_grid = zeros_like(r_grid0)

        self.create_table(param = param)
        N = r_grid.size
        n_HI = self.Gamma_grid_info['input']['n_HI']
        n_HeI = self.Gamma_grid_info['input']['n_HeI']
        points = (n_HI, n_HeI)

        if self.M >= 10 ** 8:
            method = 'LSODA'
            
        else:
            method = 'LSODA'

        while True:

            time_grid = []
            Ion_front_grid = []

            dn = self.grid_param['dn']

            n_HII0 = copy(n_HII_grid[:])
            n_HeII0 = copy(n_HeII_grid[:])
            n_HeIII0 = copy(n_HeIII_grid[:])
            n_HII_grid = zeros_like(r_grid)
            n_HeII_grid = zeros_like(r_grid)
            n_HeIII_grid = zeros_like(r_grid)

            T_grid = zeros_like(r_grid)
            T_grid += T_gamma.value * (1 + z_reion) ** 1 / (1 + 250)

            l = 0

            print('Number of time steps: ', int(math.ceil(self.grid_param['t_life'] / dt_init.value)))

            Gamma_info = self.Gamma_grid_info['Gamma']

            JHI_1, JHI_2, JHI_3 = Gamma_info['HI_1'], Gamma_info['HI_2'], Gamma_info['HI_3']
            JHeI_1, JHeI_2, JHeI_3, JHeII = Gamma_info['HeI_1'], Gamma_info['HeI_2'], Gamma_info['HeI_3'], Gamma_info[
                'HeII']
            JT_HI_1, JT_HeI_1, JT_HeII_1 = Gamma_info['T_HI_1'], Gamma_info['T_HeI_1'], Gamma_info['T_HeII_1']
            JT_2a, JT_2b = Gamma_info['T_2a'], Gamma_info['T_2b']
            while l * self.grid_param['dt_init'].value <= self.grid_param['t_life']:
                if l % 5 == 0 and l!=0:
                    print('Current Time step: ', l)

                # Calculate the redshift z(t)
                age = pl.age(z_reion)
                age = age.to(u.s)
                age += l * self.grid_param['dt_init']
                func = lambda z: pl.age(z).to(u.s).value - age.value
                zstar = fsolve(func, z_reion)

                # Initialize the values to evaluate the integrals
                K_HI = 0
                K_HeI = 0
                K_HeII = 0

                for k in (arange(0, r_grid.size, 1)):

                    table_grid = self.Gamma_grid_info['input']['r_grid']
                    dr_initial = table_grid[1]-table_grid[0]
                    dr_current = r_grid[1] - r_grid[0]
                    correction = dr_current / dr_initial


                    if k > 0:
                        dr_current = r_grid[k] - r_grid[k-1]
                        correction = dr_current / dr_initial


                        n_HI00 = n_H(zstar,C) - n_HII_grid[k - 1]

                        if n_HI00 < 0:
                            n_HI00 = 0
                        n_HeI00 = n_He(zstar, C) - n_HeII_grid[k - 1] - n_HeIII_grid[k - 1]

                        if n_HeI00 < 0:
                            n_HeI00 = 0
                        if n_HeI00 > n_He(zstar, C):
                            n_HeI00 = n_He(zstar, C)

                        K_HI += abs(nan_to_num(n_HI00)+nan_to_num(n_HeII_grid[k - 1]))*correction
                        K_HeI += abs(nan_to_num(n_HeI00))*correction
                        K_HeII += abs(nan_to_num(n_HeII_grid[k - 1]))*correction


                    if self.lifetime is not None and l * self.grid_param['dt_init'].value > (
                    (self.lifetime * u.Myr).to(u.s)).value:

                        I1_HI = 0
                        I2_HI = 0
                        I3_HI = 0

                        I1_HeI = 0
                        I2_HeI = 0
                        I3_HeI = 0

                        I1_HeII = 0

                        I1_T_HI = 0
                        I1_T_HeI = 0
                        I1_T_HeII = 0

                        I2_Ta = 0
                        I2_Tb = 0

                    else:

                        r2 = r_grid[k] ** 2
                        n_corr = exp(-dr_current*diff*K_HeII)
                        corr_ag = (integrate.quad(lambda x: x ** -self.alpha, E_0, E_upp)[0]) / (
                        integrate.quad(lambda x: x ** -self.alpha, E_0, 0.1 * E_upp)[0]) # numerical correction 
                        if self.M == self.Gamma_grid_info['input']['M']:
                            m_corr = 1
                        else:
                            m_corr = self.M/self.Gamma_grid_info['input']['M']


                        I1_HI = interpolate.interpn(points, JHI_1, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I2_HI = interpolate.interpn(points, JHI_2, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I3_HI = interpolate.interpn(points, JHI_3, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag

                        I1_HeI = interpolate.interpn(points, JHeI_1, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I2_HeI = interpolate.interpn(points, JHeI_2, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I3_HeI = interpolate.interpn(points, JHeI_3, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag

                        I1_HeII = interpolate.interpn(points, JHeII, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag

                        I1_T_HI = interpolate.interpn(points, JT_HI_1, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I1_T_HeI = interpolate.interpn(points, JT_HeI_1, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I1_T_HeII = interpolate.interpn(points, JT_HeII_1, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag

                        I2_Ta = interpolate.interpn(points, JT_2a, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag
                        I2_Tb = interpolate.interpn(points, JT_2b, (K_HI, K_HeI), method='linear') * n_corr * m_corr / r2 *corr_ag


                    def rhs(t, n):
                        """
                        Calculate the RHS of the radiative transfer equations.

                        RHS of the coupled nHII, n_HeII, n_HeIII and T equations. The equations are labelled as A,B,C,
                        and D and the rest of the variables are the terms contained in the respective equations.

                        Parameters
                        ----------
                        t : float
                         Time of evaluation in s.
                        n : array-like
                         1-D array containing the variables nHII, nHeII, nHeIII, T for evaluating the RHS.

                        Returns
                        -------
                        array_like
                         The RHS of the radiative transfer equations.
                        """

                        if isnan(n[0]) or isnan(n[1]) or isnan(n[2]) or isnan(n[3]):
                            print('Warning: calculations contain nan values, check the rhs')

                        n_HIIx = n[0]
                        n_HIx = n_H(zstar, C) - n[0]
                        if isnan(n_HIIx):
                            n_HIIx = n_H(zstar, C)
                            n_HIx = 0
                        if n_HIIx > n_H(zstar, C):
                            n_HIIx = n_H(zstar, C)
                            n_HIx = 0
                        if n_HIIx < 0:
                            n_HIIx = 0
                            n_HIx = n_H(zstar, C)

                        n_HeIIx = n[1]
                        n_HeIIIx = n[2]
                        n_HeIx = n_He(zstar, C) - n[1] - n[2]
                        if isnan(n_HeIIIx):
                            n_HeIIIx = n_He(zstar, C)
                            n_HeIIx = 0
                            n_HeIx = 0

                        if n_HeIIIx > n_He(zstar, C):
                            n_HeIIIx = n_He(zstar, C)
                            n_HeIIx = 0
                            n_HeIx = 0

                        if n_HeIIIx < 0:
                            n_HeIIIx = 0
                            n_HeIIx = 0
                            n_HeIx = n_He(zstar, C)

                        Tx = n[3]

                        if isnan(Tx):
                            print('Tx is nan')
                        if (Tx < T_gamma.value * (1 + zstar) ** 1 / (1 + 250)):
                            Tx = T_gamma.value * (1 + zstar) ** 1 / (1 + 250)

                        n_ee = n_HIIx + n_HeIIx + 2 * n_HeIIIx

                        mu = (n_H(zstar, C) + 4 * n_He(zstar, C)) / (
                                    n_H(zstar, C) + n_He(zstar, C) + n_ee)
                        n_B = n_H(zstar, C) + n_He(zstar, C) + n_ee

                        A1_HI = xi_HI(Tx) * n_HIx * n_ee
                        A1_HeI = xi_HeI(Tx) * n_HeIx * n_ee
                        A1_HeII = xi_HeII(Tx) * n_HeIIx * n_ee
                        A2_HII = eta_HII(Tx) * n_HIIx * n_ee
                        A2_HeII = eta_HeII(Tx) * n_HeIIx * n_ee
                        A2_HeIII = eta_HeIII(Tx) * n_HeIIIx * n_ee

                        A3 = omega_HeII(Tx) * n_ee * n_HeIIIx

                        A4_HI = psi_HI(Tx) * n_HIx * n_ee
                        A4_HeI = psi_HeI(Tx, n_ee, n_HeIIx) * n_ee
                        A4_HeII = psi_HeII(Tx) * n_HeIIx * n_ee

                        A5 = theta_ff(Tx) * (n_HIIx + n_HeIIx + 4 * n_HeIIIx) * n_ee

                        H = pl.H(zstar)
                        H = H.to(u.s ** -1)

                        A6 = (2 * H * kb * Tx * n_B / mu).value

                        A = gamma_HI(n_HIIx, n_HeIx, n_HeIIx, n_HeIIIx, Tx, I1_HI, I2_HI, I3_HI, zstar,C,  gamma_2c) * n_HIx - alpha_HII(
                            Tx) * n_HIIx * n_ee
                        B = gamma_HeI(n_HIIx, n_HeIx, n_HeIIx, n_HeIIIx, I1_HeI, I2_HeI, I3_HeI, zstar, C) * n_HeIx + beta_HeI(
                            Tx) * n_ee * n_HeIx - beta_HeII(Tx) * n_ee * n_HeIIx - alpha_HeII(
                            Tx) * n_ee * n_HeIIx + alpha_HeIII(Tx) * n_ee * n_HeIIIx - zeta_HeII(
                            Tx) * n_ee * n_HeIIx
                        Cc = gamma_HeII(I1_HeII) * n_HeIIx + beta_HeII(
                            Tx) * n_ee * n_HeIIx - alpha_HeIII(Tx) * n_ee * n_HeIIIx
                        Dd = (Tx / mu) * (-mu / (n_H(zstar, C) + n_He(zstar, C) + n_ee)) * (A + B + 2 * Cc)
                        D = (2 / 3) * mu / (kb.value * n_B) * (
                                    f_Heat(n_HIIx/n_H(zstar,C), zstar) * n_HIx * I1_T_HI + f_Heat(n_HIIx/n_H(zstar,C),
                                                                                       zstar) * n_HeIx * I1_T_HeI + f_Heat(
                                n_HIIx/n_H(zstar,C), zstar) * n_HeIIx * I1_T_HeII + sigma_s.value * n_ee / (m_e * c ** 2).value * (
                                            I2_Ta + Tx * I2_Tb) - (
                                            A1_HI + A1_HeI + A1_HeII + A2_HII + A2_HeII + A2_HeIII + A3 + A4_HI + A4_HeI + A4_HeII + A5 + A6)) + Dd

                        return ravel(array([A, B, Cc, D]))


                    y0 = zeros(4)
                    y0[0] = n_HII_grid[k]
                    y0[1] = n_HeII_grid[k]
                    y0[2] = n_HeIII_grid[k]
                    y0[3] = T_grid[k]

                    t_start_solve_TIME = datetime.datetime.now()
                    sol = integrate.solve_ivp(rhs, [l * dt_init.value, (l + 1) * dt_init.value], y0, method=method)

                    n_HII_grid[k] = sol.y[0, -1]
                    n_HeII_grid[k] = sol.y[1, -1]
                    n_HeIII_grid[k] = sol.y[2, -1]
                    T_grid[k] = nan_to_num(sol.y[3, -1])

                    if isnan(n_HII_grid[k]):
                        n_HII_grid[k] = n_H(zstar, C)

                    if n_HII_grid[k] > n_H(zstar, C):
                        n_HII_grid[k] = n_H(zstar, C)


                    if n_HeII_grid[k] > n_He(zstar, C):
                        n_HeII_grid[k] = n_He(zstar, C)
                        n_HeIII_grid[k] = 0

                    if isnan(n_HeIII_grid[k]):
                        n_HeIII_grid[k] = n_He(zstar, C)


                    if n_HeIII_grid[k] > n_He(zstar, C):
                        n_HeIII_grid[k] = n_He(zstar, C)
                        n_HeII_grid[k] = 0

                    if isnan(n_HeII_grid[k]):
                        print('Warning: Calculations contains NaNs.')
                        n_HeII_grid[k] =  n_He(zstar, C)-n_HeIII_grid[k]



                time_grid.append(l * self.grid_param['dt_init'].value)
                Ion_front_grid.append(find_Ifront(n_HII_grid/n_H(zstar,C), r_grid, zstar))
                l += 1

            r1 = find_Ifront(n_HII0/n_H(zstar,C),  r_grid0, zstar, show=True)
            r2 = find_Ifront(n_HII_grid/n_H(zstar,C),  r_grid, zstar, show=True)
            time_step = datetime.datetime.now()
            print('The accuracy is: ', abs((r1 - r2) / min(abs(r1), abs(r2))), ' -> 0.05 needed. It took : ', time_step-t_start_solver)
            if abs((r1 - r2) / min(abs(r1), abs(r2))) > 0.05 or r2 == self.r_start.value:

                if r2 == self.r_start.value:
                    print('Ionization front is still at the starting point. Starting again with smaller steps... ')
                r_grid0 = copy(r_grid[:])
                print('old:', r_grid0.size)
                r_grid = adaptive_mesh(r_grid0,1-n_HII_grid/n_H(zstar, C), 0.01, 0.99)
                print('new:', r_grid.size)


            else:
                time_grid = array([time_grid])
                time_grid = time_grid.reshape(time_grid.size, 1)
                Ion_front_grid = array([Ion_front_grid])
                Ion_front_grid = Ion_front_grid.reshape(Ion_front_grid.size, 1)
                time_end_solve = datetime.datetime.now()	
                print('solver took :', time_end_solve-t_start_solver)		
                break
        age = pl.age(self.z)
        age = age.to(u.s)
        age += self.evol
        func = lambda z: pl.age(z).to(u.s).value - age.value
        znow = fsolve(func, z_reion)
        self.n_HI_grid = n_H(znow,self.C) - n_HII_grid
        self.n_HII_grid = n_HII_grid
        self.n_HeI_grid = n_He(znow,self.C) - n_HeII_grid - n_HeIII_grid
        self.n_HeII_grid = n_HeII_grid
        self.n_HeIII_grid = n_HeIII_grid
        self.n_H = n_H(znow,self.C)
        self.n_He = n_He(znow,self.C)
        self.T_grid = T_grid
        self.r_grid = r_grid
        self.time_grid = time_grid
Ejemplo n.º 32
0
def backsplash_analysis_single_cluster(hdf_dir, cluster_name, plot_dir, snap):
    """ Backsplash analysis contamination for single cluster"""
    print('Analysing single object:', cluster_name)

    # Read in data.
    t0 = time.time()
    halo_data = pd.read_hdf(hdf_dir + cluster_name + '_tracking.hdf5',
                            'halo_evo', mode='r',
                            where="""var in \
                            [x_comov,y_comov,z_comov,redshift,snapid,hmass,gmass,mtot]""")
    cluster_data = pd.read_hdf(hdf_dir + cluster_name + '_tracking.hdf5',
                               'cluster_evo', mode='r',
                               where='var in [x_comov,y_comov,z_comov,rvir,redshift,hmass]')
    cluster_data = cluster_data.sort_index()
    print('Done data read in', time.time() - t0, 's')

    # Parameters
    redshift = cluster_data.loc[snap, 'redshift']
    rvir = cluster_data.loc[snap, 'rvir']
    masscut = 0  # 100 * 9e8

    # Calculate d_min vs d_z
    d_min, d_z, d = calculate_dmin_dz(halo_data, cluster_data, snap, rvir)

    # Find snapshot at which d_min occurs.
    idx_mins = d.groupby(['halo_id']).idxmin().values
    snap_mins = [x[0] for x in idx_mins]

    # Find properties of things at snapshot of d_min for later selection.
    # Pandas only slices unique snapshots, need loop.
    unique_snap_mins = np.unique(snap_mins)
    cluster_rvir_snaps = cluster_data.loc[snap_mins, 'rvir'].values
    redshift_at_snaps = cluster_data.loc[snap_mins, 'redshift'].values
    cluster_rvir_mins = np.zeros(np.size(snap_mins))
    dmin_redshifts = np.zeros(np.size(snap_mins))
    for i in range(0, np.size(unique_snap_mins)):
        ith_snap = unique_snap_mins[i]
        cluster_rvir_mins += (snap_mins == ith_snap) * \
            cluster_rvir_snaps[i]
        dmin_redshifts += (snap_mins == ith_snap) * \
            redshift_at_snaps[i]

    # Select out backsplash and calcukate percent.
    region_select, backsplash_select = select_backsplash(
        halo_data, snap, masscut, d_z, d_min)
    backsplash_percentage = calculate_backsplash_percent(halo_data,
                                                         region_select,
                                                         backsplash_select,
                                                         snap)

    # Plot parameters
    halo_mass = halo_data.loc[snap, :, 'hmass']
    gfrac = (halo_data.loc[snap, :, 'gmass'].values /
             halo_data.loc[snap, :, 'mtot'].values)
    time_since_dmin = WMAP7.age(redshift) - WMAP7.age(dmin_redshifts)

    # Plot parameters
    prop = [halo_mass.values, gfrac, time_since_dmin]
    plot_vmin = [halo_mass.values.min(), 1e-4, 1e-7]
    plot_vmax = [halo_mass.values.max(), gfrac.max(), 8]
    cbar_label = ['Halo mass', 'Gas fraction', r'Time since $D_{min}$ [Gyr]']
    scat_cmap = ['Blues', 'Greens', 'Purples']
    save_label = ['hm_', 'gfrac_', 'time_']

    # Plots of various properties.
    for i in range(0, len(prop)):
        dmin_vs_dz(snap, redshift, d_z, d_min, cluster_name,
                   backsplash_percentage, prop[i], plot_vmin[i],
                   plot_vmax[i], cbar_label[i], scat_cmap[i],
                   save_label[i], plot_dir)
    projected_backsplash_cluster(snap, redshift, plot_dir,
                                 cluster_name, halo_data,
                                 cluster_data, d_z, d_min)
Ejemplo n.º 33
0
if (args.calibration_run == 'True'):

    def epsilon_efficency_fct(Mh_in, size_in=1.0):
        '''
        This function returns an efficency from
        the calibrated distribution for a given halo mass.
        '''
        return (np.zeros(size_in))
else:
    epsilon_efficency_fct = read_in_efficency.read_in_efficency(
        path_SFH_cat + args.filename_efficiency)

# get SFH: random burst in last step

t_snapshots = 10**3 * cosmo.age(z_table_in).value  # in Myr

# split halo in bins


def get_halo_ids(number_of_bins, idx_halo_key=1.0, **kwargs):
    idx_all_halos = range(len(M_table_in))
    idx_bins_all_halos = np.array_split(idx_all_halos, number_of_bins)
    print idx_bins_all_halos[int(float(idx_halo_key)) - 1]
    return (idx_bins_all_halos[int(float(idx_halo_key)) - 1]
            )  # -1 since slurm counts from 1 (and not from 0)


idx_halo_considered = get_halo_ids(**run_params)

# loop over all halos
Ejemplo n.º 34
0
 def dLS(self):
     return cosmo.angular_diameter_distance_z1z2(
         self.__galaxy.redshift, self.__quasar.redshift).to('lyr')
Ejemplo n.º 35
0
 def calculateGravRad(mass, qz):
     linRG = (mass.to('kg') * const.G / const.c / const.c).to('m')
     angG = linRG / cosmo.angular_diameter_distance(qz).to('m')
     rgUnit = u.def_unit('r_g', angG * u.rad)
     return rgUnit
Ejemplo n.º 36
0
def main(datadir='/data',
         resultsdirs=['results'],
         plotsdir='plots',
         labels=['results'],
         counts_file='galaxy_counts.txt',
         snapnum_file='snapnum_redshift.csv',
         dwarf_limit=0.05,
         plotlabel='',
         evolution=False):
    """
    Plot results of Millennium Simulation compact group analysis
    """
    if not os.path.isdir(datadir):
        raise ValueError("{0} not found!".format(datadir))
    for resultsdir in resultsdirs:
        if not os.path.isdir(resultsdir):
            raise ValueError("{0} not found!".format(resultsdir))
    if not os.path.isdir(plotsdir):
        os.mkdir(plotsdir)
    if not os.path.exists(snapnum_file):
        raise ValueError("{0} not found!".format(snapnum_file))
    #
    # Read snapnum file to convert from snapnum to redshift
    #
    snap_to_z = pandas.read_csv(snapnum_file,
                                header=0,
                                comment='#',
                                skip_blank_lines=True,
                                index_col=0,
                                skipinitialspace=True)
    #
    # Determine number of snapnums we have in datadir
    #
    if evolution:
        data_snapnum_dirs = np.arange(64)
    else:
        data_snapnum_dirs = np.sort(
            glob.glob(os.path.join(datadir, 'snapnum_*')))
    print("Found {0} snapnum directories in {1}.".format(
        len(data_snapnum_dirs), datadir))
    if len(data_snapnum_dirs) == 0 and not os.path.exists(counts_file):
        return

    #
    # Count the number and standard devation of non-dwarf galaxies in raw data files
    #
    if os.path.exists(counts_file):
        print("Found {0}".format(counts_file))
    else:
        generate_snapnum_counts(datadir, data_snapnum_dirs, data_file,
                                dwarf_limit, counts_file)

    #
    # Read the galaxy counts file
    #
    galaxy_counts = pandas.read_csv(counts_file,
                                    header=0,
                                    comment='#',
                                    skip_blank_lines=True,
                                    index_col=0,
                                    skipinitialspace=True)

    #
    # Get results from each resultsdir
    #
    if evolution:
        num_members, num_members_std = data_read_in_evolution(
            resultsdirs, data_snapnum_dirs)

    else:
        members, groups, num_non_dwarf_members, non_dwarf_members, num_members_std, num_non_dwarf_members_std, num_groups_std = data_read_in(
            resultsdirs, data_snapnum_dirs, datadir)

    #
    # Convert snapnums to redshifts and to lookback times
    #
    snapnums = [snapnum for snapnum in range(len(data_snapnum_dirs))]
    redshifts = np.array([snap_to_z['Z'][snapnum] for snapnum in snapnums])
    lbtimes = WMAP7.lookback_time(redshifts).value
    plot_redshifts = [0.0, 0.1, 0.2, 0.3, 0.5, 1, 1.5, 2, 3, 5, 10]
    plot_lookback_times = WMAP7.lookback_time(plot_redshifts).value
    #
    colors = ['#d73027', '#fc8d59', '#fee090']
    symbols = ['o', 's', '^', '*', 'p']

    #
    # Make Evolution Plots
    #

    if evolution:
        plot_evolution(plotlabel, galaxy_counts, num_members, num_members_std,
                       resultsdirs, colors, symbols, lbtimes,
                       plot_lookback_times, plot_redshifts, plotsdir, labels)
        return

    #
    # Plot total number of compact groups vs. redshift
    #
    figname = os.path.join(plotsdir, '{0}_num_groups.eps'.format(plotlabel))
    num_cgs = np.array([[len(df) for df in groups[result_ind]]
                        for result_ind in range(len(resultsdirs))])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    for ind, (num_cg, num_cg_std) in enumerate(zip(num_cgs, num_groups_std)):
        ax.plot(lbtimes,
                num_cg,
                color=colors[ind],
                marker=symbols[ind],
                label=labels[ind])
        ax.fill_between(lbtimes,
                        num_cg - num_cg_std,
                        num_cg + num_cg_std,
                        facecolor=colors[ind],
                        edgecolor="none",
                        alpha=0.6)
    ax.set_xlabel('Lookback Time (Gyr)')
    ax.set_ylabel('Number of Compact Groups')
    ax.set_yscale('log')
    ax.set_xlim(0, WMAP7.age(0).to('Gyr').value)
    ax.set_ylim(1.e2, 1.e5)
    ax.legend(loc='best', fontsize=12, numpoints=1)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(plot_lookback_times)
    ax2.set_xticklabels(plot_redshifts)
    ax2.set_xlabel('Redshift')
    ax2.grid(False)
    plt.savefig(figname)
    plt.close()
    #
    # Plot total number of galaxies in compact groups vs. redshift
    #
    figname = os.path.join(plotsdir, '{0}_num_members.eps'.format(plotlabel))
    num_galaxies = np.array([[len(df) for df in non_dwarf_members[result_ind]]
                             for result_ind in range(len(resultsdirs))])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    for ind, (num_galaxy, num_galaxy_std) in enumerate(
            zip(num_galaxies, num_non_dwarf_members_std)):
        ax.plot(lbtimes,
                num_galaxy,
                color=colors[ind],
                marker=symbols[ind],
                label=labels[ind])
        ax.fill_between(lbtimes,
                        num_galaxy - num_galaxy_std,
                        num_galaxy + num_galaxy_std,
                        facecolor=colors[ind],
                        edgecolor='none',
                        alpha=0.6)
    ax.set_xlabel('Lookback Time (Gyr)')
    ax.set_ylabel('Number of non-dwarf Compact Group Members')
    ax.set_yscale('log')
    ax.legend(loc='best', fontsize=12, numpoints=1)
    ax.set_xlim(0, WMAP7.age(0).to('Gyr').value)
    ax.set_ylim(1.e3, 5.e5)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(plot_lookback_times)
    ax2.set_xticklabels(plot_redshifts)
    ax2.set_xlabel('Redshift')
    ax2.grid(False)
    plt.savefig(figname)
    plt.close()
    #
    # Plot fractional number of galaxies in compact groups vs. redshift
    #
    figname = os.path.join(plotsdir, '{0}_frac_galaxies.eps'.format(plotlabel))
    frac_galaxies = np.array([[
        len(df) / galaxy_counts['num_galaxies'][snapnum]
        for snapnum, df in enumerate(non_dwarf_members[result_ind])
    ] for result_ind in range(len(resultsdirs))])
    frac_galaxies_std = frac_galaxies * np.sqrt(
        np.array([[(num_galaxy_std / len(df))**2. +
                   (galaxy_counts['std_galaxies'][snapnum] /
                    galaxy_counts['num_galaxies'][snapnum])**2.
                   for snapnum, (df, num_galaxy_std) in enumerate(
                       zip(non_dwarf_members[result_ind],
                           num_non_dwarf_members_std[result_ind]))]
                  for result_ind in range(len(resultsdirs))]))
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    for ind, (frac_galaxy, frac_galaxy_std) in enumerate(
            zip(frac_galaxies, frac_galaxies_std)):
        ax.plot(lbtimes,
                100. * frac_galaxy,
                color=colors[ind],
                marker=symbols[ind],
                label=labels[ind])
        ax.fill_between(lbtimes,
                        100. * (frac_galaxy - frac_galaxy_std),
                        100. * (frac_galaxy + frac_galaxy_std),
                        facecolor=colors[ind],
                        edgecolor='none',
                        alpha=0.6)
    ax.set_xlabel('Lookback Time (Gyr)')
    ax.set_ylabel('Percent of non-dwarf Galaxies in Compact Groups')
    #ax.set_yscale('log')
    ax.legend(loc='best', fontsize=12, numpoints=1)
    ax.set_xlim(0, WMAP7.age(0).to('Gyr').value)
    ax.set_ylim(0., 1.5)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(plot_lookback_times)
    ax2.set_xticklabels(plot_redshifts)
    ax2.set_xlabel('Redshift')
    ax2.grid(False)
    plt.savefig(figname)
    plt.close()
    return
    #
    # Now with redshift
    #
    #
    # Plot total number of compact groups vs. redshift
    #
    num_cgs = [len(df) for df in groups]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    ax.plot(redshifts, num_cgs, 'k-')
    ax.plot(redshifts, num_cgs, 'ko')
    ax.set_xlabel('Redshift')
    ax.set_ylabel('Number of Compact Groups')
    ax.set_yscale('log')
    ax.set_xlim(0, 12)
    ax.set_ylim(1.e2, 1.e5)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(np.arange(13))
    ax2.set_xticklabels(WMAP7.lookback_time(np.arange(13)).value)
    ax2.set_xlabel('Lookback time (Gyr)')
    ax2.grid(False)
    plt.savefig('num_groups_z.eps')
    plt.close()
    #
    # Plot total number of galaxies in compact groups vs. redshift
    #
    num_galaxies = [len(df) for df in non_dwarf_members]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    ax.plot(redshifts, num_galaxies, 'k-')
    ax.plot(redshifts, num_galaxies, 'ko')
    ax.set_xlabel('Redshift')
    ax.set_ylabel('Number of non-dwarf Compact Group Members')
    ax.set_yscale('log')
    ax.set_xlim(0, 12)
    ax.set_ylim(1.e2, 1.e5)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(np.arange(13))
    ax2.set_xticklabels(WMAP7.lookback_time(np.arange(13)).value)
    ax2.set_xlabel('Lookback time (Gyr)')
    ax2.grid(False)
    plt.savefig('num_members_z.eps')
    plt.close()
    #
    # Plot fractional number of galaxies in compact groups vs. redshift
    #
    frac_galaxies = [
        len(df) / galaxy_counts['num_galaxies'][snapnum]
        for snapnum, df in enumerate(non_dwarf_members)
    ]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax2 = ax.twiny()
    ax.plot(redshifts, frac_galaxies, 'k-')
    ax.plot(redshifts, frac_galaxies, 'ko')
    ax.set_xlabel('Redshift')
    ax.set_ylabel('Fracion of non-dwarf Galaxies in Compact Groups')
    ax.set_xlim(0, 12)
    ax.set_ylim(1.e-4, 1.e-2)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(np.arange(13))
    ax2.set_xticklabels(WMAP7.lookback_time(np.arange(13)).value)
    ax2.set_xlabel('Lookback time (Gyr)')
    ax2.grid(False)
    plt.savefig('frac_galaxies_z.eps')
    plt.close()
    return
Ejemplo n.º 37
0
    F.DLA = d.zabs, 10**d.NH2 / (10**d.NHI + 2*10**d.NH2)

    pl.rc('font', size=14)
    #pl.rc('legend', fontsize=12)
    fig = pl.figure(figsize=(3.5, 3.7))
    fig.subplots_adjust(top=0.88, right=0.97, left=0.165, bottom=0.12)
    ax = pl.gca()
    fvals = np.array(list(np.log10(F.MWplane[1])) + list(np.log10(F.SMC[1])) + \
                              list(np.log10(F.LMC[1])))
    f0,f1,f2 = np.percentile(fvals[fvals > -20], [10,50, 90])

    ax.plot(0, f1, 'r^', ms=8, mew=0, label='$\mathrm{Local\ group}$',)
    ax.errorbar(0, f1, yerr=np.transpose([(f1-f0, f2-f1)]),
                ecolor='r', capsize=3, mew=1, fmt=None) 
    
    ax.plot(WMAP7.lookback_time(F.DLA[0]),np.log10(F.DLA[1]), 'ok', ms=5, mfc='none', mew=0.5, label='$z>1.5\ \ \mathrm{DLA/sub\,DLA}$')
    x = WMAP7.lookback_time(F.C[0])
    y = np.log10(F.C[1])
    ax.scatter(x,y, marker='o', c='k',s=70, zorder=10,linewidths=0.5,label='$\mathrm{This\ paper}$')
    plot([x,x], [y-0.36, y+0.36], 'k')


    ax.set_xlabel('$\mathrm{Lookback\  time\ (Gyr)}$')
    ax.set_ylabel('$\log_{10}\ f_{\mathrm{H}_2}$')
    ax.set_xlim(-0.9, 13.5)
    ax.set_ylim(-8.99, 0.49)

    leg = ax.legend(loc='lower left', frameon=0, scatterpoints=1)
    leg.get_frame().set_lw(0.5)

    ax1 = pl.twiny(ax)