Communitygithub.com

Astropy

用于天文学和天体物理学工作流的核心Python库,提供Astropy API,包括单位/量值、坐标、FITS I/O、表格、时间系统、WCS和宇宙学。在实现或调试基于Astropy的天文数据分析代码时使用。

Astropy 是什么?

Astropy是天文学领域的核心Python包,为天文研究和数据分析提供基本功能。该技能覆盖了坐标变换、单位与量值计算、FITS文件操作、宇宙学计算、精确时间处理、表格数据操作以及天文图像处理等关键能力。它支持在ICRS、银河系、FK5、AltAz等多个坐标系之间转换,处理物理单位转换,读取和写入FITS文件,计算光度距离和回溯时间,等多种标准时间尺度之间的转换,进行表格数据的交叉匹配和过滤,以及像素坐标与世界坐标之间的WCS变换。该技能适用于Claude Code、Cursor等AI编码助手,通过详细的参考文件(如`references/units.md`、`references/coordinates.md`)提供深入指导,并强调了最佳实践,如始终使用单位、使用上下文管理器处理FITS文件、优先使用数组而非循环、以及注意网络请求的安全性。当前稳定版本为Astropy 7.2.0,要求Python 3.11+,并即将推出Astropy 8.0。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/astropy

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Astropy 是做什么的?

概述

Astropy是天文学领域的核心Python包,为天文研究和数据分析提供基本功能。使用astropy进行坐标变换、单位与量值计算、FITS文件操作、宇宙学计算、精确时间处理、表格数据操作以及天文图像处理。

何时使用该技能

当任务涉及以下内容时,使用astropy:

  • 在天体坐标系(ICRS、银河系、FK5、AltAz等)之间转换
  • 处理物理单位和量值(将Jy转换为mJy,秒差距转换为千米等)
  • 读取、写入或操作FITS文件(图像或表格)
  • 宇宙学计算(光度距离、回溯时间、哈勃参数)
  • 使用不同时间尺度(UTC、TAI、TT、TDB)和格式(JD、MJD、ISO)进行精确时间处理
  • 表格操作(读取星表、交叉匹配、过滤、连接)
  • 像素坐标与世界坐标之间的WCS变换
  • 天文常数和计算

快速开始

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 Planck18

# 单位和量值
distance = 100 * u.pc
distance_km = distance.to(u.km)

# 坐标
coord = SkyCoord(ra=10.5*u.degree, dec=41.2*u.degree, frame='icrs')
coord_galactic = coord.galactic

# 时间
t = Time('2023-01-15 12:30:00')
jd = t.jd  # 儒略日

# FITS文件
data = fits.getdata('image.fits')
header = fits.getheader('image.fits')

# 表格
table = Table.read('catalog.fits')

# 宇宙学
d_L = Planck18.luminosity_distance(z=1.0)

核心能力

1. 单位和量值 (astropy.units)

处理带单位的物理量,执行单位转换,并确保计算中的量纲一致性。

关键操作:

  • 通过将值乘以单位来创建量值
  • 使用.to()方法在不同单位之间转换
  • 使用自动单位处理执行算术运算
  • 使用等效性进行特定领域的转换(光谱、多普勒、视差)
  • 处理对数单位(星等、分贝)

参考: references/units.md 获取全面文档,包括单位系统、等效性、性能优化和单位算术。

2. 坐标系 (astropy.coordinates)

表示天体位置并在不同坐标框架之间转换。

关键操作:

  • 使用SkyCoord在任意框架(ICRS、银河系、FK5、AltAz等)中创建坐标
  • 在坐标系之间转换
  • 计算角分离和位置角
  • 将坐标匹配到星表
  • 包含距离以实现3D坐标操作
  • 处理自行和径向速度
  • 从在线数据库查询命名对象

参考: references/coordinates.md 获取详细的坐标框架描述、变换、观测者相关框架(AltAz)、星表匹配和性能技巧。

3. 宇宙学计算 (astropy.cosmology)

使用标准宇宙学模型执行宇宙学计算。

关键操作:

  • 使用内置宇宙学模型(Planck18、WMAP9等)
  • 创建自定义宇宙学模型
  • 计算距离(光度、共动、角直径)
  • 计算年龄和回溯时间
  • 确定任意红移处的哈勃参数
  • 计算密度参数和体积
  • 执行逆计算(查找给定距离的红移)

参考: references/cosmology.md 获取可用模型、距离计算、时间计算、密度参数和中微子效应。

