Astropy

zLanqing/codex-claude-academic-skills/scientific-toolkit-skill/references/scientific-skills/astropy

作者 zLanqing7ed6377f0efb6a38951b48ef03b19d996e454b1fBSD-3-Clause license收录于 2026年10月9日更新于 2026年10月9日

Comprehensive Python library for astronomy and astrophysics. This skill should be used when working with astronomical data including celestial coordinates, physical units, FITS files, cosmological calculations, time systems, tables, world coordinate systems (WCS), and astronomical data analysis. Use when tasks involve coordinate transformations, unit conversions, FITS file manipulation, cosmological distance calculations, time scale conversions, or astronomical data processing.

AI 生成的概览

指导使用 Astropy Python 库处理天文数据:坐标、单位、FITS 文件、宇宙学、时间、表格和 WCS。

功能
该技能提供使用 Astropy Python 包进行天文工作的说明和参考文档。内容涵盖天球坐标变换、物理单位与量值换算、FITS 文件读写、宇宙学距离与年龄计算、时间尺度与格式处理、表格操作与星表交叉匹配,以及像素与世界坐标的 WCS 变换。它输出的是指导和代码示例而非文件,且不附带脚本。
适用场景
适用于涉及天文数据处理的任务,例如在坐标框架之间转换、换算单位、操作 FITS 文件、计算宇宙学距离、转换时间尺度或匹配星表。它面向天文学与天体物理分析,而非一般数据处理。
运行要求
需要 Astropy Python 包(可通过 pip 安装,可选安装全部附加依赖)和 Python 运行环境;示例中使用了 NumPy。部分操作需要网络访问,例如从在线数据库查询具名天体,或通过 S3、HTTP 访问远程 FITS 文件。该技能不包含脚本,仅为说明和参考文档。

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.

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

Quick Start

python
import astropy.units as ufrom astropy.coordinates import SkyCoordfrom astropy.time import Timefrom astropy.io import fitsfrom astropy.table import Tablefrom astropy.cosmology import Planck18
# Units and quantitiesdistance = 100 * u.pcdistance_km = distance.to(u.km)
# Coordinatescoord = SkyCoord(ra=10.5*u.degree, dec=41.2*u.degree, frame='icrs')coord_galactic = coord.galactic
# Timet = Time('2023-01-15 12:30:00')jd = t.jd  # Julian Date
# FITS filesdata = fits.getdata('image.fits')header = fits.getheader('image.fits')
# Tablestable = Table.read('catalog.fits')
# Cosmologyd_L = Planck18.luminosity_distance(z=1.0)

Core Capabilities

1. Units and Quantities (astropy.units)

Handle 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 .to() method
  • Perform arithmetic with automatic unit handling
  • Use equivalencies for domain-specific conversions (spectral, doppler, parallax)
  • Work with logarithmic units (magnitudes, decibels)

See: references/units.md for comprehensive documentation, unit systems, equivalencies, performance optimization, and unit arithmetic.

2. Coordinate Systems (astropy.coordinates)

Represent celestial positions and transform between different coordinate frames.

Key operations:

  • Create coordinates with SkyCoord in any frame (ICRS, Galactic, FK5, AltAz, etc.)
  • 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: references/coordinates.md for detailed coordinate frame descriptions, transformations, observer-dependent frames (AltAz), catalog matching, and performance tips.

3. Cosmological Calculations (astropy.cosmology)

Perform 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: references/cosmology.md for available models, distance calculations, time calculations, density parameters, and neutrino effects.

4. FITS File Handling (astropy.io.fits)

Read, 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: references/fits.md for comprehensive file operations, header manipulation, image and table handling, multi-extension files, and performance considerations.

5. Table Operations (astropy.table)

Work 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: references/tables.md for table creation, I/O operations, data manipulation, sorting, filtering, joins, grouping, and performance tips.

6. Time Handling (astropy.time)

Precise 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: references/time.md for time formats, time scales, conversions, arithmetic, observing features, and precision handling.

7. World Coordinate System (astropy.wcs)

Transform 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: references/wcs_and_other_modules.md for WCS operations and transformations.

Additional Capabilities

The references/wcs_and_other_modules.md file also covers:

NDData and CCDData

Containers for n-dimensional datasets with metadata, uncertainty, masking, and WCS information.

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
# Install astropyuv pip install astropy
# With optional dependencies for full functionalityuv pip install astropy[all]

Common Workflows

Converting Coordinates Between Systems

python
from astropy.coordinates import SkyCoordimport astropy.units as u
# Create coordinatec = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs')
# Transform to galacticc_gal = c.galacticprint(f"l={c_gal.l.deg}, b={c_gal.b.deg}")
# Transform to alt-az (requires time and location)from astropy.time import Timefrom astropy.coordinates import EarthLocation, AltAz
observing_time = Time('2023-06-15 23:00:00')observing_location = EarthLocation(lat=40*u.deg, lon=-120*u.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}")

Reading and Analyzing FITS Files

python
from astropy.io import fitsimport numpy as np
# Open FITS filewith 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}")

Cosmological Distance Calculations

python
from astropy.cosmology import Planck18import astropy.units as uimport numpy as np
# Calculate distances at z=1.5z = 1.5d_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 redshiftage = Planck18.age(z)print(f"Age at z={z}: {age.to(u.Gyr)}")
# Lookback timet_lookback = Planck18.lookback_time(z)print(f"Lookback time: {t_lookback.to(u.Gyr)}")

Cross-Matching Catalogs

python
from astropy.table import Tablefrom astropy.coordinates import SkyCoord, match_coordinates_skyimport astropy.units as u
# Read catalogscat1 = Table.read('catalog1.fits')cat2 = Table.read('catalog2.fits')
# Create coordinate objectscoords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree)coords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree)
# Find matchesidx, sep, _ = coords1.match_to_catalog_sky(coords2)
# Filter by separation thresholdmax_sep = 1 * u.arcsecmatches = sep < max_sep
# Create matched catalogscat1_matched = cat1[matches]cat2_matched = cat2[idx[matches]]print(f"Found {len(cat1_matched)} matches")

Best Practices

  1. Always use units: Attach units to quantities to avoid errors and ensure dimensional consistency
  2. Use context managers for FITS files: Ensures proper file closing
  3. Prefer arrays over loops: Process multiple coordinates/times as arrays for better performance
  4. Check coordinate frames: Verify the frame before transformations
  5. Use appropriate cosmology: Choose the right cosmological model for your analysis
  6. Handle missing data: Use masked columns for tables with missing values
  7. Specify time scales: Be explicit about time scales (UTC, TT, TDB) for precise timing
  8. Use QTable for unit-aware tables: When table columns have units
  9. Check WCS validity: Verify WCS before using transformations
  10. Cache frequently used values: Expensive calculations (e.g., cosmological distances) can be cached

Documentation and Resources

Reference Files

For detailed information on specific modules:

  • references/units.md - Units, quantities, conversions, and equivalencies
  • references/coordinates.md - Coordinate systems, transformations, and catalog matching
  • references/cosmology.md - Cosmological models and calculations
  • references/fits.md - FITS file operations and manipulation
  • references/tables.md - Table creation, I/O, and operations
  • references/time.md - Time formats, scales, and calculations
  • references/wcs_and_other_modules.md - WCS, NDData, modeling, visualization, constants, and utilities

来源与署名

来源:zLanqing/codex-claude-academic-skills位于scientific-toolkit-skill/references/scientific-skills/astropy提交7ed6377

许可证: BSD-3-Clause license

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架