def calc_zeff(data_z, data_zerr, table_z_max=2.0, nz=101, z_min=0.6, z_max=0.8, \
interp_flag=True, **cosmology) :
	import numpy as np
	from scipy.integrate import quad
	
	assert table_z_max > z_max, 'To avoid extrapolation, table_z_max must be larger \
	than z_max: table_z_max={}, z_max={}'.format(table_z_max, z_max)
	
	## Get the redshift distribution
	phi = phi_interpolator(data_z, data_zerr, table_z_max, nz)
	
	if interp_flag :
		## In this case, get the distance and Hubble splines
		xi = distance_interpolator(table_z_max, nz, **cosmology)
		H = Hubble_interpolator(table_z_max, nz, **cosmology)
		## Calculate the numerator and denominator
		zeff_num = quad(zeff_numerator_integrand, z_min, z_max, args=(H, xi, phi, \
		interp_flag))[0]
		zeff_denom = quad(zeff_denominator_integrand, z_min, z_max, args=(H, xi, phi, \
		interp_flag))[0]
	else :
		## Here we need to set up the cosmology instead
		from astropy.cosmology import w0waCDM
		cosmo = w0waCDM(100.*cosmology['h0'], cosmology['omega_m'], \
		1.-cosmology['omega_k']-cosmology['omega_m'], w0=cosmology['w'], \
		wa=cosmology['wa'])
		## Calculate the numerator and denominator
		zeff_num = quad(zeff_numerator_integrand, z_min, z_max, args=(cosmo.H, \
		cosmo.comoving_distance, phi, interp_flag))[0]
		zeff_denom = quad(zeff_denominator_integrand, z_min, z_max, args=(cosmo.H, \
		cosmo.comoving_distance, phi, interp_flag))[0]
	
	## Now we just return zeff = zeff_num/zeff_denom
	return zeff_num/zeff_denom
Example #2
0
def llhood_jlad_wzcdm(model_param, ndim, nparam):
    om, w0, wa, a, b, MB, DM, od, g = [model_param[i] for i in range(9)]

    h0 = 70

    A = []
    for i in range(0, 50):
        At = 10**(od) * attenuation(om, h0, z50[i], w0, wa, g)
        A.append(At)
    A_inter = interp1d(z50, A)
    DUST = A_inter(jla.zcmb.values)

    dist_th = w0waCDM(h0, om, 1 - om, w0,
                      wa).luminosity_distance(jla.zcmb.values).value
    mod_th = 5 * np.log10(dist_th) + 25

    hub_res = jla.mb.values + a * jla.x1.values - b * jla.color.values - MB - mod_th - DUST
    hub_res[jla.hm.values >= 10.] += DM

    C = mu_cov(a, b)
    iC = np.linalg.inv(C)

    chisq = np.dot(hub_res.T, np.dot(iC, hub_res))

    if cmb == 1:
        T = cmb_chisq(om, h0, w0, wa)
        chisq += T

    return -0.5 * chisq
Example #3
0
	def __init__(self,fp=None,pool=None,length_unit=1.0*kpc,mass_unit=1.0e10*Msun,velocity_unit=1.0*km/s,header_kwargs=dict()):

		self.pool = pool

		self._length_unit = length_unit.to(cm).value
		self._mass_unit = mass_unit.to(g).value
		self._velocity_unit = velocity_unit.to(cm/s).value

		if fp is not None:
		
			self.fp = fp

			#Load the header
			self._header = self.getHeader(**header_kwargs)
			
			#Check that header has been loaded correctly
			self._check_header()

			#Hubble parameter
			h = self._header["h"]

			#Define the Mpc/h, and kpc/h units for convenience
			if h>0.0:
				
				self.kpc_over_h = def_unit("kpc/h",kpc/self._header["h"])
				self.Mpc_over_h = def_unit("Mpc/h",Mpc/self._header["h"])

				#Scale box to kpc/h
				self._header["box_size"] *= self.kpc_over_h
				#Convert to Mpc/h
				self._header["box_size"] = self._header["box_size"].to(self.Mpc_over_h)

				#Read in the comoving distance
				if "comoving_distance" in self._header:
					self._header["comoving_distance"] = (self._header["comoving_distance"] / 1.0e3) * self.Mpc_over_h

			else:
				self._header["box_size"] *= kpc
				logging.debug("Warning! Hubble parameter h is zero!!")

			#Scale masses to correct units
			if h>0.0:
				self._header["masses"] *= (self._mass_unit / self._header["h"])
				self._header["masses"] = (self._header["masses"]*g).to(Msun) 

			#Scale Hubble parameter to correct units
			self._header["H0"] = self._header["h"] * 100 * km / (s*Mpc)

			#Update the dictionary with the number of particles per side
			self._header["num_particles_total_side"] = int(np.round(self._header["num_particles_total"]**(1/3)))

			#Once all the info is available, add a wCDM instance as attribute to facilitate the cosmological calculations
			if h>0.0:
				self.cosmology = w0waCDM(H0=self._header["H0"],Om0=self._header["Om0"],Ode0=self._header["Ode0"],w0=self._header["w0"],wa=self._header["wa"])

			#Set particle number limits that this instance will handle
			self.setLimits()
Example #4
0
def test_assign_cosmo():
    """
        Test to make sure it reassigns the cosmology
    """
    from resspect import cosmo_metric_utils as cmu

    cosmo = w0waCDM(70, 0.3, 0.7, -0.9, 0.0)
    updated_cosmo = cmu.assign_cosmo(cosmo, model=[72, 0.29, 0.71, -1, 0.0])

    assert int(updated_cosmo.H0.value) == int(72)
    assert hasattr(updated_cosmo, 'distmod')
    assert isinstance(updated_cosmo, w0waCDM)
