# Astropy > Librería Python central para astronomía y astrofísica: unidades/cantidades, coordenadas, E/S de FITS, tablas, sistemas de tiempo, WCS y cosmología, para implementar o depurar código con Astropy. Fuente: https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/astropy Markdown: https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/astropy.md Repositorio: https://github.com/K-Dense-AI/scientific-agent-skills Autor: K-Dense-AI Licencia: BSD-3-Clause license Actualizado: el mes pasado Coste de contexto: 65 tok instalada, 3.6k tok al activarse, 17.5k tok con todos los archivos del bundle Bundle: 8 archivos, 68 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent claude-code # Cursor npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent cursor # Codex npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent codex # Gemini CLI npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent gemini # Windsurf npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent windsurf # Cline npx -y skills add K-Dense-AI/scientific-agent-skills --skill astropy --agent cline ``` ## Qué hace - Convierte y opera con cantidades físicas y unidades, con equivalencias específicas del dominio (espectral, doppler, paralaje) - Transforma coordenadas celestes entre sistemas (ICRS, Galactic, FK5, AltAz) y calcula separaciones angulares - Lee, escribe y manipula archivos FITS (imágenes y tablas), incluido acceso remoto y mapeo en memoria - Realiza cálculos cosmológicos (distancia de luminosidad, tiempo de retroceso, parámetro de Hubble) con modelos como Planck18 - Maneja tiempo astronómico de precisión (UTC, TAI, TT, TDB) y transformaciones WCS entre píxeles y coordenadas del mundo ## Cuándo usarla - Convertir entre sistemas de coordenadas celestes o entre unidades físicas - Leer, escribir o manipular archivos FITS (imágenes o tablas) - Hacer cálculos cosmológicos (distancias, edad del universo, tiempo de retroceso) - Trabajar con tiempo astronómico de precisión o transformaciones WCS ## Qué la activa - "Convierte estas coordenadas de ICRS a galácticas con astropy" - "Lee este archivo FITS y muestra su cabecera" - "Calcula la distancia de luminosidad a z=1.5 con Planck18" - "Haz el cross-match de estos dos catálogos por coordenadas" ## Antes de instalar - Requiere Python 3.11+ con astropy instalado (uv); resolución de nombres, sitios, lectura remota de FITS y actualizaciones IERS necesitan acceso a red. ## Archivos - SKILL.md — 14 KB - references/coordinates.md — 8 KB - references/cosmology.md — 7 KB - references/fits.md — 9 KB - references/tables.md — 9 KB - references/time.md — 9 KB - references/units.md — 4 KB - references/wcs_and_other_modules.md — 9 KB ## SKILL.md Reproducido tal cual desde K-Dense-AI/scientific-agent-skills bajo BSD-3-Clause license. Esta sección es el documento original y está en inglés. # Astropy ## Overview Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis. Use astropy for coordinate transformations, unit and quantity calculations, FITS file operations, cosmological calculations, precise time handling, tabular data manipulation, and astronomical image processing. ## When to Use This Skill Use astropy when tasks involve: - Converting between celestial coordinate systems (ICRS, Galactic, FK5, AltAz, etc.) - Working with physical units and quantities (converting Jy to mJy, parsecs to km, etc.) - Reading, writing, or manipulating FITS files (images or tables) - Cosmological calculations (luminosity distance, lookback time, Hubble parameter) - Precise time handling with different time scales (UTC, TAI, TT, TDB) and formats (JD, MJD, ISO) - Table operations (reading catalogs, cross-matching, filtering, joining) - WCS transformations between pixel and world coordinates - Astronomical constants and calculations ## Quick Start ```python 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 # Units and quantities distance = 100 * u.pc distance_km = distance.to(u.km) # Coordinates coord = SkyCoord(ra=10.5*u.degree, dec=41.2*u.degree, frame='icrs') coord_galactic = coord.galactic # Time t = Time('2023-01-15 12:30:00') jd = t.jd # Julian Date # FITS files data = fits.getdata('image.fits') header = fits.getheader('image.fits') # Tables table = Table.read('catalog.fits') # Cosmology d_L = Planck18.luminosity_distance(z=1.0) ``` ## Core Capabilities ### 1. Units and Quantities (`astropy.units`) Handle physical quantities with units, perform unit conversions, and ensure dimensional consistency in calculations. **Key operations:** - Create quantities by multiplying values with units - Convert between units using `.to()` method - Perform arithmetic with automatic unit handling - Use equivalencies for domain-specific conversions (spectral, doppler, parallax) - Work with logarithmic units (magnitudes, decibels) **See:** `references/units.md` for comprehensive documentation, unit systems, equivalencies, performance optimization, and unit arithmetic. ### 2. Coordinate Systems (`astropy.coordinates`) Represent celestial positions and transform between different coordinate frames. **Key operations:** - Create coordinates with `SkyCoord` in any frame (ICRS, Galactic, FK5, AltAz, etc.) - Transform between coordinate systems - Calculate angular separations and position angles - Match coordinates to catalogs - Include distance for 3D coordinate operations - Handle proper motions and radial velocities - Query named objects from online databases **See:** `references/coordinates.md` for detailed coordinate frame descriptions, transformations, observer-dependent frames (AltAz), catalog matching, and performance tips. ### 3. Cosmological Calculations (`astropy.cosmology`) Perform cosmological calculations using standard cosmological models. **Key operations:** - Use built-in cosmologies (Planck18, WMAP9, etc.) - Create custom cosmological models - Calculate distances (luminosity, comoving, angular diameter) - Compute ages and lookback times - Determine Hubble parameter at any redshift - Calculate density parameters and volumes - Perform inverse calculations (find z for given distance) **See:** `references/cosmology.md` for available models, distance calculations, time calculations, density parameters, and neutrino effects. ### 4. FITS File Handling (`astropy.io.fits`) Read, write, and manipulate FITS (Flexible Image Transport System) files. **Key operations:** - Open FITS files with context managers - Access HDUs (Header Data Units) by index or name - Read and modify headers (keywords, comments, history) - Work with image data (NumPy arrays) - Handle table data (binary and ASCII tables) - Create new FITS files (single or multi-extension) - Use memory mapping for large files - Access remote FITS files (S3, HTTP) **See:** `references/fits.md` for comprehensive file operations, header manipulation, image and table handling, multi-extension files, and performance considerations. ### 5. Table Operations (`astropy.table`) Work with tabular data with support for units, metadata, and various file formats. **Key operations:** - Create tables from arrays, lists, or dictionaries - Read/write tables in multiple formats (FITS, CSV, HDF5, VOTable) - Access and modify columns and rows - Sort, filter, and index tables - Perform database-style operations (join, group, aggregate) - Stack and concatenate tables - Work with unit-aware columns (QTable) - Handle missing data with masking **See:** `references/tables.md` for table creation, I/O operations, data manipulation, sorting, filtering, joins, grouping, and performance tips. ### 6. Time Handling (`astropy.time`) Precise time representation and conversion between time scales and formats. **Key operations:** - Create Time objects in various formats (ISO, JD, MJD, Unix, etc.) - Convert between time scales (UTC, TAI, TT, TDB, etc.) - Perform time arithmetic with TimeDelta - Calculate sidereal time for observers - Compute light travel time corrections (barycentric, heliocentric) - Work with time arrays efficiently - Handle masked (missing) times **See:** `references/time.md` for time formats, time scales, conversions, arithmetic, observing features, and precision handling. ### 7. World Coordinate System (`astropy.wcs`) Transform between pixel coordinates in images and world coordinates. **Key operations:** - Read WCS from FITS headers - Convert pixel coordinates to world coordinates (and vice versa) - Calculate image footprints - Access WCS parameters (reference pixel, projection, scale) - Create custom WCS objects **See:** `references/wcs_and_other_modules.md` for WCS operations and transformations. ## Additional Capabilities The `references/wcs_and_other_modules.md` file also covers: ### NDData and CCDData Containers for n-dimensional datasets with metadata, uncertainty, masking, and WCS information. ### Modeling Framework for creating and fitting mathematical models to astronomical data. ### Visualization Tools for astronomical image display with appropriate stretching and scaling. ### Constants Physical and astronomical constants with proper units (speed of light, solar mass, Planck constant, etc.). ### Convolution Image processing kernels for smoothing and filtering. ### Statistics Robust statistical functions including sigma clipping and outlier rejection. ## Installation ```bash # Reproducible install against the current stable release uv pip install "astropy==7.2.0" # Recommended optional dependencies for plotting and common workflows uv pip install "astropy[recommended]==7.2.0" # Full optional dependency set for broad astronomy workflows uv pip install "astropy[all]==7.2.0" ``` Astropy 7.2.0 requires Python 3.11+ and depends on NumPy, PyERFA, PyYAML, and packaging. Use an isolated virtual environment; do not install Astropy with elevated privileges. Note that the `[recommended]` and `[all]` extras pull in transitive dependencies (matplotlib, scipy, etc.) at unpinned versions. For reproducible production environments, pin the full dependency tree with a lockfile (`uv lock` in a project, or `uv pip compile` for requirements files) and review the resolved versions before deploying. ## Common Workflows ### Converting Coordinates Between Systems ```python from astropy.coordinates import SkyCoord import astropy.units as u # Create coordinate c = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs') # Transform to galactic c_gal = c.galactic print(f"l={c_gal.l.deg}, b={c_gal.b.deg}") # Transform to alt-az (requires time and location) 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}") ``` ### Reading and Analyzing FITS Files ```python from astropy.io import fits import numpy as np # Open FITS file with fits.open('observation.fits') as hdul: # Display structure hdul.info() # Get image data and header data = hdul[1].data header = hdul[1].header # Access header values exptime = header['EXPTIME'] filter_name = header['FILTER'] # Analyze data mean = np.mean(data) median = np.median(data) print(f"Mean: {mean}, Median: {median}") ``` ### Cosmological Distance Calculations ```python from astropy.cosmology import Planck18 import astropy.units as u import numpy as np # Calculate distances at z=1.5 z = 1.5 d_L = Planck18.luminosity_distance(z) d_A = Planck18.angular_diameter_distance(z) print(f"Luminosity distance: {d_L}") print(f"Angular diameter distance: {d_A}") # Age of universe at that redshift age = Planck18.age(z) print(f"Age at z={z}: {age.to(u.Gyr)}") # Lookback time t_lookback = Planck18.lookback_time(z) print(f"Lookback time: {t_lookback.to(u.Gyr)}") ``` ### Cross-Matching Catalogs ```python from astropy.table import Table from astropy.coordinates import SkyCoord, match_coordinates_sky import astropy.units as u # Read catalogs cat1 = Table.read('catalog1.fits') cat2 = Table.read('catalog2.fits') # Create coordinate objects coords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree) coords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree) # Find matches idx, sep, _ = coords1.match_to_catalog_sky(coords2) # Filter by separation threshold max_sep = 1 * u.arcsec matches = sep < max_sep # Create matched catalogs cat1_matched = cat1[matches] cat2_matched = cat2[idx[matches]] print(f"Found {len(cat1_matched)} matches") ``` ## Best Practices 1. **Always use units**: Attach units to quantities to avoid errors and ensure dimensional consistency 2. **Use context managers for FITS files**: Ensures proper file closing 3. **Prefer arrays over loops**: Process multiple coordinates/times as arrays for better performance 4. **Check coordinate frames**: Verify the frame before transformations 5. **Use appropriate cosmology**: Choose the right cosmological model for your analysis 6. **Handle missing data**: Use masked columns for tables with missing values 7. **Specify time scales**: Be explicit about time scales (UTC, TT, TDB) for precise timing 8. **Use QTable for unit-aware tables**: When table columns have units 9. **Check WCS validity**: Verify WCS before using transformations 10. **Cache frequently used values**: Expensive calculations (e.g., cosmological distances) can be cached 11. **Be explicit about network access**: `SkyCoord.from_name()`, `EarthLocation.of_site(refresh_cache=True)`, `EarthLocation.of_address()`, `download_file()`, remote FITS reads, and some IERS time/coordinate transforms can contact external services or update local caches. Avoid sending sensitive target names, addresses, URLs, or proprietary file locations to third-party services. When working with potentially sensitive targets or data locations, confirm with the user before making these network calls. 12. **Pin for reproducibility**: Use pinned versions such as `astropy==7.2.0` for shared environments; update pins intentionally after reviewing release notes. ## Current-Version Notes - Current stable release researched: Astropy 7.2.0 (released 2025-11-25; verified current as of 2026-06-10) - Python requirement: 3.11+ - **Astropy 8.0 is at release-candidate stage** (8.0.0rc1, 2026-05-26). Key changes to anticipate: - The deprecated `astropy.cosmology` submodule shims (`astropy.cosmology.flrw`, `.core`, `.funcs`, `.connect`, `.parameter`) are removed — import everything directly from `astropy.cosmology` (e.g., `from astropy.cosmology import FlatLambdaCDM, z_at_value`) - `astropy.constants` defaults change from CODATA 2018 to CODATA 2022; pin a constants version via the `astropyconst` science states if reproducibility matters - NumPy 2.0 becomes the minimum supported version; the 7.2.x LTS branch retains NumPy 1.x support for six months after the 8.0 release - The built-in test runner (`astropy.test()`, `TestRunner`) is formally deprecated — invoke `pytest` directly - Recent 7.x deprecations to avoid in new code: passing a table index identifier as the first `.loc` element (`t.loc["b", 2]`) — use `t.loc.with_index("b")[2]` instead (removal planned for 9.0); `astropy.utils.isiterable()` — use `numpy.iterable()` - Recent 7.0 removals: older deprecated FITS APIs such as `(Bin)Table.update`, `_ExtensionHDU`, `_NonstandardExtHDU`, and the `tile_size` argument for `CompImageHDU`; `CompImageHeader` is deprecated. Avoid those legacy patterns in new examples. - The recommended optional extras are `recommended` for common plotting/scientific dependencies and `all` only when a broad optional feature set is needed. ## Documentation and Resources - Official Astropy Documentation: https://docs.astropy.org/en/stable/ - Tutorials: https://learn.astropy.org/ - GitHub: https://github.com/astropy/astropy ## Reference Files For detailed information on specific modules: - `references/units.md` - Units, quantities, conversions, and equivalencies - `references/coordinates.md` - Coordinate systems, transformations, and catalog matching - `references/cosmology.md` - Cosmological models and calculations - `references/fits.md` - FITS file operations and manipulation - `references/tables.md` - Table creation, I/O, and operations - `references/time.md` - Time formats, scales, and calculations - `references/wcs_and_other_modules.md` - WCS, NDData, modeling, visualization, constants, and utilities ## Dónde encaja - Categoría: [Investigación](https://skillsagentes.com/categorias/investigacion.md) — Investigación estructurada, búsqueda de fuentes y síntesis. - Creador: [K-Dense-AI](https://skillsagentes.com/creators/k-dense-ai.md) — 163 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Citation Management](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/citation-management.md): Gestión integral de citas académicas: busca en OpenAlex, PubMed y Google Scholar, extrae metadatos precisos, valida citas y genera entradas BibTeX correctamente formateadas. - [Scientific Slides](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/scientific-slides.md): Crea decks de diapositivas y presentaciones para charlas de investigación: PowerPoint, presentaciones de conferencia, seminarios, defensas de tesis. Da estructura, plantillas, guía de tiempos y validación visual. - [Literature Review](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/literature-review.md): Realiza revisiones bibliográficas sistemáticas y completas usando varias bases académicas (PubMed, arXiv, bioRxiv, Semantic Scholar). Genera markdown y PDF con citas verificadas en varios estilos (APA, Nature, Vancouver). - [Infographics](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/infographics.md): Crea infografías profesionales con Nano Banana Pro AI y refinamiento iterativo inteligente. Usa Gemini 3.6 Flash para revisar la calidad e integra investigación con Perplexity Sonar. Soporta 10 tipos, 8 estilos y paletas para daltonismo. - [Latex Posters](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/latex-posters.md): Crea pósteres de investigación profesionales en LaTeX con beamerposter, tikzposter o baposter, para conferencias y comunicación científica: layout, colores, columnas múltiples e integración de figuras. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)