Skill Tracer
Skills › Scientific Agent Skills › astropy › cosmology.md

cosmology.md

334 lines · skills/astropy/references/cosmology.md at 5f2bc03

Open on GitHub
1# Cosmological Calculations (astropy.cosmology)
2
3The `astropy.cosmology` subpackage provides tools for cosmological calculations based on various cosmological models. Requires SciPy for these workflows.
4Pass redshifts positionally in 8.0.1. The shorter formula fragments below assume
5`cosmo`, `z`, and any measured magnitudes are defined for the science case.
6
7> **Import paths:** Always import classes and functions directly from `astropy.cosmology` (as shown in all examples below). The old submodule import paths (`astropy.cosmology.flrw`, `.core`, `.funcs`, `.connect`, `.parameter`) were deprecated in v7.1 and removed in Astropy 8.0.
8

Cosmological Calculations (astropy.cosmology)

The astropy.cosmology subpackage provides tools for cosmological calculations based on various cosmological models. Requires SciPy for these workflows. Pass redshifts positionally in 8.0.1. The shorter formula fragments below assume cosmo, z, and any measured magnitudes are defined for the science case.

Import paths: Always import classes and functions directly from astropy.cosmology (as shown in all examples below). The old submodule import paths (astropy.cosmology.flrw, .core, .funcs, .connect, .parameter) were deprecated in v7.1 and removed in Astropy 8.0.
Raw lines 1 to 8
9## Using Built-in Cosmologies
11Preloaded cosmologies based on WMAP and Planck observations:
13```python
14from astropy.cosmology import Planck18, Planck15, Planck13
15from astropy.cosmology import WMAP9, WMAP7, WMAP5
16from astropy import units as u
18# Use Planck 2018 cosmology
19cosmo = Planck18
21# Calculate distance to z=4
22d = cosmo.luminosity_distance(4)
23print(f"Luminosity distance at z=4: {d}")
25# Age of universe at z=0
26age = cosmo.age(0)
27print(f"Current age of universe: {age.to(u.Gyr)}")
28```

Using Built-in Cosmologies

Preloaded cosmologies based on WMAP and Planck observations:

from astropy.cosmology import Planck18, Planck15, Planck13
from astropy.cosmology import WMAP9, WMAP7, WMAP5
from astropy import units as u

# Use Planck 2018 cosmology
cosmo = Planck18

# Calculate distance to z=4
d = cosmo.luminosity_distance(4)
print(f"Luminosity distance at z=4: {d}")

# Age of universe at z=0
age = cosmo.age(0)
print(f"Current age of universe: {age.to(u.Gyr)}")
Raw lines 9 to 29
30## Creating Custom Cosmologies

Creating Custom Cosmologies

Raw lines 30 to 31
32### FlatLambdaCDM (Most Common)
34Flat universe with cosmological constant:
36```python
37from astropy.cosmology import FlatLambdaCDM
39# Define cosmology
40cosmo = FlatLambdaCDM(
41 H0=70 * u.km / u.s / u.Mpc, # Hubble constant at z=0
42 Om0=0.3, # Matter density parameter at z=0
43 Tcmb0=2.725 * u.K # CMB temperature (optional)
45```

FlatLambdaCDM (Most Common)

Flat universe with cosmological constant:

from astropy.cosmology import FlatLambdaCDM

# Define cosmology
cosmo = FlatLambdaCDM(
    H0=70 * u.km / u.s / u.Mpc,  # Hubble constant at z=0
    Om0=0.3,                      # Matter density parameter at z=0
    Tcmb0=2.725 * u.K             # CMB temperature (optional)
)
Raw lines 32 to 46
47### LambdaCDM (Non-Flat)
49Non-flat universe with cosmological constant:
51```python
52from astropy.cosmology import LambdaCDM
54cosmo = LambdaCDM(
55 H0=70 * u.km / u.s / u.Mpc,
56 Om0=0.3,
57 Ode0=0.7 # Dark energy density parameter
59```

LambdaCDM (Non-Flat)

Non-flat universe with cosmological constant:

from astropy.cosmology import LambdaCDM