Example #5
0
    def getHeader(self, h=0.72, w0=-1., wa=0.):

        #Create header dictionary
        header = dict()
        header["h"] = h
        header["w0"] = w0
        header["wa"] = wa

        #Read the redshift from the filename
        header["redshift"] = float(
            re.search(r"\.z([0-9\.]+)\.", self.fp.name).groups()[0])
        header["scale_factor"] = 1. / (1. + header["redshift"])

        #Look for the log file that contains all the information we need in the header
        task_number = int(
            re.search(r"\.([0-9]{4})\.", self.fp.name).groups()[0])
        logfile = re.sub(r"\.[0-9]{4}\..*", ".{0:02d}.log".format(task_number),
                         self.fp.name)

        #Read the log file and fill the header
        with open(logfile, "r") as logfp:
            ahflog = logfp.read()

        #Cosmological parameters and box size
        Om0, Ode0, box_size = re.search(
            r"simu\.omega0\s*:\s*([0-9\.]+)\nsimu\.lambda0\s*:\s*([0-9\.]+)\nsimu\.boxsize\s*:\s*([0-9\.]+)",
            ahflog).groups()
        header["Om0"] = float(Om0)
        header["Ode0"] = float(Ode0)
        header["box_size"] = float(box_size) * 1.0e3

        #These are not important
        header["masses"] = np.zeros(6)
        header["num_particles_file"] = 1.
        header["num_particles_total"] = 1.
        header["num_files"] = 1

        #Finally compute the comoving distance
        header["comoving_distance"] = w0waCDM(
            H0=h * 100,
            Om0=header["Om0"],
            Ode0=header["Ode0"],
            w0=header["w0"],
            wa=header["wa"]).comoving_distance(header["redshift"]).to(
                u.kpc).value / h

        #Return to user
        return header
Example #6
0
    def set_cosmology(self, cosmo_dict):
        """Settig cosmological parameters

        Parameters
        ----------
            cosmo_dict : dict
                dictionary of cosmological parameters.
                cosmo_dict needs to include, Omega_de0, Omega_K0, w0, wa, h.
                Omega_m0 is computed internally by Omega_m0 = 1.0 - Omega_de0 - Omega_K0
        """
        Omega_de0 = cosmo_dict['Omega_de0']
        Omega_m0 = 1.0 - cosmo_dict['Omega_de0'] - cosmo_dict['Omega_K0']
        w0 = cosmo_dict['w0']
        wa = cosmo_dict['wa']
        H0 = 100.0 * cosmo_dict['h']
        self.cosmo = w0waCDM(H0, Omega_m0, Omega_de0, w0=w0, wa=wa)
Example #7
0
def llhood_pbc_wzcdm(model_param, ndim, nparam):
    om, h0, w0, wa, MB = [model_param[i] for i in range(5)]

    dist_th = w0waCDM(h0, om, 1 - om, w0,
                      wa).luminosity_distance(pb.zcmb.values).value
    mod_th = 5 * np.log10(dist_th) + 25

    hub_res = pb.mb.values - mod_th - MB

    chisq = np.dot(hub_res.T, np.dot(pb_icm, hub_res))

    if cmb == 1:
        T = cmb_chisq(om, h0, w0, wa)
        chisq += T

    return -0.5 * chisq
def distance_interpolator(z_max=2.0, nz=101, **cosmology) :
	import numpy as np
	from scipy.interpolate import UnivariateSpline
	from astropy.cosmology import w0waCDM
	## This is setting up our cosmology
	cosmo = w0waCDM(100.*cosmology['h0'], cosmology['omega_m'], \
	1.-cosmology['omega_k']-cosmology['omega_m'], w0=cosmology['w'], wa=cosmology['wa'])
	
	## Set up a grid of redshifts at which to evaluate the distance to set up the spline
	table_z = np.linspace(0.0, z_max, num=nz)
	table_r = cosmo.comoving_distance(table_z).value
	
	## Create and return the spline object. Note that a cubic spline works better than
	## a linear spline here
	distance = UnivariateSpline(table_z, table_r, s=0)
	return distance
Example #9
0
    def swift_cosmology_to_astropy(cosmo: dict, units) -> Cosmology:
        """
        Parameters
        ----------

        cosmo: dict
            Cosmology dictionary ready straight out of the SWIFT snapshot.

        units: SWIFTUnits
            The SWIFT Units instance associated with this snapshot.

        Returns
        -------

        Cosmology
            An instance of ``astropy.cosmology.Cosmology`` filled with the
            correct parameters.
        """

        H0 = unyt.unyt_quantity(cosmo["H0 [internal units]"][0],
                                units=1.0 / units.time)

        Omega_b = cosmo["Omega_b"][0]
        Omega_lambda = cosmo["Omega_lambda"][0]
        Omega_r = cosmo["Omega_r"][0]
        Omega_m = cosmo["Omega_m"][0]
        w_0 = cosmo["w_0"][0]
        w_a = cosmo["w_a"][0]

        # SWIFT provides Omega_r, but we need a consistent Tcmb0 for astropy.
        # This is an exact inversion of the procedure performed in astropy.
        critical_density_0 = astropy_units.Quantity(
            critdens_const * H0.to("1/s").value**2,
            astropy_units.g / astropy_units.cm**3,
        )

        Tcmb0 = (Omega_r * critical_density_0.value / a_B_c2)**(1.0 / 4.0)

        return w0waCDM(
            H0=H0.to_astropy(),
            Om0=Omega_m,
            Ode0=Omega_lambda,
            w0=w_0,
            wa=w_a,
            Tcmb0=Tcmb0,
            Ob0=Omega_b,
        )
