{"slug": "astrophysics-ai-with-python-unlocking-the-universe-with-astroquery", "title": "Astrophysics & AI with Python: Unlocking the Universe with Astroquery", "summary": "A developer demonstrates how to use the Python library Astroquery to programmatically access astronomical data from multiple archives, solving the heterogeneity problem of different APIs. The tutorial shows how to resolve coordinates for the Andromeda Galaxy using NED and query the MAST archive for Hubble Space Telescope observations, integrating with Astropy for unit handling and coordinate transformations.", "body_md": "The universe is no longer just observed through a physical telescope eyepiece; it is read, parsed, and analyzed through code. For the modern data-driven astronomer, the sky is a massive, distributed database. However, accessing this data presents a unique challenge: the \"Babel of Archives.\"\n\nHow do you programmatically search the accumulated knowledge of humanity when that knowledge is scattered across dozens of independent institutions, each with its own proprietary query language, format, and API?\n\nThe answer is **Astroquery**. This powerful Python library serves as the universal translator for the Virtual Observatory, turning complex web requests into simple function calls. In this guide, we will explore the theoretical foundations of this tool and walk through a practical script to fetch Hubble Space Telescope data for the Andromeda Galaxy.\n\nModern astronomy is defined by the data deluge. From the Hubble Space Telescope (HST) to the James Webb Space Telescope (JWST) and the Gaia mission, we are collecting petabytes of data. But this data isn't stored on a single central server. It is housed in specialized archives:\n\nIf you wanted to find all data on M31, you would historically need to write custom API wrappers for all three archives. This is the **Heterogeneity Problem**.\n\nThink of `astroquery`\n\nas a Universal Research Librarian. You give it a simple instruction in Python, and it performs the complex, hidden work behind the scenes:\n\nCrucially, `astroquery`\n\nintegrates tightly with `astropy.coordinates`\n\n. It handles unit conversions and reference frame transformations (like precessing coordinates from J2000 to the current epoch) automatically, eliminating a massive source of error in scientific research.\n\nLet’s put theory into practice. In this example, we will perform the standard two-step astronomical query:\n\n``` python\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord\nfrom astroquery.ned import Ned\nfrom astroquery.mast import Mast\nimport sys \n\n# --- PART 1: Coordinate Resolution using NED ---\n\n# 1. Define the target object name.\nTARGET_NAME = \"M31\"\n\nprint(f\"--- 1. Resolving Coordinates for {TARGET_NAME} using NED ---\")\n\ntry:\n    # Query NED for the object. The result is an Astropy Table.\n    ned_result_table = Ned.query_object(TARGET_NAME)\nexcept Exception as e:\n    print(f\"Error querying NED for {TARGET_NAME}: {e}\")\n    sys.exit(1)\n\n# 2. Extract RA and Dec (in decimal degrees).\ntry:\n    ra_deg = ned_result_table['RA(deg)'][0]\n    dec_deg = ned_result_table['DEC(deg)'][0]\nexcept IndexError:\n    print(f\"Error: NED returned an empty result for {TARGET_NAME}.\")\n    sys.exit(1)\n\n# 3. Create a standardized SkyCoord object with units.\ntarget_coord = SkyCoord(\n    ra=ra_deg * u.degree, \n    dec=dec_deg * u.degree, \n    frame='icrs' \n)\n\nprint(f\"Resolved Coordinates: RA={target_coord.ra.deg:.4f} deg, Dec={target_coord.dec.deg:.4f} deg\")\n\n# --- PART 2: Querying the MAST Archive ---\n\n# 4. Define the search radius. M31 is large, so we use a generous radius.\nsearch_radius = 0.5 * u.degree \n\nprint(f\"\\n--- 2. Querying MAST for HST Observations within {search_radius} of M31 ---\")\n\n# 5. Query MAST using the coordinates and radius.\nmast_observations = Mast.query_criteria(\n    coordinates=target_coord,\n    radius=search_radius,\n    obs_collection=\"HST\" # Filter for Hubble data only\n)\n\n# 6. Display the results.\nif mast_observations is not None and len(mast_observations) > 0:\n    print(f\"\\nSuccess! Found {len(mast_observations)} HST observations.\")\n    print(\"\\nMetadata Summary (First 5 entries):\")\n    # Select specific columns for a clean summary\n    summary_data = mast_observations[['obsid', 'instrument_name', 't_exptime', 'filters']][:5]\n    print(summary_data)\nelse:\n    print(\"\\nNo HST observations found.\")\n\nprint(\"\\nQuery process complete.\")\n```\n\nWe import `astropy.units`\n\n(aliased as `u`\n\n) and `SkyCoord`\n\n. In modern astronomical coding, units are mandatory. Passing a raw number like `0.5`\n\nis dangerous—is that 0.5 degrees, radians, or arcseconds? By multiplying `0.5 * u.degree`\n\n, we create a unit-aware object that `astroquery`\n\nunderstands perfectly.\n\nThe function `Ned.query_object(\"M31\")`\n\nsends a request to the NASA/IPAC Extragalactic Database. It returns an `Astropy Table`\n\ncontaining metadata (redshift, object type, etc.). We extract the `RA(deg)`\n\nand `DEC(deg)`\n\ncolumns.\n\n`[0]`\n\nbecause even a single name query returns a table (a list of rows). We grab the first row as the primary match.We wrap the raw numbers into `target_coord = SkyCoord(...)`\n\n. This object is the currency of the `Astropy`\n\necosystem. It carries not just the numbers, but the **units** (`u.degree`\n\n) and the **frame** (`icrs`\n\n- the International Celestial Reference System).\n\nWe use `Mast.query_criteria()`\n\n. This is the Swiss Army knife of MAST queries.\n\n`coordinates=target_coord`\n\n`radius=search_radius`\n\n`obs_collection=\"HST\"`\n\nThe result is an `Astropy Table`\n\n. This is superior to a standard Pandas DataFrame for astronomy because it preserves **scientific metadata**. It knows the units of every column and the provenance of the data. We slice the table to show the first 5 entries and specific columns (`obsid`\n\n, `instrument_name`\n\n, `t_exptime`\n\n, `filters`\n\n) to keep the output readable.\n\nThe most common error for beginners is forgetting `astropy.units`\n\n.\n\n**Incorrect:**\n\n```\nsearch_radius = 0.5 # Just a float\n```\n\n**Correct:**\n\n```\nsearch_radius = 0.5 * u.degree # A physical quantity\n```\n\nIf you pass a bare number, `astroquery`\n\nwill raise an error because it cannot assume the unit. Always use units!\n\n`astroquery`\n\nis more than a convenience wrapper; it is the glue that holds the fragmented world of astronomical archives together. By abstracting away the complexities of HTTP requests, XML parsing, and coordinate transformations, it allows researchers to focus on the science rather than the plumbing.\n\nWhether you are building a training set for an AI model or analyzing the spectral energy distribution of a galaxy, `astroquery`\n\nprovides the standardized, programmatic access required for reproducible, modern science.\n\n`astroquery`\n\nto programmatically curate a balanced training dataset of spiral vs. elliptical galaxies?The concepts and code demonstrated here are drawn directly from the comprehensive roadmap laid out in the ebook\n\n**Astrophysics & AI: Building Research Agents for Astronomy, Cosmology, and SETI**. You can find it [here](http://tiny.cc/PythonAstrophysics). Check all the other 50 Programming & AI ebooks with python, typescript, swift, c#: [here](http://tiny.cc/ProgrammingBooks)", "url": "https://wpnews.pro/news/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery", "canonical_source": "https://dev.to/programmingcentral/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery-2kd6", "published_at": "2026-06-15 20:00:00+00:00", "updated_at": "2026-06-15 20:02:26.566047+00:00", "lang": "en", "topics": ["artificial-intelligence", "developer-tools", "machine-learning"], "entities": ["Astroquery", "Python", "NED", "MAST", "Hubble Space Telescope", "Astropy", "Andromeda Galaxy", "Virtual Observatory"], "alternates": {"html": "https://wpnews.pro/news/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery", "markdown": "https://wpnews.pro/news/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery.md", "text": "https://wpnews.pro/news/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery.txt", "jsonld": "https://wpnews.pro/news/astrophysics-ai-with-python-unlocking-the-universe-with-astroquery.jsonld"}}