units.md
188 lines · skills/astropy/references/units.md at 5f2bc03
Units and Quantities (astropy.units)
The astropy.units module handles defining, converting between, and performing arithmetic with physical quantities.
Creating Quantities
Multiply or divide numeric values by built-in units to create Quantity objects:
from astropy import units as u
import numpy as np
# Scalar quantities
distance = 42.0 * u.meter
velocity = 100 * u.km / u.s
# Array quantities
distances = np.array([1., 2., 3.]) * u.m
wavelengths = [500, 600, 700] * u.nmAccess components via .value and .unit attributes:
distance.value # 42.0
distance.unit # Unit("m")Raw lines 5 to 27Unit Conversions
Use .to() method for conversions:
distance = 1.0 * u.parsec
distance.to(u.km) # <Quantity 30856775814671.914 km>
wavelength = 500 * u.nm
wavelength.to(u.angstrom) # <Quantity 5000. Angstrom>Raw lines 28 to 39Arithmetic Operations
Quantities support standard arithmetic with automatic unit management:
# Basic operations
speed = 15.1 * u.meter / (32.0 * u.second) # <Quantity 0.471875 m / s>
area = (5 * u.m) * (3 * u.m) # <Quantity 15. m2>
# Units cancel when appropriate
ratio = (10 * u.m) / (5 * u.m) # <Quantity 2. (dimensionless)>
# Decompose complex units
time = (3.0 * u.kilometer / (130.51 * u.meter / u.second))
time.decompose() # <Quantity 22.986744310780782 s>Raw lines 40 to 56Unit Systems
Convert between major unit systems:
# SI to CGS
pressure = 1.0 * u.Pa
pressure.cgs # <Quantity 10. Ba>
# Find equivalent representations
(u.s ** -1).compose() # [Unit("Bq"), Unit("Hz"), ...]Raw lines 57 to 69Equivalencies
Domain-specific conversions require equivalencies:
# Spectral equivalency (wavelength ↔ frequency)
wavelength = 1000 * u.nm
wavelength.to(u.Hz, equivalencies=u.spectral())
# <Quantity 2.99792458e+14 Hz>
# Doppler equivalencies
velocity = 1000 * u.km / u.s
velocity.to(u.Hz, equivalencies=u.doppler_optical(500*u.nm))
# Other equivalencies
u.brightness_temperature(500*u.GHz)
u.doppler_radio(1.4*u.GHz)
u.mass_energy()
u.parallax()A Jy is spectral flux density per frequency, not integrated flux. To convert between frequency- and wavelength-based densities, specify the reference wavelength with u.spectral_density(wavelength). Doppler conversions require an explicit rest frequency/wavelength and optical, radio or relativistic convention; do not mix their velocities. Radians remain angle units unless a calculation explicitly uses to_value(u.rad) or u.dimensionless_angles().
Logarithmic Units
Special units for magnitudes, decibels, and dex:
# Magnitudes
flux = -2.5 * u.mag(u.ct / u.s)
# Decibels
power_level = 3 * u.dB(u.W) # Absolute level relative to 1 W; u.dB alone is a ratio
# Dex (base-10 logarithm)
abundance = 8.5 * u.dex(u.cm**-3)Raw lines 98 to 112Common Units
Raw lines 113 to 114Length
u.m, u.km, u.cm, u.mm, u.micron, u.angstrom, u.au, u.pc, u.kpc, u.Mpc, u.lyr
Performance Optimization
Pre-compute composite units for array operations. These illustrative performance fragments assume a NumPy array named array; benchmark on the actual workload. A no-copy quantity can alias the input, so mutations may affect both.
# Slow (creates intermediate quantities)
result = array * u.m / u.s / u.kg / u.sr
# Fast (pre-computed composite unit)
UNIT_COMPOSITE = u.m / u.s / u.kg / u.sr
result = array * UNIT_COMPOSITE
# Fastest (avoid copying with <<)
result = array << UNIT_COMPOSITE # May share memory with array; no universal speedupRaw lines 139 to 156String Formatting
Format quantities with standard Python syntax:
velocity = 15.1 * u.meter / (32.0 * u.second)
f"{velocity:0.03f}" # '0.472 m / s'
f"{velocity:.2e}" # '4.72e-01 m / s'
f"{velocity.unit:FITS}" # 'm s-1'Raw lines 157 to 167Defining Custom Units
# Create new unit
bakers_fortnight = u.def_unit('bakers_fortnight', 13 * u.day)
# Enable in string parsing
with u.add_enabled_units([bakers_fortnight]):
duration = u.Quantity('2 bakers_fortnight')Raw lines 168 to 178Constants
Access physical constants with units:
from astropy.constants import c, G, M_sun, h, k_B
speed_of_light = c.to(u.km/u.s)
gravitational_constant = G.to(u.m**3 / u.kg / u.s**2)Raw lines 179 to 188