cosmo = LambdaCDM(
    H0=70 * u.km / u.s / u.Mpc,
    Om0=0.3,
    Ode0=0.7  # Dark energy density parameter
)
Raw lines 47 to 60
61### wCDM and w0wzCDM
63Dark energy with equation of state parameter:
65```python
66from astropy.cosmology import FlatwCDM, w0wzCDM
68# Constant w
69cosmo_w = FlatwCDM(H0=70 * u.km/u.s/u.Mpc, Om0=0.3, w0=-0.9)
71# Evolving w(z) = w0 + wz * z
72cosmo_wz = w0wzCDM(H0=70 * u.km/u.s/u.Mpc, Om0=0.3, Ode0=0.7,
73 w0=-1.0, wz=0.1)
74```
76`w0wzCDM` extrapolates `w(z)` linearly; upstream does not recommend it for
77`z > 1`. Its age integral samples to infinity and can fail numerically for
78parameters like `wz=0.1`; a finite low-redshift distance does not validate that
79extrapolation. Choose an appropriate physical model before interpreting ages.

wCDM and w0wzCDM

Dark energy with equation of state parameter:

from astropy.cosmology import FlatwCDM, w0wzCDM

# Constant w
cosmo_w = FlatwCDM(H0=70 * u.km/u.s/u.Mpc, Om0=0.3, w0=-0.9)

# Evolving w(z) = w0 + wz * z
cosmo_wz = w0wzCDM(H0=70 * u.km/u.s/u.Mpc, Om0=0.3, Ode0=0.7,
                   w0=-1.0, wz=0.1)

w0wzCDM extrapolates w(z) linearly; upstream does not recommend it for z > 1. Its age integral samples to infinity and can fail numerically for parameters like wz=0.1; a finite low-redshift distance does not validate that extrapolation. Choose an appropriate physical model before interpreting ages.

Raw lines 61 to 80
81## Distance Calculations

Distance Calculations

Raw lines 81 to 82
83### Comoving Distance
85Line-of-sight comoving distance:
87```python
88d_c = cosmo.comoving_distance(z)
89```

Comoving Distance

Line-of-sight comoving distance:

d_c = cosmo.comoving_distance(z)
Raw lines 83 to 90
91### Luminosity Distance
93Distance for calculating luminosity from observed flux:
95```python
96d_L = cosmo.luminosity_distance(z)
98# Calculate absolute magnitude from apparent magnitude
99M = m - 5*np.log10(d_L.to(u.pc).value) + 5
100```

Luminosity Distance

Distance for calculating luminosity from observed flux:

d_L = cosmo.luminosity_distance(z)

# Calculate absolute magnitude from apparent magnitude
M = m - 5*np.log10(d_L.to(u.pc).value) + 5
Raw lines 91 to 101
102### Angular Diameter Distance
104Distance for calculating physical size from angular size:
106```python
107d_A = cosmo.angular_diameter_distance(z)
109# Calculate physical size from angular size
110theta = 10 * u.arcsec # Angular size
111physical_size = d_A * theta.to(u.radian).value
112```

Angular Diameter Distance

Distance for calculating physical size from angular size:

d_A = cosmo.angular_diameter_distance(z)

# Calculate physical size from angular size
theta = 10 * u.arcsec  # Angular size
physical_size = d_A * theta.to(u.radian).value
Raw lines 102 to 113
114### Comoving Transverse Distance
116Transverse comoving distance (equals comoving distance in flat universe):
118```python
119d_M = cosmo.comoving_transverse_distance(z)
120```

Comoving Transverse Distance

Transverse comoving distance (equals comoving distance in flat universe):

d_M = cosmo.comoving_transverse_distance(z)
Raw lines 114 to 121
122### Distance Modulus
124```python
125dm = cosmo.distmod(z)
126# Relates apparent and absolute magnitudes: m - M = dm
127```

Distance Modulus

dm = cosmo.distmod(z)
# Relates apparent and absolute magnitudes: m - M = dm
Raw lines 122 to 128
129## Scale Calculations

Scale Calculations

