A

Astropy Dynamic

Production-ready skill that handles comprehensive, python, library, astronomy. Includes structured workflows, validation checks, and reusable patterns for scientific.

SkillClipticsscientificv1.0.0MIT
0 views0 copies

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

PackagePurposeKey Classes
astropy.coordinatesSky coordinate systemsSkyCoord, EarthLocation
astropy.unitsPhysical unit handlingu.meter, u.solMass
astropy.io.fitsFITS file I/Ofits.open(), HDUList
astropy.timeTime systemsTime, TimeDelta
astropy.cosmologyCosmological modelsPlanck18, FlatLambdaCDM
astropy.tableTabular dataTable, QTable
astropy.wcsWorld Coordinate SystemWCS
astropy.constantsPhysical constantsc, 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

ParameterDescriptionDefault
coordinate_frameDefault reference frameicrs
cosmology_modelCosmological parametersPlanck18
time_scaleDefault time scaleutc
fits_memmapMemory-map large FITS filesTrue
unit_equivalenciesCustom unit conversionsNone

Best Practices

  1. Always attach units to quantities. Use value * u.unit for all physical values. Astropy's unit system catches dimensional errors at runtime — 5*u.meter + 3*u.second raises an error, preventing subtle bugs in calculations.

  2. Use SkyCoord instead of raw angles. Even for simple coordinate operations, SkyCoord handles frame transformations, proper motion corrections, and epoch conversions correctly. Raw angle arithmetic can introduce errors at the poles or across the RA=0 boundary.

  3. 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.

  4. Use QTable for tables with units. When your table columns have physical units, use QTable instead of Table. This preserves unit metadata through operations and enables unit-aware arithmetic on table columns.

  5. Specify time scales explicitly. Astronomical time scales (UTC, TAI, TDB) differ by seconds. Always specify the scale when creating Time objects: 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.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates