astropy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Astropy

Astropy

Overview

概述

Astropy is the community standard Python library for astronomy, providing core functionality for astronomical data analysis and computation. This skill provides comprehensive guidance and tools for working with astropy's extensive capabilities across coordinate systems, file I/O, units and quantities, time systems, cosmology, modeling, and more.
Astropy是天文学领域的社区标准Python库,为天文数据分析与计算提供核心功能。本技能提供了全面的指南与工具,涵盖Astropy在坐标系、文件I/O、单位与量、时间系统、宇宙学、建模等方面的丰富功能。

When to Use This Skill

适用场景

This skill should be used when:
  • Working with FITS files (reading, writing, inspecting, modifying)
  • Performing coordinate transformations between astronomical reference frames
  • Calculating cosmological distances, ages, or other quantities
  • Handling astronomical time systems and conversions
  • Working with physical units and dimensional analysis
  • Processing astronomical data tables with specialized column types
  • Fitting models to astronomical data
  • Converting between pixel and world coordinates (WCS)
  • Performing robust statistical analysis on astronomical data
  • Visualizing astronomical images with proper scaling and stretching
在以下场景中可使用本技能:
  • 处理FITS文件(读取、写入、检查、修改)
  • 在天文参考系之间进行坐标转换
  • 计算宇宙学距离、年龄或其他物理量
  • 处理天文时间系统与转换
  • 物理单位与量纲分析
  • 处理带有特殊列类型的天文数据表
  • 为天文数据拟合模型
  • 在像素坐标与世界坐标(WCS)之间进行转换
  • 对天文数据进行稳健的统计分析
  • 以合适的缩放与拉伸方式可视化天文图像

Core Capabilities

核心功能

1. FITS File Operations

1. FITS文件操作

FITS (Flexible Image Transport System) is the standard file format in astronomy. Astropy provides comprehensive FITS support.
Quick FITS Inspection: Use the included
scripts/fits_info.py
script for rapid file inspection:
bash
python scripts/fits_info.py observation.fits
python scripts/fits_info.py observation.fits --detailed
python scripts/fits_info.py observation.fits --ext 1
Common FITS workflows:
python
from astropy.io import fits
FITS(Flexible Image Transport System,灵活图像传输系统)是天文学中的标准文件格式。Astropy提供了全面的FITS支持。
快速FITS文件检查: 使用附带的
scripts/fits_info.py
脚本快速检查文件:
bash
python scripts/fits_info.py observation.fits
python scripts/fits_info.py observation.fits --detailed
python scripts/fits_info.py observation.fits --ext 1
常见FITS工作流:
python
from astropy.io import fits

Read FITS file

读取FITS文件

with fits.open('image.fits') as hdul: hdul.info() # Display structure data = hdul[0].data header = hdul[0].header
with fits.open('image.fits') as hdul: hdul.info() # 显示文件结构 data = hdul[0].data header = hdul[0].header

Write FITS file

写入FITS文件

fits.writeto('output.fits', data, header, overwrite=True)
fits.writeto('output.fits', data, header, overwrite=True)

Quick access (less efficient for multiple operations)

快速访问(多次操作时效率较低)

data = fits.getdata('image.fits', ext=0) header = fits.getheader('image.fits', ext=0)
data = fits.getdata('image.fits', ext=0) header = fits.getheader('image.fits', ext=0)

Update specific header keyword

更新特定表头关键字

fits.setval('image.fits', 'OBJECT', value='M31')

**Multi-extension FITS**:
```python
from astropy.io import fits
fits.setval('image.fits', 'OBJECT', value='M31')

**多扩展FITS文件**:
```python
from astropy.io import fits

Create multi-extension FITS

创建多扩展FITS文件

primary = fits.PrimaryHDU(primary_data) image_ext = fits.ImageHDU(science_data, name='SCI') error_ext = fits.ImageHDU(error_data, name='ERR')
hdul = fits.HDUList([primary, image_ext, error_ext]) hdul.writeto('multi_ext.fits', overwrite=True)

**Binary tables**:
```python
from astropy.io import fits
primary = fits.PrimaryHDU(primary_data) image_ext = fits.ImageHDU(science_data, name='SCI') error_ext = fits.ImageHDU(error_data, name='ERR')
hdul = fits.HDUList([primary, image_ext, error_ext]) hdul.writeto('multi_ext.fits', overwrite=True)

**二进制表**:
```python
from astropy.io import fits

Read binary table

读取二进制表

with fits.open('catalog.fits') as hdul: table_data = hdul[1].data ra = table_data['RA'] dec = table_data['DEC']
with fits.open('catalog.fits') as hdul: table_data = hdul[1].data ra = table_data['RA'] dec = table_data['DEC']

Better: use astropy.table for table operations (see section 5)

更优方式:使用astropy.table处理表格(见第5节)

undefined
undefined

2. Coordinate Systems and Transformations

2. 坐标系与转换

Astropy supports ~25 coordinate frames with seamless transformations.
Quick Coordinate Conversion: Use the included
scripts/coord_convert.py
script:
bash
python scripts/coord_convert.py 10.68 41.27 --from icrs --to galactic
python scripts/coord_convert.py --file coords.txt --from icrs --to galactic --output sexagesimal
Basic coordinate operations:
python
from astropy.coordinates import SkyCoord
import astropy.units as u
Astropy支持约25种坐标系,可实现无缝转换。
快速坐标转换: 使用附带的
scripts/coord_convert.py
脚本:
bash
python scripts/coord_convert.py 10.68 41.27 --from icrs --to galactic
python scripts/coord_convert.py --file coords.txt --from icrs --to galactic --output sexagesimal
基础坐标操作:
python
from astropy.coordinates import SkyCoord
import astropy.units as u

Create coordinate (multiple input formats supported)

创建坐标(支持多种输入格式)

c = SkyCoord(ra=10.68u.degree, dec=41.27u.degree, frame='icrs') c = SkyCoord('00:42:44.3 +41:16:09', unit=(u.hourangle, u.deg)) c = SkyCoord('00h42m44.3s +41d16m09s')
c = SkyCoord(ra=10.68u.degree, dec=41.27u.degree, frame='icrs') c = SkyCoord('00:42:44.3 +41:16:09', unit=(u.hourangle, u.deg)) c = SkyCoord('00h42m44.3s +41d16m09s')

Transform between frames

在坐标系之间转换

c_galactic = c.galactic c_fk5 = c.fk5
print(f"Galactic: l={c_galactic.l.deg:.3f}, b={c_galactic.b.deg:.3f}")

**Working with coordinate arrays**:
```python
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
c_galactic = c.galactic c_fk5 = c.fk5
print(f"银道坐标: l={c_galactic.l.deg:.3f}, b={c_galactic.b.deg:.3f}")

**坐标数组操作**:
```python
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u

Arrays of coordinates

坐标数组

ra = np.array([10.1, 10.2, 10.3]) * u.degree dec = np.array([40.1, 40.2, 40.3]) * u.degree coords = SkyCoord(ra=ra, dec=dec, frame='icrs')
ra = np.array([10.1, 10.2, 10.3]) * u.degree dec = np.array([40.1, 40.2, 40.3]) * u.degree coords = SkyCoord(ra=ra, dec=dec, frame='icrs')

Calculate separations

计算角距离

sep = coords[0].separation(coords[1]) print(f"Separation: {sep.to(u.arcmin)}")
sep = coords[0].separation(coords[1]) print(f"角距离: {sep.to(u.arcmin)}")

Position angle

位置角

pa = coords[0].position_angle(coords[1])

**Catalog matching**:
```python
from astropy.coordinates import SkyCoord
import astropy.units as u

catalog1 = SkyCoord(ra=[10, 11, 12]*u.degree, dec=[40, 41, 42]*u.degree)
catalog2 = SkyCoord(ra=[10.01, 11.02, 13]*u.degree, dec=[40.01, 41.01, 43]*u.degree)
pa = coords[0].position_angle(coords[1])

**星表匹配**:
```python
from astropy.coordinates import SkyCoord
import astropy.units as u

catalog1 = SkyCoord(ra=[10, 11, 12]*u.degree, dec=[40, 41, 42]*u.degree)
catalog2 = SkyCoord(ra=[10.01, 11.02, 13]*u.degree, dec=[40.01, 41.01, 43]*u.degree)

Find nearest neighbors

查找最近邻

idx, sep2d, dist3d = catalog1.match_to_catalog_sky(catalog2)
idx, sep2d, dist3d = catalog1.match_to_catalog_sky(catalog2)

Filter by separation threshold

按角距离阈值过滤

max_sep = 1 * u.arcsec matched = sep2d < max_sep

**Horizontal coordinates (Alt/Az)**:
```python
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.time import Time
import astropy.units as u

location = EarthLocation(lat=40*u.deg, lon=-70*u.deg, height=300*u.m)
obstime = Time('2023-01-01 03:00:00')
target = SkyCoord(ra=10*u.degree, dec=40*u.degree, frame='icrs')

altaz_frame = AltAz(obstime=obstime, location=location)
target_altaz = target.transform_to(altaz_frame)

print(f"Alt: {target_altaz.alt.deg:.2f}°, Az: {target_altaz.az.deg:.2f}°")
Available coordinate frames:
  • icrs
    - International Celestial Reference System (default, preferred)
  • fk5
    ,
    fk4
    - Fifth/Fourth Fundamental Katalog
  • galactic
    - Galactic coordinates
  • supergalactic
    - Supergalactic coordinates
  • altaz
    - Horizontal (altitude-azimuth) coordinates
  • gcrs
    ,
    cirs
    ,
    itrs
    - Earth-based systems
  • Ecliptic frames:
    BarycentricMeanEcliptic
    ,
    HeliocentricMeanEcliptic
    ,
    GeocentricMeanEcliptic
max_sep = 1 * u.arcsec matched = sep2d < max_sep

**地平坐标(高度/方位角)**:
```python
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.time import Time
import astropy.units as u

location = EarthLocation(lat=40*u.deg, lon=-70*u.deg, height=300*u.m)
obstime = Time('2023-01-01 03:00:00')
target = SkyCoord(ra=10*u.degree, dec=40*u.degree, frame='icrs')

altaz_frame = AltAz(obstime=obstime, location=location)
target_altaz = target.transform_to(altaz_frame)

print(f"高度: {target_altaz.alt.deg:.2f}°, 方位角: {target_altaz.az.deg:.2f}°")
可用坐标系:
  • icrs
    - 国际天球参考系(默认,推荐使用)
  • fk5
    ,
    fk4
    - 第五/第四基本星表
  • galactic
    - 银道坐标系
  • supergalactic
    - 超银道坐标系
  • altaz
    - 地平(高度-方位角)坐标系
  • gcrs
    ,
    cirs
    ,
    itrs
    - 地球基坐标系
  • 黄道坐标系:
    BarycentricMeanEcliptic
    ,
    HeliocentricMeanEcliptic
    ,
    GeocentricMeanEcliptic

3. Units and Quantities

3. 单位与量

Physical units are fundamental to astronomical calculations. Astropy's units system provides dimensional analysis and automatic conversions.
Basic unit operations:
python
import astropy.units as u
物理单位是天文计算的基础。Astropy的单位系统提供量纲分析与自动转换功能。
基础单位操作:
python
import astropy.units as u