Raw lines 129 to 130
131### kpc per Arcminute
133Physical scale at a given redshift:
135```python
136scale = cosmo.kpc_proper_per_arcmin(z)
137# Returns proper kpc / arcmin; keep the angular unit when applying the scale.
138```

kpc per Arcminute

Physical scale at a given redshift:

scale = cosmo.kpc_proper_per_arcmin(z)
# Returns proper kpc / arcmin; keep the angular unit when applying the scale.
Raw lines 131 to 139
140### Comoving Volume
142Volume element for survey volume calculations:
144```python
145vol = cosmo.comoving_volume(z) # Total volume to redshift z
146vol_element = cosmo.differential_comoving_volume(z) # dV / (dz dOmega), Mpc3 / sr
147```

Comoving Volume

Volume element for survey volume calculations:

vol = cosmo.comoving_volume(z)  # Total volume to redshift z
vol_element = cosmo.differential_comoving_volume(z)  # dV / (dz dOmega), Mpc3 / sr
Raw lines 140 to 148
149## Time Calculations

Time Calculations

Raw lines 149 to 150
151### Age of Universe
153Age at a given redshift:
155```python
156age = cosmo.age(z)
157age_now = cosmo.age(0) # Current age
158age_at_z1 = cosmo.age(1) # Age at z=1
159```

Age of Universe

Age at a given redshift:

age = cosmo.age(z)
age_now = cosmo.age(0)  # Current age
age_at_z1 = cosmo.age(1)  # Age at z=1
Raw lines 151 to 160
161### Lookback Time
163Time since photons were emitted:
165```python
166t_lookback = cosmo.lookback_time(z)
167# Time between z and z=0
168```

Lookback Time

Time since photons were emitted:

t_lookback = cosmo.lookback_time(z)
# Time between z and z=0
Raw lines 161 to 169
170## Hubble Parameter
172Hubble parameter as function of redshift:
174```python
175H_z = cosmo.H(z) # H(z) in km/s/Mpc
176E_z = cosmo.efunc(z) # E(z) = H(z)/H0
177```

Hubble Parameter

Hubble parameter as function of redshift:

H_z = cosmo.H(z)  # H(z) in km/s/Mpc
E_z = cosmo.efunc(z)  # E(z) = H(z)/H0
Raw lines 170 to 178
179## Density Parameters
181Evolution of density parameters with redshift:
183```python
184Om_z = cosmo.Om(z) # Matter density at z
185Ode_z = cosmo.Ode(z) # Dark energy density at z
186Ok_z = cosmo.Ok(z) # Curvature density at z
187Ogamma_z = cosmo.Ogamma(z) # Photon density at z
188Onu_z = cosmo.Onu(z) # Neutrino density at z
189```

Density Parameters

Evolution of density parameters with redshift:

Om_z = cosmo.Om(z)        # Matter density at z
Ode_z = cosmo.Ode(z)      # Dark energy density at z
Ok_z = cosmo.Ok(z)        # Curvature density at z
Ogamma_z = cosmo.Ogamma(z)  # Photon density at z
Onu_z = cosmo.Onu(z)      # Neutrino density at z
Raw lines 179 to 190
191## Critical and Characteristic Densities
193```python
194rho_c = cosmo.critical_density(z) # Critical density at z
195rho_m = cosmo.critical_density(z) * cosmo.Om(z) # Matter density
196```

Critical and Characteristic Densities

rho_c = cosmo.critical_density(z)  # Critical density at z
rho_m = cosmo.critical_density(z) * cosmo.Om(z)  # Matter density
Raw lines 191 to 197
198## Inverse Calculations
200Find redshift corresponding to a specific value:
202```python
203from astropy.cosmology import z_at_value
205# Find z at specific lookback time
206z = z_at_value(cosmo.lookback_time, 10*u.Gyr)
208# Find z at specific luminosity distance
209z = z_at_value(cosmo.luminosity_distance, 1000*u.Mpc)
211# Find z at specific age
212z = z_at_value(cosmo.age, 1*u.Gyr)
213```
215Angular-diameter distance is not monotonic. Select a scientifically justified
216`zmin`/`zmax` branch and check the forward residual; a two-point Brent `bracket`
217does not constrain the solution to that interval.
219```python
220z_low = z_at_value(Planck18.angular_diameter_distance, 1500*u.Mpc, zmax=1.5)
221z_high = z_at_value(Planck18.angular_diameter_distance, 1500*u.Mpc, zmin=2.5, zmax=10)
222```

