예제 #1
0
def compute_scales(z_current):

    cosmo = FlatLambdaCDM(H0=70, Om0=0.3)

    # Age of universe at current z
    age = cosmo.age(z_current)

    # Compute redshift when universe was 10 Myr younger than current z
    z_10Myr = z_at_value(cosmo.age, cosmo.age(0.8) - (10. * u.Myr))

    # Compute scalefactors
    a_current = 1. / (1. + z_current)
    a_10Myr = 1. / (1. + z_10Myr)

    return a_current, a_10Myr
예제 #2
0
 def star_age(scale_factor):
     zform = [(1. / a) - 1. for a in scale_factor]
     cosmo = FlatLambdaCDM(H0=70.4, Om0=0.2726, Ob0=0.0456)
     tform = [float(cosmo.age(z) / u.Gyr) for z in zform
              ]  #time the stars formed in lookback time, not age
     tage = np.array([13.8 - t for t in tform])
     return tage
예제 #3
0
def test_fit_tofz(): 
    z_table, t_table = UT.zt_table()
    
    cosmo = FlatLambdaCDM(H0=70, Om0=0.274)

    prettyplot()
    fig = plt.figure()
    sub = fig.add_subplot(111)

    for deg in range(2,10): 
        coeff = UT.fit_tofz(deg)
        if deg > 5: 
            print 'deg = ', deg, coeff
        tofz = np.poly1d(coeff)
        
        z_arr = np.arange(0., 2., 0.1)
        t_arr = cosmo.age(z_arr).value 

        sub.plot(z_arr, (tofz(z_arr) - t_arr)/t_arr, label='Degree='+str(deg))

    t_of_z = interpolate.interp1d(z_arr, t_arr, kind='cubic') 
    tint = t_of_z(z_table[1:20])#np.interp(t_table[:20], t_arr, z_arr)

    sub.scatter(z_table[1:20], (t_table[1:20] - tint)/tint, c='k', s=30) 
    sub.plot(np.arange(0., 2., 0.1), np.repeat(-0.025, len(np.arange(0., 2., 0.1))), c='k', ls='--', lw=3)
    sub.plot(np.arange(0., 2., 0.1), np.repeat(0.025, len(np.arange(0., 2., 0.1))), c='k', ls='--', lw=3)

    sub.set_ylim([-0.05, 0.05])
    sub.set_xlim([0., 2.])
    sub.legend(loc='upper left')
    plt.show()
예제 #4
0
def mass_sfr(mass, SFR, redshift, scatter='t-Student', df=3, scale=0.3):
    #Speagle+ 14 - log(M*) = (0.84-0.026*t)logM - (6.51-0.11*t)
    #cosmology used in paper to calculate ages (t) is (h,omega_m,omega_lambda) = (0.7,0.3,0.7)
    #Shivaei+ 15 measure scatter in log(SFR(Halpha))-log(M*) to be 0.3 dex (corrected for uncertainties)
    #We employ cauchy scatter - although I think it should only be scatter in one direction...
    logM = np.log10(mass)
    logSFR = np.log10(SFR)

    cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
    t = cosmo.age(redshift).value
    mean_SFR = (0.84-0.026*t)*logM - (6.51-0.11*t)

    pdf = np.zeros(len(logM))

    for i in range(len(logSFR)):

        if scatter.lower() == 't-student':
            pdf[i] = stats.t.pdf(logSFR[i], df=df, loc=mean_SFR[i], scale=scale)
        elif scatter.lower() == 'gaussian':
            pdf[i] = stats.norm.pdf(logSFR[i], loc=mean_SFR[i], scale=0.3)
        elif scatter.lower() == 'cauchy':
            pdf[i] = stats.cauchy.pdf(logSFR[i], loc=mean_SFR[i], scale=0.3)
        else:
            raise ValueError('The input scatter '+scatter+' is not supported!')

    return pdf
예제 #5
0
def sim_pop(num_sim_gals, H0, toff, V, serr, zrange):
    z = np.linspace(0.3, 3, 1000)
    cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
    limcurve = cosmo.age(z).value

    cosmo = FlatLambdaCDM(H0=H0, Om0=0.3)
    curve = cosmo.age(z).value - toff

    zdist = np.random.rand(num_sim_gals) * (zrange[1] - zrange[0]) + zrange[0]
    icurve = interp1d(z, curve)(zdist)
    ilimcurve = interp1d(z, limcurve)(zdist)

    Voffset = []

    while len(Voffset) < num_sim_gals:
        initoff = np.random.normal(loc=0, scale=np.sqrt(V))
        if 0 < icurve[len(Voffset)] + initoff < ilimcurve[len(Voffset)]:
            Voffset.append(initoff)
        else:
            pass

    initsnr = []
    print('at snr')
    while len(initsnr) < num_sim_gals:
        initerr = np.random.normal(isnr(zdist[len(initsnr)]), 5.5)
        if initerr > 5:
            initsnr.append(initerr)
        else:
            pass
    rerr = (icurve + Voffset) / np.array(initsnr)
    Soffset = []

    while len(Soffset) < num_sim_gals:
        initoff = np.random.normal(loc=0, scale=rerr[len(Soffset)])
        if 0 < icurve[len(Soffset)] + Voffset[len(
                Soffset)] + initoff < ilimcurve[len(Soffset)]:
            Soffset.append(initoff)
        else:
            pass

    return zdist, icurve + np.array(Voffset) + np.array(Soffset), rerr
예제 #6
0
def ln_likelihood(pars):
    """ The likelihood function evaluation requires a particular set of model parameters and the data """
    H, toff, Va, lnVb = pars

    cosmo = FlatLambdaCDM(H0=H, Om0=0.3)
    V = -Va * rshifts + np.exp(lnVb)
    V[V < 0] = 0

    N = len(t50s)
    dy = t50s - (cosmo.age(rshifts).value - toff)
    ivar = 1 / (serr**2 + V)  # inverse-variance now includes intrinsic scatter

    return -0.5 * (N * np.log(2 * np.pi) - np.sum(np.log(ivar)) +
                   np.sum(dy**2 * ivar))
예제 #7
0
def Z_Calc(Time):
    cosmo = FlatLambdaCDM(H0=70., Om0=0.3)
    forcalc_x = []
    forcalc_y = []

    for i in range(100):
        forcalc_y.append(0.01 * (i + 1))
        forcalc_x.append(cosmo.age(0.01 * (i + 1)).value)

    curve = optimize.curve_fit(lambda t, a, b, c: a * t**-b + c,
                               forcalc_x,
                               forcalc_y,
                               p0=(2, 1, 0.5))

    return curve[0][0] * Time**-curve[0][1] + curve[0][2]
예제 #8
0
def age_hist(filename):
    
    ''' plot histograms for stellar age (taken from stellar formation time)
    '''
    stars = np.loadtxt('../data/%s'%filename)
    aform = np.array(stars[:,7]) #a= 1/(1+z) --> z = 1/a - 1
    aform = aform[aform >= 0.]
    print 'number of star particles', len(aform)
    zform = [(1./a) -1. for a in aform]
    cosmo = FlatLambdaCDM(H0=70.4, Om0=0.2726, Ob0=0.0456)
    tform = [float(cosmo.age(z)/u.Gyr) for z in zform] #time the stars formed in lookback time, not age
    tage = np.array([13.8-t for t in tform])
    tage = tage[tage <= 5.]
    print 'number of star particles < 5 Gyr old', len(tage)
    plt.figure()
    plt.hist(tage, bins=20, histtype='step', lw=2, weights=np.ones_like(tage)/len(tage), color='crimson')
    plt.xlabel('stellar ages [Gyr]')
    plt.title('M31 analog - Illustris %s'%filename[10:15])
    plt.savefig('stellar_age_hist_%s.pdf'%filename[10:15])
    plt.close()

    return 0
예제 #9
0
def singleSP_myfirefly(iz, age=1., mtot=1e8, zred=0.01):
    ''' fit the single stellar population file from `singleSP` using firefly 
    '''
    z_arr = np.array([0.5, 1.0, 2.0, 10**-1.301, 10**-1.302, 10**-2.301, 10**-2.302, 10**-0.6, 
        10**-0.9, 10**-1.2, 10**-1.6, 10**-1.9]) 

    f_spec = ''.join([UT.dat_dir(), 'SSP.iz', str(iz), '.age', str(age), '.z', str(zred), '.dat']) 
    wave, flux = np.loadtxt(f_spec, unpack=True, usecols=[0,1]) 
    wave_rest = wave/(1.+zred)
    err = flux * 0.001

    cosmo = FlatLambdaCDM(70., 0.3) 
    ffly = Fitters.myFirefly(cosmo, 
            model='m11', 
            model_lib='MILES', 
            imf='cha', 
            dust_corr=False,                        # no dust correction
            age_lim=[0., cosmo.age(zred).value],    # can't have older populations
            logZ_lim=[np.log10(z_arr[iz])-0.1, np.log10(z_arr[iz])+0.1])
    mask = ffly.emissionlineMask(wave_rest)
    ff_fit, ff_prop = ffly.Fit(wave, flux, err, zred, mask=mask, flux_unit=1.)
    
    print('total mass = %f' % ff_prop['logM_total']) 
    for i in range(ff_prop['n_ssp']): 
        print('--- SSP %i; weight=%f ---' % (i, ff_prop['weightLight_ssp_'+str(i)]))
        print('age = %f'% ff_prop['age_ssp_'+str(i)])
        print('log Z = %f'% ff_prop['logZ_ssp_'+str(i)])
        print('log M_tot = %f' % ff_prop['logM_total_ssp_'+str(i)])

    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.plot(ff_fit['wavelength'], ff_fit['flux'], label='SSP') 
    sub.plot(ff_fit['wavelength'], ff_fit['flux_model'], label='myFirefly best-fit') 
    sub.plot(ff_fit['wavelength'], ff_fit['flux'] - ff_fit['flux_model'], label='residual') 
    #sub.plot(wave_rest, flux, c='k', ls=':') 
    sub.set_xlim([3e3, 1e4]) 
    fig.savefig(''.join([UT.fig_dir(), 'myfirefly.SSP.iz', str(iz), '.age', str(age), '.z', str(zred), '.png']), 
            bbox_inches='tight')
    return None 
