Communitygithub.com

astropy

天文學與天體物理學工作流程所需的核心 Python 函式庫,提供 Astropy API,包括單位/量、座標、FITS 輸入輸出、表格、時間系統、WCS 和宇宙學。當使用 Astropy 實作或除錯天文資料分析程式碼時使用。

astropy 是什麼?

Astropy 是天文學的核心 Python 套件,為天文研究和資料分析提供基本功能。此技能涵蓋 Astropy 的主要子套件,包括 `astropy.units`(單位和量)、`astropy.coordinates`(座標系統轉換)、`astropy.io.fits`(FITS 檔案處理)、`astropy.table`(表格操作)、`astropy.time`(時間處理)、`astropy.wcs`(世界座標系統)和 `astropy.cosmology`(宇宙學計算)。開發人員可以利用此技能來轉換天體座標、處理具有單位的物理量、讀取和寫入 FITS 檔案、執行宇宙學計算(如光度距離和回溯時間)、管理表格資料以及轉換像素和世界座標。它還支援跨比對目錄、處理時間尺度和格式,以及使用內建的宇宙學模型(如 Planck18)。此技能與各種 AI 代理平台(如 Claude Code、Cursor、Codex)相容,並提供詳細的參考文件以取得深入的子模組資訊。其目標是簡化天文資料分析任務,確保單位一致性,並透過 Astropy 的標準 API 促進可重現的天體物理研究工作流程。

相容平台~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、Galactic、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、Galactic、FK5、AltAz 等)中建立座標
  • 在座標系統之間進行轉換
  • 計算角度間隔和方位角
  • 將座標與目錄匹配
  • 包含距離以進行 3D 座標操作
  • 處理自行和徑向速度
  • 從線上資料庫查詢命名天體

請參閱: references/coordinates.md 取得詳細的座標框架描述、轉換、依觀測者框架 (AltAz)、目錄匹配和效能提示。

3. 宇宙學計算 (astropy.cosmology)

使用標準宇宙學模型執行宇宙學計算。

關鍵操作:

  • 使用內建宇宙學模型(Planck18、WMAP9 等)
  • 建立自訂宇宙學模型
  • 計算距離(光度、共動、角直徑)
  • 計算年齡和回溯時間
  • 確定任何紅移下的哈伯參數
  • 計算密度參數和體積
  • 執行反向計算(針對給定距離找出 z)

請參閱: references/cosmology.md 取得可用模型、距離計算、時間計算、密度參數和微中子效應。

4. FITS 檔案處理 (astropy.io.fits)

讀取、寫入和操作 FITS(彈性影像傳輸系統)檔案。

關鍵操作:

  • 使用 context manager 開啟 FITS 檔案
  • 按索引或名稱存取 HDU(標頭資料單元)
  • 讀取和修改標頭(關鍵字、註解、歷史)
  • 處理影像資料(NumPy 陣列)
  • 處理表格資料(二進位和 ASCII 表格)
  • 建立新的 FITS 檔案(單一或多擴展)
  • 對大型檔案使用記憶體映射
  • 存取遠端 FITS 檔案(S3、HTTP)

請參閱: references/fits.md 取得全面的檔案操作、標頭操作、影像和表格處理、多擴展檔案和效能考量。

5. 表格操作 (astropy.table)

處理支援單位、中繼資料和多種檔案格式的表格資料。

關鍵操作:

  • 從陣列、列表或字典建立表格
  • 以多種格式讀取/寫入表格(FITS、CSV、HDF5、VOTable)
  • 存取和修改欄位和列
  • 排序、過濾和索引表格
  • 執行類似資料庫的操作(合併、分組、聚合)
  • 堆疊和串聯表格
  • 處理具有單位感知的欄位 (QTable)
  • 使用遮罩處理缺失資料

請參閱: references/tables.md 取得表格建立、輸入輸出操作、資料操作、排序、過濾、合併、分組和效能提示。

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}, 中位數: {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 檔案使用 context manager:確保正確關閉檔案
  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 - 表格建立、輸入輸出和操作
  • 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.

相關技能