Inverse Calculations

Find redshift corresponding to a specific value:

from astropy.cosmology import z_at_value

# Find z at specific lookback time
z = z_at_value(cosmo.lookback_time, 10*u.Gyr)

# Find z at specific luminosity distance
z = z_at_value(cosmo.luminosity_distance, 1000*u.Mpc)

# Find z at specific age
z = z_at_value(cosmo.age, 1*u.Gyr)

Angular-diameter distance is not monotonic. Select a scientifically justified zmin/zmax branch and check the forward residual; a two-point Brent bracket does not constrain the solution to that interval.

z_low = z_at_value(Planck18.angular_diameter_distance, 1500*u.Mpc, zmax=1.5)
z_high = z_at_value(Planck18.angular_diameter_distance, 1500*u.Mpc, zmin=2.5, zmax=10)
Raw lines 198 to 223
224## Array Operations
226All methods accept array inputs:
228```python
229import numpy as np
231z_array = np.linspace(0, 5, 100)
232d_L_array = cosmo.luminosity_distance(z_array)
233H_array = cosmo.H(z_array)
234age_array = cosmo.age(z_array)
235```

Array Operations

All methods accept array inputs:

import numpy as np

z_array = np.linspace(0, 5, 100)
d_L_array = cosmo.luminosity_distance(z_array)
H_array = cosmo.H(z_array)
age_array = cosmo.age(z_array)
Raw lines 224 to 236
237## Neutrino Effects
239Include massive neutrinos:
241```python
242from astropy.cosmology import FlatLambdaCDM
244# With massive neutrinos
245cosmo = FlatLambdaCDM(
246 H0=70 * u.km/u.s/u.Mpc,
247 Om0=0.3,
248 Tcmb0=2.725 * u.K,
249 Neff=3.04, # Effective number of neutrino species
250 m_nu=[0., 0., 0.06] * u.eV # Neutrino masses
252```
254Massive neutrinos can make evaluations slower. Choose their masses and `Neff`
255from the intended physical model; adding them does not establish model accuracy.
256The default `Tcmb0=0` disables photons and neutrinos, even when `m_nu` is given.

Neutrino Effects

Include massive neutrinos:

from astropy.cosmology import FlatLambdaCDM

# With massive neutrinos
cosmo = FlatLambdaCDM(
    H0=70 * u.km/u.s/u.Mpc,
    Om0=0.3,
    Tcmb0=2.725 * u.K,
    Neff=3.04,  # Effective number of neutrino species
    m_nu=[0., 0., 0.06] * u.eV  # Neutrino masses
)

Massive neutrinos can make evaluations slower. Choose their masses and Neff from the intended physical model; adding them does not establish model accuracy. The default Tcmb0=0 disables photons and neutrinos, even when m_nu is given.

Raw lines 237 to 257
258## Cloning and Modifying Cosmologies
260Cosmology objects are immutable. Clone an already named model. Astropy 8.0.1
261raises `TypeError` when cloning an unnamed model with changes, even if a new
262`name` is passed; give custom models a name when constructing them.
264```python
265# Start from a named built-in model
266cosmo = Planck18
267# Clone with different H0
268cosmo_new = cosmo.clone(name="Modified H0", H0=72 * u.km/u.s/u.Mpc)
270# Clone with modified name
271cosmo_named = cosmo.clone(name="My Custom Cosmology")
272```

Cloning and Modifying Cosmologies

Cosmology objects are immutable. Clone an already named model. Astropy 8.0.1 raises TypeError when cloning an unnamed model with changes, even if a new name is passed; give custom models a name when constructing them.

# Start from a named built-in model
cosmo = Planck18
# Clone with different H0
cosmo_new = cosmo.clone(name="Modified H0", H0=72 * u.km/u.s/u.Mpc)