예제 #10
0
def ln_likelihood(pars):
    """ The likelihood function evaluation requires a particular set of model parameters and the data """
    H, toff, Va, lnVb = pars

    cosmo = FlatLambdaCDM(H0=H, Om0=0.3)
    z50l = np.repeat(True, len(t50s))
    for i in range(len(t50s)):
        z50l[i] = (t50s[i] * u.Gyr +
                   cosmo.lookback_time(rshifts[i])) > cosmo.lookback_time(3)

    rshifts = RSHIFTS[z50l]
    t50s = T50S[z50l]
    serr = SERR[z50l]

    V = -Va * rshifts + np.exp(lnVb)
    V[V < 0] = 0

    N = len(t50s)
    dy = t50s - (cosmo.age(rshifts).value - toff)
    ivar = 1 / (serr**2 + V)  # inverse-variance now includes intrinsic scatter

    return -0.5 * (N * np.log(2 * np.pi) - np.sum(np.log(ivar)) +
                   np.sum(dy**2 * ivar))
예제 #11
0
def Mass_Calculator(init_z, obs_z, sfh, number, n, T_min, component = 1, dblp = None):
    cosmol = FlatLambdaCDM(H0=70., Om0=0.3)
    age = cosmol.age(init_z).value*1e9
    Mass, Time = [], []
    SFHs = sfh['TimesMasses'][number]
    
    if T_min is None:
        peak_time = SFHs['BurstTime']*1e9
        tmin = peak_time - 4e8
        deltat = (age - tmin)/(n)
    elif T_min:
        tmin = T_min
        deltat = (age - tmin)/(n)
        
    if component == 'dblplaw':
        tau = dblp['tau']*10**9
        for i in range(n):
            x = sfh['Time'][sfh['Time'] > (age/(n -1))*i]
            y = ((x/tau)**dblp['alpha'] + (x/tau)**-dblp['beta'])**-1
            if (len(x) == 0) or (len(y) == 0):
                break
            Mass.append(simps(y, x)*-1)
            Time.append((age/(n -1))*i)          
            
        _f = interp1d(Time, max(Mass) - Mass)
        
        return(_f(obs_z)/max(Mass))
    
    for i in range(n):
        x = sfh['Time'][sfh['Time'] > (tmin + i*deltat)]
        y = sfh['lognormlist'][number][sfh['Time'] > (tmin + i*deltat)]
        Mass.append(simps(y, x)*-1)
        Time.append(tmin + i*deltat)
    
    _f = interp1d(Time, max(Mass) - Mass)
    
    return _f(obs_z)/max(Mass)
예제 #12
0
def predict_colour_for_loop(tq, tau, z):
    cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
    age = cosmo.age(z)
    print age
    #time = N.arange(0, 0.01, 0.003)
    #t = N.arange(0, 13.7, 0.01)
    #time = N.append(time, t[1:])
    time = N.arange(28.0)/2.0
    dir ='/Users/becky/Projects/Green-Valley-Project/bc03/models/Padova1994/chabrier/ASCII/'
    model = 'extracted_bc2003_lr_m62_chab_ssp.ised_ASCII'
    data = N.loadtxt(dir+model)
    sfr = N.zeros(len(time)*len(tq)*len(tau)).reshape(len(time), len(tq), len(tau))
    nuv_u = N.zeros_like(sfr)
    u_r = N.zeros_like(sfr)
    nuv_u_age = N.zeros(len(age)*len(tq)*len(tau)).reshape(len(age),len(tq), len(tau))
    u_r_age = N.zeros_like(nuv_u_age)
    for m in range(len(tq)):
        for n in range(len(tau)):
            sfr[:,m,n] = expsfh(tau[n], tq[m], time)
            total_flux = assign_fluxes.assign_total_flux(data[0,1:], data[1:,0], data[1:,1:], time*1E9, sfr[:,m,n])
            nuv_u[:,m,n], u_r[:,m,n] = get_colours(total_flux, data)
            nuv_u_age[:,m,n] = N.interp(age, time, nuv_u[:,m,n])
            u_r_age[:,m,n] = N.interp(age, time, u_r[:,m,n])
    return nuv_u_age, u_r_age
예제 #13
0
def Mass_Calculator(init_z, obs_z, sfh, number, n, T_min):
    cosmol = FlatLambdaCDM(H0=70., Om0=0.3)
    age = cosmol.age(init_z).value * 1e9
    #point = MyCosmology.cosmocal(obs_z)['ageAtZ']*1e9
    Mass, Time = [], []
    SFHs = sfh['TimesMasses'][number]

    if T_min is None:
        peak_time = SFHs['BurstTime'] * 1e9
        tmin = peak_time - 4e8
        deltat = (age - tmin) / (n)
    elif T_min:
        tmin = T_min
        deltat = (age - tmin) / (n)

    for i in range(n):
        x = sfh['Time'][sfh['Time'] > (tmin + i * deltat)]
        y = sfh['lognormlist'][number][sfh['Time'] > (tmin + i * deltat)]
        Mass.append(simps(y, x) * -1)
        Time.append(tmin + i * deltat)

    _f = interp1d(Time, max(Mass) - Mass)

    return _f(obs_z) / max(Mass)
예제 #14
0
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import warnings

import scipy.io as sio

from astropy.cosmology import FlatLambdaCDM

cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
cosmo.age(1)

import seaborn as sns
import pandas as pd
from astropy.io import fits

sns.set(font_scale=2)
sns.set_style("whitegrid")

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d

import statsmodels.api as sm

lowess = sm.nonparametric.lowess

#----------import catalogs----------------------------

warnings.filterwarnings('ignore')