Create quantities

创建带单位的量

distance = 5.2 * u.parsec velocity = 300 * u.km / u.s time = 10 * u.year
distance = 5.2 * u.parsec velocity = 300 * u.km / u.s time = 10 * u.year

Convert units

转换单位

distance_ly = distance.to(u.lightyear) velocity_mps = velocity.to(u.m / u.s)
distance_ly = distance.to(u.lightyear) velocity_mps = velocity.to(u.m / u.s)

Arithmetic with units

带单位的算术运算

wavelength = 500 * u.nm frequency = wavelength.to(u.Hz, equivalencies=u.spectral())

**Working with arrays**:
```python
import numpy as np
import astropy.units as u

wavelengths = np.array([400, 500, 600]) * u.nm
frequencies = wavelengths.to(u.THz, equivalencies=u.spectral())

fluxes = np.array([1.2, 2.3, 1.8]) * u.Jy
luminosities = 4 * np.pi * (10*u.pc)**2 * fluxes
Important equivalencies:
  • u.spectral()
    - Convert wavelength ↔ frequency ↔ energy
  • u.doppler_optical(rest)
    - Optical Doppler velocity
  • u.doppler_radio(rest)
    - Radio Doppler velocity
  • u.doppler_relativistic(rest)
    - Relativistic Doppler
  • u.temperature()
    - Temperature unit conversions
  • u.brightness_temperature(freq)
    - Brightness temperature
Physical constants:
python
from astropy import constants as const

print(const.c)      # Speed of light
print(const.G)      # Gravitational constant
print(const.M_sun)  # Solar mass
print(const.R_sun)  # Solar radius
print(const.L_sun)  # Solar luminosity
Performance tip: Use the
<<
operator for fast unit assignment to arrays:
python
undefined
wavelength = 500 * u.nm frequency = wavelength.to(u.Hz, equivalencies=u.spectral())

**数组操作**:
```python
import numpy as np
import astropy.units as u

wavelengths = np.array([400, 500, 600]) * u.nm
frequencies = wavelengths.to(u.THz, equivalencies=u.spectral())

fluxes = np.array([1.2, 2.3, 1.8]) * u.Jy
luminosities = 4 * np.pi * (10*u.pc)**2 * fluxes
重要等效转换:
  • u.spectral()
    - 波长 ↔ 频率 ↔ 能量转换
  • u.doppler_optical(rest)
    - 光学多普勒速度转换
  • u.doppler_radio(rest)
    - 射电多普勒速度转换
  • u.doppler_relativistic(rest)
    - 相对论性多普勒转换
  • u.temperature()
    - 温度单位转换
  • u.brightness_temperature(freq)
    - 亮温转换
物理常数:
python
from astropy import constants as const

print(const.c)      # 光速
print(const.G)      # 引力常数
print(const.M_sun)  # 太阳质量
print(const.R_sun)  # 太阳半径
print(const.L_sun)  # 太阳光度
性能提示: 使用
<<
运算符为数组快速分配单位:
python
undefined

Fast

快速

result = large_array << u.m
result = large_array << u.m

Slower

较慢

result = large_array * u.m
undefined
result = large_array * u.m
undefined

4. Time Systems

4. 时间系统

Astronomical time systems require high precision and multiple time scales.
Creating time objects:
python
from astropy.time import Time
import astropy.units as u
天文时间系统需要高精度与多种时间尺度。
创建时间对象:
python
from astropy.time import Time
import astropy.units as u

Various input formats

多种输入格式

t1 = Time('2023-01-01T00:00:00', format='isot', scale='utc') t2 = Time(2459945.5, format='jd', scale='utc') t3 = Time(['2023-01-01', '2023-06-01'], format='iso')
t1 = Time('2023-01-01T00:00:00', format='isot', scale='utc') t2 = Time(2459945.5, format='jd', scale='utc') t3 = Time(['2023-01-01', '2023-06-01'], format='iso')

Convert formats

转换格式

print(t1.jd) # Julian Date print(t1.mjd) # Modified Julian Date print(t1.unix) # Unix timestamp print(t1.iso) # ISO format
print(t1.jd) # 儒略日 print(t1.mjd) # 修正儒略日 print(t1.unix) # Unix时间戳 print(t1.iso) # ISO格式

Convert time scales

转换时间尺度

print(t1.tai) # International Atomic Time print(t1.tt) # Terrestrial Time print(t1.tdb) # Barycentric Dynamical Time

**Time arithmetic**:
```python
from astropy.time import Time, TimeDelta
import astropy.units as u

t1 = Time('2023-01-01T00:00:00')
dt = TimeDelta(1*u.day)

t2 = t1 + dt
diff = t2 - t1
print(diff.to(u.hour))
print(t1.tai) # 国际原子时 print(t1.tt) # 地球时 print(t1.tdb) # 质心力学时

**时间算术运算**:
```python
from astropy.time import Time, TimeDelta
import astropy.units as u

t1 = Time('2023-01-01T00:00:00')
dt = TimeDelta(1*u.day)

t2 = t1 + dt
diff = t2 - t1
print(diff.to(u.hour))

Array of times

时间数组

times = t1 + np.arange(10) * u.day

**Astronomical time calculations**:
```python
from astropy.time import Time
from astropy.coordinates import SkyCoord, EarthLocation
import astropy.units as u

location = EarthLocation(lat=40*u.deg, lon=-70*u.deg)
t = Time('2023-01-01T00:00:00')
times = t1 + np.arange(10) * u.day

**天文时间计算**:
```python
from astropy.time import Time
from astropy.coordinates import SkyCoord, EarthLocation
import astropy.units as u