# Clone with modified name
cosmo_named = cosmo.clone(name="My Custom Cosmology")
Raw lines 258 to 273
274## Common Use Cases

Common Use Cases

Raw lines 274 to 275
276### Calculating Absolute Magnitude
278```python
279# From apparent magnitude and redshift
280z = 1.5
281m_app = 24.5 # Apparent magnitude
282d_L = cosmo.luminosity_distance(z)
283M_abs = m_app - cosmo.distmod(z).value # Distance-only; no extinction or K correction
284```

Calculating Absolute Magnitude

# From apparent magnitude and redshift
z = 1.5
m_app = 24.5  # Apparent magnitude
d_L = cosmo.luminosity_distance(z)
M_abs = m_app - cosmo.distmod(z).value  # Distance-only; no extinction or K correction
Raw lines 276 to 285
286### Survey Volume Calculations
288```python
289# Full-sky comoving volume between two redshifts; multiply by survey solid angle / (4*pi*sr)
290z_min, z_max = 0.5, 1.5
291volume = cosmo.comoving_volume(z_max) - cosmo.comoving_volume(z_min)
293# Convert to Gpc^3
294volume_gpc3 = volume.to(u.Gpc**3)
295```

Survey Volume Calculations

# Full-sky comoving volume between two redshifts; multiply by survey solid angle / (4*pi*sr)
z_min, z_max = 0.5, 1.5
volume = cosmo.comoving_volume(z_max) - cosmo.comoving_volume(z_min)

# Convert to Gpc^3
volume_gpc3 = volume.to(u.Gpc**3)
Raw lines 286 to 296
297### Physical Size from Angular Size
299```python
300theta = 1 * u.arcsec # Angular size
301z = 2.0
302d_A = cosmo.angular_diameter_distance(z)
303size_kpc = (d_A * theta.to_value(u.rad)).to(u.kpc) # Small-angle approximation
304```

Physical Size from Angular Size

theta = 1 * u.arcsec  # Angular size
z = 2.0
d_A = cosmo.angular_diameter_distance(z)
size_kpc = (d_A * theta.to_value(u.rad)).to(u.kpc)  # Small-angle approximation
Raw lines 297 to 305
306### Time Since Big Bang
308```python
309# Age at specific redshift
310z_formation = 6
311age_at_formation = cosmo.age(z_formation)
312time_since_formation = cosmo.age(0) - age_at_formation
313```

Time Since Big Bang

# Age at specific redshift
z_formation = 6
age_at_formation = cosmo.age(z_formation)
time_since_formation = cosmo.age(0) - age_at_formation
Raw lines 306 to 314
315## Comparison of Cosmologies
317```python
318# Compare different models
319from astropy.cosmology import Planck18, WMAP9
321z = 1.0
322print(f"Planck18 d_L: {Planck18.luminosity_distance(z)}")
323print(f"WMAP9 d_L: {WMAP9.luminosity_distance(z)}")
324```

Comparison of Cosmologies

# Compare different models
from astropy.cosmology import Planck18, WMAP9

z = 1.0
print(f"Planck18 d_L: {Planck18.luminosity_distance(z)}")
print(f"WMAP9 d_L: {WMAP9.luminosity_distance(z)}")
Raw lines 315 to 325
326## Performance Considerations
328- Calculations are fast for most purposes
329- Massive neutrinos reduce speed significantly
330- Array operations are vectorized and efficient
331- Numerical evaluation is not evidence of physical validity at a chosen redshift;
332 record model parameters, radiation/neutrino assumptions and domain.
333- Check distance duality `d_L = (1+z)**2 * d_A` for these standard FLRW models,
334 and record the named cosmology or all custom parameters in output provenance.

Performance Considerations

  • Calculations are fast for most purposes
  • Massive neutrinos reduce speed significantly
  • Array operations are vectorized and efficient
  • Numerical evaluation is not evidence of physical validity at a chosen redshift; record model parameters, radiation/neutrino assumptions and domain.
  • Check distance duality d_L = (1+z)**2 * d_A for these standard FLRW models, and record the named cosmology or all custom parameters in output provenance.
Raw lines 326 to 334