candels_cat_z1 = np.loadtxt('catalogs/CANDELS_GDSS_workshop_z1.dat')
예제 #15
0
class RAMSESDataset(Dataset):
    _index_class = RAMSESIndex
    _field_info_class = RAMSESFieldInfo
    gamma = 1.4  # This will get replaced on hydro_fn open

    def __init__(
        self,
        filename,
        dataset_type="ramses",
        fields=None,
        storage_filename=None,
        units_override=None,
        unit_system="cgs",
        extra_particle_fields=None,
        cosmological=None,
        bbox=None,
        max_level=None,
        max_level_convention=None,
    ):
        # Here we want to initiate a traceback, if the reader is not built.
        if isinstance(fields, str):
            fields = field_aliases[fields]
        """
        fields:
        An array of hydro variable fields in order of position in the
        hydro_XXXXX.outYYYYY file. If set to None, will try a default set of fields.

        extra_particle_fields:
        An array of extra particle variables in order of position in the
        particle_XXXXX.outYYYYY file.

        cosmological:
        If set to None, automatically detect cosmological simulation.
        If a boolean, force its value.
        """

        self._fields_in_file = fields
        # By default, extra fields have not triggered a warning
        self._warned_extra_fields = defaultdict(lambda: False)
        self._extra_particle_fields = extra_particle_fields
        self.force_cosmological = cosmological
        self._bbox = bbox

        self._force_max_level = self._sanitize_max_level(
            max_level, max_level_convention
        )

        file_handler = RAMSESFileSanitizer(filename)

        # This should not happen, but let's check nonetheless.
        if not file_handler.is_valid:
            raise ValueError(
                "Invalid filename found when building a RAMSESDataset object: %s",
                filename,
            )

        # Sanitize the filename
        info_fname = file_handler.info_fname

        if file_handler.group_name is not None:
            self.num_groups = len(
                [_ for _ in file_handler.root_folder.glob("group_?????") if _.is_dir()]
            )
        else:
            self.num_groups = 0
        self.root_folder = file_handler.root_folder

        Dataset.__init__(
            self,
            info_fname,
            dataset_type,
            units_override=units_override,
            unit_system=unit_system,
        )

        # Add the particle types
        ptypes = []
        for PH in get_particle_handlers():
            if PH.any_exist(self):
                ptypes.append(PH.ptype)

        ptypes = tuple(ptypes)
        self.particle_types = self.particle_types_raw = ptypes

        # Add the fluid types
        for FH in get_field_handlers():
            FH.purge_detected_fields(self)
            if FH.any_exist(self):
                self.fluid_types += (FH.ftype,)

        self.storage_filename = storage_filename

    @staticmethod
    def _sanitize_max_level(max_level, max_level_convention):
        # NOTE: the initialisation of the dataset class sets
        #       self.min_level _and_ requires force_max_level
        #       to be set, so we cannot convert from to yt/ramses
        #       conventions
        if max_level is None and max_level_convention is None:
            return (2 ** 999, "yt")

        # Check max_level is a valid, positive integer
        if not isinstance(max_level, (int, np.integer)):
            raise TypeError(
                f"Expected `max_level` to be a positive integer, got {max_level} "
                f"with type {type(max_level)} instead."
            )
        if max_level < 0:
            raise ValueError(
                f"Expected `max_level` to be a positive integer, got {max_level} "
                "instead."
            )

        # Check max_level_convention is set and acceptable
        if max_level_convention is None:
            raise ValueError(
                f"Received `max_level`={max_level}, but no `max_level_convention`. "
                "Valid conventions are 'yt' and 'ramses'."
            )
        if max_level_convention not in ("ramses", "yt"):
            raise ValueError(
                f"Invalid convention {max_level_convention}. "
                "Valid choices are 'yt' and 'ramses'."
            )
        return (max_level, max_level_convention)

    def create_field_info(self, *args, **kwa):
        """Extend create_field_info to add the particles types."""
        super().create_field_info(*args, **kwa)
        # Register particle filters
        if ("io", "particle_family") in self.field_list:
            for fname, value in particle_families.items():

                def loc(val):
                    def closure(pfilter, data):
                        filter = data[(pfilter.filtered_type, "particle_family")] == val
                        return filter

                    return closure

                add_particle_filter(
                    fname, loc(value), filtered_type="io", requires=["particle_family"]
                )

            for k in particle_families.keys():
                mylog.info("Adding particle_type: %s", k)
                self.add_particle_filter(f"{k}")

    def __repr__(self):
        return self.basename.rsplit(".", 1)[0]

    def _set_code_unit_attributes(self):
        """
        Generates the conversion to various physical _units based on the parameter file
        """
        # loading the units from the info file
        boxlen = self.parameters["boxlen"]
        length_unit = self.parameters["unit_l"]
        density_unit = self.parameters["unit_d"]
        time_unit = self.parameters["unit_t"]

        # calculating derived units (except velocity and temperature, done below)
        mass_unit = density_unit * length_unit ** 3
        magnetic_unit = np.sqrt(4 * np.pi * mass_unit / (time_unit ** 2 * length_unit))
        pressure_unit = density_unit * (length_unit / time_unit) ** 2

        # TODO:
        # Generalize the temperature field to account for ionization
        # For now assume an atomic ideal gas with cosmic abundances (x_H = 0.76)
        mean_molecular_weight_factor = _X ** -1

        setdefaultattr(self, "density_unit", self.quan(density_unit, "g/cm**3"))
        setdefaultattr(self, "magnetic_unit", self.quan(magnetic_unit, "gauss"))
        setdefaultattr(self, "pressure_unit", self.quan(pressure_unit, "dyne/cm**2"))
        setdefaultattr(self, "time_unit", self.quan(time_unit, "s"))
        setdefaultattr(self, "mass_unit", self.quan(mass_unit, "g"))
        setdefaultattr(
            self, "velocity_unit", self.quan(length_unit, "cm") / self.time_unit
        )
        temperature_unit = (
            self.velocity_unit ** 2 * mp * mean_molecular_weight_factor / kb
        )
        setdefaultattr(self, "temperature_unit", temperature_unit.in_units("K"))

        # Only the length unit get scales by a factor of boxlen
        setdefaultattr(self, "length_unit", self.quan(length_unit * boxlen, "cm"))

    def _parse_parameter_file(self):
        # hardcoded for now
        # These should be explicitly obtained from the file, but for now that
        # will wait until a reorganization of the source tree and better
        # generalization.
        self.dimensionality = 3
        self.refine_by = 2
        self.parameters["HydroMethod"] = "ramses"
        self.parameters["Time"] = 1.0  # default unit is 1...

        # We now execute the same logic Oliver's code does
        rheader = {}

        def read_rhs(f, cast):
            line = f.readline().replace("\n", "")
            p, v = line.split("=")
            rheader[p.strip()] = cast(v.strip())

        with open(self.parameter_filename) as f:
            for _ in range(6):
                read_rhs(f, int)
            f.readline()
            for _ in range(11):
                read_rhs(f, float)
            f.readline()
            read_rhs(f, str)
            # This next line deserves some comment.  We specify a min_level that
            # corresponds to the minimum level in the RAMSES simulation.  RAMSES is
            # one-indexed, but it also does refer to the *oct* dimensions -- so
            # this means that a levelmin of 1 would have *1* oct in it.  So a
            # levelmin of 2 would have 8 octs at the root mesh level.
            self.min_level = rheader["levelmin"] - 1
            # Now we read the hilbert indices
            self.hilbert_indices = {}
            if rheader["ordering type"] == "hilbert":
                f.readline()  # header
                for _ in range(rheader["ncpu"]):
                    dom, mi, ma = f.readline().split()
                    self.hilbert_indices[int(dom)] = (float(mi), float(ma))

        if rheader["ordering type"] != "hilbert" and self._bbox is not None:
            raise NotImplementedError(
                "The ordering %s is not compatible with the `bbox` argument."
                % rheader["ordering type"]
            )
        self.parameters.update(rheader)
        self.domain_left_edge = np.zeros(3, dtype="float64")
        self.domain_dimensions = np.ones(3, dtype="int32") * 2 ** (self.min_level + 1)
        self.domain_right_edge = np.ones(3, dtype="float64")
        # This is likely not true, but it's not clear
        # how to determine the boundary conditions
        self._periodicity = (True, True, True)

        if self.force_cosmological is not None:
            is_cosmological = self.force_cosmological
        else:
            # These conditions seem to always be true for non-cosmological datasets
            is_cosmological = not (
                rheader["time"] >= 0 and rheader["H0"] == 1 and rheader["aexp"] == 1
            )

        if not is_cosmological:
            self.cosmological_simulation = 0
            self.current_redshift = 0
            self.hubble_constant = 0
            self.omega_matter = 0
            self.omega_lambda = 0
        else:
            self.cosmological_simulation = 1
            self.current_redshift = (1.0 / rheader["aexp"]) - 1.0
            self.omega_lambda = rheader["omega_l"]
            self.omega_matter = rheader["omega_m"]
            self.hubble_constant = rheader["H0"] / 100.0  # This is H100

        force_max_level, convention = self._force_max_level
        if convention == "yt":
            force_max_level += self.min_level + 1
        self.max_level = min(force_max_level, rheader["levelmax"]) - self.min_level - 1

        if self.cosmological_simulation == 0:

            self.current_time = self.parameters['time']
        else :
            self.cosmology=FlatLambdaCDM(H0=100*self.hubble_constant,Om0=self.omega_matter)
            self.current_time=unyt_quantity.from_astropy(self.cosmology.age(self.current_redshift))
            '''
            self.tau_frw, self.t_frw, self.dtau, self.n_frw, self.time_tot = friedman(
                self.omega_matter,
                self.omega_lambda,
                1.0 - self.omega_matter - self.omega_lambda,
            )

            age = self.parameters["time"]
            iage = 1 + int(10.0 * age / self.dtau)
            iage = np.min([iage, self.n_frw // 2 + (iage - self.n_frw // 2) // 10])

            try:
                self.time_simu = self.t_frw[iage] * (age - self.tau_frw[iage - 1]) / (
                    self.tau_frw[iage] - self.tau_frw[iage - 1]
                ) + self.t_frw[iage - 1] * (age - self.tau_frw[iage]) / (
                    self.tau_frw[iage - 1] - self.tau_frw[iage]
                )

            self.current_time = (
                (self.time_tot + self.time_simu)
                / (self.hubble_constant * 1e7 / 3.08e24)
                / self.parameters["unit_t"]
            )
            '''

        if self.num_groups > 0:
            self.group_size = rheader["ncpu"] // self.num_groups

        # Read namelist.txt file (if any)
        self.read_namelist()

    def read_namelist(self):
        """Read the namelist.txt file in the output folder, if present"""
        namelist_file = os.path.join(self.root_folder, "namelist.txt")
        if os.path.exists(namelist_file):
            try:
                with open(namelist_file) as f:
                    nml = f90nml.read(f)
            except ImportError as e:
                nml = f"An error occurred when reading the namelist: {str(e)}"
            except (ValueError, StopIteration) as err:
                mylog.warning(
                    "Could not parse `namelist.txt` file as it was malformed:",
                    exc_info=err,
                )
                return

            self.parameters["namelist"] = nml

    @classmethod
    def _is_valid(cls, filename, *args, **kwargs):
        return RAMSESFileSanitizer(filename).is_valid
예제 #16
0
gv = gv_o[gv_o[:,5]==1]
print len(gv)

#Set properties
u_r_gal = gv[:,0]
u_r_gal_sigma = gv[:,6]
nuv_u_gal = gv[:,1]
nuv_u_gal_sigma = gv[:,7]


#Calculate ages of galaxies (assuming look back time) using measured redshift
age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/age_smooth.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path == False:
    age = N.array(cosmo.age(smooth[:,8]))
    N.save(age_save, age)
else:
    age = N.load(age_save)

col_gal = N.array([u_r_gal, nuv_u_gal])
sigma_gal = N.array([u_r_gal_sigma, nuv_u_gal_sigma])

#Define model properties
time = N.linspace(0.0, cosmo.age(0.0), 50) # In Gyrs
tau = N.linspace(0.001, 2.5, 50)
taus = N.outer(tau, N.ones(len(tau)))
#tq = N.array([8,9,10])
tq = N.linspace(0.0, 13.7, 50)
tqs = N.outer(N.ones(len(tq)), tq)
ext = (N.min(tq), N.max(tq), N.min(tau), N.max(tau))
예제 #17
0
파일: sfr_df.py 프로젝트: gavrodge/shp
cosmo = FlatLambdaCDM(H0=68., Om0=0.3)

# Load up snap file
snap_file = h5py.File('snap_m100n1024_151.hdf5','r')

# Extract arrays of star particle information from snap file
all_star_masses = np.array(snap_file["PartType4"]["Masses"])
all_star_ids = np.array(snap_file["PartType4"]["ParticleIDs"])
all_star_ages = np.array(snap_file["PartType4"]["StellarFormationTime"])

# Set up pandas dataframe with star particle information
df = pd.DataFrame(data=np.c_[all_star_ids, all_star_masses, all_star_ages],index=all_star_ids,columns=["ID", "mass", "formation_time"])

# Do unit conversions
df["formation_redshift"] = (1./np.copy(df["formation_time"].values)) - 1.
df["formation_time"] = cosmo.age(df["formation_redshift"]).value # Units to Gyr
df["mass"] *= 10**10 # Units from 10^10 Solar masses/h to Solar masses/h
df["mass"] /= 0.68 # Units from Solar masses/h to Solar masses

# Save star particle table to normal fits file
tab = Table.from_pandas(df)
fits.BinTableHDU(data=tab).writeto("star_data.fits", overwrite=True)

# Loading the table up again
tab = Table.read("star_data.fits").to_pandas()

print(tab)
mass_array = tab["mass"].values

star_data_array = tab.values
snList= n.array(glob.glob(os.path.join(os.environ["HOME"], 'MD04', "hlists", "hlist_*.list")))
snList.sort()
	
out_name = os.path.join(os.environ["HOME"], 'MD04', 'output_MD_0.4Gpc.fits')

names = n.array([el.split('_')[-1][:-5] for el in snList])
aexps =names.astype('float')