4. FITS文件处理 (astropy.io.fits)

读取、写入和操作FITS(灵活图像传输系统)文件。

关键操作:

  • 使用上下文管理器打开FITS文件
  • 按索引或名称访问HDU(头数据单元)
  • 读取和修改头信息(关键字、注释、历史记录)
  • 处理图像数据(NumPy数组)
  • 处理表格数据(二进制和ASCII表格)
  • 创建新的FITS文件(单扩展或多扩展)
  • 对大文件使用内存映射
  • 访问远程FITS文件(S3、HTTP)

参考: references/fits.md 获取全面的文件操作、头信息处理、图像和表格处理、多扩展文件以及性能考虑。

5. 表格操作 (astropy.table)

使用支持单位、元数据和多种文件格式的表格数据。

关键操作:

  • 从数组、列表或字典创建表格
  • 以多种格式(FITS、CSV、HDF5、VOTable)读取/写入表格
  • 访问和修改列和行
  • 排序、过滤和索引表格
  • 执行数据库风格操作(连接、分组、聚合)
  • 堆叠和串联表格
  • 处理带单位的列(QTable)
  • 使用掩码处理缺失数据

参考: references/tables.md 获取表格创建、I/O操作、数据操作、排序、过滤、连接、分组和性能技巧。

6. 时间处理 (astropy.time)

精确的时间表示以及时间尺度和格式之间的转换。

关键操作:

  • 以各种格式(ISO、JD、MJD、Unix等)创建Time对象
  • 在不同时间尺度(UTC、TAI、TT、TDB等)之间转换
  • 使用TimeDelta执行时间算术
  • 为观测者计算恒星时
  • 计算光行时修正(质心、日心)
  • 高效处理时间数组
  • 处理掩码(缺失)时间

参考: references/time.md 获取时间格式、时间尺度、转换、算术、观测功能和精度处理。

7. 世界坐标系统 (astropy.wcs)

在图像的像素坐标和世界坐标之间转换。

关键操作:

  • 从FITS头信息读取WCS
  • 将像素坐标转换为世界坐标(反之亦然)
  • 计算图像足迹
  • 访问WCS参数(参考像素、投影、比例)
  • 创建自定义WCS对象

参考: references/wcs_and_other_modules.md 获取WCS操作和转换。

附加能力

references/wcs_and_other_modules.md文件还涵盖:

NDData和CCDData

用于多维数据集的容器,包含元数据、不确定性、掩码和WCS信息。

建模

用于创建和拟合天文数据数学模型的框架。

可视化

用于天文图像显示的工具,具有适当的拉伸和缩放。

常量

带有适当单位的物理和天文常量(光速、太阳质量、普朗克常数等)。

卷积

用于平滑和滤波的图像处理核。

统计

稳健的统计函数,包括sigma裁剪和异常值剔除。

安装

# 针对当前稳定版本的可重现安装
uv pip install "astropy==7.2.0"

# 推荐的可选依赖项,用于绘图和常见工作流
uv pip install "astropy[recommended]==7.2.0"

# 用于广泛天文学工作流的全部可选依赖项
uv pip install "astropy[all]==7.2.0"

Astropy 7.2.0需要Python 3.11+,并依赖于NumPy、PyERFA、PyYAML和packaging。使用隔离的虚拟环境;不要使用提升的权限安装Astropy。

请注意,[recommended]和[all]附加项会拉取传递依赖项(matplotlib、scipy等),版本未固定。对于可重现的生产环境,请使用锁文件(项目中的uv lock,或需求文件的uv pip compile)固定整个依赖树,并在部署前审查已解析的版本。

常见工作流

在系统之间转换坐标

from astropy.coordinates import SkyCoord
import astropy.units as u

# 创建坐标
c = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs')

# 转换到银河系坐标
c_gal = c.galactic
print(f"l={c_gal.l.deg}, b={c_gal.b.deg}")

# 转换到地平坐标(需要时间和位置)
from astropy.time import Time
from 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}")

读取和分析FITS文件

from astropy.io import fits
import numpy as np

# 打开FITS文件
with 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}")

宇宙学距离计算

from astropy.cosmology import Planck18
import astropy.units as u
import numpy as np

# 计算z=1.5处的距离
z = 1.5
d_L = Planck18.luminosity_distance(z)
d_A = Planck18.angular_diameter_distance(z)

print(f"光度距离: {d_L}")
print(f"角直径距离: {d_A}")

