0
# Units and Quantities
1
2
Complete physical unit system with quantity objects supporting all astronomical and physical units, unit conversions, and equivalencies for spectroscopic, photometric, and distance measurements.
3
4
## Core Imports
5
6
```python
7
from astropy import units as u
8
from astropy.units import Quantity, Unit
9
from astropy.units import def_unit, get_physical_type
10
from astropy.units import dimensionless_unscaled
11
from astropy.units import set_enabled_units
12
from astropy.units.equivalencies import spectral, doppler_optical, doppler_radio
13
```
14
15
## Capabilities
16
17
### Quantity Creation and Basic Operations
18
19
Create physical quantities by combining numerical values with units, supporting arithmetic operations, comparisons, and array operations with automatic unit handling.
20
21
```python { .api }
22
class Quantity:
23
"""
24
A numerical value associated with an astronomical or physical unit.
25
26
Parameters:
27
- value: scalar, array-like, or Quantity instance
28
- unit: Unit instance or string representation
29
- dtype: numpy dtype for the value
30
- copy: bool, whether to copy the value
31
"""
32
def __init__(self, value, unit=None, dtype=None, copy=True): ...
33
34
def to(self, unit, equivalencies=[]):
35
"""
36
Convert to different unit.
37
38
Parameters:
39
- unit: target unit
40
- equivalencies: list of unit equivalencies to apply
41
42
Returns:
43
Quantity: converted quantity
44
"""
45
46
def to_value(self, unit=None, equivalencies=[]):
47
"""
48
Extract numerical value in specified unit.
49
50
Returns:
51
scalar or array: numerical value
52
"""
53
54
@property
55
def value(self):
56
"""Numerical value of the quantity."""
57
58
@property
59
def unit(self):
60
"""Unit of the quantity."""
61
62
def decompose(self, bases=[]):
63
"""Decompose into fundamental units."""
64
65
def __add__(self, other): ...
66
def __sub__(self, other): ...
67
def __mul__(self, other): ...
68
def __truediv__(self, other): ...
69
def __pow__(self, power): ...
70
```
71
72
### Unit Definition and Management
73
74
Create, manipulate, and combine physical units with support for SI, CGS, imperial, and astronomical unit systems.
75
76
```python { .api }
77
class Unit:
78
"""
79
Physical unit with support for operations and conversions.
80
81
Parameters:
82
- s: string representation of unit
83
- parse_strict: how strict to be in parsing ('raise', 'warn', 'silent')
84
"""
85
def __init__(self, s, parse_strict='raise'): ...
86
87
def to(self, other, value=1.0, equivalencies=[]):
88
"""Convert between units."""
89
90
def is_equivalent(self, other, equivalencies=[]):
91
"""Check if units are equivalent."""
92
93
def decompose(self, bases=[]):
94
"""Decompose into base units."""
95
96
@property
97
def physical_type(self):
98
"""Physical type of the unit (e.g., 'length', 'time')."""
99
100
def __mul__(self, other): ...
101
def __truediv__(self, other): ...
102
def __pow__(self, power): ...
103
104
def def_unit(s, represents=None, doc=None, format=None):
105
"""
106
Define a new unit.
107
108
Parameters:
109
- s: string symbol for the unit
110
- represents: Unit instance this represents
111
- doc: documentation string
112
- format: format specification
113
114
Returns:
115
Unit: newly defined unit
116
"""
117
118
def get_current_unit_registry():
119
"""Get the currently active unit registry."""
120
121
def set_enabled_units(units):
122
"""Set which unit collections are enabled."""
123
124
def add_enabled_units(units):
125
"""Add unit collections to enabled units."""
126
```
127
128
### Standard Unit Collections
129
130
Pre-defined unit collections for different physical systems and astronomical applications.
131
132
```python { .api }
133
# SI base and derived units
134
import astropy.units.si as si
135
# si.meter, si.kilogram, si.second, si.ampere, si.kelvin, si.mole, si.candela
136
# si.newton, si.joule, si.watt, si.pascal, si.coulomb, si.volt, etc.
137
138
# CGS units
139
import astropy.units.cgs as cgs
140
# cgs.centimeter, cgs.gram, cgs.second, cgs.dyne, cgs.erg, etc.
141
142
# Astrophysical units
143
import astropy.units.astrophys as astrophys
144
# astrophys.AU, astrophys.pc, astrophys.kpc, astrophys.Mpc
145
# astrophys.Msun, astrophys.Rsun, astrophys.Lsun
146
# astrophys.year, astrophys.Myr, astrophys.Gyr
147
148
# Physical constants as units
149
import astropy.units.physical as physical
150
# physical.c, physical.G, physical.h, physical.k_B, etc.
151
152
# Photometric units
153
import astropy.units.photometric as photometric
154
# photometric.mag, photometric.Bol, photometric.AB, photometric.ST
155
156
# Angle units
157
from astropy.units import degree, arcmin, arcsec, radian
158
from astropy.units import hourangle
159
160
# Time units
161
from astropy.units import second, minute, hour, day, year
162
163
# Common unit shortcuts
164
from astropy.units import m, cm, mm, km
165
from astropy.units import g, kg
166
from astropy.units import s, Hz
167
from astropy.units import K, eV, keV, MeV, GeV
168
```
169
170
### Unit Equivalencies
171
172
Specialized unit equivalencies for spectroscopic, photometric, and astronomical conversions that allow physically meaningful unit transformations.
173
174
```python { .api }
175
def spectral():
176
"""
177
Frequency, wavelength, and energy equivalencies for electromagnetic radiation.
178
179
Returns:
180
list: equivalency list for use with to() method
181
"""
182
183
def spectral_density(wav):
184
"""
185
Flux density equivalencies (per frequency vs per wavelength).
186
187
Parameters:
188
- wav: reference wavelength
189
190
Returns:
191
list: spectral density equivalencies
192
"""
193
194
def doppler_relativistic(rest):
195
"""
196
Relativistic Doppler shift equivalencies.
197
198
Parameters:
199
- rest: rest frequency/wavelength
200
"""
201
202
def doppler_optical(rest):
203
"""Optical Doppler convention equivalencies."""
204
205
def doppler_radio(rest):
206
"""Radio Doppler convention equivalencies."""
207
208
def parallax():
209
"""Distance and parallax equivalencies."""
210
211
def brightness_temperature(frequency, beam_area=None):
212
"""
213
Brightness temperature equivalencies for radio astronomy.
214
215
Parameters:
216
- frequency: observation frequency
217
- beam_area: telescope beam area
218
"""
219
220
def temperature():
221
"""Temperature scale equivalencies (Kelvin, Celsius, Fahrenheit)."""
222
223
def temperature_energy():
224
"""Temperature and energy equivalencies (kT)."""
225
226
def mass_energy():
227
"""Mass-energy equivalencies (E=mc²)."""
228
229
def with_H0(H0=None):
230
"""Cosmological equivalencies using Hubble parameter."""
231
```
232
233
### Function Unit Support
234
235
Decorators and utilities for adding unit support to functions and ensuring proper unit handling in calculations.
236
237
```python { .api }
238
def quantity_input(**kwargs):
239
"""
240
Decorator to validate function inputs as quantities with specified units.
241
242
Parameters:
243
- **kwargs: parameter name -> allowed unit(s) mapping
244
245
Usage:
246
@quantity_input(distance='length', time='time')
247
def velocity(distance, time):
248
return distance / time
249
"""
250
251
class UnitsError(ValueError):
252
"""Exception for unit-related errors."""
253
254
class UnitConversionError(UnitsError):
255
"""Exception for unit conversion errors."""
256
257
class UnitsWarning(UserWarning):
258
"""Warning for unit-related issues."""
259
260
def with_unit(unit):
261
"""Context manager for setting default unit."""
262
```
263
264
### Logarithmic and Function Units
265
266
Specialized unit support for logarithmic scales, magnitudes, and other function-based units common in astronomy.
267
268
```python { .api }
269
class LogUnit(Unit):
270
"""
271
Logarithmic unit (magnitudes, decibels, etc.).
272
273
Parameters:
274
- unit: base unit
275
- function: logarithmic function (log10, ln, etc.)
276
"""
277
def __init__(self, unit, function=np.log10): ...
278
279
class MagUnit(LogUnit):
280
"""
281
Magnitude unit for astronomical photometry.
282
283
Parameters:
284
- unit: physical unit for flux/luminosity
285
"""
286
def __init__(self, unit): ...
287
288
class DecibelUnit(LogUnit):
289
"""Decibel unit for ratios."""
290
def __init__(self, unit): ...
291
292
# Pre-defined magnitude units
293
from astropy.units import mag, AB, ST, Bol
294
```
295
296
## Usage Examples
297
298
### Basic Quantity Operations
299
300
```python
301
import astropy.units as u
302
303
# Create quantities
304
distance = 100 * u.pc
305
velocity = 30 * u.km / u.s
306
time = 1 * u.Myr
307
308
# Unit conversions
309
print(distance.to(u.lightyear)) # 326.156 lightyear
310
print(velocity.to(u.m / u.s)) # 30000.0 m / s
311
312
# Arithmetic with automatic unit handling
313
acceleration = velocity / time
314
force = acceleration * (1 * u.Msun)
315
energy = 0.5 * (1 * u.Msun) * velocity**2
316
317
print(f"Energy: {energy.to(u.erg)}")
318
```
319
320
### Unit Equivalencies
321
322
```python
323
# Spectroscopic equivalencies
324
freq = 1420 * u.MHz # 21-cm line
325
wavelength = freq.to(u.cm, equivalencies=u.spectral())
326
print(f"21-cm wavelength: {wavelength}")
327
328
# Parallax and distance
329
parallax_angle = 10 * u.mas # milliarcseconds
330
distance = parallax_angle.to(u.pc, equivalencies=u.parallax())
331
print(f"Distance: {distance}")
332
333
# Temperature equivalencies
334
temp_k = 5778 * u.K # Sun's temperature
335
temp_ev = temp_k.to(u.eV, equivalencies=u.temperature_energy())
336
print(f"Solar temperature: {temp_ev}")
337
```
338
339
### Custom Unit Definitions
340
341
```python
342
# Define custom units
343
fortnight = u.def_unit('fortnight', 14 * u.day)
344
barn = u.def_unit('barn', 1e-24 * u.cm**2)
345
346
# Use custom units
347
cross_section = 5 * barn
348
time_period = 2 * fortnight
349
350
print(f"Cross section: {cross_section.to(u.m**2)}")
351
print(f"Time period: {time_period.to(u.s)}")
352
```
353
354
### Function Unit Validation
355
356
```python
357
@u.quantity_input(mass=u.kg, radius=u.m)
358
def escape_velocity(mass, radius):
359
"""Calculate escape velocity."""
360
import astropy.constants as const
361
return (2 * const.G * mass / radius)**0.5
362
363
# This works - units are compatible
364
v_escape = escape_velocity(1 * u.Msun, 1 * u.Rsun)
365
366
# This would raise an error - incompatible units
367
# v_escape = escape_velocity(1 * u.kg, 1 * u.s) # Error!
368
```