Example #10
0
	def setHeaderInfo(self,Om0=0.26,Ode0=0.74,w0=-1.0,wa=0.0,h=0.72,redshift=100.0,box_size=15.0*u.Mpc/0.72,flag_cooling=0,flag_sfr=0,flag_feedback=0,flag_stellarage=0,flag_metals=0,flag_entropy_instead_u=0,masses=np.array([0,1.03e10,0,0,0,0])*u.Msun,num_particles_file_of_type=None,npartTotalHighWord=np.zeros(6,dtype=np.uint32)):

		"""
		Sets the header info in the snapshot to write

		"""

		if num_particles_file_of_type is None:
			num_particles_file_of_type = np.array([0,1,0,0,0,0],dtype=np.int32) * self.positions.shape[0]

		assert num_particles_file_of_type.sum()==self.positions.shape[0],"The total number of particles must match!!"
		assert box_size.unit.physical_type=="length"
		assert masses.unit.physical_type=="mass"

		#Create the header
		self._header = Gadget2Header()
		
		#Fill in
		self._header["Om0"] = Om0
		self._header["Ode0"] = Ode0
		self._header["w0"] = w0
		self._header["wa"] = wa
		self._header["h"] = h
		self._header["H0"] = 100.0*h*u.km/(u.s*u.Mpc)
		self._header["redshift"] = redshift
		self._header["scale_factor"] = 1.0 / (1.0 + redshift)
		self._header["box_size"] = box_size
		self._header["flag_cooling"] = flag_cooling
		self._header["flag_sfr"] = flag_sfr
		self._header["flag_feedback"] = flag_feedback
		self._header["flag_stellarage"] = flag_stellarage
		self._header["flag_metals"] = flag_metals
		self._header["flag_entropy_instead_u"] = flag_entropy_instead_u
		self._header["masses"] = masses
		self._header["num_particles_file_of_type"] = num_particles_file_of_type
		self._header["num_particles_file"] = num_particles_file_of_type.sum()
		self._header["num_particles_total_of_type"] = num_particles_file_of_type
		self._header["num_particles_total"] = num_particles_file_of_type.sum()
		self._header["npartTotalHighWord"] = npartTotalHighWord

		#Define the kpc/h and Mpc/h units for convenience
		self.kpc_over_h = u.def_unit("kpc/h",u.kpc/self._header["h"])
		self.Mpc_over_h = u.def_unit("Mpc/h",u.Mpc/self._header["h"])

		#Compute the comoving distance according to the model
		cosmo = w0waCDM(H0=100.0*h,Om0=Om0,Ode0=Ode0,w0=w0,wa=wa)
		self._header["comoving_distance"] = cosmo.comoving_distance(redshift).to(self.Mpc_over_h)
Example #11
0
    def cosmo(self, kwargs):
        """

        :param kwargs: keyword arguments of parameters (can include others not used for the cosmology)
        :return: astropy.cosmology instance
        """
        if self._cosmology == "FLCDM":
            cosmo = FlatLambdaCDM(H0=kwargs['h0'], Om0=kwargs['om'])
        elif self._cosmology == "FwCDM":
            cosmo = FlatwCDM(H0=kwargs['h0'], Om0=kwargs['om'], w0=kwargs['w'])
        elif self._cosmology == "w0waCDM":
            cosmo = w0waCDM(H0=kwargs['h0'], Om0=kwargs['om'], Ode0=1.0 - kwargs['om'], w0=kwargs['w0'], wa=kwargs['wa'])
        elif self._cosmology == "oLCDM":
            cosmo = LambdaCDM(H0=kwargs['h0'], Om0=kwargs['om'], Ode0=1.0 - kwargs['om'] - kwargs['ok'])
        else:
            raise ValueError("Cosmology %s is not supported" % self._cosmology)
        return cosmo
Example #12
0
def log_prob_ddt(theta, lenses, cosmology):
    """
    Compute the likelihood of the given cosmological parameters against the
    modeled angular diameter distances of the lenses.

    param theta: list of loat, folded cosmological parameters.
    param lenses: list of lens objects (currently either GLEELens or LenstronomyLens).
    param cosmology: string, keyword indicating the choice of cosmology to work with.
    """

    lp = log_prior(theta, cosmology)
    if not np.isfinite(lp):
        return -np.inf
    else:
        logprob = lp
        if cosmology == "FLCDM":
            h0, om = theta
            cosmo = FlatLambdaCDM(H0=h0, Om0=om)
        elif cosmology == "ULCDM":
            h0 = theta[0]
            cosmo = FlatLambdaCDM(H0=h0, Om0=0.3)
        elif cosmology == "FwCDM":
            h0, om, w = theta
            cosmo = FlatwCDM(H0=h0, Om0=om, w0=w)
        elif cosmology == "w0waCDM":
            h0, om, w0, wa = theta
            cosmo = w0waCDM(H0=h0, Om0=om, Ode0=1.0 - om, w0=w0, wa=wa)
        elif cosmology == "oLCDM":
            h0, om, ok = theta
            # assert we are not in a crazy cosmological situation that prevents computing the angular distance integral
            if np.any([
                    ok * (1.0 + lens.zsource)**2 + om *
                (1.0 + lens.zsource)**3 + (1.0 - om - ok) <= 0
                    for lens in lenses
            ]):
                return -np.inf
            else:
                cosmo = LambdaCDM(H0=h0, Om0=om, Ode0=1.0 - om - ok)
        else:
            raise ValueError("I don't know the cosmology %s" % cosmology)
        for lens in lenses:
            logprob += log_like_add(lens=lens, cosmo=cosmo)
        return logprob
Example #13
0
def llhood_jlac_wzcdm(model_param, ndim, nparam):
    om, w0, wa, a, b, MB, DM = [model_param[i] for i in range(7)]

    h0 = 70

    dist_th = w0waCDM(h0, om, 1 - om, w0,
                      wa).luminosity_distance(jla.zcmb.values).value
    mod_th = 5 * np.log10(dist_th) + 25

    hub_res = jla.mb.values + a * jla.x1.values - b * jla.color.values - MB - mod_th
    hub_res[jla.hm.values >= 10.] += DM

    C = mu_cov(a, b)
    iC = np.linalg.inv(C)

    chisq = np.dot(hub_res.T, np.dot(iC, hub_res))

    if cmb == 1:
        T = cmb_chisq(om, h0, w0, wa)
        chisq += T

    return -0.5 * chisq
