def sed_from_galacticus_mags(galacticus_mags, redshift, h=0.71, omega_m=0.265): """ galacticus_mags is a numpy array such that galacticus_mags[i][j] is the magnitude of the jth star in the ith bandpass, where the bandpasses are ordered in ascending order of minimum wavelength. Will return a numpy array of SED names and a numpy array of magNorms. """ if not _LSST_IS_AVAILABLE: raise RuntimeError("You cannot use sed_from_galacticus_mags\n" "You do not have *lsst* installed and setup") if not hasattr(sed_from_galacticus_mags, '_sed_color_tree'): catsim_dir \ = os.path.join(getPackageDir('sims_GCRCatSimInterface'), 'data') color_grid_file = os.path.join(catsim_dir, 'CatSimMagGrid.txt') if not os.path.exists(color_grid_file): msg = '\n%s does not exist\n' % color_grid_file msg += 'Go into the directory %s ' % catsim_dir msg += 'and run the script get_sed_mags.py' raise RuntimeError(msg) dtype_list = [('name', str, 200)] for ii in range(30): dtype_list.append(('mag%d' % ii, float)) dtype_list.append(('magNorm', float)) dtype = np.dtype(dtype_list) sed_data = np.genfromtxt(color_grid_file, dtype=dtype) sed_colors = np.array([sed_data['mag%d' % (ii+1)] - sed_data['mag%d' % ii] for ii in range(29)]) sed_from_galacticus_mags._sed_colors = sed_colors.transpose() sed_from_galacticus_mags._sed_names = sed_data['name'] sed_from_galacticus_mags._mag_norm = sed_data['magNorm'] sed_from_galacticus_mags._sed_mags = np.array([sed_data['mag%d' % ii] for ii in range(30)]).transpose() cosmology = CosmologyObject(H0=100.0*h, Om0=omega_m) distance_modulus = cosmology.distanceModulus(redshift=redshift) assert len(distance_modulus) == len(galacticus_mags[0]) galacticus_colors = np.array([galacticus_mags[ii+1]-galacticus_mags[ii] for ii in range(29)]).transpose() mag_dex = np.zeros(len(galacticus_colors), dtype=int) for i_star in range(len(galacticus_colors)): dd = np.sum((galacticus_colors[i_star] -sed_from_galacticus_mags._sed_colors)**2, axis=1) mag_dex[i_star] = np.argmin(dd) output_names = sed_from_galacticus_mags._sed_names[mag_dex] chosen_mags = sed_from_galacticus_mags._sed_mags[mag_dex] galacticus_mags_t = galacticus_mags.transpose() d_mag = (galacticus_mags_t - chosen_mags).sum(axis=1)/30.0 output_mag_norm = sed_from_galacticus_mags._mag_norm[mag_dex] + d_mag + distance_modulus assert len(output_mag_norm) == len(output_names) return output_names, output_mag_norm
def testComovingDistance(self): """ Test comoving distance calculation Note: this is comoving distance defined as X in the FRW metric ds^2 = -c^2 dt^2 + a^2 dX^2 + sin^2(X) dOmega^2 where spatial curvature is accounted for in the sin function """ H0 = 73.0 for Om0 in np.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.85, step=0.2): for wa in np.arange(start=-0.1, stop=0.115, step=0.02): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in np.arange(start=0.1, stop=4.2, step=2.0): comovingControl = universe.comovingDistance(redshift=zz) comovingTest = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] self.assertAlmostEqual(comovingControl/comovingTest, 1.0, 4)
class CosmologyMixin(object): """ This class is designed to operate as a mixin for InstanceCatalog classes. It provides a member variable self.cosmology which is an instantiation of the CosmologyObject class. self.cosmology defaults to the Milliennium Simulation cosmology. This mixin also provides a method self.setCosmology() which will allow the user to customize self.cosmology and a getter for the column cosmologicalDistanceModulus that reflects the effect of the luminosity distance on a galaxy's component magnitudes. NOTE: one should only include this mixin in catalogs whose magNorm is normalized to an absolute magnitude of some sort (i.e. the magnitude if the galaxy was at redshift=0). The magNorms for galaxies stored on the University of Washington LSSTCATSIM database do not fit this criterion. magNorms on the University of Washington LSSTCATSIM database include the effects of cosmological distance modulus. """ cosmology = CosmologyObject() def setCosmology(self, H0=73.0, Om0=0.25, Ok0=None, w0=None, wa=None): """ This method customizes the member variable self.cosmology by re-instantiating the CosmologyObject class param [in] H0 is the Hubble parameter today in km/s/Mpc param [in] Om0 is the density paramter (fraction of critical) associated with matter today param [in] Ode0 is the density paratmer associated with dark energy today param [in] w0 is the w0 parameter associated with the equation of state of dark energy w = w0 + wa z/(1+z) param [in] wa is the wa parameter usesd to set the equation of state of dark energy w = w0 + wa z/(1+z) """ self.cosmology = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) @cached def get_cosmologicalDistanceModulus(self): """ getter for cosmologicalDistanceModulus (the effect of the luminosity distance on a galaxy's component magnitudes) """ redshift = self.column_by_name("redshift") if len(redshift) == 0: #newer versions of astropy do not appreciate being passed an #empty numpy array of redshifts; avoid nasty exceptions by #just returning an empty numpy array if we got an empty numpy array return numpy.array([]) return self.cosmology.distanceModulus(redshift)
def get_m_i(abs_mag_i, redshift): """ Take numpy arrays of absolute i-band magnitude and cosmological redshift. Return a numpy array of observed i-band magnitudes """ z_grid, k_grid = create_k_corr_grid() k_corr = np.interp(redshift, z_grid, k_grid) dc2_cosmo = CosmologyObject(H0=71.0, Om0=0.265) distance_modulus = dc2_cosmo.distanceModulus(redshift=redshift) obs_mag_i = abs_mag_i + distance_modulus + k_corr return obs_mag_i
def testDistanceModulusAtZero(self): """ Test to make sure that the distance modulus is set to zero if the distance modulus method returns a negative number """ universe = CosmologyObject() ztest = [0.0, 1.0, 2.0, 0.0, 3.0] mm = universe.distanceModulus(redshift=ztest) self.assertEqual(mm[0], 0.0) self.assertEqual(mm[3], 0.0) self.assertEqual(mm[1], 5.0*np.log10(universe.luminosityDistance(ztest[1])) + 25.0) self.assertEqual(mm[2], 5.0*np.log10(universe.luminosityDistance(ztest[2])) + 25.0) self.assertEqual(mm[4], 5.0*np.log10(universe.luminosityDistance(ztest[4])) + 25.0)
def testGetCurrent(self): """ Test to make sure that getCurrent returns the activeCosmology """ for Om0 in np.arange(start=0.2, stop=0.5, step=0.29): for Ok0 in np.arange(start=-0.2, stop=0.2, step=0.39): for w0 in np.arange(start=-1.2, stop=-0.7, step=0.49): for wa in np.arange(start=-0.2, stop=0.2, step=0.39): universe = CosmologyObject(Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) testUniverse = universe.getCurrent() for zz in np.arange(start=1.0, stop=2.1, step=1.0): self.assertEqual(universe.OmegaMatter(redshift=zz), testUniverse.Om(zz)) self.assertEqual( universe.OmegaDarkEnergy(redshift=zz), testUniverse.Ode(zz)) self.assertEqual( universe.OmegaPhotons(redshift=zz), testUniverse.Ogamma(zz)) self.assertEqual( universe.OmegaNeutrinos(redshift=zz), testUniverse.Onu(zz)) self.assertEqual( universe.OmegaCurvature(redshift=zz), testUniverse.Ok(zz))
def testLuminosityDistance(self): """ Test the calculation of the luminosity distance """ H0 = 73.0 for Om0 in numpy.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in numpy.arange(start=-0.1, stop=0.11, step=0.2): for w0 in numpy.arange(start=-1.1, stop=-0.85, step=0.2): for wa in numpy.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = numpy.sqrt( numpy.abs(universe.OmegaCurvature())) * universe.H( ) / self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in numpy.arange(start=0.1, stop=4.2, step=2.0): luminosityControl = universe.luminosityDistance( redshift=zz) comovingDistance = self.speedOfLight * scipy.integrate.quad( comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature() < 0.0: nn = sqrtkCurvature * comovingDistance nn = numpy.sin(nn) luminosityTest = (1.0 + zz) * nn / sqrtkCurvature elif universe.OmegaCurvature() > 0.0: nn = sqrtkCurvature * comovingDistance nn = numpy.sinh(nn) luminosityTest = (1.0 + zz) * nn / sqrtkCurvature else: luminosityTest = (1.0 + zz) * comovingDistance self.assertAlmostEqual( luminosityControl / luminosityTest, 1.0, 4)
def setCosmology(self, H0=73.0, Om0=0.25, Ok0=None, w0=None, wa=None): """ This method customizes the member variable self.cosmology by re-instantiating the CosmologyObject class param [in] H0 is the Hubble parameter today in km/s/Mpc param [in] Om0 is the density paramter (fraction of critical) associated with matter today param [in] Ode0 is the density paratmer associated with dark energy today param [in] w0 is the w0 parameter associated with the equation of state of dark energy w = w0 + wa z/(1+z) param [in] wa is the wa parameter usesd to set the equation of state of dark energy w = w0 + wa z/(1+z) """ self.cosmology = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa)
def get_m_i(abs_mag_i, redshift): """ (Edited from original because of error) Take numpy arrays of absolute i-band magnitude and cosmological redshift. Returns ------- array-like observed i-band magnitudes """ z_grid, k_grid = create_k_corr_grid(redshift) k_corr = np.interp(redshift, z_grid, k_grid) dc2_cosmo = CosmologyObject(H0=71.0, Om0=0.265) distance_modulus = dc2_cosmo.distanceModulus(redshift=redshift) obs_mag_i = abs_mag_i + distance_modulus + k_corr return obs_mag_i
def testNonFlatW0Wa(self): """ Test the evolution of H and Omega_i as a function of redshift for non-flat models with w = w0 + wa * z / (1+z) """ H0 = 60.0 for Om0 in np.arange(start=0.15, stop=0.76, step=0.3): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.89, step=0.2): for wa in np.arange(start=-0.1, stop=0.15, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual(Ok0, universe.OmegaCurvature(redshift=0.0), 10) self.assertAlmostEqual(1.0 - Om0 - Ok0 - universe.OmegaDarkEnergy(redshift=0.0), Og0 + Onu0, 10) self.assertAlmostEqual(universe.H(redshift=0.0), H0, 10) Om0 = universe.OmegaMatter(redshift=0.0) Ode0 = universe.OmegaDarkEnergy(redshift=0.0) for zz in np.arange(start=0.0, stop=4.0, step=2.0): wControl = w0 + wa*(1.0 - 1.0/(1.0+zz)) self.assertAlmostEqual(wControl, universe.w(redshift=zz), 6) Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0, w0=w0, wa=wa, Ode0=Ode0) self.assertAlmostEqual(OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual(OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual(OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual(OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual(OkControl, universe.OmegaCurvature(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
def testCatalogDistanceModulus(self): """ Does cosmologicalDistanceModulus get properly applied """ dbObj = myTestGals(database=self.dbName) cosmoCat = cosmologicalGalaxyCatalog(dbObj) controlCat = absoluteGalaxyCatalog(dbObj) cosmoIter = cosmoCat.iter_catalog(chunk_size=self.dbSize) controlIter = controlCat.iter_catalog(chunk_size=self.dbSize) cosmology = CosmologyObject() for (cosmoRow, controlRow) in zip(cosmoIter, controlIter): modulus = cosmology.distanceModulus(controlRow[25]) self.assertEqual(cosmoRow[0], controlRow[0]) self.assertEqual(cosmoRow[25], controlRow[25]) self.assertEqual(cosmoRow[26], modulus) for i in range(1,25): self.assertAlmostEqual(cosmoRow[i], controlRow[i] + modulus, 6)
def testCatalogDistanceModulus(self): """ Does cosmologicalDistanceModulus get properly applied """ dbObj = myTestGals(database=self.dbName) cosmoCat = cosmologicalGalaxyCatalog(dbObj, obs_metadata=self.obs) controlCat = absoluteGalaxyCatalog(dbObj, obs_metadata=self.obs) cosmoIter = cosmoCat.iter_catalog(chunk_size=self.dbSize) controlIter = controlCat.iter_catalog(chunk_size=self.dbSize) cosmology = CosmologyObject() for (cosmoRow, controlRow) in zip(cosmoIter, controlIter): modulus = cosmology.distanceModulus(controlRow[25]) self.assertEqual(cosmoRow[0], controlRow[0]) self.assertEqual(cosmoRow[25], controlRow[25]) self.assertEqual(cosmoRow[26], modulus) for i in range(1, 25): self.assertAlmostEqual(cosmoRow[i], controlRow[i] + modulus, 6)
def testDistanceModulus(self): """ Test the calculation of the distance modulus out to a certain redshift """ H0 = 73.0 universe = CosmologyObject() for Om0 in np.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.85, step=0.2): for wa in np.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = \ np.sqrt(np.abs(universe.OmegaCurvature()))*universe.H()/self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in np.arange(start=0.1, stop=4.2, step=2.0): modulusControl = universe.distanceModulus(redshift=zz) comovingDistance = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature() < 0.0: nn = sqrtkCurvature*comovingDistance nn = np.sin(nn) luminosityDistance = (1.0+zz)*nn/sqrtkCurvature elif universe.OmegaCurvature() > 0.0: nn = sqrtkCurvature*comovingDistance nn = np.sinh(nn) luminosityDistance = (1.0+zz)*nn/sqrtkCurvature else: luminosityDistance = (1.0+zz)*comovingDistance modulusTest = 5.0*np.log10(luminosityDistance) + 25.0 self.assertAlmostEqual(modulusControl/modulusTest, 1.0, 4)
class CosmologyMixin(object): """ This class is designed to operate as a mixin for InstanceCatalog classes. It provides a member variable self.cosmology which is an instantiation of the CosmologyObject class. self.cosmology defaults to the Milliennium Simulation cosmology. This mixin also provides a method self.setCosmology() which will allow the user to customize self.cosmology and a getter for the column cosmologicalDistanceModulus that reflects the effect of the luminosity distance on a galaxy's component magnitudes. NOTE: one should only include this mixin in catalogs whose magNorm is normalized to an absolute magnitude of some sort (i.e. the magnitude if the galaxy was at redshift=0). The magNorms for galaxies stored on the University of Washington LSST database do not fit this criterion. magNorms on the University of Washington LSST database include the effects of cosmological distance modulus. """ cosmology = CosmologyObject() def setCosmology(self, H0=73.0, Om0=0.25, Ok0=None, w0=None, wa=None): """ This method customizes the member variable self.cosmology by re-instantiating the CosmologyObject class param [in] H0 is the Hubble parameter today in km/s/Mpc param [in] Om0 is the density paramter (fraction of critical) associated with matter today param [in] Ode0 is the density paratmer associated with dark energy today param [in] w0 is the w0 parameter associated with the equation of state of dark energy w = w0 + wa z/(1+z) param [in] wa is the wa parameter usesd to set the equation of state of dark energy w = w0 + wa z/(1+z) """ self.cosmology = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) @cached def get_cosmologicalDistanceModulus(self): """ getter for cosmologicalDistanceModulus (the effect of the luminosity distance on a galaxy's component magnitudes) """ redshift = self.column_by_name("redshift") if len(redshift) == 0: #newer versions of astropy do not appreciate being passed an #empty numpy array of redshifts; avoid nasty exceptions by #just returning an empty numpy array if we got an empty numpy array return numpy.array([]) return self.cosmology.distanceModulus(redshift)
def testComovingDistance(self): """ Test comoving distance calculation Note: this is comoving distance defined as X in the FRW metric ds^2 = -c^2 dt^2 + a^2 dX^2 + sin^2(X) dOmega^2 where spatial curvature is accounted for in the sin function """ H0 = 73.0 for Om0 in numpy.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in numpy.arange(start=-0.1, stop=0.11, step=0.2): for w0 in numpy.arange(start=-1.1, stop=-0.85, step=0.2): for wa in numpy.arange(start=-0.1, stop=0.115, step=0.02): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in numpy.arange(start=0.1, stop=4.2, step=2.0): comovingControl = universe.comovingDistance( redshift=zz) comovingTest = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] self.assertAlmostEqual( comovingControl / comovingTest, 1.0, 4)
def testAngularDiameterDistance(self): """ Test the calculation of the angular diameter distance """ H0 = 56.0 universe = CosmologyObject() for Om0 in np.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.85, step=0.2): for wa in np.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = \ np.sqrt(np.abs(universe.OmegaCurvature()))*universe.H()/self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in np.arange(start=0.1, stop=4.2, step=2.0): angularControl = universe.angularDiameterDistance(redshift=zz) comovingDistance = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature() < 0.0: nn = sqrtkCurvature*comovingDistance nn = np.sin(nn) angularTest = nn/sqrtkCurvature elif universe.OmegaCurvature() > 0.0: nn = sqrtkCurvature*comovingDistance nn = np.sinh(nn) angularTest = nn/sqrtkCurvature else: angularTest = comovingDistance angularTest /= (1.0+zz) self.assertAlmostEqual(angularControl/angularTest, 1.0, 4)
def sed_from_galacticus_mags(galacticus_mags, redshift, catalog_name='protoDC2'): """ galacticus_mags is a numpy array such that galacticus_mags[i][j] is the magnitude of the jth star in the ith bandpass, where the bandpasses are ordered in ascending order of minimum wavelength. Will return a numpy array of SED names and a numpy array of magNorms. """ assert catalog_name, '`catalog_name` cannot be None or empty' if getattr(sed_from_galacticus_mags, '_catalog_name', None) != catalog_name: sed_names, sed_mag_list, sed_mag_norm, cosmo = _get_sed_mags_and_cosmology( catalog_name) sed_colors = sed_mag_list[:, 1:] - sed_mag_list[:, :-1] sed_from_galacticus_mags._catalog_name = catalog_name sed_from_galacticus_mags._sed_names = sed_names # N_sed sed_from_galacticus_mags._mag_norm = sed_mag_norm # N_sed sed_from_galacticus_mags._sed_mags = sed_mag_list # N_sed by N_mag sed_from_galacticus_mags._sed_colors = sed_colors # N_sed by (N_mag - 1) sed_from_galacticus_mags._cosmo = CosmologyObject(**cosmo) galacticus_mags_t = np.asarray(galacticus_mags).T # N_star by N_mag assert galacticus_mags_t.shape == ( len(redshift), sed_from_galacticus_mags._sed_mags.shape[1]) def _find_closest_sed(colors_this): return np.argmin( np.sum((sed_from_galacticus_mags._sed_colors - colors_this)**2, axis=1)) galacticus_colors = galacticus_mags_t[:, 1:] - galacticus_mags_t[:, : -1] # N_star by (N_mag - 1) sed_idx = np.fromiter( (_find_closest_sed(colors_this) for colors_this in galacticus_colors), np.int, len(galacticus_colors), ) # N_star distance_modulus = sed_from_galacticus_mags._cosmo.distanceModulus( redshift=redshift) output_names = sed_from_galacticus_mags._sed_names[sed_idx] d_mag = (galacticus_mags_t - sed_from_galacticus_mags._sed_mags[sed_idx]).mean(axis=1) output_mag_norm = sed_from_galacticus_mags._mag_norm[ sed_idx] + d_mag + distance_modulus return output_names, output_mag_norm
def testFlatW0(self): """ Test the evolution of H and Omega_i as a function of redshift for flat models with constant w """ H0 = 96.0 for Om0 in numpy.arange(start=0.1, stop=0.95, step=0.4): for w0 in numpy.arange(start=-1.5, stop=-0.49, step=1.0): universe = CosmologyObject(H0=H0, Om0=Om0, w0=w0) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual(1.0 - Om0 - universe.OmegaDarkEnergy(redshift=0.0), Og0+Onu0, 6) self.assertAlmostEqual(universe.H(redshift=0.0),H0,10) self.assertEqual(universe.OmegaCurvature(),0.0) Om0 = universe.OmegaMatter(redshift=0.0) Ode0 = universe.OmegaDarkEnergy(redshift=0.0) for zz in numpy.arange(start=0.0, stop=4.1, step=2.0): self.assertAlmostEqual(w0, universe.w(redshift=zz), 6) Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0, w0=w0, wa=0.0) self.assertAlmostEqual(OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual(OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual(OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual(OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
def testGetCurrent(self): """ Test to make sure that getCurrent returns the activeCosmology """ for Om0 in np.arange(start=0.2, stop=0.5, step=0.29): for Ok0 in np.arange(start=-0.2, stop=0.2, step=0.39): for w0 in np.arange(start=-1.2, stop=-0.7, step=0.49): for wa in np.arange(start=-0.2, stop=0.2, step=0.39): universe = CosmologyObject(Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) testUniverse = universe.getCurrent() for zz in np.arange(start=1.0, stop=2.1, step=1.0): self.assertEqual(universe.OmegaMatter(redshift=zz), testUniverse.Om(zz)) self.assertEqual(universe.OmegaDarkEnergy(redshift=zz), testUniverse.Ode(zz)) self.assertEqual(universe.OmegaPhotons(redshift=zz), testUniverse.Ogamma(zz)) self.assertEqual(universe.OmegaNeutrinos(redshift=zz), testUniverse.Onu(zz)) self.assertEqual(universe.OmegaCurvature(redshift=zz), testUniverse.Ok(zz))
def testLuminosityDistance(self): """ Test the calculation of the luminosity distance """ H0 = 73.0 for Om0 in numpy.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in numpy.arange(start=-0.1, stop=0.11, step=0.2): for w0 in numpy.arange(start=-1.1, stop=-0.85, step=0.2): for wa in numpy.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = numpy.sqrt(numpy.abs(universe.OmegaCurvature()))*universe.H()/self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in numpy.arange(start=0.1, stop=4.2, step=2.0): luminosityControl = universe.luminosityDistance(redshift=zz) comovingDistance = self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature()<0.0: nn =sqrtkCurvature*comovingDistance nn = numpy.sin(nn) luminosityTest = (1.0+zz)*nn/sqrtkCurvature elif universe.OmegaCurvature()>0.0: nn = sqrtkCurvature*comovingDistance nn = numpy.sinh(nn) luminosityTest = (1.0+zz)*nn/sqrtkCurvature else: luminosityTest = (1.0+zz)*comovingDistance self.assertAlmostEqual(luminosityControl/luminosityTest,1.0,4)
def testDistanceModulusAtZero(self): """ Test to make sure that the distance modulus is set to zero if the distance modulus method returns a negative number """ universe = CosmologyObject() ztest = [0.0, 1.0, 2.0, 0.0, 3.0] mm = universe.distanceModulus(redshift=ztest) self.assertEqual(mm[0], 0.0) self.assertEqual(mm[3], 0.0) self.assertEqual( mm[1], 5.0 * np.log10(universe.luminosityDistance(ztest[1])) + 25.0) self.assertEqual( mm[2], 5.0 * np.log10(universe.luminosityDistance(ztest[2])) + 25.0) self.assertEqual( mm[4], 5.0 * np.log10(universe.luminosityDistance(ztest[4])) + 25.0)
def testAngularDiameterDistance(self): """ Test the calculation of the angular diameter distance """ H0 = 56.0 universe = CosmologyObject() for Om0 in np.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.85, step=0.2): for wa in np.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = \ np.sqrt(np.abs(universe.OmegaCurvature()))*universe.H()/self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in np.arange(start=0.1, stop=4.2, step=2.0): angularControl = universe.angularDiameterDistance( redshift=zz) comovingDistance = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature() < 0.0: nn = sqrtkCurvature * comovingDistance nn = np.sin(nn) angularTest = nn / sqrtkCurvature elif universe.OmegaCurvature() > 0.0: nn = sqrtkCurvature * comovingDistance nn = np.sinh(nn) angularTest = nn / sqrtkCurvature else: angularTest = comovingDistance angularTest /= (1.0 + zz) self.assertAlmostEqual( angularControl / angularTest, 1.0, 4)
#import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt import h5py import sncosmo import numpy as np from lsst.sims.photUtils import BandpassDict from lsst.sims.photUtils import Sed from lsst.sims.photUtils import CosmologyObject import time rng = np.random.RandomState(654) cosmo = CosmologyObject() c0_min = -0.3 x1_min = -3.0 z_min = 0.01 c0_range = 0.6 x1_range = 6.0 z_range = 1.2 d_c0 = 0.1 d_x1 = 1.0 d_z=0.01 bp_dict = BandpassDict.loadTotalBandpassesFromFiles() wav_grid = bp_dict['g'].wavelen
def testNonFlatLCDM(self): """ Test the evolution of H and Omega_i as a function of redshift for non-flat Lambda CDM models """ w0 = -1.0 wa = 0.0 H0 = 77.0 for Om0 in numpy.arange(start=0.15, stop=0.96, step=0.4): for Ok0 in numpy.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual(universe.OmegaCurvature(redshift=0.0), Ok0, 10) self.assertAlmostEqual( 1.0 - Ok0 - Om0 - universe.OmegaDarkEnergy(redshift=0.0), Og0 + Onu0, 6) self.assertAlmostEqual(universe.H(redshift=0.0), H0, 10) Om0 = universe.OmegaMatter(redshift=0.0) Ode0 = universe.OmegaDarkEnergy(redshift=0.0) Ok0 = universe.OmegaCurvature(redshift=0.0) for zz in numpy.arange(start=0.0, stop=4.0, step=2.0): Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0, Ode0=Ode0) self.assertAlmostEqual(OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual( OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual(OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual( OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual( OkControl, universe.OmegaCurvature(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
ebv_list = ebv_list[first_disk] av_list = av_list[first_disk] true_redshift_list = catalog_qties['redshift_true'][first_disk] full_redshift_list = catalog_qties['redshift'][first_disk] # hack to use the redshift at the snapshot of the galaxy true_redshift_list = [] for step in catalog_qties['step'][first_disk]: true_redshift_list.append(step_to_z[step]) true_redshift_list = np.array(true_redshift_list) full_redshift_list = true_redshift_list from lsst.sims.photUtils import CosmologyObject cosmo = CosmologyObject(H0=71.0, Om0=0.265) dm = cosmo.distanceModulus(true_redshift_list) fudge = 2.5*np.log10(1.0+true_redshift_list) u_control = -2.5*np.log10(u_control) + dm - fudge g_control = -2.5*np.log10(g_control) + dm - fudge r_control = -2.5*np.log10(r_control) + dm - fudge i_control = -2.5*np.log10(i_control) + dm - fudge z_control = -2.5*np.log10(z_control) + dm - fudge y_control = -2.5*np.log10(y_control) + dm - fudge u_dustless = -2.5*np.log10(u_dustless) + dm - fudge g_dustless = -2.5*np.log10(g_dustless) + dm - fudge r_dustless = -2.5*np.log10(r_dustless) + dm - fudge
base_sed = Sed() base_sed.readSED_flambda(sed_name) bp_dict = BandpassDict.loadTotalBandpassesFromFiles() bp = bp_dict['i'] z_grid = np.arange(0.0, 16.0, 0.01) k_grid = np.zeros(len(z_grid), dtype=float) for i_z, zz in enumerate(z_grid): ss = Sed(flambda=base_sed.flambda, wavelen=base_sed.wavelen) ss.redshiftSED(zz, dimming=True) k = k_correction(ss, bp, zz) k_grid[i_z] = k cosmo = CosmologyObject() db = DBObject(database='LSSTCATSIM', host='fatboy.phys.washington.edu', port=1433, driver='mssql+pymssql') query = 'SELECT magnorm_agn, redshift, varParamStr FROM ' query += 'galaxy WHERE varParamStr IS NOT NULL ' query += 'AND dec BETWEEN -2.5 AND 2.5 ' query += 'AND (ra<2.5 OR ra>357.5)' dtype = np.dtype([('magnorm', float), ('redshift', float), ('varParamStr', str, 400)]) data_iter = db.get_arbitrary_chunk_iterator(query,
dc2_data = np.genfromtxt('data/proto_dc2_bh_params.txt', dtype=dc2_dtype) print('max z %e' % dc2_data['redshift'].max()) valid = np.where(np.logical_and(dc2_data['bhmass']!=0.0, dc2_data['accretion_rate']!=0.0)) dc2_data = dc2_data[valid] mass_cut = np.where(dc2_data['bhmass']>=10.0**7) dc2_data = dc2_data[mass_cut] dc2_log_edd_rat = log_Eddington_ratio(dc2_data['bhmass'], dc2_data['accretion_rate']) dc2_abs_mag_i = M_i_from_L_Mass(dc2_log_edd_rat, np.log10(dc2_data['bhmass'])) dc2_cosmo = CosmologyObject(H0=71.0, Om0=0.265) DM = dc2_cosmo.distanceModulus(redshift=dc2_data['redshift']) bp_dict = BandpassDict.loadTotalBandpassesFromFiles() bp_i = bp_dict['i'] sed_dir = os.path.join(getPackageDir('sims_sed_library'), 'agnSED') sed_name = os.path.join(sed_dir, 'agn.spec.gz') if not os.path.exists(sed_name): raise RuntimeError('\n\n%s\n\nndoes not exist\n\n' % sed_name) base_sed = Sed() base_sed.readSED_flambda(sed_name) z_grid = np.arange(0.0, dc2_data['redshift'].max(), 0.01) k_grid = np.zeros(len(z_grid),dtype=float)
def testFlatLCDM(self): """ Test the evolution of H and Omega_i as a function of redshift for flat Lambda CDM models """ H0 = 50.0 for Om0 in np.arange(start=0.1, stop=0.91, step=0.4): universe = CosmologyObject(H0=H0, Om0=Om0) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual( 1.0 - Om0 - universe.OmegaDarkEnergy(redshift=0.0), Og0 + Onu0, 6) self.assertAlmostEqual(universe.H(redshift=0.0), H0, 10) self.assertEqual(universe.OmegaCurvature(), 0.0) Om0 = universe.OmegaMatter(redshift=0.0) for zz in np.arange(start=0.0, stop=4.1, step=2.0): Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl, = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0) self.assertAlmostEqual(OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual(OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual(OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual(OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
def sed_from_galacticus_mags(galacticus_mags, redshift, redshift_true, H0, Om0, wav_min, wav_width, obs_lsst_mags): """ Fit SEDs from sims_sed_library to Galacticus galaxies based on the magnitudes in tophat filters. Parameters ---------- galacticus_mags is a numpy array such that galacticus_mags[i][j] is the magnitude of the jth star in the ith bandpass, where the bandpasses are ordered in ascending order of minimum wavelength. redshift is an array of redshifts for the galaxies being fit (includes cosmology and proper motion) redshift_true is an array of cosmological redshifts for the galaxies being fit H0 is the Hubbleparameter in units of km/s/Mpc Om0 is the critical density parameter for matter wav_min is a numpy array of the minimum wavelengths of the tophat filters (in nm) wav_grid is a numpy array of the widths of the tophat filters (in nm) ob_lsst_mags is a numpy array of observer frame LSST magnitudes. obs_lsst_mags[0] will contain the u band magnitudes of every object. Returns ------- a numpy array of SED names and a numpy array of magNorms. """ if (not hasattr(sed_from_galacticus_mags, '_color_tree') or not np.allclose(wav_min, sed_from_galacticus_mags._wav_min, atol=1.0e-10, rtol=0.0) or not np.allclose(wav_width, sed_from_galacticus_mags._wav_width, atol=1.0e-10, rtol=0.0)): (sed_names, sed_mag_list, sed_mag_norm, av_grid, rv_grid) = _create_sed_library_mags(wav_min, wav_width) assert rv_grid.min() > 0.0 assert len(np.where(np.logical_not(np.isfinite(rv_grid)))[0]) == 0 sed_colors = sed_mag_list[:, 1:] - sed_mag_list[:, :-1] sed_from_galacticus_mags._sed_names = sed_names sed_from_galacticus_mags._mag_norm = sed_mag_norm # N_sed sed_from_galacticus_mags._av_grid = av_grid sed_from_galacticus_mags._rv_grid = rv_grid sed_from_galacticus_mags._sed_mags = sed_mag_list # N_sed by N_mag sed_from_galacticus_mags._color_tree = scipy_spatial.cKDTree( sed_colors) sed_from_galacticus_mags._wav_min = wav_min sed_from_galacticus_mags._wav_width = wav_width if (not hasattr(sed_from_galacticus_mags, '_cosmo') or np.abs(sed_from_galacticus_mags._cosmo.H() - H0) > 1.0e-6 or np.abs(sed_from_galacticus_mags._cosmo.OmegaMatter() - Om0) > 1.0e-6): sed_from_galacticus_mags._cosmo = CosmologyObject(H0=H0, Om0=Om0) galacticus_mags_t = np.asarray(galacticus_mags).T # N_star by N_mag assert galacticus_mags_t.shape == ( len(redshift), sed_from_galacticus_mags._sed_mags.shape[1]) with np.errstate(invalid='ignore', divide='ignore'): galacticus_colors = galacticus_mags_t[:, 1:] - galacticus_mags_t[:, : -1] # N_star by (N_mag - 1) t_start = time.time() (sed_dist, sed_idx) = sed_from_galacticus_mags._color_tree.query(galacticus_colors, k=1) # cKDTree returns an invalid index (==len(tree_data)) in cases # where the distance is not finite sed_idx = np.where(sed_idx < len(sed_from_galacticus_mags._sed_names), sed_idx, 0) distance_modulus = sed_from_galacticus_mags._cosmo.distanceModulus( redshift=redshift_true) output_names = sed_from_galacticus_mags._sed_names[sed_idx] (lsst_bp_dict, dummy_bp_dict) = BandpassDict.loadBandpassesFromFiles() output_mag_norm = np.zeros((6, len(output_names)), dtype=float) base_norm = sed_from_galacticus_mags._mag_norm[sed_idx] assert len(np.where(np.logical_not(np.isfinite(base_norm)))[0]) == 0 ccm_w = None av_arr = sed_from_galacticus_mags._av_grid[sed_idx] rv_arr = sed_from_galacticus_mags._rv_grid[sed_idx] assert rv_arr.min() > 0.0 assert len(np.where(np.logical_not(np.isfinite(rv_arr)))[0]) == 0 for i_bp in range(6): output_mag_norm[i_bp, :] = base_norm + distance_modulus sed_dir = getPackageDir('sims_sed_library') for i_obj in range(len(output_names)): spec = Sed() spec.readSED_flambda(os.path.join(sed_dir, output_names[i_obj])) if ccm_w is None or not np.array_equal(spec.wavelen, ccm_w): ccm_w = np.copy(spec.wavelen) ax, bx = spec.setupCCM_ab() spec.addDust(ax, bx, A_v=av_arr[i_obj], R_v=rv_arr[i_obj]) spec.redshiftSED(redshift[i_obj], dimming=True) lsst_mags = lsst_bp_dict.magListForSed(spec) d_mag = obs_lsst_mags[:, i_obj] - lsst_mags output_mag_norm[:, i_obj] += d_mag return (output_names, output_mag_norm, av_arr, rv_arr)
def testNonFlatW0(self): """ Test the evolution of H and Omega_i as a function of redshift for non-flat models with constant w """ H0 = 60.0 for Om0 in np.arange(start=0.15, stop=0.76, step=0.3): for Ok0 in np.arange(start=0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.89, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual( Ok0, universe.OmegaCurvature(redshift=0.0), 10) self.assertAlmostEqual( 1.0 - Om0 - Ok0 - universe.OmegaDarkEnergy(redshift=0.0), Og0 + Onu0, 10) self.assertAlmostEqual(universe.H(redshift=0.0), H0, 10) Om0 = universe.OmegaMatter(redshift=0.0) Ode0 = universe.OmegaDarkEnergy(redshift=0.0) for zz in np.arange(start=0.0, stop=4.0, step=2.0): self.assertAlmostEqual(w0, universe.w(redshift=zz), 6) Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0, w0=w0, wa=0.0, Ode0=Ode0) self.assertAlmostEqual( OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual( OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual( OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual( OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual( OkControl, universe.OmegaCurvature(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
def sed_from_galacticus_mags(galacticus_mags, redshift, H0, Om0, wav_min, wav_width): """ Fit SEDs from sims_sed_library to Galacticus galaxies based on the magnitudes in tophat filters. Parameters ---------- galacticus_mags is a numpy array such that galacticus_mags[i][j] is the magnitude of the jth star in the ith bandpass, where the bandpasses are ordered in ascending order of minimum wavelength. redshift is an array of redshifts for the galaxies being fit H0 is the Hubbleparameter in units of km/s/Mpc Om0 is the critical density parameter for matter wav_min is a numpy array of the minimum wavelengths of the tophat filters (in nm) wav_grid is a numpy array of the widths of the tophat filters (in nm) Returns ------- a numpy array of SED names and a numpy array of magNorms. """ if (not hasattr(sed_from_galacticus_mags, '_color_tree') or not np.allclose(wav_min, sed_from_galacticus_mags._wav_min, atol=1.0e-10, rtol=0.0) or not np.allclose(wav_width, sed_from_galacticus_mags._wav_width, atol=1.0e-10, rtol=0.0)): (sed_names, sed_mag_list, sed_mag_norm) = _create_sed_library_mags(wav_min, wav_width) sed_colors = sed_mag_list[:, 1:] - sed_mag_list[:, :-1] sed_from_galacticus_mags._sed_names = sed_names sed_from_galacticus_mags._mag_norm = sed_mag_norm # N_sed sed_from_galacticus_mags._sed_mags = sed_mag_list # N_sed by N_mag sed_from_galacticus_mags._color_tree = scipy_spatial.cKDTree( sed_colors) sed_from_galacticus_mags._wav_min = wav_min sed_from_galacticus_mags._wav_width = wav_width if (not hasattr(sed_from_galacticus_mags, '_cosmo') or np.abs(sed_from_galacticus_mags._cosmo.H() - H0) > 1.0e-6 or np.abs(sed_from_galacticus_mags._cosmo.OmegaMatter() - Om0) > 1.0e-6): sed_from_galacticus_mags._cosmo = CosmologyObject(H0=H0, Om0=Om0) galacticus_mags_t = np.asarray(galacticus_mags).T # N_star by N_mag assert galacticus_mags_t.shape == ( len(redshift), sed_from_galacticus_mags._sed_mags.shape[1]) with np.errstate(invalid='ignore', divide='ignore'): galacticus_colors = galacticus_mags_t[:, 1:] - galacticus_mags_t[:, : -1] # N_star by (N_mag - 1) (sed_dist, sed_idx) = sed_from_galacticus_mags._color_tree.query(galacticus_colors, k=1) # cKDTree returns an invalid index (==len(tree_data)) in cases # where the distance is not finite sed_idx = np.where(sed_idx < len(sed_from_galacticus_mags._sed_names), sed_idx, 0) distance_modulus = sed_from_galacticus_mags._cosmo.distanceModulus( redshift=redshift) output_names = sed_from_galacticus_mags._sed_names[sed_idx] d_mag = (galacticus_mags_t - sed_from_galacticus_mags._sed_mags[sed_idx]).mean(axis=1) output_mag_norm = sed_from_galacticus_mags._mag_norm[ sed_idx] + d_mag + distance_modulus return output_names, output_mag_norm
def testFlatW0Wa(self): """ Test the evolution of H and Omega_i as a function of redshift for flat models with w = w0 + wa * z / (1 + z) """ H0 = 96.0 for Om0 in np.arange(start=0.1, stop=0.95, step=0.4): for w0 in np.arange(start=-1.1, stop=-0.89, step=0.2): for wa in np.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, w0=w0, wa=wa) Og0 = universe.OmegaPhotons(redshift=0.0) Onu0 = universe.OmegaNeutrinos(redshift=0.0) self.assertAlmostEqual(universe.OmegaMatter(redshift=0.0), Om0, 10) self.assertAlmostEqual( 1.0 - Om0 - universe.OmegaDarkEnergy(redshift=0.0), Og0 + Onu0, 6) self.assertAlmostEqual(universe.H(redshift=0.0), H0, 10) self.assertEqual(universe.OmegaCurvature(), 0.0) Om0 = universe.OmegaMatter(redshift=0.0) for zz in np.arange(start=0.0, stop=4.1, step=2.0): wControl = w0 + wa * (1.0 - 1.0 / (1.0 + zz)) self.assertAlmostEqual(wControl, universe.w(redshift=zz), 6) Hcontrol, OmControl, OdeControl, OgControl, OnuControl, \ OkControl = cosmologicalOmega(zz, H0, Om0, Og0=Og0, Onu0=Onu0, w0=w0, wa=wa) self.assertAlmostEqual( OmControl, universe.OmegaMatter(redshift=zz), 6) self.assertAlmostEqual( OdeControl, universe.OmegaDarkEnergy(redshift=zz), 6) self.assertAlmostEqual( OgControl, universe.OmegaPhotons(redshift=zz), 6) self.assertAlmostEqual( OnuControl, universe.OmegaNeutrinos(redshift=zz), 6) self.assertAlmostEqual(Hcontrol, universe.H(redshift=zz), 6) del universe
duration = (time.time()-t_start)/3600.0 pred = n_samples*duration/ii print('%d in %e hrs; predict %e' % (ii,duration,pred)) out_dict[dict_key] = (mag_interp, mag_truth) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--n_samples', type=int, default=1000000) parser.add_argument('--n_processes', type=int, default=30) args = parser.parse_args() bp_dict = BandpassDict.loadTotalBandpassesFromFiles() cosmo = CosmologyObject() grid_name = '../data/sne_interp_models.h5' rng = np.random.RandomState(44) c0_range = 0.6 x1_range = 6.0 z_range = 1.2 abs_mag_mean = -19.3 abs_mag_std = 0.3 d_samples = args.n_samples//args.n_processes with h5py.File(grid_name, 'r') as in_file: param_mins = in_file['param_mins'].value
def test_sne(grid_name, x1_vals, c0_vals, z_vals, abs_mag_vals, t_vals, dict_key, out_dict): bp_dict = BandpassDict.loadTotalBandpassesFromFiles() cosmo = CosmologyObject() n_samples = len(z_vals) mag_truth = np.zeros((6,n_samples), dtype=float) mag_interp = np.zeros((6,n_samples), dtype=float) mag_grid_dict = {} with h5py.File(grid_name, 'r') as in_file: param_mins = in_file['param_mins'].value d_params = in_file['d_params'].value t_grid = in_file['t_grid'].value for name in in_file.keys(): if name == 'param_mins': continue if name == 'd_params': continue if name == 't_grid': continue mag_grid_dict[name] = in_file[name].value t_start = time.time() for ii in range(n_samples): x1 = x1_vals[ii] c0 = c0_vals[ii] z = z_vals[ii] abs_mag = abs_mag_vals[ii] t = t_vals[ii] sn = sncosmo.Model(source='salt2-extended') sn.set(x1=x1,c=c0,z=z) sn.source.set_peakmag(abs_mag+cosmo.distanceModulus(z), band='bessellb', magsys='ab') flambda = 10.0*sn.flux(time=t, wave=10.0*bp_dict['g'].wavelen) ss = Sed(flambda=flambda, wavelen=bp_dict['g'].wavelen) mag_truth[:,ii] = bp_dict.magListForSed(ss) i_x1 = np.round((x1-param_mins[0])/d_params[0]).astype(int) i_c0 = np.round((c0-param_mins[1])/d_params[1]).astype(int) i_z = np.round((z-param_mins[2])/d_params[2]).astype(int) d_mag = abs_mag-param_mins[3] tag = i_x1+i_c0*100+i_z*10000 mag_grid = mag_grid_dict['%d' % tag] interp_mags = np.zeros(6, dtype=float) for i_bp in range(6): mm = np.interp(t, t_grid, mag_grid[i_bp])+d_mag mag_interp[i_bp,ii] = mm if ii>0 and ii%100 == 0: duration = (time.time()-t_start)/3600.0 pred = n_samples*duration/ii print('%d in %e hrs; predict %e' % (ii,duration,pred)) out_dict[dict_key] = (mag_interp, mag_truth)
def testDistanceModulus(self): """ Test the calculation of the distance modulus out to a certain redshift """ H0 = 73.0 universe = CosmologyObject() for Om0 in np.arange(start=0.15, stop=0.56, step=0.2): for Ok0 in np.arange(start=-0.1, stop=0.11, step=0.2): for w0 in np.arange(start=-1.1, stop=-0.85, step=0.2): for wa in np.arange(start=-0.1, stop=0.11, step=0.2): universe = CosmologyObject(H0=H0, Om0=Om0, Ok0=Ok0, w0=w0, wa=wa) sqrtkCurvature = \ np.sqrt(np.abs(universe.OmegaCurvature()))*universe.H()/self.speedOfLight Og0 = universe.OmegaPhotons() Onu0 = universe.OmegaNeutrinos() Ode0 = universe.OmegaDarkEnergy() for zz in np.arange(start=0.1, stop=4.2, step=2.0): modulusControl = universe.distanceModulus( redshift=zz) comovingDistance = \ self.speedOfLight*scipy.integrate.quad(comovingDistanceIntegrand, 0.0, zz, args=(H0, Om0, Ode0, Og0, Onu0, w0, wa))[0] if universe.OmegaCurvature() < 0.0: nn = sqrtkCurvature * comovingDistance nn = np.sin(nn) luminosityDistance = (1.0 + zz) * nn / sqrtkCurvature elif universe.OmegaCurvature() > 0.0: nn = sqrtkCurvature * comovingDistance nn = np.sinh(nn) luminosityDistance = (1.0 + zz) * nn / sqrtkCurvature else: luminosityDistance = (1.0 + zz) * comovingDistance modulusTest = 5.0 * np.log10( luminosityDistance) + 25.0 self.assertAlmostEqual( modulusControl / modulusTest, 1.0, 4)