# 该红移处的宇宙年龄
age = Planck18.age(z)
print(f"z={z}处的年龄: {age.to(u.Gyr)}")

# 回溯时间
t_lookback = Planck18.lookback_time(z)
print(f"回溯时间: {t_lookback.to(u.Gyr)}")

交叉匹配星表

from astropy.table import Table
from astropy.coordinates import SkyCoord, match_coordinates_sky
import astropy.units as u

# 读取星表
cat1 = Table.read('catalog1.fits')
cat2 = Table.read('catalog2.fits')

# 创建坐标对象
coords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree)
coords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree)

# 查找匹配
idx, sep, _ = coords1.match_to_catalog_sky(coords2)

# 按分离阈值过滤
max_sep = 1 * u.arcsec
matches = sep < max_sep

# 创建匹配后的星表
cat1_matched = cat1[matches]
cat2_matched = cat2[idx[matches]]
print(f"找到 {len(cat1_matched)} 个匹配")

最佳实践

  1. 始终使用单位:为量值附加单位以避免错误并确保量纲一致性
  2. 对FITS文件使用上下文管理器:确保文件正确关闭
  3. 优先使用数组而非循环:将多个坐标/时间作为数组处理以获得更好性能
  4. 检查坐标框架:在转换前确认框架
  5. 使用适当的宇宙学模型:为分析选择正确的宇宙学模型
  6. 处理缺失数据:对含有缺失值的表格使用掩码列
  7. 指定时间尺度:对于精确计时,明确时间尺度(UTC、TT、TDB)
  8. 对单位感知表格使用QTable:当表格列具有单位时
  9. 检查WCS有效性:在使用变换前验证WCS
  10. 缓存频繁使用的值:昂贵的计算(如宇宙学距离)可以缓存
  11. 明确网络访问:SkyCoord.from_name()、EarthLocation.of_site(refresh_cache=True)、EarthLocation.of_address()、download_file()、远程FITS读取以及某些IERS时间/坐标变换可能联系外部服务或更新本地缓存。避免将敏感目标名称、地址、URL或专有文件位置发送给第三方服务。在处理可能敏感的目标或数据位置时,在进行这些网络调用之前请与用户确认。
  12. 为可重现性固定版本:对共享环境使用固定版本,如astropy==7.2.0;在审查发布说明后有意更新固定版本。

当前版本说明

  • 当前稳定版本已研究:Astropy 7.2.0(发布于2025-11-25;截至2026-06-10已验证为当前版本)
  • Python要求:3.11+
  • Astropy 8.0处于候选发布阶段(8.0.0rc1,2026-05-26)。需要预期的关键变更:
    • 已弃用的astropy.cosmology子模块填充(astropy.cosmology.flrw、.core、.funcs、.connect、.parameter)已被移除——直接从astropy.cosmology导入所有内容(例如from astropy.cosmology import FlatLambdaCDM, z_at_value)
    • astropy.constants默认值从CODATA 2018变更为CODATA 2022;如果可重现性重要,请通过astropyconst科学状态固定常数版本
    • NumPy 2.0成为最低支持的版本;7.2.x LTS分支将在8.0发布后保留NumPy 1.x支持六个月
    • 内置测试运行器(astropy.test()、TestRunner)正式弃用——直接调用pytest
  • 在新代码中避免使用的近期7.x弃用功能:将表格索引标识符作为.loc的第一个元素传递(t.loc["b", 2])——改用t.loc.with_index("b")[2](计划在9.0中移除);astropy.utils.isiterable()——改用numpy.iterable()
  • 近期7.0移除:较旧的弃用FITS API,例如(Bin)Table.update、_ExtensionHDU、_NonstandardExtHDU以及CompImageHDU的tile_size参数;CompImageHeader已弃用。在新示例中避免使用这些遗留模式。
  • 推荐的可选附加项是recommended(用于常见绘图/科学依赖)和all(仅当需要广泛的可选功能集时)。

文档和资源

参考文件

关于特定模块的详细信息:

  • references/units.md - 单位、量值、转换和等效性
  • references/coordinates.md - 坐标系、变换和星表匹配
  • references/cosmology.md - 宇宙学模型和计算
  • references/fits.md - FITS文件操作和处理
  • references/tables.md - 表格创建、I/O和操作
  • references/time.md - 时间格式、尺度和计算
  • references/wcs_and_other_modules.md - WCS、NDData、建模、可视化、常量和实用工具

引用科学智能体技能

该技能是Scientific Agent Skills集合的一部分。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

cobrapy

Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.

相关技能