Example #14
0
def llhood_pbd_wzcdm(model_param, ndim, nparam):
    om, h0, w0, wa, MB, od, g = [model_param[i] for i in range(7)]

    A = []
    for i in range(0, len(pb.zcmb.values)):
        At = 10**(od) * attenuation(om, h0, pb.zcmb.values[i], w0, wa, g)
        A.append(At)
    #A_inter = interp1d(z50, A)
    #DUST = A_inter(pb.zcmb.values)

    dist_th = w0waCDM(h0, om, 1 - om, w0,
                      wa).luminosity_distance(pb.zcmb.values).value
    mod_th = 5 * np.log10(dist_th) + 25

    hub_res = pb.mb.values - mod_th - MB - A

    chisq = np.dot(hub_res.T, np.dot(pb_icm, hub_res))

    if cmb == 1:
        T = cmb_chisq(om, h0, w0, wa)
        chisq += T

    return -0.5 * chisq
Example #15
0
	def getHeader(self,h=0.72,w0=-1.,wa=0.):

		#Create header dictionary
		header = dict()
		header["h"] = h
		header["w0"] = w0
		header["wa"] = wa

		#Read the redshift from the filename
		header["redshift"] = float(re.search(r"\.z([0-9\.]+)\.",self.fp.name).groups()[0])
		header["scale_factor"] = 1./(1.+header["redshift"])
		
		#Look for the log file that contains all the information we need in the header
		task_number = int(re.search(r"\.([0-9]{4})\.",self.fp.name).groups()[0])
		logfile = re.sub(r"\.[0-9]{4}\..*",".{0:02d}.log".format(task_number),self.fp.name)

		#Read the log file and fill the header
		with open(logfile,"r") as logfp:
			ahflog = logfp.read()

		#Cosmological parameters and box size
		Om0,Ode0,box_size = re.search(r"simu\.omega0\s*:\s*([0-9\.]+)\nsimu\.lambda0\s*:\s*([0-9\.]+)\nsimu\.boxsize\s*:\s*([0-9\.]+)",ahflog).groups()
		header["Om0"] = float(Om0)
		header["Ode0"] = float(Ode0)
		header["box_size"] = float(box_size)*1.0e3

		#These are not important
		header["masses"] = np.zeros(6)
		header["num_particles_file"] = 1.
		header["num_particles_total"] = 1.
		header["num_files"] = 1

		#Finally compute the comoving distance
		header["comoving_distance"] = w0waCDM(H0=h*100,Om0=header["Om0"],Ode0=header["Ode0"],w0=header["w0"],wa=header["wa"]).comoving_distance(header["redshift"]).to(u.kpc).value / h

		#Return to user
		return header
def fish_deriv_m(redshift, model, step, screen=False):
    """Calculates the derivatives and the base function at given redshifts.

    Parameters
    ----------
    redshift: float or list
        Redshift where derivatives will be calculated.
    model: list
        List of cosmological model parameters.
        Order is [H0, Om, Ode, w0, wa].
    step: list
        List of steps the cosmological model parameter will take when determining
         the derivative.
        If a given entry is zero, that parameter will be kept constant.
        Length must match the number of parameters in "model" variable.
    screen: bool (optional)
        Print debug options to screen. Default is False.

    Returns
    -------
    m: list
        List of theoretical distance modulus (mu) at a given redshift from
         the base cosmology.
    m_deriv: list [len(redshift), len(model)]
        List of parameter derivatives of the likelihood function
         at given redshifts.
    """
    
    Ob0=0.022
    Om0=model[1]
    Ode0 =model[2]
    cosmo = w0waCDM(model[0], Ob0, Om0, Ode0, model[3],model[4])

    cosmo=assign_cosmo(cosmo, model)

    m = []
    m_deriv = []
    c = const.c.to('km/s')
    base_theory = cosmo.distmod(redshift)
    m = base_theory.value
    step_inds = np.where(step)[0] # look for non-zero step indices
    deriv = np.zeros((len(base_theory), len(model)))

    if (step_inds.size==0):
        print('No steps taken, abort')
        exit

    else:
        if screen:
            print('\n')
            print('Computing Fisher derivatives...')

        for i, stepp in enumerate(step_inds):
            if screen:
                print('we are stepping in :', model[stepp], 
                      ' with step size', step[stepp])
            cosmo = assign_cosmo(cosmo, model)

            theory = np.zeros((len(base_theory),2))
            for count,j  in enumerate([-1,1]):

                tempmodel = list(model)
                tempmodel[stepp] = model[stepp] + j*step[stepp]
                c = const.c.to('km/s')
                cosmo = assign_cosmo(cosmo, tempmodel)
                tmp = cosmo.distmod(redshift)
                theory[:,count] = tmp

            deriv[:,stepp] = (theory[:,1] - theory[:,0])/(2.*step[stepp])

    m_deriv = deriv

    return m, m_deriv