location = EarthLocation(lat=40*u.deg, lon=-70*u.deg)
t = Time('2023-01-01T00:00:00')

Local sidereal time

地方恒星时

lst = t.sidereal_time('apparent', longitude=location.lon)
lst = t.sidereal_time('apparent', longitude=location.lon)

Barycentric correction

质心修正

target = SkyCoord(ra=10u.deg, dec=40u.deg) ltt = t.light_travel_time(target, location=location) t_bary = t.tdb + ltt

**Available time scales**:
- `utc` - Coordinated Universal Time
- `tai` - International Atomic Time
- `tt` - Terrestrial Time
- `tcb`, `tcg` - Barycentric/Geocentric Coordinate Time
- `tdb` - Barycentric Dynamical Time
- `ut1` - Universal Time
target = SkyCoord(ra=10u.deg, dec=40u.deg) ltt = t.light_travel_time(target, location=location) t_bary = t.tdb + ltt

**可用时间尺度**:
- `utc` - 协调世界时
- `tai` - 国际原子时
- `tt` - 地球时
- `tcb`, `tcg` - 质心/地心坐标时
- `tdb` - 质心力学时
- `ut1` - 世界时

5. Data Tables

5. 数据表

Astropy tables provide astronomy-specific enhancements over pandas.
Creating and manipulating tables:
python
from astropy.table import Table
import astropy.units as u
Astropy数据表相比pandas提供了天文学特有的增强功能。
创建与操作数据表:
python
from astropy.table import Table
import astropy.units as u

Create table

创建表

t = Table() t['name'] = ['Star1', 'Star2', 'Star3'] t['ra'] = [10.5, 11.2, 12.3] * u.degree t['dec'] = [41.2, 42.1, 43.5] * u.degree t['flux'] = [1.2, 2.3, 0.8] * u.Jy
t = Table() t['name'] = ['Star1', 'Star2', 'Star3'] t['ra'] = [10.5, 11.2, 12.3] * u.degree t['dec'] = [41.2, 42.1, 43.5] * u.degree t['flux'] = [1.2, 2.3, 0.8] * u.Jy

Column metadata

列元数据

t['flux'].description = 'Flux at 1.4 GHz' t['flux'].format = '.2f'
t['flux'].description = '1.4 GHz处的流量' t['flux'].format = '.2f'

Add calculated column

添加计算列

t['flux_mJy'] = t['flux'].to(u.mJy)
t['flux_mJy'] = t['flux'].to(u.mJy)

Filter and sort

过滤与排序

bright = t[t['flux'] > 1.0 * u.Jy] t.sort('flux')

**Table I/O**:
```python
from astropy.table import Table
bright = t[t['flux'] > 1.0 * u.Jy] t.sort('flux')

**数据表读写**:
```python
from astropy.table import Table

Read (format auto-detected from extension)

读取(格式从扩展名自动检测)

t = Table.read('data.fits') t = Table.read('data.csv', format='ascii.csv') t = Table.read('data.ecsv', format='ascii.ecsv') # Preserves units! t = Table.read('data.votable', format='votable')
t = Table.read('data.fits') t = Table.read('data.csv', format='ascii.csv') t = Table.read('data.ecsv', format='ascii.ecsv') # 保留单位! t = Table.read('data.votable', format='votable')

Write

写入

t.write('output.fits', overwrite=True) t.write('output.ecsv', format='ascii.ecsv', overwrite=True)

**Advanced operations**:
```python
from astropy.table import Table, join, vstack, hstack
t.write('output.fits', overwrite=True) t.write('output.ecsv', format='ascii.ecsv', overwrite=True)

**高级操作**:
```python
from astropy.table import Table, join, vstack, hstack

Join tables (like SQL)

连接表(类似SQL)

joined = join(table1, table2, keys='id')
joined = join(table1, table2, keys='id')

Stack tables

合并表

combined_rows = vstack([t1, t2]) combined_cols = hstack([t1, t2])
combined_rows = vstack([t1, t2]) combined_cols = hstack([t1, t2])

Grouping and aggregation

分组与聚合

t.group_by('category').groups.aggregate(np.mean)

**Tables with astronomical objects**:
```python
from astropy.table import Table
from astropy.coordinates import SkyCoord
from astropy.time import Time
import astropy.units as u

coords = SkyCoord(ra=[10, 11, 12]*u.deg, dec=[40, 41, 42]*u.deg)
times = Time(['2023-01-01', '2023-01-02', '2023-01-03'])

t = Table([coords, times], names=['coords', 'obstime'])
print(t['coords'][0].ra)  # Access coordinate properties
t.group_by('category').groups.aggregate(np.mean)

**包含天文对象的表**:
```python
from astropy.table import Table
from astropy.coordinates import SkyCoord
from astropy.time import Time
import astropy.units as u

coords = SkyCoord(ra=[10, 11, 12]*u.deg, dec=[40, 41, 42]*u.deg)
times = Time(['2023-01-01', '2023-01-02', '2023-01-03'])

t = Table([coords, times], names=['coords', 'obstime'])
print(t['coords'][0].ra)  # 访问坐标属性

6. Cosmological Calculations

6. 宇宙学计算

Quick cosmology calculations using standard models.
Using the cosmology calculator:
bash
python scripts/cosmo_calc.py 0.5 1.0 1.5
python scripts/cosmo_calc.py --range 0 3 0.5 --cosmology Planck18
python scripts/cosmo_calc.py 0.5 --verbose
python scripts/cosmo_calc.py --convert 1000 --from luminosity_distance
Programmatic usage:
python
from astropy.cosmology import Planck18
import astropy.units as u
import numpy as np

