Communitygithub.com

Astropy 天文學 Python 套件

Astropy 是天文學研究與資料分析的核心 Python 套件,提供座標轉換、單位與量值計算、FITS 檔案操作、宇宙學計算、精確時間處理、表格資料操作以及天文影像處理等必備功能。

Astropy 天文學 Python 套件 是什麼?

Astropy 技能專為需要在 Python 環境中處理天文資料的開發者與研究人員設計,是天文學領域最核心的第三方套件。此技能涵蓋 astropy 套件的七大核心功能:1)透過 `astropy.units` 進行物理單位與量值轉換;2)使用 `astropy.coordinates` 在 ICRS、銀道、FK5、AltAz 等不同天球座標系統之間轉換;3)以 `astropy.cosmology` 計算光度距離、回溯時間、哈伯參數等宇宙學量;4)利用 `astropy.io.fits` 讀寫與操縱 FITS 影像及表格檔案;5)透過 `astropy.table` 處理具單位感知的表格資料,支援過濾、排序、交叉比對與資料庫風格操作;6)使用 `astropy.time` 在 UTC、TAI、TT、TDB 等時間尺度與 JD、MJD、ISO 格式之間進行精確轉換;7)利用 `astropy.wcs` 在像素座標與世界座標系統之間轉換。技能支援 Python 3.8+ 環境,可透過 `uv` 或 `pip` 安裝。建議使用者善用單位系統避免維度錯誤、使用環境管理器處理 FITS 檔案,並優先採用陣列操作提升效能。此技能亦提供多份詳細參考文件(位於 `references/` 目錄),涵蓋單位、座標、宇宙學、FITS、表格、時間與 WCS 等模組的進階用法與最佳實踐。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/K-Dense-AI/claude-scientific-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 等)
  • 建立自訂宇宙學模型
  • 計算距離(光度、同移、角直徑)
  • 計算年齡與回溯時間
  • 決定任意紅移下的哈伯參數
  • 計算密度參數與體積
  • 執行反算(給定距離求 z)

請參閱: 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 資訊的多維資料集容器。

建模 (Modeling)

用於建立數學模型並擬合天文資料的框架。

視覺化 (Visualization)

以適當的拉伸與縮放顯示天文影像的工具。

常數 (Constants)

附有適當單位的物理與天文常數(光速、太陽質量、普朗克常數等)。

卷積 (Convolution)

用於平滑與濾波的影像處理核心。

統計 (Statistics)

穩健的統計函數,包含 sigma 修剪與離群值排除。

安裝

# 安裝 astropy
uv pip install astropy

# 安裝含完整功能的選用相依套件
uv pip install astropy[all]

常見工作流程

在系統之間轉換座標

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. 快取常用值:耗時的計算(例如宇宙學距離)可以進行快取

文件與資源

參考檔案

如需特定模組的詳細資訊,請參閱:

  • 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、建模、視覺化、常數與公用程式

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能