### Example unit test output Source: https://github.com/bdiemer/colossus/blob/master/README.rst This is an example of the expected output when running the Colossus unit tests. 'ok' indicates successful test execution. ```shell test_home_dir (colossus.tests.test_utils.TCGen) ... ok test_Ez (colossus.tests.test_cosmology.TCComp) ... ok ... test_DK14ConstructorOuter (colossus.tests.test_halo_profile.TCDK14) ... ok test_DK14ConstructorWrapper (colossus.tests.test_halo_profile.TCDK14) ... ok ---------------------------------------------------------------------- Ran 86 tests in 7.026s OK ``` -------------------------------- ### Install Colossus using pip Source: https://github.com/bdiemer/colossus/blob/master/README.rst Use this command to install the Colossus package. You may need to use 'sudo' depending on your system's permissions. ```shell pip install colossus ``` -------------------------------- ### Example Unit Test Output Source: https://github.com/bdiemer/colossus/blob/master/docs/source/installation.md This is an example of the expected output when running the Colossus unit tests. Successful execution will show 'ok' for each test case. ```text test_get_version (colossus.tests.test_utils.TCVersions) ... ok test_versions (colossus.tests.test_utils.TCVersions) ... ok ... test_DK14ConstructorOuter (colossus.tests.test_halo_profile.TCDK14) ... ok test_DK14ConstructorWrapper (colossus.tests.test_halo_profile.TCDK14) ... ok ---------------------------------------------------------------------- Ran 97 tests in 16.697s OK ``` -------------------------------- ### Check Colossus Version Source: https://github.com/bdiemer/colossus/blob/master/docs/source/faq.md Execute this code to print the installed Colossus version. If this fails, an update may be needed. ```python from colossus import version print(version.__version__) ``` -------------------------------- ### Create and Plot NFW Profile Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_profile.html Demonstrates creating an NFW profile with given mass, concentration, and redshift, then plotting its density profile against the mean density. Ensure the colossus library is installed and the desired cosmology is set. ```python from colossus.halo import profile_nfw Mvir = 1E15 cvir = 5.0 z = 0.0 p_nfw = profile_nfw.NFWProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') r = 10**np.arange(0,4,0.02) rho_m = cosmo.rho_m(z) rho_nfw = p_nfw.density(r) plt.figure() plt.loglog() plt.xlabel('r(kpc/h)') plt.ylabel('density / mean') plt.plot(r, rho_nfw / rho_m, '-', label = 'NFW'); plt.ylim(1E0, 1E7) plt.legend() ``` -------------------------------- ### Run Colossus unit tests Source: https://github.com/bdiemer/colossus/blob/master/README.rst After installation, import and run the unit tests to ensure Colossus is working correctly. The output should indicate that all tests passed. ```python from colossus.tests import run_tests ``` -------------------------------- ### Import Libraries and Set Cosmology Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_lss_bias.html Imports necessary libraries and sets the cosmology for calculations. Ensure Colossus is installed. ```python from __future__ import print_function import matplotlib.pyplot as plt import numpy as np %matplotlib inline ``` ```python from colossus.cosmology import cosmology cosmology.setCosmology('planck18'); ``` -------------------------------- ### Import Colossus Modules and Set Cosmology Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_splashback.html Imports necessary Colossus modules and sets the cosmological parameters. Ensure Colossus is installed and a cosmology is selected before proceeding. ```python from __future__ import print_function import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ```python from colossus.cosmology import cosmology cosmology.setCosmology('planck18'); ``` -------------------------------- ### Import Colossus Modules Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_so.html Import necessary Colossus modules for cosmology and halo mass calculations. This is a standard setup for using the library. ```python from __future__ import print_function import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ```python from colossus.cosmology import cosmology cosmology.setCosmology('planck18'); ``` ```python from colossus.halo import mass_so ``` -------------------------------- ### Set Cosmology and Prepare Mass Array for Comparison Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_concentration.html Sets the cosmology to 'bolshoi' and creates a wide range of halo masses for comparing different concentration models. This is a setup step for a comparative analysis. ```python cosmology.setCosmology('bolshoi') M = 10**np.arange(8.0, 15.4, 0.1) ``` -------------------------------- ### User-Defined Power Spectrum from File Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_powerspec.html This example shows how to load and use a user-defined matter power spectrum from a text file. The file should contain two columns: log10(k) and log10(P). Ensure the requested wavenumbers are within the range of the provided file. ```python from colossus.utils import utilities file_path = utilities.getCodeDir()[:-9] + '/docs/source/_data/power_spectrum.txt' ps_args_table = dict(model='mytable', path=file_path) k_table = 10**np.linspace(-4.0, 2.2, 200) P_table = cosmo.matterPowerSpectrum(k_table, **ps_args_table) plt.figure() plt.loglog() plt.xlabel('k(h / Mpc)') plt.ylabel('P(k)') plt.plot(k_table, P_table, '-') ``` -------------------------------- ### Generate and Compare Power Spectra with CAMB Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_powerspec.html This snippet generates the Eisenstein & Hu (1998) and CAMB matter power spectra and plots their relative difference. Ensure CAMB is installed (`pip install camb`). ```python import numpy as np import matplotlib.pyplot as plt from pycolossus import cosmology cosmo = cosmology.Cosmology() k = 10**np.linspace(-4.0, 2.2, 200) P_eh98 = cosmo.matterPowerSpectrum(k, model = 'eisenstein98') P_camb = cosmo.matterPowerSpectrum(k, model = 'camb') plt.figure() plt.xscale('log') plt.xlabel('k(h / Mpc)') plt.ylabel('Difference in P(k)') plt.axhline(0.0, ls = '--', color = 'gray') plt.plot(k, P_eh98 / P_camb - 1.0, '-'); ``` -------------------------------- ### Compute and Compare Power Spectra with CAMB and Reionization Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_powerspec.html This snippet computes the matter power spectrum using CAMB with default parameters and then with reionization enabled. It plots the ratio of the reionized spectrum to the default spectrum, highlighting the differences on various scales. Ensure 'camb' is installed and imported. ```python import camb k = 10**np.linspace(-4.0, 1.5, 200) P_def = cosmo.matterPowerSpectrum(k, model = 'camb') cosmo2 = cosmology.setCosmology('planck18', persistence = 'r') Reion = camb.reionization.TanhReionization(Reionization = True) P_reion = cosmo2.matterPowerSpectrum(k, model = 'camb', Reion = Reion) plt.figure() plt.xscale('log') plt.xlabel('k(h / Mpc)') plt.ylabel('CDM / Total - 1') plt.axhline(0.0, ls = '--', color = 'gray') plt.plot(k, P_reion / P_def - 1.0, '-'); ``` -------------------------------- ### Load and Plot Cosmological Power Spectrum Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_powerspec.html Loads cosmological data and plots the power spectrum. Ensure necessary libraries are installed. ```python import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import InterpolatedUnivariateSpline from classy import Class # Set parameters for CLASS params = { 'output': 'tCl,lCl,dCl', 'l_max': 2500, 'lensing': 'yes', 'non linear': 'halofit' } # Initialize CLASS m = Class() m.set(params) m.compute() # Get power spectra spectra = m.get_results()['cls'] # Extract relevant spectra (e.g., TT, EE, TE) ls = np.arange(2, params['l_max'] + 1) TT = spectra['tt'][2:] EE = spectra['ee'][2:] TE = spectra['te'][2:] # Plotting plt.figure(figsize=(10, 6)) # Plot TT spectrum plt.loglog(ls, TT, label='TT') # Plot EE spectrum plt.loglog(ls, EE, label='EE') # Plot TE spectrum plt.loglog(ls, TE, label='TE') plt.xlabel(r'$l$') plt.ylabel(r'$l(l+1)C_l / 2\pi$ [$\/\mu K^2$]') plt.title('Cosmological Power Spectra') plt.legend() plt.grid(True, which='both', linestyle='--', linewidth=0.5) plt.show() ``` -------------------------------- ### Compare Eisenstein-1998 and CAMB Power Spectra Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_cosmology_powerspec.ipynb Compares the matter power spectrum calculated using the Eisenstein-1998 model with the one computed by CAMB. Requires CAMB to be installed. The first execution may take a few seconds due to CAMB's more involved calculation. ```python import camb import matplotlib.pyplot as plt import numpy as np from pycolossus import cosmology cosmo = cosmology.setCosmology('planck18') k = 10**np.linspace(-4.0, 2.2, 200) P_eh98 = cosmo.matterPowerSpectrum(k, model = 'eisenstein98') P_camb = cosmo.matterPowerSpectrum(k, model = 'camb') plt.figure() plt.xscale('log') plt.xlabel('k(h / Mpc)') plt.ylabel('Difference in P(k)') plt.axhline(0.0, ls = '--', color = 'gray') plt.plot(k, P_eh98 / P_camb - 1.0, '-'); ``` -------------------------------- ### Add Colossus to PYTHONPATH Source: https://github.com/bdiemer/colossus/blob/master/docs/source/installation.md Manually add the Colossus installation directory to your PYTHONPATH environment variable. Replace the example path with the actual location of Colossus on your system. This is typically added to your shell's initialization script (e.g., bashrc). ```shell export PYTHONPATH=$PYTHONPATH:/users/me/code/colossus ``` -------------------------------- ### Initialize Other Density Profiles Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_halo_profile.ipynb Initializes Einasto and Diemer-23 density profiles for comparison with the NFW profile. ```python from colossus.halo import profile_einasto from colossus.halo import profile_diemer23 p_einasto = profile_einasto.EinastoProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') p_d23 = profile_diemer23.ModelAProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') rho_einasto = p_einasto.density(r) rho_d23 = p_d23.density(r) ``` -------------------------------- ### Initialize and Plot NFW Profile Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_halo_profile.ipynb Creates an NFW density profile initialized by mass and concentration, then plots its density profile relative to the mean density. ```python from colossus.halo import profile_nfw Mvir = 1E15 cvir = 5.0 z = 0.0 p_nfw = profile_nfw.NFWProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') r = 10**np.arange(0,4,0.02) rho_m = cosmo.rho_m(z) rho_nfw = p_nfw.density(r) plt.figure() plt.loglog() plt.xlabel('r(kpc/h)') plt.ylabel('density / mean') plt.plot(r, rho_nfw / rho_m, '-', label = 'NFW'); plt.ylim(1E0, 1E7) plt.legend(); ``` -------------------------------- ### Initialize MCMC Parameters Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_utils_mcmc.ipynb Sets up initial guess for parameters and the number of walkers for the MCMC simulation. ```python param_names = ['x1', 'x2'] x_initial = np.array([1.0, 1.0]) n_params = len(param_names) ``` -------------------------------- ### Initialize Cosmology and Compute Power Spectrum Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_powerspec.html This snippet demonstrates initializing a cosmology and computing the matter power spectrum for a given set of wavenumbers. It highlights the potential for initial computation time due to interpolation table generation. ```python from colossus.cosmology import cosmology cosmo = cosmology.setCosmology('planck18') k = np.logspace(-4, 1, 100) P = cosmo.matterPowerSpectrum(k) ``` -------------------------------- ### Get Current Cosmology Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_basics.html Retrieve the currently active cosmology object and print its name. ```python cosmo = cosmology.getCurrent() print(cosmo.name) ``` -------------------------------- ### Call plotChain function Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_profile.html This is an example call to the plotChain function, passing the thinned MCMC results and parameter labels. ```python plotChain(fit_results['chain_thin'], ['rhos', 'rs']) ``` -------------------------------- ### Import Colossus Cosmology Module Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_cosmology_basics.ipynb Import the necessary cosmology module from the Colossus library. Ensure Colossus is installed to avoid errors. ```python from colossus.cosmology import cosmology ``` -------------------------------- ### Get Current Cosmology Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_cosmology_basics.ipynb Retrieve the currently active cosmology object from anywhere in the code using getCurrent(). Access its name attribute. ```python cosmo = cosmology.getCurrent() print(cosmo.name) ``` -------------------------------- ### Define Likelihood Function Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_utils_mcmc.ipynb Defines a double Gaussian likelihood function with correlated parameters. This function is used to guide the MCMC sampling. ```python def likelihood(x): sig1 = 1.0 sig2 = 2.0 r = 0.95 r2 = r * r res = np.exp(-0.5 * ((x[:, 0] / sig1)**2 + (x[:, 1] / sig2)**2 - 2.0 * r * x[:, 0] * x[:, 1] / (sig1 * sig2)) / (1.0 - r2)) / (2 * np.pi * sig1 * sig2) / np.sqrt(1.0 - r2) return res ``` -------------------------------- ### Instantiate and Compare Density Profiles Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_halo_profile.html Instantiate the custom HernquistProfile using both direct parameter setting and conversion from mass and concentration. Compare its surface density with the NFW profile. ```python Mvir = 1E12 cvir = 7.0 p_nfw = profile_nfw.NFWProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') p_hernquist1 = HernquistProfile(rhos = p_nfw.par['rhos'], rs = p_nfw.par['rs']) p_hernquist2 = HernquistProfile(M = Mvir, c = cvir, z = z, mdef = 'vir') ``` ```python r = 10**np.arange(0,3,0.02) Sigma_nfw = p_nfw.surfaceDensity(r) Sigma_hernquist = p_hernquist2.surfaceDensity(r) plt.figure() plt.loglog() plt.xlabel('r(kpc/h)') plt.ylabel('Surface density') plt.plot(r, Sigma_nfw, '-', label = 'NFW'); plt.plot(r, Sigma_hernquist, '-', label = 'Hernquist'); plt.ylim(1E5, 1E9) plt.legend(); ``` -------------------------------- ### Switch Between Cosmologies Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_cosmology_basics.ipynb Demonstrates how to set a new cosmology, make it current, and then switch back to a previously stored cosmology object. ```python cosmo2 = cosmology.setCosmology('WMAP9') cosmology.setCurrent(cosmo2) print(cosmology.getCurrent().name) cosmology.setCurrent(cosmo) print(cosmology.getCurrent().name) ``` -------------------------------- ### Get Age of the Universe Source: https://github.com/bdiemer/colossus/blob/master/docs/source/_static/tutorial_cosmology_basics.html After setting a cosmology, you can evaluate standard cosmological quantities. The `age()` function returns the age of the universe in Gyr, taking redshift as an argument. ```python cosmo = cosmology.setCosmology('planck18') print(cosmo.age(0.0)) ``` -------------------------------- ### Handle Unsupported Instantaneous MAR Calculation Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_halo_accretion_history.ipynb Demonstrates error handling when requesting an instantaneous MAR ('inst') for a model that does not support it. The 'bera26' model, for example, only provides time-averaged rates. ```python try: macc.massAccretionRate(1E12, 2.0, model = 'bera26', delta_t = 'inst') except Exception as e: print('Got expected error:', e) ``` -------------------------------- ### Load and Use Custom Power Spectrum from File Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_cosmology_powerspec.ipynb Loads a custom matter power spectrum from a text file and computes it over a specified range of wavenumbers. Ensure the file contains two columns: log10(k) and log10(P). ```python from colossus.utils import utilities file_path = utilities.getCodeDir()[:-9] + '/docs/source/_data/power_spectrum.txt' ps_args_table = dict(model = 'mytable', path = file_path) k_table = 10**np.linspace(-4.0, 2.2, 200) P_table = cosmo.matterPowerSpectrum(k_table, **ps_args_table) plt.figure() plt.loglog() plt.xlabel('k(h / Mpc)') plt.ylabel('P(k)') plt.plot(k_table, P_table, '-'); ``` -------------------------------- ### Set Cosmology Interpolation Range Source: https://github.com/bdiemer/colossus/blob/master/docs/source/faq.md When using tabulated power spectra, adjust the interpolation range to avoid 'x must be strictly increasing' errors. This example limits interpolation at smaller radii. ```python R_min_sigma = 1E-3 ``` -------------------------------- ### Import Libraries for Colossus Tutorial Source: https://github.com/bdiemer/colossus/blob/master/tutorials/tutorial_lss_bias.ipynb Imports necessary libraries for plotting and numerical operations, including matplotlib and numpy. Sets up the environment for inline plotting. ```python from __future__ import print_function import matplotlib.pyplot as plt import numpy as np %matplotlib inline ```