cosmo = Planck18
使用标准模型快速进行宇宙学计算。
使用宇宙学计算器:
bash
python scripts/cosmo_calc.py 0.5 1.0 1.5
python scripts/cosmo_calc.py --range 0 3 0.5 --cosmology Planck18
python scripts/cosmo_calc.py 0.5 --verbose
python scripts/cosmo_calc.py --convert 1000 --from luminosity_distance
编程式使用:
python
from astropy.cosmology import Planck18
import astropy.units as u
import numpy as np

cosmo = Planck18

Calculate distances

计算距离

z = 1.5 d_L = cosmo.luminosity_distance(z) d_A = cosmo.angular_diameter_distance(z) d_C = cosmo.comoving_distance(z)
z = 1.5 d_L = cosmo.luminosity_distance(z) d_A = cosmo.angular_diameter_distance(z) d_C = cosmo.comoving_distance(z)

Time calculations

时间计算

age = cosmo.age(z) lookback = cosmo.lookback_time(z)
age = cosmo.age(z) lookback = cosmo.lookback_time(z)

Hubble parameter

哈勃参数

H_z = cosmo.H(z)
print(f"At z={z}:") print(f" Luminosity distance: {d_L:.2f}") print(f" Age of universe: {age:.2f}")

**Convert observables**:
```python
from astropy.cosmology import Planck18
import astropy.units as u

cosmo = Planck18
z = 1.5
H_z = cosmo.H(z)
print(f"红移z={z}时:") print(f" 光度距离: {d_L:.2f}") print(f" 宇宙年龄: {age:.2f}")

**可观测值转换**:
```python
from astropy.cosmology import Planck18
import astropy.units as u

cosmo = Planck18
z = 1.5

Angular size to physical size

角大小转物理大小

d_A = cosmo.angular_diameter_distance(z) angular_size = 1 * u.arcsec physical_size = (angular_size.to(u.radian) * d_A).to(u.kpc)
d_A = cosmo.angular_diameter_distance(z) angular_size = 1 * u.arcsec physical_size = (angular_size.to(u.radian) * d_A).to(u.kpc)

Flux to luminosity

流量转光度

flux = 1e-17 * u.erg / u.s / u.cm2 d_L = cosmo.luminosity_distance(z) luminosity = flux * 4 * np.pi * d_L2
flux = 1e-17 * u.erg / u.s / u.cm2 d_L = cosmo.luminosity_distance(z) luminosity = flux * 4 * np.pi * d_L2

Find redshift for given distance

根据距离查找红移

from astropy.cosmology import z_at_value z = z_at_value(cosmo.luminosity_distance, 1000*u.Mpc)

**Available cosmologies**:
- `Planck18`, `Planck15`, `Planck13` - Planck satellite parameters
- `WMAP9`, `WMAP7`, `WMAP5` - WMAP satellite parameters
- Custom: `FlatLambdaCDM(H0=70*u.km/u.s/u.Mpc, Om0=0.3)`
from astropy.cosmology import z_at_value z = z_at_value(cosmo.luminosity_distance, 1000*u.Mpc)

**可用宇宙学模型**:
- `Planck18`, `Planck15`, `Planck13` - 普朗克卫星参数
- `WMAP9`, `WMAP7`, `WMAP5` - WMAP卫星参数
- 自定义: `FlatLambdaCDM(H0=70*u.km/u.s/u.Mpc, Om0=0.3)`

7. Model Fitting

7. 模型拟合

Fit mathematical models to astronomical data.
1D fitting example:
python
from astropy.modeling import models, fitting
import numpy as np
为天文数据拟合数学模型。
一维拟合示例:
python
from astropy.modeling import models, fitting
import numpy as np

Generate data

生成数据

x = np.linspace(0, 10, 100) y_data = 10 * np.exp(-0.5 * ((x - 5) / 1)**2) + np.random.normal(0, 0.5, x.shape)
x = np.linspace(0, 10, 100) y_data = 10 * np.exp(-0.5 * ((x - 5) / 1)**2) + np.random.normal(0, 0.5, x.shape)

Create and fit model

创建并拟合模型

g_init = models.Gaussian1D(amplitude=8, mean=4.5, stddev=0.8) fitter = fitting.LevMarLSQFitter() g_fit = fitter(g_init, x, y_data)
g_init = models.Gaussian1D(amplitude=8, mean=4.5, stddev=0.8) fitter = fitting.LevMarLSQFitter() g_fit = fitter(g_init, x, y_data)

Results

结果

print(f"Amplitude: {g_fit.amplitude.value:.3f}") print(f"Mean: {g_fit.mean.value:.3f}") print(f"Stddev: {g_fit.stddev.value:.3f}")
print(f"振幅: {g_fit.amplitude.value:.3f}") print(f"均值: {g_fit.mean.value:.3f}") print(f"标准差: {g_fit.stddev.value:.3f}")

Evaluate fitted model

评估拟合后的模型

y_fit = g_fit(x)

**Common 1D models**:
- `Gaussian1D` - Gaussian profile
- `Lorentz1D` - Lorentzian profile
- `Voigt1D` - Voigt profile
- `Moffat1D` - Moffat profile (PSF modeling)
- `Polynomial1D` - Polynomial
- `PowerLaw1D` - Power law
- `BlackBody` - Blackbody spectrum

**Common 2D models**:
- `Gaussian2D` - 2D Gaussian
- `Moffat2D` - 2D Moffat (stellar PSF)
- `AiryDisk2D` - Airy disk (diffraction pattern)
- `Disk2D` - Circular disk

**Fitting with constraints**:
```python
from astropy.modeling import models, fitting

g = models.Gaussian1D(amplitude=10, mean=5, stddev=1)
y_fit = g_fit(x)

**常见一维模型**:
- `Gaussian1D` - 高斯轮廓
- `Lorentz1D` - 洛伦兹轮廓
- `Voigt1D` - 佛克脱轮廓
- `Moffat1D` - 莫菲特轮廓(PSF建模)
- `Polynomial1D` - 多项式
- `PowerLaw1D` - 幂律
- `BlackBody` - 黑体谱

**常见二维模型**:
- `Gaussian2D` - 二维高斯
- `Moffat2D` - 二维莫菲特(恒星PSF)
- `AiryDisk2D` - 艾里斑(衍射图案)
- `Disk2D` - 圆盘

**带约束的拟合**:
```python
from astropy.modeling import models, fitting

g = models.Gaussian1D(amplitude=10, mean=5, stddev=1)

Set bounds

设置边界

g.amplitude.bounds = (0, None) # Positive only g.mean.bounds = (4, 6) # Constrain center
g.amplitude.bounds = (0, None) # 仅允许正值 g.mean.bounds = (4, 6) # 约束中心位置

Fix parameters

固定参数

g.stddev.fixed = True
g.stddev.fixed = True

Compound models

复合模型

model = models.Gaussian1D() + models.Polynomial1D(degree=1)

**Available fitters**:
- `LinearLSQFitter` - Linear least squares (fast, for linear models)
- `LevMarLSQFitter` - Levenberg-Marquardt (most common)
- `SimplexLSQFitter` - Downhill simplex
- `SLSQPLSQFitter` - Sequential Least Squares with constraints
model = models.Gaussian1D() + models.Polynomial1D(degree=1)

**可用拟合器**:
- `LinearLSQFitter` - 线性最小二乘(快速,适用于线性模型)
- `LevMarLSQFitter` - 列文伯格-马夸尔特法(最常用)
- `SimplexLSQFitter` - 下山单纯形法
- `SLSQPLSQFitter` - 带约束的序列最小二乘法

8. World Coordinate System (WCS)

8. 世界坐标系(WCS)

Transform between pixel and world coordinates in images.
Basic WCS usage:
python
from astropy.io import fits
from astropy.wcs import WCS
在图像的像素坐标与世界坐标之间进行转换。
基础WCS使用:
python
from astropy.io import fits
from astropy.wcs import WCS

Read FITS with WCS

读取带WCS的FITS文件

hdu = fits.open('image.fits')[0] wcs = WCS(hdu.header)
hdu = fits.open('image.fits')[0] wcs = WCS(hdu.header)

Pixel to world

像素转世界坐标

ra, dec = wcs.pixel_to_world_values(100, 200)
ra, dec = wcs.pixel_to_world_values(100, 200)

World to pixel

世界坐标转像素

x, y = wcs.world_to_pixel_values(ra, dec)
x, y = wcs.world_to_pixel_values(ra, dec)

Using SkyCoord (more powerful)

使用SkyCoord(功能更强大)

from astropy.coordinates import SkyCoord import astropy.units as u
coord = SkyCoord(ra=150u.deg, dec=-30u.deg) x, y = wcs.world_to_pixel(coord)

**Plotting with WCS**:
```python
from astropy.io import fits
from astropy.wcs import WCS
from astropy.visualization import ImageNormalize, LogStretch, PercentileInterval
import matplotlib.pyplot as plt

hdu = fits.open('image.fits')[0]
wcs = WCS(hdu.header)
data = hdu.data
from astropy.coordinates import SkyCoord import astropy.units as u
coord = SkyCoord(ra=150u.deg, dec=-30u.deg) x, y = wcs.world_to_pixel(coord)

**结合WCS绘图**:
```python
from astropy.io import fits
from astropy.wcs import WCS
from astropy.visualization import ImageNormalize, LogStretch, PercentileInterval
import matplotlib.pyplot as plt

hdu = fits.open('image.fits')[0]
wcs = WCS(hdu.header)
data = hdu.data

Create figure with WCS projection

创建带WCS投影的图

fig = plt.figure() ax = fig.add_subplot(111, projection=wcs)
fig = plt.figure() ax = fig.add_subplot(111, projection=wcs)

Plot with coordinate grid

绘图并添加坐标网格

norm = ImageNormalize(data, interval=PercentileInterval(99.5), stretch=LogStretch()) ax.imshow(data, norm=norm, origin='lower', cmap='viridis')
norm = ImageNormalize(data, interval=PercentileInterval(99.5), stretch=LogStretch()) ax.imshow(data, norm=norm, origin='lower', cmap='viridis')

Coordinate labels and grid

坐标标签与网格

ax.set_xlabel('RA') ax.set_ylabel('Dec') ax.coords.grid(color='white', alpha=0.5)
undefined
ax.set_xlabel('赤经') ax.set_ylabel('赤纬') ax.coords.grid(color='white', alpha=0.5)
undefined

9. Statistics and Data Processing

9. 统计与数据处理

Robust statistical tools for astronomical data.
Sigma clipping (remove outliers):
python
from astropy.stats import sigma_clip, sigma_clipped_stats
用于天文数据的稳健统计工具。
Sigma裁剪(移除异常值):
python
from astropy.stats import sigma_clip, sigma_clipped_stats

Remove outliers

移除异常值

clipped = sigma_clip(data, sigma=3, maxiters=5)
clipped = sigma_clip(data, sigma=3, maxiters=5)

Get statistics on cleaned data

获取清洗后数据的统计量

mean, median, std = sigma_clipped_stats(data, sigma=3)
mean, median, std = sigma_clipped_stats(data, sigma=3)

Use clipped data

使用裁剪后的数据

background = median signal = data - background snr = signal / std