Example #17
0
def readFITS(cls,filename,init_cosmology=True):

	#Read the FITS file with the plane information (if there are two HDU's the second one is the imaginary part)
	if fitsio is not None:
		hdu = fitsio(filename)
	else:
		hdu = fits.open(filename)
			
	if len(hdu)>2:
		raise ValueError("There are more than 2 HDUs, file format unknown")

	if fitsio is not None:
		header = hdu[0].read_header()
	else:
		header = hdu[0].header

	#Retrieve the info from the header (handle old FITS header format too)
	try:
		hubble = header["H0"] * (u.km/(u.s*u.Mpc))
		h = header["h"]
	except:
		hubble = header["H_0"] * (u.km/(u.s*u.Mpc))
		h = hubble.value / 100

	Om0 = header["OMEGA_M"]
	Ode0 = header["OMEGA_L"]

	try:
		w0 = header["W0"]
		wa = header["WA"]
	except:
		w0 = header["W_0"]
		wa = header["W_A"]
			
	redshift = header["Z"]
	comoving_distance = (header["CHI"] / h) * u.Mpc

	if "SIDE" in header.keys():
		angle = header["SIDE"] * u.Mpc / h
	elif "ANGLE" in header.keys():
		angle = header["ANGLE"] * u.deg
	else:
		angle = ((header["RES_X"] * header["NAXIS1"] / header["CHI"]) * u.rad).to(u.deg)

	#Build the cosmology object if options directs
	if init_cosmology:
		cosmology = w0waCDM(H0=hubble,Om0=Om0,Ode0=Ode0,w0=w0,wa=wa)
	else:
		cosmology = None

	#Read the number of particles, if present
	try:
		num_particles = header["NPART"]
	except:
		num_particles = None

	#Read the units if present
	try:
		unit_string = header["UNIT"]
		name,exponent = re.match(r"([a-zA-Z]+)([0-9])?",unit_string).groups()
		unit = getattr(u,name)
		if exponent is not None:
			unit **= exponent
	except AttributeError:
		unit = u.dimensionless_unscaled
	except (ValueError,KeyError):
		unit = u.rad**2

	#Instantiate the new PotentialPlane instance
	if fitsio is not None:

		if len(hdu)==1:
			new_plane = cls(hdu[0].read(),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)
		else:
			new_plane = cls(hdu[1].read() + 1.0j*hdu[1].read(),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)

	else:
			
		if len(hdu)==1:
			new_plane = cls(hdu[0].data.astype(np.float64),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)
		else:
			new_plane = cls((hdu[0].data + 1.0j*hdu[1].data).astype(np.complex128),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)

	#Close the FITS file and return
	hdu.close()
	return new_plane
Example #18
0
    def __init__(self,
                 metricName='SNSimulation',
                 mjdCol='observationStartMJD',
                 RACol='fieldRA',
                 DecCol='fieldDec',
                 filterCol='filter',
                 m5Col='fiveSigmaDepth',
                 exptimeCol='visitExposureTime',
                 nightCol='night',
                 obsidCol='observationId',
                 nexpCol='numExposures',
                 vistimeCol='visitTime',
                 seeingEffCol='seeingFwhmEff',
                 airmassCol='airmass',
                 skyCol='sky',
                 moonCol='moonPhase',
                 seeingGeomCol='seeingFwhmGeom',
                 uniqueBlocks=False,
                 config=None,
                 x0_norm=None,
                 **kwargs):

        self.mjdCol = mjdCol
        self.m5Col = m5Col
        self.filterCol = filterCol
        self.RACol = RACol
        self.DecCol = DecCol
        self.exptimeCol = exptimeCol
        self.seasonCol = 'season'
        self.nightCol = nightCol
        self.obsidCol = obsidCol
        self.nexpCol = nexpCol
        self.vistimeCol = vistimeCol
        self.seeingEffCol = seeingEffCol
        self.seeingGeomCol = seeingGeomCol
        self.airmassCol = airmassCol
        self.skyCol = skyCol
        self.moonCol = moonCol

        cols = [
            self.RACol, self.DecCol, self.nightCol, self.m5Col, self.filterCol,
            self.mjdCol, self.obsidCol, self.nexpCol, self.vistimeCol,
            self.exptimeCol, self.seeingEffCol, self.seeingGeomCol,
            self.nightCol, self.airmassCol, self.moonCol
        ]

        # self.airmassCol, self.skyCol, self.moonCol]
        self.stacker = None

        coadd = config['Observations']['coadd']

        if coadd:
            # cols += ['sn_coadd']
            self.stacker = CoaddStacker(
                mjdCol=self.mjdCol,
                RACol=self.RACol,
                DecCol=self.DecCol,
                m5Col=self.m5Col,
                nightCol=self.nightCol,
                filterCol=self.filterCol,
                numExposuresCol=self.nexpCol,
                visitTimeCol=self.vistimeCol,
                visitExposureTimeCol='visitExposureTime')
        super(SNSimulation, self).__init__(col=cols,
                                           metricName=metricName,
                                           **kwargs)

        # bands considered
        self.filterNames = 'ugrizy'

        # grab config file
        self.config = config

        # healpix nside and area
        self.nside = config['Pixelisation']['nside']
        self.area = hp.nside2pixarea(self.nside, degrees=True)

        # prodid
        self.prodid = config['ProductionID']

        # load cosmology
        cosmo_par = config['Cosmology']
        self.cosmology = w0waCDM(H0=cosmo_par['H0'],
                                 Om0=cosmo_par['Omega_m'],
                                 Ode0=cosmo_par['Omega_l'],
                                 w0=cosmo_par['w0'],
                                 wa=cosmo_par['wa'])

        # load telescope
        tel_par = config['Instrument']
        self.telescope = Telescope(name=tel_par['name'],
                                   throughput_dir=tel_par['throughput_dir'],
                                   atmos_dir=tel_par['atmos_dir'],
                                   atmos=tel_par['atmos'],
                                   aerosol=tel_par['aerosol'],
                                   airmass=tel_par['airmass'])

        # sn parameters
        self.sn_parameters = config['SN parameters']
        self.gen_par = SimuParameters(
            self.sn_parameters,
            cosmo_par,
            mjdCol=self.mjdCol,
            area=self.area,
            dirFiles=self.sn_parameters['x1_color']['dirFile'],
            web_path=config['Web path'])

        # this is for output

        save_status = config['Output']['save']
        self.save_status = save_status
        self.outdir = config['Output']['directory']

        # number of procs to run simu here
        self.nprocs = config['Multiprocessing']['nproc']

        # if saving activated, prepare output dirs
        """
        if self.save_status:
            self.prepareSave(outdir, prodid)
        """
        # simulator parameter
        self.simu_config = config['Simulator']

        # LC display in "real-time"
        self.display_lc = config['Display_LC']['display']
        self.time_display = config['Display_LC']['time']

        # fieldtype, season
        self.field_type = config['Observations']['fieldtype']
        self.season = config['Observations']['season']

        self.type = 'simulation'

        # get the x0_norm values to be put on a 2D(x1,color) griddata
        self.x0_grid = x0_norm

        # SALT2DIR
        self.salt2Dir = self.sn_parameters['salt2Dir']

        # hdf5 index
        self.index_hdf5 = 100

        # load reference LC if simulator is sn_fast
        self.reference_lc = None
        self.gamma = None
        self.mag_to_flux = None
        self.dustcorr = None
        web_path = config['Web path']
        self.error_model = self.simu_config['error_model']

        if 'sn_fast' in self.simu_config['name']:
            templateDir = self.simu_config['Template Dir']
            gammaDir = self.simu_config['Gamma Dir']
            gammaFile = self.simu_config['Gamma File']
            dustDir = self.simu_config['DustCorr Dir']

            # x1 and color are unique for this simulator
            x1 = self.sn_parameters['x1']['min']
            color = self.sn_parameters['color']['min']
            bluecutoff = self.sn_parameters['blue_cutoff']
            redcutoff = self.sn_parameters['red_cutoff']
            # Loading reference file
            lcname = 'LC_{}_{}_{}_{}_ebvofMW_0.0_vstack.hdf5'.format(
                x1, color, bluecutoff, redcutoff)

            self.reference_lc = GetReference(templateDir, lcname, gammaDir,
                                             gammaFile, web_path,
                                             self.telescope)

            dustFile = 'Dust_{}_{}_{}_{}.hdf5'.format(x1, color, bluecutoff,
                                                      redcutoff)
            self.dustcorr = LoadDust(dustDir, dustFile, web_path).dustcorr

        else:
            gammas = LoadGamma('grizy', self.simu_config['Gamma Dir'],
                               self.simu_config['Gamma File'], web_path,
                               self.telescope)

            self.gamma = gammas.gamma
            self.mag_to_flux = gammas.mag_to_flux

        if self.error_model:
            SALT2Dir = 'SALT2.Guy10_UV2IR'
            check_get_dir(web_path, SALT2Dir, SALT2Dir)

        self.nprocdict = {}
        self.simu_out = {}
        self.lc_out = {}
        self.SNID = {}
        self.sn_meta = {}
