Astropy Dynamic
Production-ready skill that handles comprehensive, python, library, astronomy. Includes structured workflows, validation checks, and reusable patterns for scientific.
Astropy Dynamic
A scientific computing skill for astronomical research using Astropy — the core Python package providing coordinate transformations, unit conversions, FITS file handling, time systems, cosmological calculations, and table operations for astronomy.
When to Use This Skill
Choose Astropy Dynamic when:
- Performing coordinate transformations between astronomical systems (ICRS, Galactic, AltAz)
- Working with FITS files (reading, writing, header manipulation)
- Converting between time systems (UTC, TAI, TDB, Julian dates)
- Doing unit conversions and cosmological calculations
Consider alternatives when:
- You need image processing (use photutils or SExtractor)
- You need spectral analysis (use specutils)
- You're building observation planning tools (use astroplan)
- You need gravitational wave data analysis (use GWpy)
Quick Start
claude "Convert equatorial coordinates to galactic and calculate angular separation"
from astropy.coordinates import SkyCoord import astropy.units as u # Create a sky coordinate (Andromeda Galaxy) andromeda = SkyCoord(ra=10.6847*u.deg, dec=41.2687*u.deg, frame='icrs') # Convert to galactic coordinates galactic = andromeda.galactic print(f"Galactic: l={galactic.l:.4f}, b={galactic.b:.4f}") # Calculate angular separation orion_nebula = SkyCoord(ra=83.8221*u.deg, dec=-5.3911*u.deg, frame='icrs') sep = andromeda.separation(orion_nebula) print(f"Separation: {sep.deg:.2f} degrees") # Convert to AltAz for observation planning from astropy.coordinates import EarthLocation, AltAz from astropy.time import Time location = EarthLocation(lat=34.05*u.deg, lon=-118.25*u.deg, height=100*u.m) time = Time("2025-01-15 22:00:00", scale='utc') altaz = andromeda.transform_to(AltAz(obstime=time, location=location)) print(f"Altitude: {altaz.alt:.2f}, Azimuth: {altaz.az:.2f}")
Core Concepts
Astropy Subpackages
| Package | Purpose | Key Classes |
|---|---|---|
astropy.coordinates | Sky coordinate systems | SkyCoord, EarthLocation |
astropy.units | Physical unit handling | u.meter, u.solMass |
astropy.io.fits | FITS file I/O | fits.open(), HDUList |
astropy.time | Time systems | Time, TimeDelta |
astropy.cosmology | Cosmological models | Planck18, FlatLambdaCDM |
astropy.table | Tabular data | Table, QTable |
astropy.wcs | World Coordinate System | WCS |
astropy.constants | Physical constants | c, G, M_sun |
FITS File Operations
from astropy.io import fits import numpy as np # Read FITS file hdul = fits.open("image.fits") header = hdul[0].header data = hdul[0].data print(f"Image shape: {data.shape}") print(f"Telescope: {header.get('TELESCOP', 'Unknown')}") print(f"Exposure: {header.get('EXPTIME', 'Unknown')} seconds") # Modify header header['OBSERVER'] = 'Your Name' header.add_history('Processed with Astropy') # Write modified FITS hdul.writeto("processed.fits", overwrite=True) hdul.close() # Create FITS from scratch new_data = np.zeros((512, 512), dtype=np.float32) hdu = fits.PrimaryHDU(new_data) hdu.header['OBJECT'] = 'NGC 1234' hdu.writeto("new_image.fits")
Cosmological Calculations
from astropy.cosmology import Planck18 as cosmo # Distance calculations z = 1.0 # Redshift d_L = cosmo.luminosity_distance(z) d_A = cosmo.angular_diameter_distance(z) d_C = cosmo.comoving_distance(z) print(f"Luminosity distance: {d_L:.1f}") print(f"Angular diameter distance: {d_A:.1f}") print(f"Comoving distance: {d_C:.1f}") print(f"Age at z={z}: {cosmo.age(z):.2f}") print(f"Lookback time: {cosmo.lookback_time(z):.2f}")
Configuration
| Parameter | Description | Default |
|---|---|---|
coordinate_frame | Default reference frame | icrs |
cosmology_model | Cosmological parameters | Planck18 |
time_scale | Default time scale | utc |
fits_memmap | Memory-map large FITS files | True |
unit_equivalencies | Custom unit conversions | None |
Best Practices
-
Always attach units to quantities. Use
value * u.unitfor all physical values. Astropy's unit system catches dimensional errors at runtime —5*u.meter + 3*u.secondraises an error, preventing subtle bugs in calculations. -
Use
SkyCoordinstead of raw angles. Even for simple coordinate operations,SkyCoordhandles frame transformations, proper motion corrections, and epoch conversions correctly. Raw angle arithmetic can introduce errors at the poles or across the RA=0 boundary. -
Memory-map large FITS files. For FITS files larger than available RAM, use
fits.open("large.fits", memmap=True)to access data without loading the entire file. Access only the slices you need for analysis. -
Use
QTablefor tables with units. When your table columns have physical units, useQTableinstead ofTable. This preserves unit metadata through operations and enables unit-aware arithmetic on table columns. -
Specify time scales explicitly. Astronomical time scales (UTC, TAI, TDB) differ by seconds. Always specify the scale when creating
Timeobjects:Time("2025-01-01", scale="utc"). The default is UTC, but being explicit prevents errors when converting between scales.
Common Issues
Coordinate transformation gives unexpected results. Check that you're using the correct coordinate frame and epoch. Proper motion and parallax can shift coordinates significantly between epochs. If comparing positions from different catalogs, transform to a common epoch first.
FITS header KeyError for expected keywords. FITS standards are loosely enforced — different telescopes use different keyword names. Use header.get('KEYWORD', default_value) instead of header['KEYWORD'] to handle missing keywords gracefully. Check the FITS standard documentation for your instrument.
Unit conversion fails with "not convertible" error. Some unit conversions require equivalencies — for example, converting between frequency and wavelength needs spectral equivalencies: wavelength.to(u.Hz, equivalencies=u.spectral()). Check Astropy's equivalency documentation for the appropriate context.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.