**Other statistical functions**:
```python
from astropy.stats import mad_std, biweight_location, biweight_scale
background = median signal = data - background snr = signal / std

**其他统计函数**:
```python
from astropy.stats import mad_std, biweight_location, biweight_scale

Robust standard deviation

稳健标准差

std_robust = mad_std(data)
std_robust = mad_std(data)

Robust central location

稳健中心位置

center = biweight_location(data)
center = biweight_location(data)

Robust scale

稳健尺度

scale = biweight_scale(data)
undefined
scale = biweight_scale(data)
undefined

10. Visualization

10. 可视化

Display astronomical images with proper scaling.
Image normalization and stretching:
python
from astropy.visualization import (ImageNormalize, MinMaxInterval,
                                   PercentileInterval, ZScaleInterval,
                                   SqrtStretch, LogStretch, PowerStretch,
                                   AsinhStretch)
import matplotlib.pyplot as plt
以合适的缩放方式显示天文图像。
图像归一化与拉伸:
python
from astropy.visualization import (ImageNormalize, MinMaxInterval,
                                   PercentileInterval, ZScaleInterval,
                                   SqrtStretch, LogStretch, PowerStretch,
                                   AsinhStretch)
import matplotlib.pyplot as plt

Common combination: percentile interval + sqrt stretch

常见组合:百分位区间 + 平方根拉伸

norm = ImageNormalize(data, interval=PercentileInterval(99), stretch=SqrtStretch())
plt.imshow(data, norm=norm, origin='lower', cmap='gray') plt.colorbar()

**Available intervals** (determine min/max):
- `MinMaxInterval()` - Use actual min/max
- `PercentileInterval(percentile)` - Clip to percentile (e.g., 99%)
- `ZScaleInterval()` - IRAF's zscale algorithm
- `ManualInterval(vmin, vmax)` - Specify manually

**Available stretches** (nonlinear scaling):
- `LinearStretch()` - Linear (default)
- `SqrtStretch()` - Square root (common for images)
- `LogStretch()` - Logarithmic (for high dynamic range)
- `PowerStretch(power)` - Power law
- `AsinhStretch()` - Arcsinh (good for wide range)
norm = ImageNormalize(data, interval=PercentileInterval(99), stretch=SqrtStretch())
plt.imshow(data, norm=norm, origin='lower', cmap='gray') plt.colorbar()

**可用区间(确定最小值/最大值)**:
- `MinMaxInterval()` - 使用实际的最小/最大值
- `PercentileInterval(percentile)` - 裁剪到指定百分位(如99%)
- `ZScaleInterval()` - IRAF的zscale算法
- `ManualInterval(vmin, vmax)` - 手动指定

**可用拉伸方式(非线性缩放)**:
- `LinearStretch()` - 线性(默认)
- `SqrtStretch()` - 平方根(图像常用)
- `LogStretch()` - 对数(适用于高动态范围)
- `PowerStretch(power)` - 幂律
- `AsinhStretch()` - 反双曲正弦(适用于宽范围数据)

Bundled Resources

附带资源

scripts/

scripts/

fits_info.py
- Comprehensive FITS file inspection tool
bash
python scripts/fits_info.py observation.fits
python scripts/fits_info.py observation.fits --detailed
python scripts/fits_info.py observation.fits --ext 1
coord_convert.py
- Batch coordinate transformation utility
bash
python scripts/coord_convert.py 10.68 41.27 --from icrs --to galactic
python scripts/coord_convert.py --file coords.txt --from icrs --to galactic
cosmo_calc.py
- Cosmological calculator
bash
python scripts/cosmo_calc.py 0.5 1.0 1.5
python scripts/cosmo_calc.py --range 0 3 0.5 --cosmology Planck18
fits_info.py
- 全面的FITS文件检查工具
bash
python scripts/fits_info.py observation.fits
python scripts/fits_info.py observation.fits --detailed
python scripts/fits_info.py observation.fits --ext 1
coord_convert.py
- 批量坐标转换工具
bash
python scripts/coord_convert.py 10.68 41.27 --from icrs --to galactic
python scripts/coord_convert.py --file coords.txt --from icrs --to galactic
cosmo_calc.py
- 宇宙学计算器
bash
python scripts/cosmo_calc.py 0.5 1.0 1.5
python scripts/cosmo_calc.py --range 0 3 0.5 --cosmology Planck18

references/

references/

module_overview.md
- Comprehensive reference of all astropy subpackages, classes, and methods. Consult this for detailed API information, available functions, and module capabilities.
common_workflows.md
- Complete working examples for common astronomical data analysis tasks. Contains full code examples for FITS operations, coordinate transformations, cosmology, modeling, and complete analysis pipelines.
module_overview.md
- 所有Astropy子包、类与方法的全面参考。如需详细API信息、可用函数与模块功能,请查阅此文档。
common_workflows.md
- 常见天文数据分析任务的完整工作示例。包含FITS操作、坐标转换、宇宙学、建模及完整分析流程的完整代码示例。

Best Practices