num_z_points = 100
redshift_max = 3
redshift_min = 0
redshifts = np.linspace(redshift_min, redshift_max, num=num_z_points)


# h, Om, Oa, w 
param1 = np.array([1,  1.0, 0.0,   0  ])
param2 = np.array([1, 0.25, 0.75, -1  ])
param3 = np.array([1, 0.25, 0.75, -0.8])
param4 = np.array([1, 0.25, 0.75, -1.2])
hval = 1.0

paramALL = np.array([param1, param2, param3, param4])

cosmo1 = w0waCDM(H0=100.*hval*param1[0], Om0=param1[1], Ode0=param1[2] )
cosmo2 = w0waCDM(H0=100.*hval*param2[0], Om0=param2[1], Ode0=param2[2], w0=param2[3])
cosmo3 = w0waCDM(H0=100.*hval*param3[0], Om0=param3[1], Ode0=param3[2], w0=param3[3])
cosmo4 = w0waCDM(H0=100.*hval*param4[0], Om0=param4[1], Ode0=param4[2], w0=param4[3])

"""
test_z = 0.5
dc = cosmo1.comoving_distance(test_z)
print("Test value for dc = ", dc)
"""
#Units: Mpc
dcmpc1 = cosmo1.comoving_distance(redshifts)
dcmpc2 = cosmo2.comoving_distance(redshifts)
dcmpc3 = cosmo3.comoving_distance(redshifts)
dcmpc4 = cosmo4.comoving_distance(redshifts)
def get_dist_w0(z, err_per=0):
    model = w0waCDM(H0=68*u.km/u.s/u.Mpc, Om0=0.28, Ode0=0.73, w0=-0.9, wa=0.2)
    dist = model.angular_diameter_distance(z).value
    error = (err_per*dist)*np.random.normal(0,1,np.shape(z))
    return dist+error
    def __init__(self, H0=73.0, Om0=0.25, Ok0=None, w0=None, wa=None):
        """
        Initialize the cosmology wrapper with the parameters specified
        (e.g. does not account for massive neutrinos)

        param [in] H0 is the Hubble parameter at the present epoch in km/s/Mpc

        param [in] Om0 is the current matter density paramter (fraction of critical density)

        param [in] Ok0 is the current curvature density parameter

        param [in] w0 is the current dark energy equation of state w0 paramter

        param[in] wa is the current dark energy equation of state wa paramter

        The total dark energy equation of state as a function of z is
        w = w0 + wa z/(1+z)

        Currently, this wrapper class expects you to specify either a LambdaCDM (flat or non-flat) cosmology
        or a w0, wa (flat or non-flat) cosmology.

        The default cosmology is taken as the cosmology used
        in the Millennium Simulation (Springel et al 2005, Nature 435, 629 or
        arXiv:astro-ph/0504097)

        Om0 = 0.25
        Ob0  = 0.045 (baryons; not currently used in this code)
        H0 = 73.0
        Ok0 = 0.0, (implying Ode0 approx 0.75)
        w0 = -1.0
        wa = 0.0

        where 
        Om0 + Ok0 + Ode0 + Ogamma0 + Onu0 = 1.0 

        sigma_8 = 0.9 (rms mass flucutation in an 8 h^-1 Mpc sphere;
                       not currently used in this code)

        ns = 1 (index of the initial spectrum of linear mas perturbations;
                not currently used in this code)

        """

        self.activeCosmology = None

        if w0 is not None and wa is None:
            wa = 0.0

        isCosmologicalConstant = False
        if (w0 is None and wa is None) or (w0==-1.0 and wa==0.0):
            isCosmologicalConstant = True

        isFlat = False
        if Ok0 is None or (numpy.abs(Ok0) < flatnessthresh):
            isFlat = True

        if isCosmologicalConstant and isFlat:
            universe = cosmology.FlatLambdaCDM(H0=H0, Om0=Om0)
        elif isCosmologicalConstant:
            tmpmodel = cosmology.FlatLambdaCDM(H0=H0, Om0=Om0)
            Ode0 = 1.0 - Om0 - tmpmodel.Ogamma0 - tmpmodel.Onu0 - Ok0 
            universe = cosmology.LambdaCDM(H0=H0, Om0=Om0, Ode0=Ode0)
        elif isFlat:
            universe = cosmology.Flatw0waCDM(H0=H0, Om0=Om0, w0=w0, wa=wa)
        else:
            tmpmodel = cosmology.Flatw0waCDM(H0=H0, Om0=Om0, w0=w0, wa=wa)
            Ode0 = 1.0 - Om0 - tmpmodel.Ogamma0 - tmpmodel.Onu0 - Ok0 

            universe = cosmology.w0waCDM(H0=H0, Om0=Om0, Ode0=Ode0,
                                         w0=w0, wa=wa)

        self.setCurrent(universe)
