Communitygithub.com

astropy

天文学・天体物理学のワークフローでAstropy API(単位/量、座標、FITS入出力、テーブル、時刻系、WCS、宇宙論など)を活用するためのコアPythonライブラリ。Astropyを用いた天文データ解析コードの実装やデバッグ時に使用します。

astropy とは?

Astropyは、天文学研究とデータ解析に不可欠な機能を提供するPython用のコアパッケージです。このスキルは、座標変換、単位と物理量の計算、FITSファイルの操作、宇宙論的計算、精密な時刻処理、表形式データの操作、天文画像処理などのタスクを効率的に行うための包括的なガイドです。ユーザーは、`SkyCoord`による座標系間の変換、`astropy.units`を用いた単位変換と次元の一貫性確保、`astropy.io.fits`によるFITSファイルの読み書きとヘッダー操作、`astropy.cosmology`を用いた光度距離やルックバックタイムの計算などが可能です。また、`astropy.table`でのカタログクロスマッチングやフィルタリング、`astropy.time`による多様な時刻スケール間の変換など、実践的なワークフローを多数サポートしています。このスキルは、Claude CodeやCursor、CodexなどのAIエージェントと組み合わせて使用することを想定しており、開発者が天文データ解析コードを実装・デバッグする際に、ベストプラクティスに従った正確で効率的なコード生成を支援します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

astropy は何をしますか?

概要

Astropyは天文学のためのPythonコアパッケージであり、天文研究とデータ解析に不可欠な機能を提供します。座標変換、単位と物理量の計算、FITSファイル操作、宇宙論的計算、精密な時刻処理、表形式データ操作、天文画像処理などのタスクに使用します。

このスキルを使用するタイミング

以下のようなタスクに astropy を使用します:

  • 天体座標系間の変換(ICRS、銀河座標、FK5、地平座標など)
  • 物理単位と物理量の操作(JyからmJyへの変換、パーセクからkmへの変換など)
  • 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)

天体位置を表現し、異なる座標フレーム間で変換します。

主要な操作:

  • 任意のフレーム(ICRS、銀河座標、FK5、地平座標など)で SkyCoord を使用して座標を作成
  • 座標系間の変換
  • 角度分離と位置角の計算
  • カタログへの座標マッチング
  • 3次元座標操作のための距離の組み込み
  • 固有運動と視線速度の処理
  • オンラインデータベースからの名前付きオブジェクトのクエリ

参照: 詳細な座標フレームの説明、変換、観測者依存フレーム(AltAz)、カタログマッチング、パフォーマンスのヒントについては references/coordinates.md を参照してください。

3. 宇宙論的計算(astropy.cosmology)

標準的な宇宙モデルを使用して宇宙論的計算を実行します。

主要な操作:

  • 組み込み宇宙モデル(Planck18、WMAP9など)の使用
  • カスタム宇宙モデルの作成
  • 距離の計算(光度距離、共動距離、角直径距離)
  • 年齢とルックバックタイムの計算
  • 任意の赤方偏移におけるハッブルパラメータの決定
  • 密度パラメータと体積の計算
  • 逆計算(与えられた距離から赤方偏移zを求める)

参照: 利用可能なモデル、距離計算、時間計算、密度パラメータ、ニュートリノ効果については references/cosmology.md を参照してください。

4. FITSファイルの処理(astropy.io.fits)

FITS(Flexible Image Transport System)ファイルの読み取り、書き込み、操作を行います。

主要な操作:

  • コンテキストマネージャを使用した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オブジェクトの作成

参照: WCS操作と変換については references/wcs_and_other_modules.md を参照してください。

追加機能

references/wcs_and_other_modules.md ファイルでは以下の内容も扱います:

NDDataとCCDData

メタデータ、不確かさ、マスキング、WCS情報を含むn次元データセット用のコンテナ。

モデリング

天文データに数学モデルを作成しフィッティングするためのフレームワーク。

可視化

適切な引き伸ばしとスケーリングを備えた天文画像表示ツール。

定数

適切な単位を持つ物理定数と天文学定数(光速、太陽質量、プランク定数など)。

畳み込み

平滑化とフィルタリングのための画像処理カーネル。

統計

シグマクリッピングや外れ値除去を含むロバストな統計関数。

インストール

# 現在の安定版リリースに対する再現可能なインストール
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ファイルにはコンテキストマネージャを使用する: ファイルが適切に閉じられることを保証する
  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年6月10日時点で最新であることを確認済み)
  • Python要件:3.11以上
  • Astropy 8.0はリリース候補段階(8.0.0rc1、2026年5月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リリース後6ヶ月間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での削除事項:(Bin)Table.update、_ExtensionHDU、_NonstandardExtHDU、および CompImageHDU の tile_size 引数など、古い非推奨のFITS API;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.

関連スキル