redshift = 1./n.array(aexps)-1.
dCom = cosmoMD.comoving_distance(redshift)
ids = n.argsort(redshift)
col0 = fits.Column(name='snap_name'	,format='A4', array = n.array(names)[ids] )
col2 = fits.Column(name='aexp'		,format='D', array = n.array(aexps)[ids] )
col3 = fits.Column(name='redshift'	,format='D', array = redshift[ids] )
col4 = fits.Column(name='comoving_distance',format='D', array= dCom.value[ids] )
age_yr = 10**9* cosmoMD.age(redshift).value
col5 = fits.Column(name='age_yr'		,format='D', array = age_yr[ids] )
array = cosmoMD.arcsec_per_kpc_comoving(redshift).value*3.6
col6 = fits.Column(name='deg_per_Mpc_comoving', format='D', array = array[ids] )


#define the table hdu 
hdu_cols  = fits.ColDefs([col0, col2, col3, col4, col5, col6])#, col7, col8, col9, col10])
tb_hdu = fits.BinTableHDU.from_columns( hdu_cols )
#define the header
prihdr = fits.Header()
prihdr['sim'] = 'SMD'
prihdr['author'] = 'JC'
prihdu = fits.PrimaryHDU(header=prihdr)
#writes the file
thdulist = fits.HDUList([prihdu, tb_hdu])
예제 #19
0
print len(smooth)
disc = colours[colours[:,3] > 0.8]
print len(disc)
red_s = colours[colours[:,0] > colours[:,10]]
print len(red_s)
blue_c = colours[colours[:,0] < colours[:,11]]
print len(blue_c)
inter = colours[colours[:,3] < 0.8]
inter = inter[inter[:,2] < 0.8]
print len(inter)

age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/inter/age_inter.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(inter[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)

w = [7.5, 1.5, 7.0, 1.5, 4.0, 1.5, 4.0, 1.5]
nwalkers = 150
nsteps = 400
start = [7.5, 1.5, 7.5, 1.5]

f = open('/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/log.txt', 'a')
f.write('Run started at '+str(time.strftime('%H:%M'))+' on '+str(time.strftime('%d/%m/%y'))+'\n')
f.write('Reason for running iteration: ' +reason+'\n')
f.write('Number of walkers : '+str(nwalkers)+'\n')
f.write('Number of steps :'+str(nsteps)+'\n')
예제 #20
0
from posterior import *
from astropy.cosmology import FlatLambdaCDM
import numpy as N
import sys

# Use sys to assign arguments for the galaxy data from the command line
u_r, err_u_r, nuv_u, err_nuv_u, z, dr8, ra, dec = sys.argv[1:]

# Use astropy to calculate the age from the redshift in the data 
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
age = N.array(cosmo.age(float(z)))

# Define parameters needed for emcee 
nwalkers = 100 # number of monte carlo chains
nsteps= 400 # number of steps in the monte carlo chain
start = [7.5, 1.5] # starting place of all the chains
burnin = 400 # number of steps in the burn in phase of the monte carlo chain

#The rest calls the emcee module which is initialised in the sample function of the posterior file. 
samples, samples_save = sample(2, nwalkers, nsteps, burnin, start, float(u_r), float(err_u_r), float(nuv_u), float(err_nuv_u), age, dr8)
tq_mcmc, tau_mcmc,  = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]), zip(*N.percentile(samples, [16,50,84],axis=0)))
fig = corner_plot(samples, labels = [r'$ t_{quench}$', r'$ \tau$'], extents=[[N.min(samples[:,0]), N.max(samples[:,0])],[N.min(samples[:,1]),N.max(samples[:,1])]], bf=[tq_mcmc, tau_mcmc], id=dr8)
fig.savefig('starpy_output_'+str(dr8)+'.pdf')
print 'Best fit [t, tau] values found by starpy for input parameters are : [', tq_mcmc[0], tau_mcmc[0], ']'
예제 #21
0
import numpy as N
import pylab as P
import scipy as S
import pyfits as F
from t_tau_func import *
from astropy.cosmology import FlatLambdaCDM

cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
z = N.linspace(0.0001, 100, 500)
a = N.array(cosmo.age(z))
#av_z = 0.076401
#age = cosmo.age(av_z).value
age=12.878505072906682

font = {'family':'serif', 'size':16}
P.rc('font', **font)
P.rc('xtick', labelsize='medium')
P.rc('ytick', labelsize='medium')
P.rc('axes', labelsize='medium')


#
tq = N.linspace(0.0, 13.8, 75)
tau = N.linspace(0.001, 3, 75)

tqs = N.outer(tq, N.ones(len(tq)))
taus = N.outer(N.ones(len(tau)), tau)

time = N.arange(0, 0.01, 0.003)
t = N.linspace(0, 13.7, 200)
t = N.append(time, t[1:])
예제 #22
0
파일: run.py 프로젝트: rjsmethurst/hyper
gvf = colours[colours[:, 8] == 1]
gv = gvf[gvf[:, 9] == 1]

red_s = colours[colours[:, 0] > colours[:, 10]]
blue_c = colours[colours[:, 0] < colours[:, 11]]
gv_s = gv[gv[:, 2] >= 0.8]
gv_d = gv[gv[:, 3] >= 0.8]
gv_clean = N.append(gv_s, gv_d, axis=0)

hund = blue_c[:10, :]

N.save("bc_" + str(len(hund)) + ".npy", hund)


cosmo = FlatLambdaCDM(H0=71.0, Om0=0.26)
age = N.array(cosmo.age(hund[:, 6]))

w = [7.5, 1.5, 7.0, 1.5, 4.0, 1.5, 4.0, 1.5]
nwalkers = 100
nsteps = 400
start = [7.5, 1.5]
burnin = 400

X = N.linspace(0, 14, 100)
Y = N.linspace(0, 5, 100)

sums = N.zeros((len(X) - 1, len(Y) - 1))
sumd = N.zeros((len(X) - 1, len(Y) - 1))

# w is the prior conditions on my theta parameters - the mean and standard deviation of tq and tau for the disc and smooth populations
# w = [mu_tqs, mu_taus, mu_tqd, mu_taud, sig_tqs, sig_taus, sig_tqd, sig_taud]
예제 #23
0
disc = colours[colours[:, 3] > 0.8]
print len(disc)
red_s = colours[colours[:, 0] > colours[:, 10]]
print len(red_s)
blue_c = colours[colours[:, 0] < colours[:, 11]]
print len(blue_c)
# disc = colours[colours[:,3]==1]
# smooth = colours[colours[:,2]==1]
# inter = colours[[colours[:,2]!=1][:,3]!=1]

