{"id":"astropy","name":"astropy","summary":"AstropyのAPIを必要とする天文学および天体物理学のワークフロー向けのコアPythonライブラリで、単位/量、座標、FITES I/O、表、時間システム、WCS、宇宙論などが含まれます。","body":"# Astropy\n\n## Overview\n\nAstropy 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.\n\n## When to Use This Skill\n\nUse astropy when tasks involve:\n- Converting between celestial coordinate systems (ICRS, Galactic, FK5, AltAz, etc.)\n- Working with physical units and quantities (converting Jy to mJy, parsecs to km, etc.)\n- Reading, writing, or manipulating FITS files (images or tables)\n- Cosmological calculations (luminosity distance, lookback time, Hubble parameter)\n- Precise time handling with different time scales (UTC, TAI, TT, TDB) and formats (JD, MJD, ISO)\n- Table operations (reading catalogs, cross-matching, filtering, joining)\n- WCS transformations between pixel and world coordinates\n- Astronomical constants and calculations\n\n## Quick Start\n\n```python\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.time import Time\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.cosmology import Planck18\n\n# Units and quantities\ndistance = 100 * u.pc\ndistance_km = distance.to(u.km)\n\n# Coordinates\ncoord = SkyCoord(ra=10.5*u.degree, dec=41.2*u.degree, frame='icrs')\ncoord_galactic = coord.galactic\n\n# Time\nt = Time('2023-01-15 12:30:00')\njd = t.jd  # Julian Date\n\n# FITS files\ndata = fits.getdata('image.fits')\nheader = fits.getheader('image.fits')\n\n# Tables\ntable = Table.read('catalog.fits')\n\n# Cosmology\nd_L = Planck18.luminosity_distance(z=1.0)\n```\n\n## Core Capabilities\n\n### 1. Units and Quantities (`astropy.units`)\n\nHandle physical quantities with units, perform unit conversions, and ensure dimensional consistency in calculations.\n\n**Key operations:**\n- Create quantities by multiplying values with units\n- Convert between units using `.to()` method\n- Perform arithmetic with automatic unit handling\n- Use equivalencies for domain-specific conversions (spectral, doppler, parallax)\n- Work with logarithmic units (magnitudes, decibels)\n\n**See:** `references/units.md` for comprehensive documentation, unit systems, equivalencies, performance optimization, and unit arithmetic.\n\n### 2. Coordinate Systems (`astropy.coordinates`)\n\nRepresent celestial positions and transform between different coordinate frames.\n\n**Key operations:**\n- Create coordinates with `SkyCoord` in any frame (ICRS, Galactic, FK5, AltAz, etc.)\n- Transform between coordinate systems\n- Calculate angular separations and position angles\n- Match coordinates to catalogs\n- Include distance for 3D coordinate operations\n- Handle proper motions and radial velocities\n- Query named objects from online databases\n\n**See:** `references/coordinates.md` for detailed coordinate frame descriptions, transformations, observer-dependent frames (AltAz), catalog matching, and performance tips.\n\n### 3. Cosmological Calculations (`astropy.cosmology`)\n\nPerform cosmological calculations using standard cosmological models.\n\n**Key operations:**\n- Use built-in cosmologies (Planck18, WMAP9, etc.)\n- Create custom cosmological models\n- Calculate distances (luminosity, comoving, angular diameter)\n- Compute ages and lookback times\n- Determine Hubble parameter at any redshift\n- Calculate density parameters and volumes\n- Perform inverse calculations (find z for given distance)\n\n**See:** `references/cosmology.md` for available models, distance calculations, time calculations, density parameters, and neutrino effects.\n\n### 4. FITS File Handling (`astropy.io.fits`)\n\nRead, write, and manipulate FITS (Flexible Image Transport System) files.\n\n**Key operations:**\n- Open FITS files with context managers\n- Access HDUs (Header Data Units) by index or name\n- Read and modify headers (keywords, comments, history)\n- Work with image data (NumPy arrays)\n- Handle table data (binary and ASCII tables)\n- Create new FITS files (single or multi-extension)\n- Use memory mapping for large files\n- Access remote FITS files (S3, HTTP)\n\n**See:** `references/fits.md` for comprehensive file operations, header manipulation, image and table handling, multi-extension files, and performance considerations.\n\n### 5. Table Operations (`astropy.table`)\n\nWork with tabular data with support for units, metadata, and various file formats.\n\n**Key operations:**\n- Create tables from arrays, lists, or dictionaries\n- Read/write tables in multiple formats (FITS, CSV, HDF5, VOTable)\n- Access and modify columns and rows\n- Sort, filter, and index tables\n- Perform database-style operations (join, group, aggregate)\n- Stack and concatenate tables\n- Work with unit-aware columns (QTable)\n- Handle missing data with masking\n\n**See:** `references/tables.md` for table creation, I/O operations, data manipulation, sorting, filtering, joins, grouping, and performance tips.\n\n### 6. Time Handling (`astropy.time`)\n\nPrecise time representation and conversion between time scales and formats.\n\n**Key operations:**\n- Create Time objects in various formats (ISO, JD, MJD, Unix, etc.)\n- Convert between time scales (UTC, TAI, TT, TDB, etc.)\n- Perform time arithmetic with TimeDelta\n- Calculate sidereal time for observers\n- Compute light travel time corrections (barycentric, heliocentric)\n- Work with time arrays efficiently\n- Handle masked (missing) times\n\n**See:** `references/time.md` for time formats, time scales, conversions, arithmetic, observing features, and precision handling.\n\n### 7. World Coordinate System (`astropy.wcs`)\n\nTransform between pixel coordinates in images and world coordinates.\n\n**Key operations:**\n- Read WCS from FITS headers\n- Convert pixel coordinates to world coordinates (and vice versa)\n- Calculate image footprints\n- Access WCS parameters (reference pixel, projection, scale)\n- Create custom WCS objects\n\n**See:** `references/wcs_and_other_modules.md` for WCS operations and transformations.\n\n## Additional Capabilities\n\nThe `references/wcs_and_other_modules.md` file also covers:\n\n### NDData and CCDData\nContainers for n-dimensional datasets with metadata, uncertainty, masking, and WCS information.\n\n### Modeling\nFramework for creating and fitting mathematical models to astronomical data.\n\n### Visualization\nTools for astronomical image display with appropriate stretching and scaling.\n\n### Constants\nPhysical and astronomical constants with proper units (speed of light, solar mass, Planck constant, etc.).\n\n### Convolution\nImage processing kernels for smoothing and filtering.\n\n### Statistics\nRobust statistical functions including sigma clipping and outlier rejection.\n\n## Installation\n\n```bash\n# Reproducible install against the current stable release\nuv pip install \"astropy==7.2.0\"\n\n# Recommended optional dependencies for plotting and common workflows\nuv pip install \"astropy[recommended]==7.2.0\"\n\n# Full optional dependency set for broad astronomy workflows\nuv pip install \"astropy[all]==7.2.0\"\n```\n\nAstropy 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.\n\nNote 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.\n\n## Common Workflows\n\n### Converting Coordinates Between Systems\n\n```python\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\n\n# Create coordinate\nc = SkyCoord(ra='05h23m34.5s', dec='-69d45m22s', frame='icrs')\n\n# Transform to galactic\nc_gal = c.galactic\nprint(f\"l={c_gal.l.deg}, b={c_gal.b.deg}\")\n\n# Transform to alt-az (requires time and location)\nfrom astropy.time import Time\nfrom astropy.coordinates import EarthLocation, AltAz\n\nobserving_time = Time('2023-06-15 23:00:00')\nobserving_location = EarthLocation(lat=40*u.deg, lon=-120*u.deg)\naa_frame = AltAz(obstime=observing_time, location=observing_location)\nc_altaz = c.transform_to(aa_frame)\nprint(f\"Alt={c_altaz.alt.deg}, Az={c_altaz.az.deg}\")\n```\n\n### Reading and Analyzing FITS Files\n\n```python\nfrom astropy.io import fits\nimport numpy as np\n\n# Open FITS file\nwith fits.open('observation.fits') as hdul:\n    # Display structure\n    hdul.info()\n\n    # Get image data and header\n    data = hdul[1].data\n    header = hdul[1].header\n\n    # Access header values\n    exptime = header['EXPTIME']\n    filter_name = header['FILTER']\n\n    # Analyze data\n    mean = np.mean(data)\n    median = np.median(data)\n    print(f\"Mean: {mean}, Median: {median}\")\n```\n\n### Cosmological Distance Calculations\n\n```python\nfrom astropy.cosmology import Planck18\nimport astropy.units as u\nimport numpy as np\n\n# Calculate distances at z=1.5\nz = 1.5\nd_L = Planck18.luminosity_distance(z)\nd_A = Planck18.angular_diameter_distance(z)\n\nprint(f\"Luminosity distance: {d_L}\")\nprint(f\"Angular diameter distance: {d_A}\")\n\n# Age of universe at that redshift\nage = Planck18.age(z)\nprint(f\"Age at z={z}: {age.to(u.Gyr)}\")\n\n# Lookback time\nt_lookback = Planck18.lookback_time(z)\nprint(f\"Lookback time: {t_lookback.to(u.Gyr)}\")\n```\n\n### Cross-Matching Catalogs\n\n```python\nfrom astropy.table import Table\nfrom astropy.coordinates import SkyCoord, match_coordinates_sky\nimport astropy.units as u\n\n# Read catalogs\ncat1 = Table.read('catalog1.fits')\ncat2 = Table.read('catalog2.fits')\n\n# Create coordinate objects\ncoords1 = SkyCoord(ra=cat1['RA']*u.degree, dec=cat1['DEC']*u.degree)\ncoords2 = SkyCoord(ra=cat2['RA']*u.degree, dec=cat2['DEC']*u.degree)\n\n# Find matches\nidx, sep, _ = coords1.match_to_catalog_sky(coords2)\n\n# Filter by separation threshold\nmax_sep = 1 * u.arcsec\nmatches = sep < max_sep\n\n# Create matched catalogs\ncat1_matched = cat1[matches]\ncat2_matched = cat2[idx[matches]]\nprint(f\"Found {len(cat1_matched)} matches\")\n```\n\n## Best Practices\n\n1. **Always use units**: Attach units to quantities to avoid errors and ensure dimensional consistency\n2. **Use context managers for FITS files**: Ensures proper file closing\n3. **Prefer arrays over loops**: Process multiple coordinates/times as arrays for better performance\n4. **Check coordinate frames**: Verify the frame before transformations\n5. **Use appropriate cosmology**: Choose the right cosmological model for your analysis\n6. **Handle missing data**: Use masked columns for tables with missing values\n7. **Specify time scales**: Be explicit about time scales (UTC, TT, TDB) for precise timing\n8. **Use QTable for unit-aware tables**: When table columns have units\n9. **Check WCS validity**: Verify WCS before using transformations\n10. **Cache frequently used values**: Expensive calculations (e.g., cosmological distances) can be cached\n11. **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.\n12. **Pin for reproducibility**: Use pinned versions such as `astropy==7.2.0` for shared environments; update pins intentionally after reviewing release notes.\n\n## Current-Version Notes\n\n- Current stable release researched: Astropy 7.2.0 (released 2025-11-25; verified current as of 2026-06-10)\n- Python requirement: 3.11+\n- **Astropy 8.0 is at release-candidate stage** (8.0.0rc1, 2026-05-26). Key changes to anticipate:\n  - 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`)\n  - `astropy.constants` defaults change from CODATA 2018 to CODATA 2022; pin a constants version via the `astropyconst` science states if reproducibility matters\n  - 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\n  - The built-in test runner (`astropy.test()`, `TestRunner`) is formally deprecated — invoke `pytest` directly\n- 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()`\n- 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.\n- The recommended optional extras are `recommended` for common plotting/scientific dependencies and `all` only when a broad optional feature set is needed.\n\n## Documentation and Resources\n\n- Official Astropy Documentation: https://docs.astropy.org/en/stable/\n- Tutorials: https://learn.astropy.org/\n- GitHub: https://github.com/astropy/astropy\n\n## Reference Files\n\nFor detailed information on specific modules:\n- `references/units.md` - Units, quantities, conversions, and equivalencies\n- `references/coordinates.md` - Coordinate systems, transformations, and catalog matching\n- `references/cosmology.md` - Cosmological models and calculations\n- `references/fits.md` - FITS file operations and manipulation\n- `references/tables.md` - Table creation, I/O, and operations\n- `references/time.md` - Time formats, scales, and calculations\n- `references/wcs_and_other_modules.md` - WCS, NDData, modeling, visualization, constants, and utilities","author":"@K-Dense-AI","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/astropy","license":"MIT","category":"writing","lang":"en","tokens":3359,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/coordinates.md","size":7804,"sha256":"6bba23f1cedf55411293337c0b4158f83d2babe3aaa617e9b2b364a8f4e7bd1a"},{"path":"references/cosmology.md","size":6762,"sha256":"311751b8072ce53abcba210b5ebfaac048301ecb7314d164321fba56df93366c"},{"path":"references/fits.md","size":8914,"sha256":"aa1771bc8cb75a2f332bb1a9cfc31a859fd7b6e07a6314add673d17111b98838"},{"path":"references/tables.md","size":9610,"sha256":"abade45705a4bf6b0a9b27d6693163e26cb53d9a9750f8d57dd9a9ad57caf366"},{"path":"references/time.md","size":9568,"sha256":"fd7c3a1a922e7b72060fa702d9702239a0b552d34efbe8e1673604a749810f61"},{"path":"references/units.md","size":3766,"sha256":"ec3d108772f9c0f2242ede6b8499f846d21d53bfc1c255fb3306bdf685139a8e"},{"path":"references/wcs_and_other_modules.md","size":9146,"sha256":"b955cd3b0c75ae9dce3b24ccea2b78e0eceee6c81b836a30d1f4edf2821eb9fc"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["docs.astropy.org","learn.astropy.org"]}}