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

units.md

188 lines · skills/astropy/references/units.md at 5f2bc03

Open on GitHub
1# Units and Quantities (astropy.units)
2
3The `astropy.units` module handles defining, converting between, and performing arithmetic with physical quantities.
4

Units and Quantities (astropy.units)

The astropy.units module handles defining, converting between, and performing arithmetic with physical quantities.

Raw lines 1 to 4
5## Creating Quantities
6
7Multiply or divide numeric values by built-in units to create Quantity objects:
8
9```python
10from astropy import units as u
11import numpy as np
13# Scalar quantities
14distance = 42.0 * u.meter
15velocity = 100 * u.km / u.s
17# Array quantities
18distances = np.array([1., 2., 3.]) * u.m
19wavelengths = [500, 600, 700] * u.nm
20```
22Access components via `.value` and `.unit` attributes:
23```python
24distance.value # 42.0
25distance.unit # Unit("m")
26```

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.nm

Access components via .value and .unit attributes:

distance.value  # 42.0
distance.unit   # Unit("m")
Raw lines 5 to 27
28## Unit Conversions
30Use `.to()` method for conversions:
32```python
33distance = 1.0 * u.parsec
34distance.to(u.km) # <Quantity 30856775814671.914 km>
36wavelength = 500 * u.nm
37wavelength.to(u.angstrom) # <Quantity 5000. Angstrom>
38```

Unit 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 39
40## Arithmetic Operations
42Quantities support standard arithmetic with automatic unit management:
44```python
45# Basic operations
46speed = 15.1 * u.meter / (32.0 * u.second) # <Quantity 0.471875 m / s>
47area = (5 * u.m) * (3 * u.m) # <Quantity 15. m2>
49# Units cancel when appropriate
50ratio = (10 * u.m) / (5 * u.m) # <Quantity 2. (dimensionless)>
52# Decompose complex units
53time = (3.0 * u.kilometer / (130.51 * u.meter / u.second))
54time.decompose() # <Quantity 22.986744310780782 s>
55```

Arithmetic 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 56
57## Unit Systems
59Convert between major unit systems:
61```python
62# SI to CGS
63pressure = 1.0 * u.Pa
64pressure.cgs # <Quantity 10. Ba>
66# Find equivalent representations
67(u.s ** -1).compose() # [Unit("Bq"), Unit("Hz"), ...]
68```

Unit 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 69
70## Equivalencies
72Domain-specific conversions require equivalencies:
74```python
75# Spectral equivalency (wavelength ↔ frequency)
76wavelength = 1000 * u.nm
77wavelength.to(u.Hz, equivalencies=u.spectral())
78# <Quantity 2.99792458e+14 Hz>
80# Doppler equivalencies
81velocity = 1000 * u.km / u.s
82velocity.to(u.Hz, equivalencies=u.doppler_optical(500*u.nm))
84# Other equivalencies
85u.brightness_temperature(500*u.GHz)
86u.doppler_radio(1.4*u.GHz)
87u.mass_energy()
88u.parallax()
89```
91A Jy is spectral flux density per frequency, not integrated flux. To convert
92between frequency- and wavelength-based densities, specify the reference
93wavelength with `u.spectral_density(wavelength)`. Doppler conversions require
94an explicit rest frequency/wavelength and optical, radio or relativistic
95convention; do not mix their velocities. Radians remain angle units unless a
96calculation explicitly uses `to_value(u.rad)` or `u.dimensionless_angles()`.

Equivalencies

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().

Raw lines 70 to 97
98## Logarithmic Units
100Special units for magnitudes, decibels, and dex:
102```python
103# Magnitudes
104flux = -2.5 * u.mag(u.ct / u.s)
106# Decibels
107power_level = 3 * u.dB(u.W) # Absolute level relative to 1 W; u.dB alone is a ratio
109# Dex (base-10 logarithm)
110abundance = 8.5 * u.dex(u.cm**-3)
111```

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 112
113## Common Units
115### Length
116`u.m, u.km, u.cm, u.mm, u.micron, u.angstrom, u.au, u.pc, u.kpc, u.Mpc, u.lyr`

Length

u.m, u.km, u.cm, u.mm, u.micron, u.angstrom, u.au, u.pc, u.kpc, u.Mpc, u.lyr

Raw lines 115 to 117
118### Time
119`u.s, u.min, u.hour, u.day, u.year, u.Myr, u.Gyr`

Time

u.s, u.min, u.hour, u.day, u.year, u.Myr, u.Gyr

Raw lines 118 to 120
121### Mass
122`u.kg, u.g, u.M_sun, u.M_earth, u.M_jup`

Mass

u.kg, u.g, u.M_sun, u.M_earth, u.M_jup

Raw lines 121 to 123
124### Temperature
125`u.K, u.deg_C`

Temperature

u.K, u.deg_C

Raw lines 124 to 126
127### Angle
128`u.deg, u.arcmin, u.arcsec, u.rad, u.hourangle, u.mas`

Angle

u.deg, u.arcmin, u.arcsec, u.rad, u.hourangle, u.mas

Raw lines 127 to 129
130### Energy/Power
131`u.J, u.erg, u.eV, u.keV, u.MeV, u.GeV, u.W, u.L_sun`

Energy/Power

u.J, u.erg, u.eV, u.keV, u.MeV, u.GeV, u.W, u.L_sun

Raw lines 130 to 132
133### Frequency
134`u.Hz, u.kHz, u.MHz, u.GHz`

Frequency

u.Hz, u.kHz, u.MHz, u.GHz

Raw lines 133 to 135
136### Flux
137`u.Jy, u.mJy, u.erg / u.s / u.cm**2`

Flux

u.Jy, u.mJy, u.erg / u.s / u.cm**2

Raw lines 136 to 138
139## Performance Optimization
141Pre-compute composite units for array operations. These illustrative performance
142fragments assume a NumPy array named `array`; benchmark on the actual workload.
143A no-copy quantity can alias the input, so mutations may affect both.
145```python
146# Slow (creates intermediate quantities)
147result = array * u.m / u.s / u.kg / u.sr
149# Fast (pre-computed composite unit)
150UNIT_COMPOSITE = u.m / u.s / u.kg / u.sr
151result = array * UNIT_COMPOSITE
153# Fastest (avoid copying with <<)
154result = array << UNIT_COMPOSITE # May share memory with array; no universal speedup
155```

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 speedup
Raw lines 139 to 156
157## String Formatting
159Format quantities with standard Python syntax:
161```python
162velocity = 15.1 * u.meter / (32.0 * u.second)
163f"{velocity:0.03f}" # '0.472 m / s'
164f"{velocity:.2e}" # '4.72e-01 m / s'
165f"{velocity.unit:FITS}" # 'm s-1'
166```

String 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 167
168## Defining Custom Units
170```python
171# Create new unit
172bakers_fortnight = u.def_unit('bakers_fortnight', 13 * u.day)
174# Enable in string parsing
175with u.add_enabled_units([bakers_fortnight]):
176 duration = u.Quantity('2 bakers_fortnight')
177```

Defining 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 178
179## Constants
181Access physical constants with units:
183```python
184from astropy.constants import c, G, M_sun, h, k_B
186speed_of_light = c.to(u.km/u.s)
187gravitational_constant = G.to(u.m**3 / u.kg / u.s**2)
188```

Constants

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