# Calculating the look back time from the observed redshift assuming this time is also the age of the galaxy at which you're observing it
age_save = "/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/blue_cloud/age_blue_cloud.npy"
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0=71.0, Om0=0.26)
if age_path == False:
    age = N.array(cosmo.age(blue_c[:, 6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)
#
# if len(age) != len(gv):
#    raise SystemExit('Number of ages does not coincide with number of galaxies...')

# w is the prior conditions on my theta parameters - the mean and standard deviation of tq and tau for the disc and smooth populations
# w = [mu_tqs, mu_taus, mu_tqd, mu_taud, sig_tqs, sig_taus, sig_tqd, sig_taud]
w = [9.0, 1.25, 9.0, 1.25, 2.0, 0.5, 2.0, 0.5]
nwalkers = 100
start_time = time.time()
# The rest calls the emcee code and makes plots....
samples, fig = sample(
예제 #24
0
class CosmicIntegrator(object):
    """

    The cosmological integrator calculates the rate 
    an object given the SFR that went into it at birth

    The entire class consists of several subclasses and their instances
    are done in this order (since they are dependent of each other)


    -Class cosmo: Astropy class from python library to set the cosmological relations
                  betweeN luminosity distance, redshift, age univere etc. We define it once
                  here so we can consistently pass around in other classes.


    -Class MergerTimes: Creates the numpy arrays for the shells at which we calculate
                        The mergers. In turn it also creates the lookback times for the systems
                        of the Data class

    -Class MSSFR: Class that calculates the metallicity Specific StarFormation rate
                  for each inidividual object at each individual merger time of interest

    Each class lives in a seperate file (except cosmo which is inbuilt library astropy

    
    """

    def __init__(self, fileName=None, pathCOMPAS=None, Cosmology='WMAP',hubbleConstant = 67.8,\
                omegaMatter=0.308,redshiftFirstSFR=10., \
                minRedshift=0.0,   maxRedshift=2., nrRedshiftBins=20,\
                RedshiftTabulated =True, RedshiftTabulatedResolution=100000,
                GWdetector_sensitivity='O1', GWdetector_snrThreshold=8, verbose = False):

        #################################################
        #                                               #
        #     initialize universe and shell integral    #
        #                                               #
        #################################################

        #Define topology universe using astropy
        self.verbose                  = verbose
        self.pathCOMPAS               = pathCOMPAS
        self.fileName                 = fileName

        if Cosmology == 'WMAP':
            self.cosmology            = WMAP9
        if Cosmology == 'Custom Flat':
            self.cosmology            = FlatLambdaCDM(H0=hubbleConstant *\
                                        u.km / u.s / u.Mpc, Om0=omegaMatter)
        self.redshiftFirstSFR         = redshiftFirstSFR
        self.ageFirstSFR              = self.cosmology.age(self.redshiftFirstSFR).value
        
        #These are the redshifts shells we integrate over
        self.minRedshift              = minRedshift
        self.maxRedshift              = maxRedshift
        self.nrRedshiftBins           = nrRedshiftBins
        #These are set by function
        self.Shell_centerRedshift     = None
        self.Shell_volume             = None
        self.Shell_dz                 = None
        self.Shell_luminosityDistance = None
        self.createConcentricRedshiftShells()


        ################################################################
        #     initialize classCOMPAS popsynth                          #
        #     uses dummy variables which dont work such that           #
        #     user HAS TO define it and check their input              #
        ################################################################
        print("reminders of what to set in the following order:")
        print()

        if self.verbose:
            print("Creating instance COMPAS class User has to still set DCO and Data")
        #setting Mlower/Mupper etc to None to force warning for user
        if fileName is None:
            # ClassCOMPAS will assume default filename "COMPAS_output.h5"
            self.COMPAS  = ClassCOMPAS.COMPASData(path=self.pathCOMPAS, lazyData=True,\
                                              Mlower=None, Mupper=None, \
                                              binaryFraction=None)
        else:
            self.COMPAS  = ClassCOMPAS.COMPASData(path=self.pathCOMPAS, fileName=fileName, lazyData=True,\
                                              Mlower=None, Mupper=None, \
                                              binaryFraction=None)

        #####################################################
        #     set the MSSFR class                           #
        #####################################################
        if self.verbose:
            print("Creating instance MSSFR class User has to still set grid")
        self.MSSFR = ClassMSSFR.MSSFR(metallicityGrid=None, cosmo=self.cosmology)       

        #additionally needed for sensitivity
        self.GWdetector_sensitivity     = GWdetector_sensitivity
        self.GWdetector_snrThreshold    = GWdetector_snrThreshold

        print("ClassCosmicIntegrator: Remember to setBirthTimesAnd2Darrays()")
        print("                        to prepare calculation/results")
        print("                        do you have the GW-detector you want?")

        #################################################
        #                                               #
        #     the eventual results of interest          #
        #     if we already have data we can set it     #
        #     else we have to manually call tis function#
        #################################################
        #Calculating birth age is simple subtraction age-merger -delaytime
        self.PerSystemPerRedshift_ageBirth       = None
        #Cannot do this in redshift so convert table above to a redshift table
        self.PerSystemPerRedshift_redshiftBirth  = None
        # dN Gpc-3 per year at z=redshift.     #each row is redshift merger
        self.PerSystemPerRedshift_ratesIntrinsic = None
        # dN per year in detector from shell 
        self.PerSystemPerRedshift_ratesObserved  = None

        self.RedshiftTabulated                   = RedshiftTabulated
        self.RedshiftTabulatedResolution         = RedshiftTabulatedResolution
        self.redshiftAgeTable                    = None 
        

    def createConcentricRedshiftShells(self):
        if self.verbose:
            print("Creating redshift shells for integral")

        #Thanx Jim Barrett for cleaning up this part a bit :D
        #Flat universe with Hubble constant of 70 and OmegaM of 0.3
        redshiftEdges = np.linspace(self.minRedshift,\
                                    self.maxRedshift,\
                                    self.nrRedshiftBins+1) #The bin edges in redshift
        #Central value of each redshift bin, this is the value used in cosmic Int
        self.Shell_dz             = np.diff(redshiftEdges)
        self.Shell_centerRedshift = 0.5*(redshiftEdges[:-1] + redshiftEdges[1:])      
        #Corresponding luminosity Distances [Mpc]
        self.Shell_luminosityDistance = \
        [x.value for x in self.cosmology.luminosity_distance(self.Shell_centerRedshift)] 

        #cosmology.comoving volume is in units of Mpc^-3
        #The line below translates this to Gpc^-3 (times 1e-9) 
        #and gives me the spehrical volume of each redshift bin.
        comovEdges    = [x.value*1e-9 for x in self.cosmology.comoving_volume(redshiftEdges)]
        #The difference between the spherical volumes gives me 
        #the shell volume of each redshift we are looking at
        self.Shell_volume   = np.diff(comovEdges)



    def setAgeBirthSystems(self):
        #each row is a redshift each column a system
        self.PerSystemPerRedshift_ageBirth       = np.zeros(shape=(int(self.nrRedshiftBins),\
                                                            len(self.COMPAS.delayTimes)))

        #the age of the universe at the birth of the system is the 
        #age of the universe at merger minus the delay time.
        #for the age of the universe in a redshift shell 
        #we use the center redshift value
        for nrz, redshift in enumerate(self.Shell_centerRedshift):
            ageUniverseAtMergerGyr = self.cosmology.age(redshift)
            delayTimeGyr           = self.COMPAS.delayTimes / 1000.
            ageBirth               = ageUniverseAtMergerGyr.value - delayTimeGyr
            maskUnreal             = ageBirth < self.ageFirstSFR
            self.PerSystemPerRedshift_ageBirth[nrz] = ageBirth
            self.PerSystemPerRedshift_ageBirth[nrz][maskUnreal] = -1


    def setRedshiftBirthSystems(self):
        self.PerSystemPerRedshift_redshiftBirth = np.zeros(shape=(int(self.nrRedshiftBins),\
                                                            len(self.COMPAS.delayTimes)))

        #calculating redshift from age is cheap, inverse not
        #either we precalulate a grid and look up closest value
        #cheap and quick but technically less precise
        #or we use an inverse function, which is slower
        if (self.RedshiftTabulated) and (self.redshiftAgeTable is None):
            redshifts  =  np.linspace(0.0000001,\
                                      self.redshiftFirstSFR,\
                                      self.RedshiftTabulatedResolution)
            ages       = self.cosmology.age(redshifts).value
            self.redshiftAgeTable = np.column_stack((redshifts,ages))

        for nrR, row in enumerate(self.PerSystemPerRedshift_ageBirth):
            maskUnphysical = (row == -1) #born before first SFR
            maskPhysical   = np.logical_not(maskUnphysical)
            
            if self.RedshiftTabulated:
                #find indices in precalculated table 
                inds      = np.digitize(row[maskPhysical], self.redshiftAgeTable[:,1])
                redshifts = self.redshiftAgeTable[inds,0]
            else:
                """
                All credits go to
                https://mail.scipy.org/pipermail/astropy/2013-December/002950.html
                The problem is that astropy seems to only have redshift->time
                not time->redshift
                """
                redshifts = np.zeros(np.sum(maskPhysical))
                for nra, age in enumerate(maskPhysical):
                     redshifts[nra] = newton(lambda x: \
                                    self.cosmology.age(x).value-age, 0)
            #fill in values
            self.PerSystemPerRedshift_redshiftBirth[nrR][maskUnphysical] = -1
            self.PerSystemPerRedshift_redshiftBirth[nrR][maskPhysical]   = redshifts

    def setBirthTimesAnd2Darrays(self):            

        if self.COMPAS.delayTimes is not None:
            if self.verbose:
                print("creating 2D arrays with birth ages and redshift")
               
            
            #from the COMPAS data we need the birth ages of each system
            #in our integral, only if we actually have data. 
            #Introduced this because you might want an empty class (without data)
            #for testing and explaining code in notebooks :D

            #Calculating birth age is simple subtraction age-merger -delaytime
            self.setAgeBirthSystems()
            #Cannot do this in redshift so convert table above to a redshift table
            self.setRedshiftBirthSystems()
            if self.verbose:
                print("creating 2D array with intrinsic and observed rate to be calculated")
             # dN Gpc-3 per year at z=redshift.     #each row is redshift merger
            self.PerSystemPerRedshift_ratesIntrinsic = np.zeros(shape=(int(self.nrRedshiftBins),\
                                                                len(self.COMPAS.delayTimes)))
            # dN per year in detector from shell 
            self.PerSystemPerRedshift_ratesObserved  = np.zeros(shape=(int(self.nrRedshiftBins),\
                                                                len(self.COMPAS.delayTimes)))    
        else:
            print()
            print("cannot set 2D-array of rates")
            print("COMPAS data is empty (COMPAS.setCOMPASData) " )

    def cosmologicalIntegration(self):
        if self.verbose:
            print("Doing the actual cosmic integration")
            print("Filling in the 2D arrays with rate per system per redshift")
        #For each row in 2D array wich corresponds to a merger redshift
        # Get birth Age in Gyr , redshifts birth, and metallicities from COMPAS
        #Calcultate MSSFR for that row and fill in the answer
        for nr in range(int(self.nrRedshiftBins)):
            for nrZ, Z in enumerate(self.COMPAS.metallicityGrid):
                maskZ    = self.COMPAS.metallicitySystems == Z
                MSSFR  = self.MSSFR.returnMSSFR(metallicity=Z,\
                                                  agesBirth=self.PerSystemPerRedshift_ageBirth[nr][maskZ],
                                                  redshiftBirth=self.PerSystemPerRedshift_redshiftBirth[nr][maskZ])
                RatesZ   = np.divide(MSSFR, self.COMPAS.totalMassEvolvedPerZ[nrZ])
                self.PerSystemPerRedshift_ratesIntrinsic[nr][maskZ] = RatesZ   # intrinric dN Gpc-3 per year at z=redshift.
                probObservingZ     = selection_effects.detection_probability(\
                                    self.COMPAS.mass1[maskZ],self.COMPAS.mass2[maskZ], self.Shell_centerRedshift[nr],\
                                    self.Shell_luminosityDistance[nr], self.GWdetector_snrThreshold,\
                                    sensitivity=self.GWdetector_sensitivity)
                NrMergersInShell  = np.multiply(RatesZ,self.Shell_volume[nr])                    # intrinsic rate per system per shell
                NrMergersInShell  = NrMergersInShell * (1./(1.+self.Shell_centerRedshift[nr])) # rate observer frame per system per shell
                self.PerSystemPerRedshift_ratesObserved[nr][maskZ]  = np.multiply(NrMergersInShell,probObservingZ)      # observed  dN per year prob between 0-1 
        if np.sum(self.PerSystemPerRedshift_ratesObserved[-1]) != 0 :
            print("The detected rate of the outermost redshift shell is nonzero, did we integrate far enough?")
예제 #25
0
import numpy as N
import pylab as P
import scipy as S
import pyfits as F
from t_tau_func import *
from astropy.cosmology import FlatLambdaCDM

cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
av_z = 0.076401
age = cosmo.age(av_z)


font = {'family':'serif', 'size':12}
P.rc('font', **font)
P.rc('xtick', labelsize='small')
P.rc('ytick', labelsize='small')

dir ='/Users/becky/Projects/Green-Valley-Project/bc03/models/Padova1994/chabrier/ASCII/'
model = 'extracted_bc2003_lr_m62_chab_ssp.ised_ASCII'
data = N.loadtxt(dir+model)

tq = N.linspace(0.0, 13.6, 10)
tau = N.linspace(3.0, 0.001, 10)

ur = N.zeros((len(tq),len(tau)))
nuv = N.zeros_like(ur)
for n in range(len(tq)):
    for m in range(len(tau)):
        nuv[n,m], ur[n,m] = predict_c_one([tq[n], tau[m]], age)

N.save('ur.npy', ur)
예제 #26
0
    n = norm_kde(n, 20.)
    x0 = 0.5 * (b[1:] + b[:-1])
    y0 = n
    
    return x0, y0 / np.trapz(y0,x0)

def Derive_SFH_weights(SFH, grid):
    Y = np.array(SFH)

    weights = np.zeros(len(grid))
    for i in range(len(grid)):
        weights[i] = np.sum((grid[i][0:len(Y)] - Y) ** 2) ** -1
    return weights

rshifts = np.arange(0,14,0.01)
age_at_z = cosmo.age(rshifts).value
age_to_z = interp1d(age_at_z, rshifts)
lbt_at_z = cosmo.lookback_time(rshifts).value
lbt_to_z = interp1d(lbt_at_z, rshifts)

class Rescale_sfh(object):
    def __init__(self, field, galaxy, trials = 1000):

        ppf_dict = {}
        params = ['a', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10', 'lm']

        for i in params:
            x,px = np.load('../data/posteriors/{0}_{1}_tabfit_P{2}.npy'.format(field, galaxy, i),allow_pickle=True)
            ppf_dict[i] = Gen_PPF(x,px)

        idx = 0
예제 #27
0
col[:,10] = gz2data.field('upper_GV')
col[:,11] = gz2data.field('lower_GV')
col[:,12] = gz2data.field('dr7objid')
col[:,13] = gz2data.field('dr8objid')
col[:,14] = gz2data.field('ra_1')
col[:,15] = gz2data.field('dec_1')

# Remove NaN values from data
non_nan = N.logical_not(N.isnan(col[:,1])).astype(int)
data = N.compress(non_nan, col, axis=0)

age_save = str(raw_input('Desired or current location of galaxy ages from astropy.cosmology, e.g. "~/starfpy/galaxy_data_ages.npy" : '))
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(data[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)

nwalkers = 100
nsteps= 400
start = [7.5, 1.5]
burnin = 400

start_time = time.time()
#The rest calls the emcee module through the 'posterior.py' functions and makes a plot....
for n in range(len(data)):
    url = 'http://casjobs.sdss.org/ImgCutoutDR7/getjpeg.aspx?ra='+str(data[n,14])+'&dec='+str(data[n,15])+'&scale=0.099183&width=424&height=424'
    f = wget.download(url, out=str(int(data[n,13]))+'.jpeg')
예제 #28
0
    aexps.append(aaa)
    mps.append(mass_particle)
    Lboxs.append(box_length)

out_name = os.path.join(os.environ["NUGC_DIR"], 'output_NUGC.fits')

redshift = 1. / n.array(aexps) - 1.
dCom = cosmoNGC.comoving_distance(redshift)
ids = n.argsort(redshift)

col0 = fits.Column(name='snap_name', format='A20', array=n.array(names)[ids])
col1 = fits.Column(name='N_columns', format='I', array=n.array(colN)[ids])
col2 = fits.Column(name='aexp', format='D', array=n.array(aexps)[ids])
col3 = fits.Column(name='redshift', format='D', array=redshift[ids])
col4 = fits.Column(name='comoving_distance', format='D', array=dCom.value[ids])
array = 10**9 * cosmoNGC.age(redshift).value
col5 = fits.Column(name='age_yr', format='D', array=array[ids])
array = cosmoNGC.arcsec_per_kpc_comoving(redshift).value * 3.6
col6 = fits.Column(name='deg_per_Mpc_comoving', format='D', array=array[ids])
col7 = fits.Column(name='box_length', format='D', array=n.array(Lboxs)[ids])
col8 = fits.Column(name='mass_particle', format='D', array=n.array(mps)[ids])

#define the table hdu
hdu_cols = fits.ColDefs([col0, col1, col2, col3, col4, col5, col6, col7,
                         col8])  #, col9, col10])
tb_hdu = fits.BinTableHDU.from_columns(hdu_cols)
#define the header
prihdr = fits.Header()
prihdr['sim'] = 'NUGC'
prihdr['author'] = 'JC'
prihdu = fits.PrimaryHDU(header=prihdr)
예제 #29
0
gv = gvf[gvf[:, 9] == 1]
print len(gv)
smooth = colours[colours[:, 2] > 0.8]
print len(smooth)
disc = colours[colours[:, 3] > 0.8]
print len(disc)
red_s = colours[colours[:, 0] > colours[:, 10]]
print len(red_s)
blue_c = colours[colours[:, 0] < colours[:, 11]]
print len(blue_c)

age_save = "/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/gv/age_gv.npy"
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0=71.0, Om0=0.26)
if age_path == False:
    age = N.array(cosmo.age(gv[:, 6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)

w = [7.5, 1.5, 7.5, 1.5, 4.0, 1.5, 4.0, 1.5]
nwalkers = 100
nsteps = 150
start = [7.5, 1.5, 7.5, 1.5]

f = open("/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/log.txt", "a")
f.write("Run started at " + str(time.strftime("%H:%M")) + " on " + str(time.strftime("%d/%m/%y")) + "\n")
f.write("Reason for running iteration: " + reason + "\n")
f.write("Number of walkers : " + str(nwalkers) + "\n")
f.write("Number of steps :" + str(nsteps) + "\n")
예제 #30
0
gv = gvf[gvf[:,9]==1]
print len(gv)
smooth = colours[colours[:,2] > 0.8]
print len(smooth)
disc = colours[colours[:,3] > 0.8]
print len(disc)
red_s = colours[colours[:,0] > colours[:,10]]
print len(red_s)
blue_c = colours[colours[:,0] < colours[:,11]]
print len(blue_c)

age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/age_all.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(colours[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)


#col = N.zeros([1,8])
#col[:,0] = 2.1
#col[:,1] = 1.2
#col[:,2] = 0.1
#col[:,3] = 0.9
#col[:,4] = 0.05
#col[:,5] = 0.1
#col[:,6] = 13.0
#col[:,7] = 0.001
예제 #31
0
        np.logspace(lalpha_min, lalpha_max, nalpha),
        -1 * np.logspace(lbeta_min, lbeta_max, nbeta),
        np.linspace(tau_min, tau_max, ntau))

    sfh_params = np.vstack([alphas.flatten(),
                            betas.flatten(),
                            taus.flatten()]).T
    return sfh_params


sfhs = make_dbl_sfhs(2, 2, 2)

zrange = np.linspace(0.1, 2, 39)
zform = 20.

ages = cosmo.age(zrange) - cosmo.age(zform)

metallicities = [0.1, 1.]
dusts = [0., 0.5, 1.]  #np.linspace(0., 2., 11) # Av range

models.build(ages, sfhs, dusts, metallicities, sfh_law=dblpower, verbose=True)

models.save_to_hdf('test_hdf_set.hdf')

models2 = S.CSP(bc03)
models2.load_from_hdf('test_hdf_set.hdf')

# """
# Example: Save intermediate models
# """
with open('candels.goodss.csp.pkl', 'wb') as output:
예제 #32
0
gv = gvf[gvf[:,9]==1]
print len(gv)
smooth = colours[colours[:,2] >= 0.8]
print len(smooth)
disc = colours[colours[:,3] >= 0.8]
print len(disc)
red_s = colours[colours[:,0] > colours[:,10]]
print len(red_s)
blue_c = colours[colours[:,0] < colours[:,11]]
print len(blue_c)

age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/smooth/age_smooth.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(smooth[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)

w = [7.5, 1.5, 7.5, 1.5, 4.0, 1.5, 4.0, 1.5]
nwalkers = 100
nsteps= 300
start = [7.5, 1.5, 7.5, 1.5]

f = open('/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/log.txt', 'a')
f.write('Run started at '+str(time.strftime('%H:%M'))+' on '+str(time.strftime('%d/%m/%y'))+'\n')
f.write('Reason for running iteration: ' +reason+'\n')
f.write('Number of walkers : '+str(nwalkers)+'\n')
f.write('Number of steps :'+str(nsteps)+'\n')
예제 #33
0
disc = colours[colours[:,3] > 0.8]
print len(disc)
red_s = colours[colours[:,0] > colours[:,10]]
print len(red_s)
blue_c = colours[colours[:,0] < colours[:,11]]
print len(blue_c)
#disc = colours[colours[:,3]==1]
#smooth = colours[colours[:,2]==1]
#inter = colours[[colours[:,2]!=1][:,3]!=1]

#Calculating the look back time from the observed redshift assuming this time is also the age of the galaxy at which you're observing it
age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/age_red_seq.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(red_s[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)
#
#if len(age) != len(gv):
#    raise SystemExit('Number of ages does not coincide with number of galaxies...')

# w is the prior conditions on my theta parameters - the mean and standard deviation of tq and tau for the disc and smooth populations
# w = [mu_tqs, mu_taus, mu_tqd, mu_taud, sig_tqs, sig_taus, sig_tqd, sig_taud]
w = [9.0, 1.25, 9.0, 1.25, 2.0, 0.5, 2.0, 0.5]
nwalkers = 100
start_time = time.time()
#The rest calls the emcee code and makes plots....
samples, fig = sample(4, nwalkers, w, red_s[:,0], red_s[:,4], red_s[:, 1], red_s[:, 5], age, red_s[:,3], red_s[:,2])
예제 #34
0
### Making the lin plot
lin_plot.plot(lin_age, csf, color='k', linestyle='solid', linewidth=3)
lin_plot.errorbar(lin_age, csf, yerr=[csf_low, csf_up], capsize=0, color='k')
lin_plot.invert_xaxis()
lin_plot.set_xlabel('Time(Gyr)', fontsize=20)
lin_plot.set_ylabel('Fraction of Stellar Mass Formed', fontsize=22)
lin_plot.tick_params(axis='both', which='major', labelsize=20)
lin_plot.set_xlim(max(lin_age), min(lin_age))
lin_plot.set_xticks(np.array([13, 12, 10, 8, 6, 4, 2, 0]))

### Making the redshift axis on top
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)

ageticks = np.array([0.5, 1, 1.5, 2, 3, 6])
age_loc = 13.7 - cosmo.age(ageticks).value

rs = lin_plot.twiny()
rs.invert_xaxis()
rs.set_xlim(max(lin_age), min(lin_age))
rs.set_xticks(age_loc)
rs.set_xticklabels(['%.1f' % age for age in ageticks])
rs.set_xlabel('Redshift (z)', fontsize=20)
rs.xaxis.set_label_coords(0.9, 1.02)
rs.tick_params('x', labelsize=18)

### Put labels for two plots
fig.text(.14, .85, '(a)', fontsize=22)
fig.text(.56, .85, '(b)', fontsize=22)

plt.savefig(name + '.png')
예제 #35
0
data_dir = '/home/rad/data/' + model + '/' + wind + '/'
if snap == '151':
    halflight_file = '/home/sapple/simba_sizes/sizes/data/pyloser_sdss_r.h5'
else:
    halflight_file = '/home/sapple/simba_sizes/sizes/data/pyloser_v.h5'
snapfile = data_dir + 'snap_' + model + '_' + snap + '.hdf5'

sim = caesar.load(data_dir + 'Groups/' + model + '_' + snap + '.hdf5')

h = sim.simulation.hubble_constant
redshift = sim.simulation.redshift
cosmo = FlatLambdaCDM(H0=100 * h,
                      Om0=sim.simulation.omega_matter,
                      Ob0=sim.simulation.omega_baryon,
                      Tcmb0=2.73)
thubble = cosmo.age(redshift).value  # in Gyr

# load in the caesar galaxy data to make an initial cut of star forming galaxies
gal_cent = np.array([i.central for i in sim.galaxies])
gal_sm = np.array([i.masses['stellar'].in_units('Msun') for i in sim.galaxies])
gal_sfr = np.array([i.sfr.in_units('Msun/yr') for i in sim.galaxies])
gal_ssfr = gal_sfr / gal_sm
gal_sm = np.log10(gal_sm)
gal_ssfr = np.log10(gal_ssfr)

with h5py.File(halflight_file, 'r') as f:
    gal_rad = f['abs_' + model + '_' + wind + '_' +
                snap][:]  # these are in pkpc
gal_rad = np.sum(gal_rad, axis=0) / 3.

gal_ids = np.array([True for i in range(len(sim.galaxies))])
예제 #36
0
def redshifttot(Z):
    ##Return the corresponding t in Gyr for a redshift
    from astropy.cosmology import FlatLambdaCDM
    cosmo = FlatLambdaCDM(H0=69.6, Om0=0.286)
    return cosmo.age(Z).value
예제 #37
0
import pandas as pd
import numpy as np
from astropy.io import fits
from scipy.stats.distributions import chi2
from astropy.cosmology import FlatLambdaCDM
import math

cosmo = FlatLambdaCDM(H0=70, Om0=.3)

filename = 'output_cats/sample_fulldata.fits'

with fits.open(filename) as hdu:
    data = hdu[1].data

    mask = data['redshift_2.5'] > 2
    data = data[mask]

    #mask = (chi2.sf(data['chisq_phot'],(data['n_bands']-10))) > (0.5*math.erfc(5*(2**-0.5)))
    #data = data[mask]

    age = cosmo.age(data['redshift_50']).value * (10**9)
    factor = 0.2 / age
    mask = 10**data['ssfr_97.5'] < factor
    data = data[mask]

    print(data.shape)
    newhdu = fits.BinTableHDU(data=data)
    newhdu.writeto('output_cats/subsample.fits')
예제 #38
0
    bin_widths = np.zeros_like(midpoints)

    if make_rhs:
        bin_lhs = np.zeros(midpoints.shape[0]+1)
        bin_lhs[0] = midpoints[0] - (midpoints[1]-midpoints[0])/2
        bin_widths[-1] = (midpoints[-1] - midpoints[-2])
        bin_lhs[-1] = midpoints[-1] + (midpoints[-1]-midpoints[-2])/2
        bin_lhs[1:-1] = (midpoints[1:] + midpoints[:-1])/2
        bin_widths[:-1] = bin_lhs[1:-1]-bin_lhs[:-2]

    else:
        bin_lhs = np.zeros_like(midpoints)
        bin_lhs[0] = midpoints[0] - (midpoints[1]-midpoints[0])/2
        bin_widths[-1] = (midpoints[-1] - midpoints[-2])
        bin_lhs[1:] = (midpoints[1:] + midpoints[:-1])/2
        bin_widths[:-1] = bin_lhs[1:]-bin_lhs[:-1]

    return bin_lhs, bin_widths


# Set up necessary variables for cosmological calculations.
cosmo = FlatLambdaCDM(H0=70., Om0=0.3)
z_array = np.arange(0., 100., 0.01)
age_at_z = cosmo.age(z_array).value
ldist_at_z = cosmo.luminosity_distance(z_array).value

install_dir = os.path.dirname(os.path.realpath(__file__))
grid_dir = install_dir + "/models/grids"
working_dir = os.getcwd()
    return B[0] * x + B[1]


START = 0
END = 25

COSMO = FlatLambdaCDM(H0=70 * u.km / u.s / u.Mpc, Tcmb0=2.725 * u.K, Om0=0.3)

intercepts = list(np.loadtxt('{}Computed_Files/intercepts_9_z_20K'.format(ROOT)))
err = list(np.loadtxt('{}Computed_Files/intercept_errs_z_20K'.format(ROOT)))

univ_age = []
for i in range(Nr * Nc):
    lower_z = i / (Nr * Nc) * (MAX_Z - MIN_Z) + MIN_Z
    upper_z = lower_z + 1 / (Nr * Nc) * (MAX_Z - MIN_Z)
    min_age = COSMO.age(lower_z).value
    max_age = COSMO.age(upper_z).value
    age = (min_age + max_age) / 2
    univ_age.append(age)

intercepts = intercepts[START:END]
err = err[START:END]
univ_age = univ_age[START:END]

coeff = np.polyfit(univ_age, intercepts, 1)
linear = regression.Model(line)
mydata = regression.Data(univ_age, intercepts)
myodr = regression.ODR(mydata, linear, beta0=coeff)
output = myodr.run()
coeff = output.beta
error = output.sd_beta
예제 #40
0
#u_r_gal_sigma = N.array([0.01, 0.015])
#nuv_u_gal = N.array([0.5, 1.2])
#nuv_u_gal_sigma = N.array([0.02, 0.015])
u_r_gal = smooth[100:101,0]
print N.shape(u_r_gal)
print 'u_r_gal', u_r_gal
u_r_gal_sigma = smooth[100:101,16]
print 'u_r_gal_sigma', u_r_gal_sigma
nuv_u_gal = smooth[100:101,1]
nuv_u_gal_sigma = smooth[100:101,17]

age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/age_smooth.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path == True:
    age = N.array(cosmo.age(smooth[100:101,18]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
#age = cosmo.age(z_gal)
print age
print N.shape(age)
#
#col_gal = N.array([u_r_gal, nuv_u_gal])
#sigma_gal = N.array([u_r_gal_sigma, nuv_u_gal_sigma])

#Define model properties
#time = (N.arange(28.0)/2.0) # In Gyrs
#time = N.linspace(0.0, cosmo.age(0.0), 50) # In Gyrs
#tim = N.arange(0, 0.01, 0.003)
#times = N.arange(0, 13.7, 0.01)
예제 #41
0
    opt.base_path = "/work/06147/pberger/maverick2/gadget_runs/cgrid0/"

opt.n_cond_params = n_cond_params

# this dictates the number of ilters in each layer, multiplied by ngf or ndf (number of generator filters/number of discriminator filters)
sizes = np.array([8, 4, 2, 1])

#redshift_bins = np.array([1., 0.5, 0.25, 0.])
#redshift_strings = np.array(['006', '007', '008', '009'])
redshift_strings = np.array(['003', '005', '007', '009'])
redshift_bins = np.array([3., 1.5, 0.5, 0.])
#redshift_bins = np.array([2., 1., 0.])
#redshift_bins = np.array([0.5, 0.25, 0.])*opt.cond_scale_fac
#redshift_strings = np.array(['007', '008', '009'])

age_bins = cosmo.age(redshift_bins) / cosmo.age(0)
print('age bins:', age_bins)

if opt.redshift_code:
    if opt.age_bins:
        print('using fractional ages instead of redshifts')
        opt.redshift_bins = age_bins
    else:
        opt.redshift_bins = redshift_bins

    opt.redshift_idxs = np.array([int(r) for r in redshift_strings])
    output1shape = (opt.cubedim / (2 * opt.ds_factor),
                    opt.cubedim / (2 * opt.ds_factor),
                    opt.cubedim / (2 * opt.ds_factor)
                    )  # for conditional feature maps in discriminator
    print('Redshifts:', redshift_bins)
예제 #42
0
def singleSP_SFH_myfirefly(iz, zred=0.01):
    ''' construct spectra with single metallicity, with eagle SFH, no dust, no nonsense  
    '''
    z_arr = np.array([0.5, 1.0, 2.0, 10**-1.301, 10**-1.302, 10**-2.301, 10**-2.302, 10**-0.6, 
        10**-0.9, 10**-1.2, 10**-1.6, 10**-1.9]) 
    z_strs = np.array(['z001', 'z002', 'z004', 'z0001.bhb', 'z0001.rhb', 'z10m4.bhb', 'z10m4.rhb', 
        'z-0.6', 'z-0.9', 'z-1.2', 'z-1.6', 'z-1.9']) 
    z_metal = z_arr[iz]

    # read in SFH and M_* 
    f_eagle = h5py.File(''.join([UT.dat_dir(), '0EAGLE_SFRHs.hdf5']), 'r') 
    i_zmid = np.abs(z_arr[iz] - 10**np.array(logZ_mid)).argmin()
    logZ = logZ_mid[i_zmid] 
    t = age_bounds[:,1]
    dt = age_bounds[:,2] - age_bounds[:,0]
    sfh = f_eagle['SFRH'].value[0,:,i_zmid]

    f_ssp = os.environ['STELLARPOPMODELS_DIR']+'/data/SSP_M11_MILES/ssp_M11_MILES.cha'+z_strs[iz]
    model_age, model_wave, model_flux = np.loadtxt(f_ssp, unpack=True, usecols=[0,2,3]) 
    
    age_uniq = np.sort(np.unique(model_age))
    age_bin = np.concatenate([[0], 0.5*(age_uniq[1:] + age_uniq[:-1])])
    
    mtot_bin, flux_bin = [], [] 
    for i_a in range(len(age_bin)-1): 
        in_agebin = ((14.-t >= age_bin[i_a]) & (14-t < age_bin[i_a+1]))
        mtot_i = np.sum(dt[in_agebin] * sfh[in_agebin] * 1e9)
        mtot_bin.append(mtot_i) 

    assert np.sum(mtot_bin) == np.sum(sfh * dt * 1e9)
    print('log M_tot = %f' % np.log10(np.sum(mtot_bin)))

    # read in spectra 
    f_spec = ''.join([UT.dat_dir(), 'SSP_SFH.iz', str(iz), '.z', str(zred), '.dat']) 
    wave, flux = np.loadtxt(f_spec, unpack=True, usecols=[0,1]) 
    wave_rest = wave/(1.+zred)
    err = flux * 0.001

    cosmo = FlatLambdaCDM(70., 0.3) 
    ffly = Fitters.myFirefly(cosmo, 
            model='m11', 
            model_lib='MILES', 
            imf='cha', 
            dust_corr=False,                        # no dust correction
            age_lim=[0., cosmo.age(zred).value],    # can't have older populations
            logZ_lim=[np.log10(z_arr[iz])-0.1, np.log10(z_arr[iz])+0.1])
    mask = ffly.emissionlineMask(wave_rest)
    ff_fit, ff_prop = ffly.Fit(wave, flux, err, zred, mask=mask, flux_unit=1.)
    
    print('total mass = %f' % ff_prop['logM_total']) 
    ssp_age_bin0, ssp_age_bin1 = [], [] 
    ssp_mtot = [] 
    for i in range(ff_prop['n_ssp']): 
        print('--- SSP %i; weight=%f ---' % (i, ff_prop['weightLight_ssp_'+str(i)]))
        print('age = %f'% ff_prop['age_ssp_'+str(i)])
        print('log Z = %f'% ff_prop['logZ_ssp_'+str(i)])
        print('log M_tot = %f' % ff_prop['logM_total_ssp_'+str(i)])
        i_age_bin = np.abs(age_uniq - ff_prop['age_ssp_'+str(i)]).argmin()
        ssp_age_bin0.append(age_bin[i_age_bin]) 
        ssp_age_bin1.append(age_bin[i_age_bin+1])
        ssp_mtot.append(10**ff_prop['logM_total_ssp_'+str(i)]) 
    
    fig = plt.figure(figsize=(12,4))
    sub = fig.add_subplot(121)
    sub.bar(age_bin[:-1], mtot_bin, width=age_bin[:-1]-age_bin[1:], alpha=0.75)
    sub.bar(ssp_age_bin0, ssp_mtot, width=np.array(ssp_age_bin0)-np.array(ssp_age_bin1), alpha=0.75)
    sub.set_xlabel('Lookback Time [Gyr]', fontsize=25) 
    sub.set_xlim([0., 14]) 
    sub.set_ylabel("$M_\mathrm{form}$", fontsize=25)
    sub.set_yscale("log") 
    sub.set_ylim([1e7, 5e9]) 

    sub = fig.add_subplot(122)
    sub.plot(ff_fit['wavelength'], ff_fit['flux'], label='SSP') 
    sub.plot(ff_fit['wavelength'], ff_fit['flux_model'], label='myFirefly best-fit') 
    sub.plot(ff_fit['wavelength'], ff_fit['flux'] - ff_fit['flux_model'], label='residual') 
    #sub.plot(wave_rest, flux, c='k', ls=':') 
    sub.set_xlim([3e3, 1e4]) 
    fig.savefig(''.join([UT.fig_dir(), 'myfirefly.SSP_SFH.iz', str(iz), '.z', str(zred), '.png']), 
            bbox_inches='tight')
    return None 
예제 #43
0
from matplotlib import colors as mcolors
from matplotlib import gridspec

from astropy.cosmology import FlatLambdaCDM
from astropy.cosmology import z_at_value

## Setting up the cosmology...
cosmo = FlatLambdaCDM(H0=68.0, Om0=0.31)  #Banados thesis
#ages     = np.array([13, 10, 8, 6, 5, 4, 3, 2, 1.5, 1.2, 1, 0.8, 0.70, 0.50, 0.25, 0.10])*u.Gyr
ages = np.array([13, 10, 8, 6, 5, 4, 3, 2, 1.5, 1.25, 0.75, 0.50, 0.25, 0.10
                 ]) * u.Gyr
ageticks = [z_at_value(cosmo.age, age) for age in ages]

redshifts = np.array([6, 7, 8, 9, 10, 12, 15, 20])
redshiftticks = [cosmo.age(redshift).value for redshift in redshifts]

##
##  READ-IN THE   D A T A     F I L E (S)
##  Inayoshi, Visbal, Haiman   Annu. Rev. Astron. Astrophys. 2019. 58:1–79
filename = 'Inayoshi_2019_ARAA_203quasars.dat'
VHzQs = ascii.read(filename, delimiter=r'\s', guess=False)

z_VHzQs = VHzQs['redshift']
log_MBH_VHzQs = np.log10(VHzQs['Mbh'])
age_VHzQs = cosmo.age(z_VHzQs).value

##  Trakhtenbrot et al. (2011) z=4.8 objects
##  name, redshift, L_bol, log_MBH, l_Edd
##  J143+0635	4.850	46.98		8.99	-0.19
path = '/cos_pc19a_npr/data/highest_z_QSOs/Trakhtenbrot2011/'
    #print os.path.basename(snLi)[4:-5], len(lin1), aaa
    names.append(os.path.basename(snLi)[4:-5])
    colN.append(len(lin1))
    aexps.append(aaa)

out_name = os.path.join(os.environ["MD40"], 'output_MD_4.0Gpc.fits')

redshift = 1. / n.array(aexps) - 1.
dCom = cosmoMD.comoving_distance(redshift)
ids = n.argsort(redshift)
col0 = fits.Column(name='snap_name', format='A4', array=n.array(names)[ids])
col1 = fits.Column(name='N_columns', format='I', array=n.array(colN)[ids])
col2 = fits.Column(name='aexp', format='D', array=n.array(aexps)[ids])
col3 = fits.Column(name='redshift', format='D', array=redshift[ids])
col4 = fits.Column(name='comoving_distance', format='D', array=dCom.value[ids])
array = 10**9 * cosmoMD.age(redshift).value
col5 = fits.Column(name='age_yr', format='D', array=array[ids])
array = cosmoMD.arcsec_per_kpc_comoving(redshift).value * 3.6
col6 = fits.Column(name='deg_per_Mpc_comoving', format='D', array=array[ids])

#define the table hdu
hdu_cols = fits.ColDefs([col0, col1, col2, col3, col4, col5,
                         col6])  #, col7, col8, col9, col10])
tb_hdu = fits.BinTableHDU.from_columns(hdu_cols)
#define the header
prihdr = fits.Header()
prihdr['sim'] = 'HMD'
prihdr['author'] = 'JC'
prihdu = fits.PrimaryHDU(header=prihdr)
#writes the file
thdulist = fits.HDUList([prihdu, tb_hdu])
예제 #45
0
        'z': z,
        'lgMh': lgMh,
        'lgMs': lgMs,
        'SFR': SFR
    })
    Data_a['%s' % m] = data

from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import matplotlib.transforms as mtransforms
from matplotlib.patches import FancyBboxPatch

# Papovich15 AM
Ms_pop = np.array([9.48, 9.7, 9.88, 10.06, 10.21, 10.35, 10.47, 10.6])
z_pop = np.array([2.5, 2.1, 1.85, 1.55, 1.25, 1.0, 0.8, 0.45])
t_pop = cosmo.age(z_pop)

bb = mtransforms.Bbox([[0.36, 0.28], [0.988, 0.36]])


def draw_box(ax, bb):
    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width),
                             abs(bb.height),
                             transform=ax.transAxes,
                             boxstyle="square,pad=0",
                             fc="w",
                             ec="gray",
                             alpha=.5,
                             zorder=3)
    ax.add_patch(p_fancy)
예제 #46
0
gv = gvf[gvf[:,9]==1]
print len(gv)
smooth = colours[colours[:,2] >= 0.8]
print len(smooth)
disc = colours[colours[:,3] >= 0.8]
print len(disc)
red_s = colours[colours[:,0] > colours[:,10]]
print len(red_s)
blue_c = colours[colours[:,0] < colours[:,11]]
print len(blue_c)

age_save = '/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/disc/age_disc.npy'
age_path = os.path.exists(age_save)
cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26)
if age_path ==False:
    age = N.array(cosmo.age(disc[:,6]))
    N.save(age_save, age)
else:
    age = N.load(age_save)
print len(age)



w = [7.5, 1.5, 7.5, 1.5, 4.0, 1.5, 4.0, 1.5]
nwalkers = 100
nsteps= 250
start = [7.5, 1.5, 7.5, 1.5]

f = open('/Users/becky/Projects/Green-Valley-Project/bayesian/find_t_tau/log.txt', 'a')
f.write('Run started at '+str(time.strftime('%H:%M'))+' on '+str(time.strftime('%d/%m/%y'))+'\n')
f.write('Reason for running iteration: ' +reason+'\n')