最佳实践

  1. Use context managers for FITS files:
    python
    with fits.open('file.fits') as hdul:
        # Work with file
  2. Prefer astropy.table over raw FITS tables for better unit/metadata support
  3. Use SkyCoord for coordinates (high-level interface) rather than low-level frame classes
  4. Always attach units to quantities when possible for dimensional safety
  5. Use ECSV format for saving tables when you want to preserve units and metadata
  6. Vectorize coordinate operations rather than looping for performance
  7. Use memmap=True when opening large FITS files to save memory
  8. Install Bottleneck package for faster statistics operations
  9. Pre-compute composite units for repeated operations to improve performance
  10. Consult
    references/module_overview.md
    for detailed module information and
    references/common_workflows.md
    ** for complete working examples
  1. 使用上下文管理器处理FITS文件:
    python
    with fits.open('file.fits') as hdul:
        # 处理文件
  2. 优先使用astropy.table而非原始FITS表,以获得更好的单位/元数据支持
  3. 使用SkyCoord处理坐标(高层接口)而非底层框架类
  4. 尽可能为量附加单位,以保证量纲安全
  5. 保存表时使用ECSV格式,以便保留单位与元数据
  6. 向量化坐标操作而非循环,以提升性能
  7. 打开大型FITS文件时使用memmap=True,以节省内存
  8. 安装Bottleneck包以加快统计操作速度
  9. 预计算复合单位以提升重复操作的性能
  10. **查阅
    references/module_overview.md
    **获取详细模块信息,查阅
    references/common_workflows.md
    **获取完整工作示例

Common Patterns

常见模式

Pattern: FITS → Process → FITS

模式:FITS → 处理 → FITS

python
from astropy.io import fits
from astropy.stats import sigma_clipped_stats
python
from astropy.io import fits
from astropy.stats import sigma_clipped_stats

Read

读取

with fits.open('input.fits') as hdul: data = hdul[0].data header = hdul[0].header
# Process
mean, median, std = sigma_clipped_stats(data, sigma=3)
processed = (data - median) / std

# Write
fits.writeto('output.fits', processed, header, overwrite=True)
undefined
with fits.open('input.fits') as hdul: data = hdul[0].data header = hdul[0].header
# 处理
mean, median, std = sigma_clipped_stats(data, sigma=3)
processed = (data - median) / std

# 写入
fits.writeto('output.fits', processed, header, overwrite=True)
undefined

Pattern: Catalog Matching

模式:星表匹配

python
from astropy.coordinates import SkyCoord
from astropy.table import Table
import astropy.units as u
python
from astropy.coordinates import SkyCoord
from astropy.table import Table
import astropy.units as u

Load 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'], dec=cat1['DEC'], unit=u.degree) coords2 = SkyCoord(ra=cat2['RA'], dec=cat2['DEC'], unit=u.degree)
coords1 = SkyCoord(ra=cat1['RA'], dec=cat1['DEC'], unit=u.degree) coords2 = SkyCoord(ra=cat2['RA'], dec=cat2['DEC'], unit=u.degree)

Match

匹配

idx, sep2d, dist3d = coords1.match_to_catalog_sky(coords2)
idx, sep2d, dist3d = coords1.match_to_catalog_sky(coords2)

Filter by separation

按角距离过滤

max_sep = 1 * u.arcsec matched_mask = sep2d < max_sep
max_sep = 1 * u.arcsec matched_mask = sep2d < max_sep

Create matched catalog

创建匹配后的星表

matched_cat1 = cat1[matched_mask] matched_cat2 = cat2[idx[matched_mask]]
undefined
matched_cat1 = cat1[matched_mask] matched_cat2 = cat2[idx[matched_mask]]
undefined

Pattern: Time Series Analysis

模式:时间序列分析

python
from astropy.time import Time
from astropy.timeseries import TimeSeries
import astropy.units as u
python
from astropy.time import Time
from astropy.timeseries import TimeSeries
import astropy.units as u

Create time series

创建时间序列

times = Time(['2023-01-01', '2023-01-02', '2023-01-03']) flux = [1.2, 2.3, 1.8] * u.Jy
ts = TimeSeries(time=times) ts['flux'] = flux
times = Time(['2023-01-01', '2023-01-02', '2023-01-03']) flux = [1.2, 2.3, 1.8] * u.Jy
ts = TimeSeries(time=times) ts['flux'] = flux

Fold on period

按周期折叠

from astropy.timeseries import aggregate_downsample period = 1.5 * u.day folded = ts.fold(period=period)
undefined
from astropy.timeseries import aggregate_downsample period = 1.5 * u.day folded = ts.fold(period=period)
undefined

Pattern: Image Display with WCS

模式:结合WCS的图像显示

python
from astropy.io import fits
from astropy.wcs import WCS
from astropy.visualization import ImageNormalize, SqrtStretch, PercentileInterval
import matplotlib.pyplot as plt

hdu = fits.open('image.fits')[0]
wcs = WCS(hdu.header)
data = hdu.data

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection=wcs)

norm = ImageNormalize(data, interval=PercentileInterval(99),
                     stretch=SqrtStretch())
im = ax.imshow(data, norm=norm, origin='lower', cmap='viridis')

ax.set_xlabel('RA')
ax.set_ylabel('Dec')
ax.coords.grid(color='white', alpha=0.5, linestyle='solid')
plt.colorbar(im, ax=ax)
python
from astropy.io import fits
from astropy.wcs import WCS
from astropy.visualization import ImageNormalize, SqrtStretch, PercentileInterval
import matplotlib.pyplot as plt

hdu = fits.open('image.fits')[0]
wcs = WCS(hdu.header)
data = hdu.data

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection=wcs)

norm = ImageNormalize(data, interval=PercentileInterval(99),
                     stretch=SqrtStretch())
im = ax.imshow(data, norm=norm, origin='lower', cmap='viridis')

ax.set_xlabel('赤经')
ax.set_ylabel('赤纬')
ax.coords.grid(color='white', alpha=0.5, linestyle='solid')
plt.colorbar(im, ax=ax)

Installation Note

安装说明

Ensure astropy is installed in the Python environment:
bash
pip install astropy
For additional performance and features:
bash
pip install astropy[all]  # Includes optional dependencies
确保Python环境中已安装Astropy:
bash
pip install astropy
如需额外性能与功能:
bash
pip install astropy[all]  # 包含可选依赖

Additional Resources

额外资源