Astronomy and astrophysics core library providing comprehensive tools for astronomical computations and data handling
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Complete physical unit system with quantity objects supporting all astronomical and physical units, unit conversions, and equivalencies for spectroscopic, photometric, and distance measurements.
from astropy import units as u
from astropy.units import Quantity, Unit
from astropy.units import def_unit, get_physical_type
from astropy.units import dimensionless_unscaled
from astropy.units import set_enabled_units
from astropy.units.equivalencies import spectral, doppler_optical, doppler_radioCreate physical quantities by combining numerical values with units, supporting arithmetic operations, comparisons, and array operations with automatic unit handling.
class Quantity:
"""
A numerical value associated with an astronomical or physical unit.
Parameters:
- value: scalar, array-like, or Quantity instance
- unit: Unit instance or string representation
- dtype: numpy dtype for the value
- copy: bool, whether to copy the value
"""
def __init__(self, value, unit=None, dtype=None, copy=True): ...
def to(self, unit, equivalencies=[]):
"""
Convert to different unit.
Parameters:
- unit: target unit
- equivalencies: list of unit equivalencies to apply
Returns:
Quantity: converted quantity
"""
def to_value(self, unit=None, equivalencies=[]):
"""
Extract numerical value in specified unit.
Returns:
scalar or array: numerical value
"""
@property
def value(self):
"""Numerical value of the quantity."""
@property
def unit(self):
"""Unit of the quantity."""
def decompose(self, bases=[]):
"""Decompose into fundamental units."""
def __add__(self, other): ...
def __sub__(self, other): ...
def __mul__(self, other): ...
def __truediv__(self, other): ...
def __pow__(self, power): ...Create, manipulate, and combine physical units with support for SI, CGS, imperial, and astronomical unit systems.
class Unit:
"""
Physical unit with support for operations and conversions.
Parameters:
- s: string representation of unit
- parse_strict: how strict to be in parsing ('raise', 'warn', 'silent')
"""
def __init__(self, s, parse_strict='raise'): ...
def to(self, other, value=1.0, equivalencies=[]):
"""Convert between units."""
def is_equivalent(self, other, equivalencies=[]):
"""Check if units are equivalent."""
def decompose(self, bases=[]):
"""Decompose into base units."""
@property
def physical_type(self):
"""Physical type of the unit (e.g., 'length', 'time')."""
def __mul__(self, other): ...
def __truediv__(self, other): ...
def __pow__(self, power): ...
def def_unit(s, represents=None, doc=None, format=None):
"""
Define a new unit.
Parameters:
- s: string symbol for the unit
- represents: Unit instance this represents
- doc: documentation string
- format: format specification
Returns:
Unit: newly defined unit
"""
def get_current_unit_registry():
"""Get the currently active unit registry."""
def set_enabled_units(units):
"""Set which unit collections are enabled."""
def add_enabled_units(units):
"""Add unit collections to enabled units."""Pre-defined unit collections for different physical systems and astronomical applications.
# SI base and derived units
import astropy.units.si as si
# si.meter, si.kilogram, si.second, si.ampere, si.kelvin, si.mole, si.candela
# si.newton, si.joule, si.watt, si.pascal, si.coulomb, si.volt, etc.
# CGS units
import astropy.units.cgs as cgs
# cgs.centimeter, cgs.gram, cgs.second, cgs.dyne, cgs.erg, etc.
# Astrophysical units
import astropy.units.astrophys as astrophys
# astrophys.AU, astrophys.pc, astrophys.kpc, astrophys.Mpc
# astrophys.Msun, astrophys.Rsun, astrophys.Lsun
# astrophys.year, astrophys.Myr, astrophys.Gyr
# Physical constants as units
import astropy.units.physical as physical
# physical.c, physical.G, physical.h, physical.k_B, etc.
# Photometric units
import astropy.units.photometric as photometric
# photometric.mag, photometric.Bol, photometric.AB, photometric.ST
# Angle units
from astropy.units import degree, arcmin, arcsec, radian
from astropy.units import hourangle
# Time units
from astropy.units import second, minute, hour, day, year
# Common unit shortcuts
from astropy.units import m, cm, mm, km
from astropy.units import g, kg
from astropy.units import s, Hz
from astropy.units import K, eV, keV, MeV, GeVSpecialized unit equivalencies for spectroscopic, photometric, and astronomical conversions that allow physically meaningful unit transformations.
def spectral():
"""
Frequency, wavelength, and energy equivalencies for electromagnetic radiation.
Returns:
list: equivalency list for use with to() method
"""
def spectral_density(wav):
"""
Flux density equivalencies (per frequency vs per wavelength).
Parameters:
- wav: reference wavelength
Returns:
list: spectral density equivalencies
"""
def doppler_relativistic(rest):
"""
Relativistic Doppler shift equivalencies.
Parameters:
- rest: rest frequency/wavelength
"""
def doppler_optical(rest):
"""Optical Doppler convention equivalencies."""
def doppler_radio(rest):
"""Radio Doppler convention equivalencies."""
def parallax():
"""Distance and parallax equivalencies."""
def brightness_temperature(frequency, beam_area=None):
"""
Brightness temperature equivalencies for radio astronomy.
Parameters:
- frequency: observation frequency
- beam_area: telescope beam area
"""
def temperature():
"""Temperature scale equivalencies (Kelvin, Celsius, Fahrenheit)."""
def temperature_energy():
"""Temperature and energy equivalencies (kT)."""
def mass_energy():
"""Mass-energy equivalencies (E=mc²)."""
def with_H0(H0=None):
"""Cosmological equivalencies using Hubble parameter."""Decorators and utilities for adding unit support to functions and ensuring proper unit handling in calculations.
def quantity_input(**kwargs):
"""
Decorator to validate function inputs as quantities with specified units.
Parameters:
- **kwargs: parameter name -> allowed unit(s) mapping
Usage:
@quantity_input(distance='length', time='time')
def velocity(distance, time):
return distance / time
"""
class UnitsError(ValueError):
"""Exception for unit-related errors."""
class UnitConversionError(UnitsError):
"""Exception for unit conversion errors."""
class UnitsWarning(UserWarning):
"""Warning for unit-related issues."""
def with_unit(unit):
"""Context manager for setting default unit."""Specialized unit support for logarithmic scales, magnitudes, and other function-based units common in astronomy.
class LogUnit(Unit):
"""
Logarithmic unit (magnitudes, decibels, etc.).
Parameters:
- unit: base unit
- function: logarithmic function (log10, ln, etc.)
"""
def __init__(self, unit, function=np.log10): ...
class MagUnit(LogUnit):
"""
Magnitude unit for astronomical photometry.
Parameters:
- unit: physical unit for flux/luminosity
"""
def __init__(self, unit): ...
class DecibelUnit(LogUnit):
"""Decibel unit for ratios."""
def __init__(self, unit): ...
# Pre-defined magnitude units
from astropy.units import mag, AB, ST, Bolimport astropy.units as u
# Create quantities
distance = 100 * u.pc
velocity = 30 * u.km / u.s
time = 1 * u.Myr
# Unit conversions
print(distance.to(u.lightyear)) # 326.156 lightyear
print(velocity.to(u.m / u.s)) # 30000.0 m / s
# Arithmetic with automatic unit handling
acceleration = velocity / time
force = acceleration * (1 * u.Msun)
energy = 0.5 * (1 * u.Msun) * velocity**2
print(f"Energy: {energy.to(u.erg)}")# Spectroscopic equivalencies
freq = 1420 * u.MHz # 21-cm line
wavelength = freq.to(u.cm, equivalencies=u.spectral())
print(f"21-cm wavelength: {wavelength}")
# Parallax and distance
parallax_angle = 10 * u.mas # milliarcseconds
distance = parallax_angle.to(u.pc, equivalencies=u.parallax())
print(f"Distance: {distance}")
# Temperature equivalencies
temp_k = 5778 * u.K # Sun's temperature
temp_ev = temp_k.to(u.eV, equivalencies=u.temperature_energy())
print(f"Solar temperature: {temp_ev}")# Define custom units
fortnight = u.def_unit('fortnight', 14 * u.day)
barn = u.def_unit('barn', 1e-24 * u.cm**2)
# Use custom units
cross_section = 5 * barn
time_period = 2 * fortnight
print(f"Cross section: {cross_section.to(u.m**2)}")
print(f"Time period: {time_period.to(u.s)}")@u.quantity_input(mass=u.kg, radius=u.m)
def escape_velocity(mass, radius):
"""Calculate escape velocity."""
import astropy.constants as const
return (2 * const.G * mass / radius)**0.5
# This works - units are compatible
v_escape = escape_velocity(1 * u.Msun, 1 * u.Rsun)
# This would raise an error - incompatible units
# v_escape = escape_velocity(1 * u.kg, 1 * u.s) # Error!