astropy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAstropy
Astropy
Overview
概述
Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis. Use astropy for coordinate transformations, unit and quantity calculations, FITS file operations, cosmological calculations, precise time handling, tabular data manipulation, and astronomical image processing.
Astropy是天文学领域的核心Python包,为天文研究和数据分析提供必要功能。可使用astropy进行坐标转换、单位与量值计算、FITS文件操作、宇宙学计算、高精度时间处理、表格数据操作以及天文图像处理。
When to Use This Skill
适用场景
Use astropy when tasks involve:
- Converting between celestial coordinate systems (ICRS, Galactic, FK5, AltAz, etc.)
- Working with physical units and quantities (converting Jy to mJy, parsecs to km, etc.)
- Reading, writing, or manipulating FITS files (images or tables)
- Cosmological calculations (luminosity distance, lookback time, Hubble parameter)
- Precise time handling with different time scales (UTC, TAI, TT, TDB) and formats (JD, MJD, ISO)
- Table operations (reading catalogs, cross-matching, filtering, joining)
- WCS transformations between pixel and world coordinates
- Astronomical constants and calculations
当任务涉及以下内容时,可使用astropy:
- 天球坐标系间的转换(ICRS、银道坐标系、FK5、地平坐标系等)
- 物理单位与量值的处理(如将Jy转换为mJy、秒差距转换为千米等)
- FITS文件的读取、写入或操作(图像或表格)
- 宇宙学计算(光度距离、回溯时间、哈勃参数)
- 不同时间尺度(UTC、TAI、TT、TDB)与格式(JD、MJD、ISO)的高精度时间处理
- 表格操作(读取星表、交叉匹配、过滤、连接)
- 像素坐标与世界坐标系(WCS)间的转换
- 天文常数与相关计算
Quick Start
快速开始
python
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from astropy.io import fits
from astropy.table import Table
from astropy.cosmology import Planck18python
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from astropy.io import fits
from astropy.table import Table
from astropy.cosmology import Planck18Units and quantities
单位与量值
distance = 100 * u.pc
distance_km = distance.to(u.km)
distance = 100 * u.pc
distance_km = distance.to(u.km)
Coordinates
坐标
coord = SkyCoord(ra=10.5u.degree, dec=41.2u.degree, frame='icrs')
coord_galactic = coord.galactic
coord = SkyCoord(ra=10.5u.degree, dec=41.2u.degree, frame='icrs')
coord_galactic = coord.galactic
Time
时间
t = Time('2023-01-15 12:30:00')
jd = t.jd # Julian Date
t = Time('2023-01-15 12:30:00')
jd = t.jd # 儒略日
FITS files
FITS文件
data = fits.getdata('image.fits')
header = fits.getheader('image.fits')
data = fits.getdata('image.fits')
header = fits.getheader('image.fits')
Tables
表格
table = Table.read('catalog.fits')
table = Table.read('catalog.fits')
Cosmology
宇宙学计算
d_L = Planck18.luminosity_distance(z=1.0)
undefinedd_L = Planck18.luminosity_distance(z=1.0)
undefinedCore Capabilities
核心功能
1. Units and Quantities (astropy.units
)
astropy.units1. 单位与量值(astropy.units
)
astropy.unitsHandle physical quantities with units, perform unit conversions, and ensure dimensional consistency in calculations.
Key operations:
- Create quantities by multiplying values with units
- Convert between units using method
.to() - Perform arithmetic with automatic unit handling
- Use equivalencies for domain-specific conversions (spectral, doppler, parallax)
- Work with logarithmic units (magnitudes, decibels)
See: for comprehensive documentation, unit systems, equivalencies, performance optimization, and unit arithmetic.
references/units.md处理带单位的物理量,执行单位转换,并确保计算中的维度一致性。
主要操作:
- 通过数值与单位相乘创建量值
- 使用方法进行单位转换
.to() - 执行带自动单位处理的算术运算
- 使用等效关系进行领域特定转换(光谱、多普勒、视差)
- 处理对数单位(星等、分贝)
参考: 包含全面的文档、单位系统、等效关系、性能优化与单位运算内容。
references/units.md2. Coordinate Systems (astropy.coordinates
)
astropy.coordinates2. 坐标系(astropy.coordinates
)
astropy.coordinatesRepresent celestial positions and transform between different coordinate frames.
Key operations:
- Create coordinates with in any frame (ICRS, Galactic, FK5, AltAz, etc.)
SkyCoord - Transform between coordinate systems
- Calculate angular separations and position angles
- Match coordinates to catalogs
- Include distance for 3D coordinate operations
- Handle proper motions and radial velocities
- Query named objects from online databases
See: for detailed coordinate frame descriptions, transformations, observer-dependent frames (AltAz), catalog matching, and performance tips.
references/coordinates.md表示天球位置并在不同坐标框架间转换。
主要操作:
- 使用在任意框架(ICRS、银道坐标系、FK5、地平坐标系等)中创建坐标
SkyCoord - 坐标系间的转换
- 计算角距离与位置角
- 将坐标与星表匹配
- 包含距离信息以进行3D坐标操作
- 自行与视向速度处理
- 从在线数据库查询命名天体
参考: 包含详细的坐标框架说明、转换方法、依赖观测者的框架(地平坐标系)、星表匹配与性能优化技巧。
references/coordinates.md3. Cosmological Calculations (astropy.cosmology
)
astropy.cosmology3. 宇宙学计算(astropy.cosmology
)
astropy.cosmologyPerform cosmological calculations using standard cosmological models.
Key operations:
- Use built-in cosmologies (Planck18, WMAP9, etc.)
- Create custom cosmological models
- Calculate distances (luminosity, comoving, angular diameter)
- Compute ages and lookback times
- Determine Hubble parameter at any redshift
- Calculate density parameters and volumes
- Perform inverse calculations (find z for given distance)
See: for available models, distance calculations, time calculations, density parameters, and neutrino effects.
references/cosmology.md使用标准宇宙学模型执行宇宙学计算。
主要操作:
- 使用内置宇宙学模型(Planck18、WMAP9等)
- 创建自定义宇宙学模型
- 计算距离(光度距离、共动距离、角直径距离)
- 计算年龄与回溯时间
- 确定任意红移下的哈勃参数
- 计算密度参数与体积
- 执行逆运算(根据给定距离求红移z)
参考: 包含可用模型、距离计算、时间计算、密度参数与中微子效应内容。
references/cosmology.md4. FITS File Handling (astropy.io.fits
)
astropy.io.fits4. FITS文件处理(astropy.io.fits
)
astropy.io.fitsRead, write, and manipulate FITS (Flexible Image Transport System) files.
Key operations:
- Open FITS files with context managers
- Access HDUs (Header Data Units) by index or name
- Read and modify headers (keywords, comments, history)
- Work with image data (NumPy arrays)
- Handle table data (binary and ASCII tables)
- Create new FITS files (single or multi-extension)
- Use memory mapping for large files
- Access remote FITS files (S3, HTTP)
See: for comprehensive file operations, header manipulation, image and table handling, multi-extension files, and performance considerations.
references/fits.md读取、写入与操作FITS(灵活图像传输系统)文件。
主要操作:
- 使用上下文管理器打开FITS文件
- 通过索引或名称访问HDU(头数据单元)
- 读取与修改头信息(关键字、注释、历史记录)
- 处理图像数据(NumPy数组)
- 处理表格数据(二进制与ASCII表格)
- 创建新的FITS文件(单扩展或多扩展)
- 对大文件使用内存映射
- 访问远程FITS文件(S3、HTTP)
参考: 包含全面的文件操作、头信息处理、图像与表格操作、多扩展文件与性能考量内容。
references/fits.md5. Table Operations (astropy.table
)
astropy.table5. 表格操作(astropy.table
)
astropy.tableWork with tabular data with support for units, metadata, and various file formats.
Key operations:
- Create tables from arrays, lists, or dictionaries
- Read/write tables in multiple formats (FITS, CSV, HDF5, VOTable)
- Access and modify columns and rows
- Sort, filter, and index tables
- Perform database-style operations (join, group, aggregate)
- Stack and concatenate tables
- Work with unit-aware columns (QTable)
- Handle missing data with masking
See: for table creation, I/O operations, data manipulation, sorting, filtering, joins, grouping, and performance tips.
references/tables.md处理带单位、元数据支持的表格数据,兼容多种文件格式。
主要操作:
- 从数组、列表或字典创建表格
- 以多种格式(FITS、CSV、HDF5、VOTable)读取/写入表格
- 访问与修改列和行
- 排序、过滤与索引表格
- 执行类数据库操作(连接、分组、聚合)
- 堆叠与拼接表格
- 处理带单位的列(QTable)
- 使用掩码处理缺失数据
参考: 包含表格创建、I/O操作、数据处理、排序、过滤、连接、分组与性能优化技巧。
references/tables.md6. Time Handling (astropy.time
)
astropy.time6. 时间处理(astropy.time
)
astropy.timePrecise time representation and conversion between time scales and formats.
Key operations:
- Create Time objects in various formats (ISO, JD, MJD, Unix, etc.)
- Convert between time scales (UTC, TAI, TT, TDB, etc.)
- Perform time arithmetic with TimeDelta
- Calculate sidereal time for observers
- Compute light travel time corrections (barycentric, heliocentric)
- Work with time arrays efficiently
- Handle masked (missing) times
See: for time formats, time scales, conversions, arithmetic, observing features, and precision handling.
references/time.md高精度时间表示与不同时间尺度、格式间的转换。
主要操作:
- 创建多种格式的Time对象(ISO、JD、MJD、Unix等)
- 时间尺度间的转换(UTC、TAI、TT、TDB等)
- 使用TimeDelta执行时间算术
- 计算观测者的恒星时
- 计算光行时修正(质心、日心)
- 高效处理时间数组
- 处理掩码(缺失)时间
参考: 包含时间格式、时间尺度、转换、算术运算、观测特性与精度处理内容。
references/time.md7. World Coordinate System (astropy.wcs
)
astropy.wcs7. 世界坐标系(astropy.wcs
)
astropy.wcsTransform between pixel coordinates in images and world coordinates.
Key operations:
- Read WCS from FITS headers
- Convert pixel coordinates to world coordinates (and vice versa)
- Calculate image footprints
- Access WCS parameters (reference pixel, projection, scale)
- Create custom WCS objects
See: for WCS operations and transformations.
references/wcs_and_other_modules.md在图像像素坐标与世界坐标间转换。
主要操作:
- 从FITS头读取WCS信息
- 像素坐标与世界坐标间的转换(双向)
- 计算图像覆盖区域
- 访问WCS参数(参考像素、投影、尺度)
- 创建自定义WCS对象
参考: 包含WCS操作与转换内容。
references/wcs_and_other_modules.mdAdditional Capabilities
附加功能
The file also covers:
references/wcs_and_other_modules.mdreferences/wcs_and_other_modules.mdNDData and CCDData
NDData与CCDData
Containers for n-dimensional datasets with metadata, uncertainty, masking, and WCS information.
用于存储带元数据、不确定性、掩码与WCS信息的n维数据集容器。
Modeling
建模
Framework for creating and fitting mathematical models to astronomical data.
用于创建数学模型并拟合天文数据的框架。
Visualization
可视化
Tools for astronomical image display with appropriate stretching and scaling.
用于天文图像显示的工具,支持适当的拉伸与缩放。
Constants
常数
Physical and astronomical constants with proper units (speed of light, solar mass, Planck constant, etc.).
带正确单位的物理与天文常数(光速、太阳质量、普朗克常数等)。
Convolution
卷积
Image processing kernels for smoothing and filtering.
用于图像平滑与过滤的图像处理核。
Statistics
统计
Robust statistical functions including sigma clipping and outlier rejection.
鲁棒统计函数,包括σ裁剪与异常值剔除。
Installation
安装
bash
undefinedbash
undefinedInstall astropy
安装astropy
uv pip install astropy
uv pip install astropy
With optional dependencies for full functionality
安装可选依赖以获得完整功能
uv pip install astropy[all]
undefineduv pip install astropy[all]
undefinedCommon Workflows
常见工作流
Converting Coordinates Between Systems
坐标系间转换
python
from astropy.coordinates import SkyCoord
import astropy.units as upython
from astropy.coordinates import SkyCoord
import astropy.units as uCreate coordinate
创建坐标
c = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs')
c = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs')
Transform to galactic
转换为银道坐标系
c_gal = c.galactic
print(f"l={c_gal.l.deg}, b={c_gal.b.deg}")
c_gal = c.galactic
print(f"l={c_gal.l.deg}, b={c_gal.b.deg}")
Transform to alt-az (requires time and location)
转换为地平坐标系(需要时间与位置信息)
from astropy.time import Time
from astropy.coordinates import EarthLocation, AltAz
observing_time = Time('2023-06-15 23:00:00')
observing_location = EarthLocation(lat=40u.deg, lon=-120u.deg)
aa_frame = AltAz(obstime=observing_time, location=observing_location)
c_altaz = c.transform_to(aa_frame)
print(f"Alt={c_altaz.alt.deg}, Az={c_altaz.az.deg}")
undefinedfrom astropy.time import Time
from astropy.coordinates import EarthLocation, AltAz
observing_time = Time('2023-06-15 23:00:00')
observing_location = EarthLocation(lat=40u.deg, lon=-120u.deg)
aa_frame = AltAz(obstime=observing_time, location=observing_location)
c_altaz = c.transform_to(aa_frame)
print(f"Alt={c_altaz.alt.deg}, Az={c_altaz.az.deg}")
undefinedReading and Analyzing FITS Files
读取与分析FITS文件
python
from astropy.io import fits
import numpy as nppython
from astropy.io import fits
import numpy as npOpen FITS file
打开FITS文件
with fits.open('observation.fits') as hdul:
# Display structure
hdul.info()
# Get image data and header
data = hdul[1].data
header = hdul[1].header
# Access header values
exptime = header['EXPTIME']
filter_name = header['FILTER']
# Analyze data
mean = np.mean(data)
median = np.median(data)
print(f"Mean: {mean}, Median: {median}")undefinedwith fits.open('observation.fits') as hdul:
# 显示结构
hdul.info()
# 获取图像数据与头信息
data = hdul[1].data
header = hdul[1].header
# 访问头信息值
exptime = header['EXPTIME']
filter_name = header['FILTER']
# 分析数据
mean = np.mean(data)
median = np.median(data)
print(f"Mean: {mean}, Median: {median}")undefinedCosmological Distance Calculations
宇宙学距离计算
python
from astropy.cosmology import Planck18
import astropy.units as u
import numpy as nppython
from astropy.cosmology import Planck18
import astropy.units as u
import numpy as npCalculate distances at z=1.5
计算红移z=1.5时的距离
z = 1.5
d_L = Planck18.luminosity_distance(z)
d_A = Planck18.angular_diameter_distance(z)
print(f"Luminosity distance: {d_L}")
print(f"Angular diameter distance: {d_A}")
z = 1.5
d_L = Planck18.luminosity_distance(z)
d_A = Planck18.angular_diameter_distance(z)
print(f"Luminosity distance: {d_L}")
print(f"Angular diameter distance: {d_A}")
Age of universe at that redshift
该红移下的宇宙年龄
age = Planck18.age(z)
print(f"Age at z={z}: {age.to(u.Gyr)}")
age = Planck18.age(z)
print(f"Age at z={z}: {age.to(u.Gyr)}")
Lookback time
回溯时间
t_lookback = Planck18.lookback_time(z)
print(f"Lookback time: {t_lookback.to(u.Gyr)}")
undefinedt_lookback = Planck18.lookback_time(z)
print(f"Lookback time: {t_lookback.to(u.Gyr)}")
undefinedCross-Matching Catalogs
星表交叉匹配
python
from astropy.table import Table
from astropy.coordinates import SkyCoord, match_coordinates_sky
import astropy.units as upython
from astropy.table import Table
from astropy.coordinates import SkyCoord, match_coordinates_sky
import astropy.units as uRead catalogs
读取星表
cat1 = Table.read('catalog1.fits')
cat2 = Table.read('catalog2.fits')
cat1 = Table.read('catalog1.fits')
cat2 = Table.read('catalog2.fits')
Create coordinate objects
创建坐标对象
coords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree)
coords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree)
coords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree)
coords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree)
Find matches
查找匹配
idx, sep, _ = coords1.match_to_catalog_sky(coords2)
idx, sep, _ = coords1.match_to_catalog_sky(coords2)
Filter by separation threshold
按分离阈值过滤
max_sep = 1 * u.arcsec
matches = sep < max_sep
max_sep = 1 * u.arcsec
matches = sep < max_sep
Create matched catalogs
创建匹配后的星表
cat1_matched = cat1[matches]
cat2_matched = cat2[idx[matches]]
print(f"Found {len(cat1_matched)} matches")
undefinedcat1_matched = cat1[matches]
cat2_matched = cat2[idx[matches]]
print(f"Found {len(cat1_matched)} matches")
undefinedBest Practices
最佳实践
- Always use units: Attach units to quantities to avoid errors and ensure dimensional consistency
- Use context managers for FITS files: Ensures proper file closing
- Prefer arrays over loops: Process multiple coordinates/times as arrays for better performance
- Check coordinate frames: Verify the frame before transformations
- Use appropriate cosmology: Choose the right cosmological model for your analysis
- Handle missing data: Use masked columns for tables with missing values
- Specify time scales: Be explicit about time scales (UTC, TT, TDB) for precise timing
- Use QTable for unit-aware tables: When table columns have units
- Check WCS validity: Verify WCS before using transformations
- Cache frequently used values: Expensive calculations (e.g., cosmological distances) can be cached
- 始终使用单位:为量值附加单位以避免错误并确保维度一致性
- 对FITS文件使用上下文管理器:确保文件正确关闭
- 优先使用数组而非循环:以数组形式处理多个坐标/时间以提升性能
- 检查坐标框架:转换前验证框架类型
- 使用合适的宇宙学模型:为分析选择正确的宇宙学模型
- 处理缺失数据:对包含缺失值的表格使用掩码列
- 明确指定时间尺度:为高精度计时明确时间尺度(UTC、TT、TDB)
- 对带单位的表格使用QTable:当表格列包含单位时
- 检查WCS有效性:使用转换前验证WCS
- 缓存频繁使用的值:可缓存计算成本高的结果(如宇宙学距离)
Documentation and Resources
文档与资源
- Official Astropy Documentation: https://docs.astropy.org/en/stable/
- Tutorials: https://learn.astropy.org/
- GitHub: https://github.com/astropy/astropy
- Astropy官方文档:https://docs.astropy.org/en/stable/
- 教程:https://learn.astropy.org/
- GitHub:https://github.com/astropy/astropy
Reference Files
参考文件
For detailed information on specific modules:
- - Units, quantities, conversions, and equivalencies
references/units.md - - Coordinate systems, transformations, and catalog matching
references/coordinates.md - - Cosmological models and calculations
references/cosmology.md - - FITS file operations and manipulation
references/fits.md - - Table creation, I/O, and operations
references/tables.md - - Time formats, scales, and calculations
references/time.md - - WCS, NDData, modeling, visualization, constants, and utilities
references/wcs_and_other_modules.md
特定模块的详细信息请参考:
- - 单位、量值、转换与等效关系
references/units.md - - 坐标系、转换与星表匹配
references/coordinates.md - - 宇宙学模型与计算
references/cosmology.md - - FITS文件操作与处理
references/fits.md - - 表格创建、I/O与操作
references/tables.md - - 时间格式、尺度与计算
references/time.md - - WCS、NDData、建模、可视化、常数与工具
references/wcs_and_other_modules.md