Example #22
0
    print "Beginning"
    t0 = ti.time()
    for jj in np.arange(len(o_m_array)):
        o_m = o_m_array[jj]
        o_x = 1. - o_m
        for ii in np.arange(len(redshift_range)):
            dist_mods_functions[ii] = dist_mod_marg(redshift_range[ii], o_m,
                                                    w0, wa)
    print "Functions done in", ti.time() - t0, "seconds"
    print dist_mods_functions[-10:] - dist_mods_functions[-11:-1]

    t0 = ti.time()
    for ii in np.arange(len(o_m_array)):
        cpl = cosmo.w0waCDM(H0=hubble_const,
                            Om0=o_m_array[ii],
                            Ode0=o_x,
                            w0=w0,
                            wa=wa)
        dist_mods_astropy = cpl.distmod(redshift_range)
    print "Astropy done in", ti.time() - t0, "seconds"

    print dist_mods_astropy[-10:] - dist_mods_astropy[-11:-1]

    print(dist_mods_functions[:10] - dist_mods_functions[1:11]
          ) - np.array(dist_mods_astropy[:10] - dist_mods_astropy[1:11])
    '''Here we test the performance of functions against astropy for n=3 nCPL'''
    '''
	import Flatn3CPL
	import time as ti
	redshift_range = np.linspace(0.001, 10, 30)
	dist_mods_functions = np.zeros(len(redshift_range))
Example #23
0
z_min = 0.0 #min redshift
z_max = 3.0 #max redshift
num_z = 100

z_array = np.linspace(z_min, z_max, num=num_z)

hval = 1.0


"""
-------------------
-***COSMOLOGIES***-
-------------------
"""

cosmo1 = w0waCDM(H0=100.*hval, Om0=1.0, Ode0=0.0 )
cosmo2 = w0waCDM(H0=100.*hval, Om0=0.25, Ode0=0.75, w0=-1)
cosmo3 = w0waCDM(H0=100.*hval, Om0=0.25, Ode0=0.75, w0=-0.8)
cosmo4 = w0waCDM(H0=100.*hval, Om0=0.25, Ode0=0.75, w0=-1.2)


"""
-------------------------
-***COMOVING DISTANCE***-
-------------------------
"""

comoving_d1_Mpc = cosmo1.comoving_distance(z_array)
comoving_d2_Mpc = cosmo2.comoving_distance(z_array)
comoving_d3_Mpc = cosmo3.comoving_distance(z_array)
comoving_d4_Mpc = cosmo4.comoving_distance(z_array)
Example #24
0
    def cosmology(self, H0, Omega_m, Omega_l, w0, wa):

        cosmo = w0waCDM(H0=H0, Om0=Omega_m, Ode0=Omega_l, w0=w0, wa=wa)
        return cosmo
def column_deriv_m(redshift, mu_err, model, step):
    """Calculate a column derivative of your model.
    
       Define a matrix P such that P_ik = 1/sigma_i del(M(i, params)/del(param_k)
       and M=model. This column matrix holds k constant.

    Parameters
    ----------
    redshift: float or list
        Redshift.
    mu_err: float or list
        Error in distance modulus.
    model: list
        List of cosmological model parameters.
        Order is [H0, om, ol, w0, wa].
    step: list
        List of steps the cosmological model paramter will take when determining
        the derivative.
        If a given entry is zero, that parameter will be kept constant.
        Length must match the number of parameters in "model" variable.

    Returns
    -------
    m: list
        List of theoretical distance modulus (mu) at a given redshift from
         the base cosmology.
    m_deriv: list
        List of derivatives for one parameter of the likelihood function
         at given redshifts.
    """

    Ob0=0.022
    Om0=model[1]
    Ode0 =model[2]
    cosmo = w0waCDM(model[0], Ob0, Om0, Ode0, model[3],model[4])

    cosmo=assign_cosmo(cosmo, model)
    m = []
    m_deriv = []
    c = const.c.to('km/s')
    base_theory = cosmo.distmod(redshift)
    m = base_theory.value
    step_inds = np.where(step)[0] # look for non-zero step indices
    deriv = np.zeros(len(model))

    if (step_inds.size==0):
        print('No steps taken, abort')
        exit

    else:

        for i, stepp in enumerate(step_inds):
            cosmo = assign_cosmo(cosmo, model)

            theory = np.zeros((1,2))
            for count,j  in enumerate([-1,1]):

                tempmodel = list(model)
                tempmodel[stepp] = model[stepp] + j*step[stepp]
                c = const.c.to('km/s')
                cosmo = assign_cosmo(cosmo, tempmodel)
                tmp = cosmo.distmod(redshift)
                theory[:,count] = tmp.value

            deriv[stepp] = (theory[:,1] - theory[:,0])/(2.*step[stepp])

    m_deriv = 1.0/mu_err * deriv

    return m, m_deriv
Example #26
0




# w0waCDM: cm
cosmoconstants = {'H0':67.8, 'Om': 0.308, 'w0':-0.9, 'wa':0.2}
cosmo = Cosmo()
DL1 = cosmo.luminosity_distance(redshifts=redshifts, 
                                 model='w0waCDM', 
                                 units='cm',
                                 **cosmoconstants)

cosmo = w0waCDM(H0=cosmoconstants['H0'], 
                Om0=cosmoconstants['Om'],
                Ode0=1-cosmoconstants['Om'],
                w0=cosmoconstants['w0'], 
                wa=cosmoconstants['wa'])
DL2 = np.asarray(cosmo.luminosity_distance(redshifts)*u.Mpc.to(u.cm))
[print('%.6E  %.6E   %s'%(i,j, i==j)) for i,j in zip(DL1, DL2)]
print(rms(abs(np.log10(DL1) - np.log10(DL2))))
pltLims = (np.min([DL1.min(), DL2.min()]), 
           np.min([DL1.max(), DL2.max()]))
plt.clf()
plt.figure(figsize=(8,7))
plt.plot(DL1, DL2, 'r.')
plt.plot(DL1, 1*DL1+0, 'k-', alpha=0.5)
plt.xlim(*pltLims)
plt.ylim(*pltLims)
plt.show()
Example #27
0
 def __init__(self):
     self.cosmo = w0waCDM(70.0, 0.3, 0.7)
### The r_parallel grid that we will want to use
r_par = np.logspace(np.log(min_sep), np.log(max_sep), num=nbins + 1, base=np.e)
## Redshift-distance conversion spline
### First, get the cosmology
config1 = ConfigParser.RawConfigParser()
config1.read(cosmology)
cos_param_sec = 'cosmological_parameters'
h0 = config1.getfloat(cos_param_sec, 'h0')
omega_m = config1.getfloat(cos_param_sec, 'omega_m')
omega_k = config1.getfloat(cos_param_sec, 'omega_k')
omega_L = 1.0 - omega_m - omega_k
w0 = config1.getfloat(cos_param_sec, 'w')
wa = config1.getfloat(cos_param_sec, 'wa')
### Now set up the astropy cosmology object
if w0 != -1.0 or wa != 0.0:
    cosmo = w0waCDM(100 * h0, omega_m, omega_L, w0=w0, wa=wa)
else:
    cosmo = FlatLambdaCDM(100 * h0, omega_m)
### Finally, get distances at a grid of redshfits and use a spline to interpolate
table_z, delta_z = np.linspace(0.0, 2.0, num=101, retstep=True)
table_r = cosmo.comoving_distance(table_z).value
dist = UnivariateSpline(table_z, table_r, s=0)
invdist = UnivariateSpline(table_r, table_z, s=0)

# Define output file paths
save_dir = os.path.join(
    save_base,
    'pc_nbins{}_smin{}_smax{}_b{}_ncen{}_z{}min{}_z{}max{}_nz{}_scatter{}'.
    format(nbins, min_sep, max_sep, b, ncen, zbf, zmin, zbf, zmax, nz,
           args.sigmaz))
if not os.path.exists(save_dir):
Example #29
0
def readFITS(cls,filename,init_cosmology=True):

	#Read the FITS file with the plane information (if there are two HDU's the second one is the imaginary part)
	if fitsio is not None:
		hdu = fitsio(filename)
	else:
		hdu = fits.open(filename)
			
	if len(hdu)>2:
		raise ValueError("There are more than 2 HDUs, file format unknown")

	if fitsio is not None:
		header = hdu[0].read_header()
	else:
		header = hdu[0].header

	#Retrieve the info from the header (handle old FITS header format too)
	try:
		hubble = header["H0"] * (u.km/(u.s*u.Mpc))
		h = header["h"]
	except:
		hubble = header["H_0"] * (u.km/(u.s*u.Mpc))
		h = hubble.value / 100

	Om0 = header["OMEGA_M"]
	Ode0 = header["OMEGA_L"]

	try:
		w0 = header["W0"]
		wa = header["WA"]
	except:
		w0 = header["W_0"]
		wa = header["W_A"]
			
	redshift = header["Z"]
	comoving_distance = (header["CHI"] / h) * u.Mpc

	if "SIDE" in header.keys():
		angle = header["SIDE"] * u.Mpc / h
	elif "ANGLE" in header.keys():
		angle = header["ANGLE"] * u.deg
	else:
		angle = ((header["RES_X"] * header["NAXIS1"] / header["CHI"]) * u.rad).to(u.deg)

	#Build the cosmology object if options directs
	if init_cosmology:
		cosmology = w0waCDM(H0=hubble,Om0=Om0,Ode0=Ode0,w0=w0,wa=wa)
	else:
		cosmology = None

	#Read the number of particles, if present
	try:
		num_particles = header["NPART"]
	except:
		num_particles = None

	#Read the units if present
	try:
		unit_string = header["UNIT"]
		name,exponent = re.match(r"([a-zA-Z]+)([0-9])?",unit_string).groups()
		unit = getattr(u,name)
		if exponent is not None:
			unit **= exponent
	except AttributeError:
		unit = u.dimensionless_unscaled
	except (ValueError,KeyError):
		unit = u.rad**2

	#Instantiate the new PotentialPlane instance
	if fitsio is not None:

		if len(hdu)==1:
			new_plane = cls(hdu[0].read(),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)
		else:
			new_plane = cls(hdu[1].read() + 1.0j*hdu[1].read(),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)

	else:
			
		if len(hdu)==1:
			new_plane = cls(hdu[0].data.astype(np.float64),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)
		else:
			new_plane = cls((hdu[0].data + 1.0j*hdu[1].data).astype(np.complex128),angle=angle,redshift=redshift,comoving_distance=comoving_distance,cosmology=cosmology,unit=unit,num_particles=num_particles,filename=filename)

	#Close the FITS file and return
	hdu.close()
	return new_plane