{ "cells": [ { "cell_type": "raw", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "---\n", "title: \"Basic queries\"\n", "teaching: 3000\n", "exercises: 0\n", "questions:\n", "- \"How can we select and download the data we want from the Gaia server?\"\n", "\n", "objectives:\n", "- \"Compose a basic query in ADQL/SQL.\"\n", "- \"Use queries to explore a database and its tables.\"\n", "- \"Use queries to download data.\"\n", "- \"Develop, test, and debug a query incrementally.\"\n", "keypoints:\n", "- \"If you can't download an entire dataset (or it's not practical) use queries to select the data you need.\"\n", "\n", "- \"Read the metadata and the documentation to make sure you understand the tables, their columns, and what they mean.\"\n", "\n", "- \"Develop queries incrementally: start with something simple, test it, and add a little bit at a time.\"\n", "\n", "- \"Use ADQL features like `TOP` and `COUNT` to test before you run a query that might return a lot of data.\"\n", "\n", "- \"If you know your query will return fewer than 3000 rows, you can \n", "run it synchronously, which might complete faster (but it doesn't seem to make much difference). If it might return more than 3000 rows, you should run it asynchronously.\"\n", "\n", "- \"ADQL and SQL are not case-sensitive, so you don't have to \n", "capitalize the keywords, but you should.\"\n", "\n", "- \"ADQL and SQL don't require you to break a query into multiple \n", "lines, but you should.\"\n", "\n", "---\n", "\n", "{% include links.md %}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Queries\n", "\n", "This is the first in a series of lessons about working with astronomical data.\n", "\n", "As a running example, we will replicate parts of the analysis in a recent paper, \"[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00425)\" by Adrian Price-Whelan and Ana Bonaca." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Outline\n", "\n", "This lesson demonstrates the steps for selecting and downloading data from the Gaia Database:\n", "\n", "1. First we'll make a connection to the Gaia server,\n", "\n", "2. We will explore information about the database and the tables it contains,\n", "\n", "3. We will write a query and send it to the server, and finally\n", "\n", "4. We will download the response from the server.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Query Language\n", "\n", "In order to select data from a database, you have to compose a query, which is a program written in a \"query language\".\n", "The query language we'll use is ADQL, which stands for \"Astronomical Data Query Language\".\n", "\n", "ADQL is a dialect of [SQL](https://en.wikipedia.org/wiki/SQL) (Structured Query Language), which is by far the most commonly used query language. Almost everything you will learn about ADQL also works in SQL.\n", "\n", "[The reference manual for ADQL is here](http://www.ivoa.net/documents/ADQL/20180112/PR-ADQL-2.1-20180112.html).\n", "But you might find it easier to learn from [this ADQL Cookbook](https://www.gaia.ac.uk/data/gaia-data-release-1/adql-cookbook)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Jupyter\n", "\n", "If you have not worked with Jupyter notebooks before, you might start with [the tutorial on from Jupyter.org called \"Try Classic Notebook\"](https://jupyter.org/try), or [this tutorial from DataQuest](https://www.dataquest.io/blog/jupyter-notebook-tutorial/).\n", "\n", "There are two environments you can use to write and run notebooks: \n", "\n", "* \"Jupyter Notebook\" is the original, and\n", "\n", "* \"Jupyter Lab\" is a newer environment with more features.\n", "\n", "For these lessons, you can use either one." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you are too impatient for the tutorials, here are the most important things to know:\n", "\n", "1. Notebooks are made up of code cells and text cells (and a few other less common kinds). Code cells contain code; text cells, like this one, contain explanatory text written in [Markdown](https://www.markdownguide.org/).\n", "\n", "2. To run a code cell, click the cell to select it and press Shift-Enter. The output of the code should appear below the cell.\n", "\n", "3. In general, notebooks only run correctly if you run every code cell in order from top to bottom. If you run cells out of order, you are likely to get errors.\n", "\n", "4. You can modify existing cells, but then you have to run them again to see the effect.\n", "\n", "5. You can add new cells, but again, you have to be careful about the order you run them in.\n", "\n", "6. If you have added or modified cells and the behavior of the notebook seems strange, you can restart the \"kernel\", which clears all of the variables and functions you have defined, and run the cells again from the beginning.\n", "\n", "* If you are using Jupyter notebook, open the `Kernel` menu and select \"Restart and Run All\".\n", "\n", "* In Jupyter Lab, open the `Kernel` menu and select \"Restart Kernel and Run All Cells\"\n", "\n", "* In Colab, open the `Runtime` menu and select \"Restart and run all\"\n", "\n", "Before you go on, you might want to explore the other menus and the toolbar to see what else you can do." ] }, { "cell_type": "markdown", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "## Installing libraries\n", "\n", "If you are running this notebook on Colab, you should run the following cell to install the libraries we'll need.\n", "\n", "If you are running this notebook on your own computer, you might have to install these libraries yourself." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "tags": [ "remove-cell" ] }, "outputs": [], "source": [ "# If we're running on Colab, install libraries\n", "\n", "import sys\n", "IN_COLAB = 'google.colab' in sys.modules\n", "\n", "if IN_COLAB:\n", " !pip install astroquery" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Connecting to Gaia\n", "\n", "The library we'll use to get Gaia data is [Astroquery](https://astroquery.readthedocs.io/en/latest/).\n", "Astroquery provides `Gaia`, which is an [object that represents a connection to the Gaia database](https://astroquery.readthedocs.io/en/latest/gaia/gaia.html).\n", "\n", "We can connect to the Gaia database like this:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created TAP+ (v1.2.1) - Connection:\n", "\tHost: gea.esac.esa.int\n", "\tUse HTTPS: True\n", "\tPort: 443\n", "\tSSL Port: 443\n", "Created TAP+ (v1.2.1) - Connection:\n", "\tHost: geadata.esac.esa.int\n", "\tUse HTTPS: True\n", "\tPort: 443\n", "\tSSL Port: 443\n" ] } ], "source": [ "from astroquery.gaia import Gaia" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This import statement creates a [TAP+](http://www.ivoa.net/documents/TAP/) connection; TAP stands for \"Table Access Protocol\", which is a network protocol for sending queries to the database and getting back the results. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Databases and Tables\n", "\n", "What is a database, anyway? Most generally, it can be any collection of data, but when we are talking about ADQL or SQL:\n", "\n", "* A database is a collection of one or more named tables.\n", "\n", "* Each table is a 2-D array with one or more named columns of data.\n", "\n", "We can use `Gaia.load_tables` to get the names of the tables in the Gaia database. With the option `only_names=True`, it loads information about the tables, called \"metadata\", not the data itself." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO: Retrieving tables... [astroquery.utils.tap.core]\n", "INFO: Parsing tables... [astroquery.utils.tap.core]\n", "INFO: Done. [astroquery.utils.tap.core]\n" ] } ], "source": [ "tables = Gaia.load_tables(only_names=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following `for` loop prints the names of the tables." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "tags": [ "hide-output", "truncate-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "external.apassdr9\n", "external.gaiadr2_geometric_distance\n", "external.gaiaedr3_distance\n", "external.galex_ais\n", "external.ravedr5_com\n", "external.ravedr5_dr5\n", "external.ravedr5_gra\n", "external.ravedr5_on\n", "external.sdssdr13_photoprimary\n", "external.skymapperdr1_master\n", "external.skymapperdr2_master\n", "external.tmass_xsc\n", "public.hipparcos\n", "public.hipparcos_newreduction\n", "public.hubble_sc\n", "public.igsl_source\n", "public.igsl_source_catalog_ids\n", "public.tycho2\n", "public.dual\n", "tap_config.coord_sys\n", "tap_config.properties\n", "tap_schema.columns\n", "tap_schema.key_columns\n", "tap_schema.keys\n", "tap_schema.schemas\n", "tap_schema.tables\n", "gaiaedr3.gaia_source\n", "gaiaedr3.agn_cross_id\n", "gaiaedr3.commanded_scan_law\n", "gaiaedr3.dr2_neighbourhood\n", "gaiaedr3.frame_rotator_source\n", "gaiaedr3.allwise_best_neighbour\n", "gaiaedr3.allwise_neighbourhood\n", "gaiaedr3.apassdr9_best_neighbour\n", "gaiaedr3.apassdr9_join\n", "gaiaedr3.apassdr9_neighbourhood\n", "gaiaedr3.gsc23_best_neighbour\n", "gaiaedr3.gsc23_join\n", "gaiaedr3.gsc23_neighbourhood\n", "gaiaedr3.hipparcos2_best_neighbour\n", "gaiaedr3.hipparcos2_neighbourhood\n", "gaiaedr3.panstarrs1_best_neighbour\n", "gaiaedr3.panstarrs1_join\n", "gaiaedr3.panstarrs1_neighbourhood\n", "gaiaedr3.ravedr5_best_neighbour\n", "gaiaedr3.ravedr5_join\n", "gaiaedr3.ravedr5_neighbourhood\n", "gaiaedr3.sdssdr13_best_neighbour\n", "gaiaedr3.sdssdr13_join\n", "gaiaedr3.sdssdr13_neighbourhood\n", "gaiaedr3.skymapperdr2_best_neighbour\n", "gaiaedr3.skymapperdr2_join\n", "gaiaedr3.skymapperdr2_neighbourhood\n", "gaiaedr3.tmass_psc_xsc_best_neighbour\n", "gaiaedr3.tmass_psc_xsc_join\n", "gaiaedr3.tmass_psc_xsc_neighbourhood\n", "gaiaedr3.tycho2tdsc_merge_best_neighbour\n", "gaiaedr3.tycho2tdsc_merge_neighbourhood\n", "gaiaedr3.urat1_best_neighbour\n", "gaiaedr3.urat1_neighbourhood\n", "gaiaedr3.gaia_source_simulation\n", "gaiaedr3.gaia_universe_model\n", "gaiaedr3.tycho2tdsc_merge\n", "gaiadr1.aux_qso_icrf2_match\n", "gaiadr1.ext_phot_zero_point\n", "gaiadr1.allwise_best_neighbour\n", "gaiadr1.allwise_neighbourhood\n", "gaiadr1.gsc23_best_neighbour\n", "gaiadr1.gsc23_neighbourhood\n", "gaiadr1.ppmxl_best_neighbour\n", "gaiadr1.ppmxl_neighbourhood\n", "gaiadr1.sdss_dr9_best_neighbour\n", "gaiadr1.sdss_dr9_neighbourhood\n", "gaiadr1.tmass_best_neighbour\n", "gaiadr1.tmass_neighbourhood\n", "gaiadr1.ucac4_best_neighbour\n", "gaiadr1.ucac4_neighbourhood\n", "gaiadr1.urat1_best_neighbour\n", "gaiadr1.urat1_neighbourhood\n", "gaiadr1.cepheid\n", "gaiadr1.phot_variable_time_series_gfov\n", "gaiadr1.phot_variable_time_series_gfov_statistical_parameters\n", "gaiadr1.rrlyrae\n", "gaiadr1.variable_summary\n", "gaiadr1.allwise_original_valid\n", "gaiadr1.gsc23_original_valid\n", "gaiadr1.ppmxl_original_valid\n", "gaiadr1.sdssdr9_original_valid\n", "gaiadr1.tmass_original_valid\n", "gaiadr1.ucac4_original_valid\n", "gaiadr1.urat1_original_valid\n", "gaiadr1.gaia_source\n", "gaiadr1.tgas_source\n", "gaiadr2.aux_allwise_agn_gdr2_cross_id\n", "gaiadr2.aux_iers_gdr2_cross_id\n", "gaiadr2.aux_sso_orbit_residuals\n", "gaiadr2.aux_sso_orbits\n", "gaiadr2.dr1_neighbourhood\n", "gaiadr2.allwise_best_neighbour\n", "gaiadr2.allwise_neighbourhood\n", "gaiadr2.apassdr9_best_neighbour\n", "gaiadr2.apassdr9_neighbourhood\n", "gaiadr2.gsc23_best_neighbour\n", "gaiadr2.gsc23_neighbourhood\n", "gaiadr2.hipparcos2_best_neighbour\n", "gaiadr2.hipparcos2_neighbourhood\n", "gaiadr2.panstarrs1_best_neighbour\n", "gaiadr2.panstarrs1_neighbourhood\n", "gaiadr2.ppmxl_best_neighbour\n", "gaiadr2.ppmxl_neighbourhood\n", "gaiadr2.ravedr5_best_neighbour\n", "gaiadr2.ravedr5_neighbourhood\n", "gaiadr2.sdssdr9_best_neighbour\n", "gaiadr2.sdssdr9_neighbourhood\n", "gaiadr2.tmass_best_neighbour\n", "gaiadr2.tmass_neighbourhood\n", "gaiadr2.tycho2_best_neighbour\n", "gaiadr2.tycho2_neighbourhood\n", "gaiadr2.urat1_best_neighbour\n", "gaiadr2.urat1_neighbourhood\n", "gaiadr2.sso_observation\n", "gaiadr2.sso_source\n", "gaiadr2.vari_cepheid\n", "gaiadr2.vari_classifier_class_definition\n", "gaiadr2.vari_classifier_definition\n", "gaiadr2.vari_classifier_result\n", "gaiadr2.vari_long_period_variable\n", "gaiadr2.vari_rotation_modulation\n", "gaiadr2.vari_rrlyrae\n", "gaiadr2.vari_short_timescale\n", "gaiadr2.vari_time_series_statistics\n", "gaiadr2.panstarrs1_original_valid\n", "gaiadr2.gaia_source\n", "gaiadr2.ruwe\n" ] } ], "source": [ "for table in tables:\n", " print(table.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So that's a lot of tables. The ones we'll use are:\n", "\n", "* `gaiadr2.gaia_source`, which contains Gaia data from [data release 2](https://www.cosmos.esa.int/web/gaia/data-release-2),\n", "\n", "* `gaiadr2.panstarrs1_original_valid`, which contains the photometry data we'll use from PanSTARRS, and\n", "\n", "* `gaiadr2.panstarrs1_best_neighbour`, which we'll use to cross-match each star observed by Gaia with the same star observed by PanSTARRS.\n", "\n", "We can use `load_table` (not `load_tables`) to get the metadata for a single table. The name of this function is misleading, because it only downloads metadata, not the contents of the table." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Retrieving table 'gaiadr2.gaia_source'\n", "Parsing table 'gaiadr2.gaia_source'...\n", "Done.\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "meta = Gaia.load_table('gaiadr2.gaia_source')\n", "meta" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter shows that the result is an object of type `TapTableMeta`, but it does not display the contents.\n", "\n", "To see the metadata, we have to print the object." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "TAP Table name: gaiadr2.gaiadr2.gaia_source\n", "Description: This table has an entry for every Gaia observed source as listed in the\n", "Main Database accumulating catalogue version from which the catalogue\n", "release has been generated. It contains the basic source parameters,\n", "that is only final data (no epoch data) and no spectra (neither final\n", "nor epoch).\n", "Num. columns: 96\n" ] } ], "source": [ "print(meta)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Columns\n", "\n", "The following loop prints the names of the columns in the table." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "tags": [ "hide-output", "truncate-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "solution_id\n", "designation\n", "source_id\n", "random_index\n", "ref_epoch\n", "ra\n", "ra_error\n", "dec\n", "dec_error\n", "parallax\n", "parallax_error\n", "parallax_over_error\n", "pmra\n", "pmra_error\n", "pmdec\n", "pmdec_error\n", "ra_dec_corr\n", "ra_parallax_corr\n", "ra_pmra_corr\n", "ra_pmdec_corr\n", "dec_parallax_corr\n", "dec_pmra_corr\n", "dec_pmdec_corr\n", "parallax_pmra_corr\n", "parallax_pmdec_corr\n", "pmra_pmdec_corr\n", "astrometric_n_obs_al\n", "astrometric_n_obs_ac\n", "astrometric_n_good_obs_al\n", "astrometric_n_bad_obs_al\n", "astrometric_gof_al\n", "astrometric_chi2_al\n", "astrometric_excess_noise\n", "astrometric_excess_noise_sig\n", "astrometric_params_solved\n", "astrometric_primary_flag\n", "astrometric_weight_al\n", "astrometric_pseudo_colour\n", "astrometric_pseudo_colour_error\n", "mean_varpi_factor_al\n", "astrometric_matched_observations\n", "visibility_periods_used\n", "astrometric_sigma5d_max\n", "frame_rotator_object_type\n", "matched_observations\n", "duplicated_source\n", "phot_g_n_obs\n", "phot_g_mean_flux\n", "phot_g_mean_flux_error\n", "phot_g_mean_flux_over_error\n", "phot_g_mean_mag\n", "phot_bp_n_obs\n", "phot_bp_mean_flux\n", "phot_bp_mean_flux_error\n", "phot_bp_mean_flux_over_error\n", "phot_bp_mean_mag\n", "phot_rp_n_obs\n", "phot_rp_mean_flux\n", "phot_rp_mean_flux_error\n", "phot_rp_mean_flux_over_error\n", "phot_rp_mean_mag\n", "phot_bp_rp_excess_factor\n", "phot_proc_mode\n", "bp_rp\n", "bp_g\n", "g_rp\n", "radial_velocity\n", "radial_velocity_error\n", "rv_nb_transits\n", "rv_template_teff\n", "rv_template_logg\n", "rv_template_fe_h\n", "phot_variable_flag\n", "l\n", "b\n", "ecl_lon\n", "ecl_lat\n", "priam_flags\n", "teff_val\n", "teff_percentile_lower\n", "teff_percentile_upper\n", "a_g_val\n", "a_g_percentile_lower\n", "a_g_percentile_upper\n", "e_bp_min_rp_val\n", "e_bp_min_rp_percentile_lower\n", "e_bp_min_rp_percentile_upper\n", "flame_flags\n", "radius_val\n", "radius_percentile_lower\n", "radius_percentile_upper\n", "lum_val\n", "lum_percentile_lower\n", "lum_percentile_upper\n", "datalink_url\n", "epoch_photometry_url\n" ] } ], "source": [ "for column in meta.columns:\n", " print(column.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can probably infer what many of these columns are by looking at the names, but you should resist the temptation to guess.\n", "To find out what the columns mean, [read the documentation](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html).\n", "\n", "If you want to know what can go wrong when you don't read the documentation, [you might like this article](https://www.vox.com/future-perfect/2019/6/4/18650969/married-women-miserable-fake-paul-dolan-happiness)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "One of the other tables we'll use is `gaiadr2.panstarrs1_original_valid`. Use `load_table` to get the metadata for this table. How many columns are there and what are their names?" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Retrieving table 'gaiadr2.panstarrs1_original_valid'\n", "Parsing table 'gaiadr2.panstarrs1_original_valid'...\n", "Done.\n", "TAP Table name: gaiadr2.gaiadr2.panstarrs1_original_valid\n", "Description: The Panoramic Survey Telescope and Rapid Response System (Pan-STARRS) is\n", "a system for wide-field astronomical imaging developed and operated by\n", "the Institute for Astronomy at the University of Hawaii. Pan-STARRS1\n", "(PS1) is the first part of Pan-STARRS to be completed and is the basis\n", "for Data Release 1 (DR1). The PS1 survey used a 1.8 meter telescope and\n", "its 1.4 Gigapixel camera to image the sky in five broadband filters (g,\n", "r, i, z, y).\n", "\n", "The current table contains a filtered subsample of the 10 723 304 629\n", "entries listed in the original ObjectThin table.\n", "We used only ObjectThin and MeanObject tables to extract\n", "panstarrs1OriginalValid table, this means that objects detected only in\n", "stack images are not included here. The main reason for us to avoid the\n", "use of objects detected in stack images is that their astrometry is not\n", "as good as the mean objects astrometry: “The stack positions (raStack,\n", "decStack) have considerably larger systematic astrometric errors than\n", "the mean epoch positions (raMean, decMean).” The astrometry for the\n", "MeanObject positions uses Gaia DR1 as a reference catalog, while the\n", "stack positions use 2MASS as a reference catalog.\n", "\n", "In details, we filtered out all objects where:\n", "\n", "- nDetections = 1\n", "\n", "- no good quality data in Pan-STARRS, objInfoFlag 33554432 not set\n", "\n", "- mean astrometry could not be measured, objInfoFlag 524288 set\n", "\n", "- stack position used for mean astrometry, objInfoFlag 1048576 set\n", "\n", "- error on all magnitudes equal to 0 or to -999;\n", "\n", "- all magnitudes set to -999;\n", "\n", "- error on RA or DEC greater than 1 arcsec.\n", "\n", "The number of objects in panstarrs1OriginalValid is 2 264 263 282.\n", "\n", "The panstarrs1OriginalValid table contains only a subset of the columns\n", "available in the combined ObjectThin and MeanObject tables. A\n", "description of the original ObjectThin and MeanObjects tables can be\n", "found at:\n", "https://outerspace.stsci.edu/display/PANSTARRS/PS1+Database+object+and+detection+tables\n", "\n", "Download:\n", "http://mastweb.stsci.edu/ps1casjobs/home.aspx\n", "Documentation:\n", "https://outerspace.stsci.edu/display/PANSTARRS\n", "http://pswww.ifa.hawaii.edu/pswww/\n", "References:\n", "The Pan-STARRS1 Surveys, Chambers, K.C., et al. 2016, arXiv:1612.05560\n", "Pan-STARRS Data Processing System, Magnier, E. A., et al. 2016,\n", "arXiv:1612.05240\n", "Pan-STARRS Pixel Processing: Detrending, Warping, Stacking, Waters, C.\n", "Z., et al. 2016, arXiv:1612.05245\n", "Pan-STARRS Pixel Analysis: Source Detection and Characterization,\n", "Magnier, E. A., et al. 2016, arXiv:1612.05244\n", "Pan-STARRS Photometric and Astrometric Calibration, Magnier, E. A., et\n", "al. 2016, arXiv:1612.05242\n", "The Pan-STARRS1 Database and Data Products, Flewelling, H. A., et al.\n", "2016, arXiv:1612.05243\n", "\n", "Catalogue curator:\n", "SSDC - ASI Space Science Data Center\n", "https://www.ssdc.asi.it/\n", "Num. columns: 26\n", "obj_name\n", "obj_id\n", "ra\n", "dec\n", "ra_error\n", "dec_error\n", "epoch_mean\n", "g_mean_psf_mag\n", "g_mean_psf_mag_error\n", "g_flags\n", "r_mean_psf_mag\n", "r_mean_psf_mag_error\n", "r_flags\n", "i_mean_psf_mag\n", "i_mean_psf_mag_error\n", "i_flags\n", "z_mean_psf_mag\n", "z_mean_psf_mag_error\n", "z_flags\n", "y_mean_psf_mag\n", "y_mean_psf_mag_error\n", "y_flags\n", "n_detections\n", "zone_id\n", "obj_info_flag\n", "quality_flag\n" ] } ], "source": [ "# Solution\n", "\n", "meta2 = Gaia.load_table('gaiadr2.panstarrs1_original_valid')\n", "print(meta2)\n", "\n", "for column in meta2.columns:\n", " print(column.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Writing queries\n", "\n", "By now you might be wondering how we download these tables. With tables this big, you generally don't. Instead, you use queries to select only the data you want.\n", "\n", "A query is a string written in a query language like SQL; for the Gaia database, the query language is a dialect of SQL called ADQL.\n", "\n", "Here's an example of an ADQL query." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "query1 = \"\"\"SELECT \n", "TOP 10\n", "source_id, ra, dec, parallax \n", "FROM gaiadr2.gaia_source\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Python note:** We use a [triple-quoted string](https://docs.python.org/3/tutorial/introduction.html#strings) here so we can include line breaks in the query, which makes it easier to read.\n", "\n", "The words in uppercase are ADQL keywords:\n", "\n", "* `SELECT` indicates that we are selecting data (as opposed to adding or modifying data).\n", "\n", "* `TOP` indicates that we only want the first 10 rows of the table, which is useful for testing a query before asking for all of the data.\n", "\n", "* `FROM` specifies which table we want data from.\n", "\n", "The third line is a list of column names, indicating which columns we want. \n", "\n", "In this example, the keywords are capitalized and the column names are lowercase. This is a common style, but it is not required. ADQL and SQL are not case-sensitive.\n", "\n", "Also, the query is broken into multiple lines to make it more readable. This is a common style, but not required. Line breaks don't affect the behavior of the query." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To run this query, we use the `Gaia` object, which represents our connection to the Gaia database, and invoke `launch_job`:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "job = Gaia.launch_job(query1)\n", "job" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is an object that represents the job running on a Gaia server.\n", "\n", "If you print it, it displays metadata for the forthcoming results." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " name dtype unit description n_bad\n", "--------- ------- ---- ------------------------------------------------------------------ -----\n", "source_id int64 Unique source identifier (unique within a particular Data Release) 0\n", " ra float64 deg Right ascension 0\n", " dec float64 deg Declination 0\n", " parallax float64 mas Parallax 2\n", "Jobid: None\n", "Phase: COMPLETED\n", "Owner: None\n", "Output file: sync_20210315090602.xml.gz\n", "Results: None\n" ] } ], "source": [ "print(job)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Don't worry about `Results: None`. That does not actually mean there are no results.\n", "\n", "However, `Phase: COMPLETED` indicates that the job is complete, so we can get the results like this:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "astropy.table.table.Table" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results = job.get_results()\n", "type(results)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `type` function indicates that the result is an [Astropy Table](https://docs.astropy.org/en/stable/table/).\n", "\n", "**Optional detail:** Why is `table` repeated three times? The first is the name of the module, the second is the name of the submodule, and the third is the name of the class. Most of the time we only care about the last one. It's like the Linnean name for gorilla, which is *Gorilla gorilla gorilla*." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An Astropy `Table` is similar to a table in an SQL database except:\n", "\n", "* SQL databases are stored on disk drives, so they are persistent; that is, they \"survive\" even if you turn off the computer. An Astropy `Table` is stored in memory; it disappears when you turn off the computer (or shut down this Jupyter notebook).\n", "\n", "* SQL databases are designed to process queries. An Astropy `Table` can perform some query-like operations, like selecting columns and rows. But these operations use Python syntax, not SQL.\n", "\n", "Jupyter knows how to display the contents of a `Table`." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/html": [ "Table length=10\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
source_idradecparallax
degdegmas
int64float64float64float64
5887983246081387776227.978818386372-53.649969624501031.0493172163332998
5887971250213117952228.32280834041364-53.662707262037260.29455652682279093
5887991866047288704228.1582047014091-53.454724911639794-0.5789179941669236
5887968673232040832228.07420888099884-53.80646128959610.41030970779603076
5887979844465854720228.42547805195946-53.48882284470035-0.23379683441525864
5887978607515442688228.23831627636855-53.56328249482688-0.9252161956789068
5887978298278520704228.26015640396173-53.607284412896476--
5887995581231772928228.12871598211902-53.373625663608316-0.3325818206439385
5887982043490374016227.985260087594-53.6834444990555750.02878111976456593
5887982971205433856227.89884570686218-53.67430215342567--
" ], "text/plain": [ "\n", " source_id ra dec parallax \n", " deg deg mas \n", " int64 float64 float64 float64 \n", "------------------- ------------------ ------------------- --------------------\n", "5887983246081387776 227.978818386372 -53.64996962450103 1.0493172163332998\n", "5887971250213117952 228.32280834041364 -53.66270726203726 0.29455652682279093\n", "5887991866047288704 228.1582047014091 -53.454724911639794 -0.5789179941669236\n", "5887968673232040832 228.07420888099884 -53.8064612895961 0.41030970779603076\n", "5887979844465854720 228.42547805195946 -53.48882284470035 -0.23379683441525864\n", "5887978607515442688 228.23831627636855 -53.56328249482688 -0.9252161956789068\n", "5887978298278520704 228.26015640396173 -53.607284412896476 --\n", "5887995581231772928 228.12871598211902 -53.373625663608316 -0.3325818206439385\n", "5887982043490374016 227.985260087594 -53.683444499055575 0.02878111976456593\n", "5887982971205433856 227.89884570686218 -53.67430215342567 --" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each column has a name, units, and a data type.\n", "\n", "For example, the units of `ra` and `dec` are degrees, and their data type is `float64`, which is a 64-bit [floating-point number](https://en.wikipedia.org/wiki/Floating-point_arithmetic), used to store measurements with a fraction part.\n", "\n", "This information comes from the Gaia database, and has been stored in the Astropy `Table` by Astroquery." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "Read [the documentation](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html) of this table and choose a column that looks interesting to you. Add the column name to the query and run it again. What are the units of the column you selected? What is its data type?" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [], "source": [ "# Solution\n", "\n", "# Let's add\n", "#\n", "# radial_velocity : Radial velocity (double, Velocity[km/s] )\n", "#\n", "# Spectroscopic radial velocity in the solar barycentric \n", "# reference frame.\n", "#\n", "# The radial velocity provided is the median value of the \n", "# radial velocity measurements at all epochs.\n", "\n", "query = \"\"\"SELECT \n", "TOP 10\n", "source_id, ra, dec, parallax, radial_velocity\n", "FROM gaiadr2.gaia_source\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Asynchronous queries\n", "\n", "`launch_job` asks the server to run the job \"synchronously\", which normally means it runs immediately. But synchronous jobs are limited to 2000 rows. For queries that return more rows, you should run \"asynchronously\", which mean they might take longer to get started.\n", "\n", "If you are not sure how many rows a query will return, you can use the SQL command `COUNT` to find out how many rows are in the result without actually returning them. We'll see an example in the next lesson.\n", "\n", "The results of an asynchronous query are stored in a file on the server, so you can start a query and come back later to get the results.\n", "For anonymous users, files are kept for three days.\n", "\n", "As an example, let's try a query that's similar to `query1`, with these changes:\n", "\n", "* It selects the first 3000 rows, so it is bigger than we should run synchronously.\n", "\n", "* It selects two additional columns, `pmra` and `pmdec`, which are proper motions along the axes of `ra` and `dec`.\n", "\n", "* It uses a new keyword, `WHERE`." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "query2 = \"\"\"SELECT \n", "TOP 3000\n", "source_id, ra, dec, pmra, pmdec, parallax\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A `WHERE` clause indicates which rows we want; in this case, the query selects only rows \"where\" `parallax` is less than 1. This has the effect of selecting stars with relatively low parallax, which are farther away.\n", "We'll use this clause to exclude nearby stars that are unlikely to be part of GD-1.\n", "\n", "`WHERE` is one of the most common clauses in ADQL/SQL, and one of the most useful, because it allows us to download only the rows we need from the database.\n", "\n", "We use `launch_job_async` to submit an asynchronous query." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO: Query finished. [astroquery.utils.tap.core]\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "job = Gaia.launch_job_async(query2)\n", "job" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here are the results." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/html": [ "Table length=10\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
source_idradecparallaxradial_velocity
degdegmaskm / s
int64float64float64float64float64
5895270396817359872213.08433715252883-56.641047010056942.041947005434917--
5895272561481374080213.2606587905109-56.550444015357150.15693467895110133--
5895247410183786368213.38479712976664-56.97008551185148-0.19017525742552605--
5895249226912448000213.41587389088238-56.849596577635786----
5895261875598904576213.5508930114549-56.61037780154348-0.29471722363529257--
5895258302187834624213.87631129557286-56.6785372590399060.6468437015289753--
5895247444506644992213.33215109206796-56.9753477593809950.390215490234287--
5895259470417635968213.78815034206346-56.645850474515940.953377710788918--
5895264899260932352213.21521027193236-56.78420864489118----
5895265925746051584213.17082359534547-56.745408851077540.2986918215101751--
" ], "text/plain": [ "\n", " source_id ra ... parallax radial_velocity\n", " deg ... mas km / s \n", " int64 float64 ... float64 float64 \n", "------------------- ------------------ ... -------------------- ---------------\n", "5895270396817359872 213.08433715252883 ... 2.041947005434917 --\n", "5895272561481374080 213.2606587905109 ... 0.15693467895110133 --\n", "5895247410183786368 213.38479712976664 ... -0.19017525742552605 --\n", "5895249226912448000 213.41587389088238 ... -- --\n", "5895261875598904576 213.5508930114549 ... -0.29471722363529257 --\n", "5895258302187834624 213.87631129557286 ... 0.6468437015289753 --\n", "5895247444506644992 213.33215109206796 ... 0.390215490234287 --\n", "5895259470417635968 213.78815034206346 ... 0.953377710788918 --\n", "5895264899260932352 213.21521027193236 ... -- --\n", "5895265925746051584 213.17082359534547 ... 0.2986918215101751 --" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You might notice that some values of `parallax` are negative. As [this FAQ explains](https://www.cosmos.esa.int/web/gaia/archive-tips#negative%20parallax), \"Negative parallaxes are caused by errors in the observations.\" They have \"no physical meaning,\" but they can be a \"useful diagnostic on the quality of the astrometric solution.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "The clauses in a query have to be in the right order. Go back and change the order of the clauses in `query2` and run it again.\n", "The modified query should fail, but notice that you don't get much useful debugging information.\n", "\n", "For this reason, developing and debugging ADQL queries can be really hard. A few suggestions that might help:\n", "\n", "* Whenever possible, start with a working query, either an example you find online or a query you have used in the past.\n", "\n", "* Make small changes and test each change before you continue.\n", "\n", "* While you are debugging, use `TOP` to limit the number of rows in the result. That will make each test run faster, which reduces your development time. \n", "\n", "* Launching test queries synchronously might make them start faster, too." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [], "source": [ "# Solution\n", "\n", "# In this example, the WHERE clause is in the wrong place\n", "\n", "query = \"\"\"SELECT \n", "TOP 3000\n", "WHERE parallax < 1\n", "source_id, ref_epoch, ra, dec, parallax\n", "FROM gaiadr2.gaia_source\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operators\n", "\n", "In a `WHERE` clause, you can use any of the [SQL comparison operators](https://www.w3schools.com/sql/sql_operators.asp); here are the most common ones:\n", "\n", "| Symbol | Operation\n", "|--------| :---\n", "| `>` | greater than\n", "| `<` | less than\n", "| `>=` | greater than or equal\n", "| `<=` | less than or equal\n", "| `=` | equal\n", "| `!=` or `<>` | not equal\n", "\n", "Most of these are the same as Python, but some are not. In particular, notice that the equality operator is `=`, not `==`.\n", "Be careful to keep your Python out of your ADQL!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can combine comparisons using the logical operators:\n", "\n", "* AND: true if both comparisons are true\n", "* OR: true if either or both comparisons are true\n", "\n", "Finally, you can use `NOT` to invert the result of a comparison. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "[Read about SQL operators here](https://www.w3schools.com/sql/sql_operators.asp) and then modify the previous query to select rows where `bp_rp` is between `-0.75` and `2`." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [], "source": [ "# Solution\n", "\n", "# Here's a solution using > and < operators\n", "\n", "query = \"\"\"SELECT \n", "TOP 10\n", "source_id, ref_epoch, ra, dec, parallax\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1 \n", " AND bp_rp > -0.75 AND bp_rp < 2\n", "\"\"\"\n", "\n", "# And here's a solution using the BETWEEN operator\n", "\n", "query = \"\"\"SELECT \n", "TOP 10\n", "source_id, ref_epoch, ra, dec, parallax\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1 \n", " AND bp_rp BETWEEN -0.75 AND 2\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`bp_rp` contains BP-RP color, which is the difference between two other columns, `phot_bp_mean_mag` and `phot_rp_mean_mag`.\n", "You can [read about this variable here](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html).\n", "\n", "This [Hertzsprung-Russell diagram](https://sci.esa.int/web/gaia/-/60198-gaia-hertzsprung-russell-diagram) shows the BP-RP color and luminosity of stars in the Gaia catalog (Copyright: ESA/Gaia/DPAC, CC BY-SA 3.0 IGO).\n", "\n", "\n", "\n", "Selecting stars with `bp-rp` less than 2 excludes many [class M dwarf stars](https://xkcd.com/2360/), which are low temperature, low luminosity. A star like that at GD-1's distance would be hard to detect, so if it is detected, it it more likely to be in the foreground." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Formatting queries\n", "\n", "The queries we have written so far are string \"literals\", meaning that the entire string is part of the program.\n", "But writing queries yourself can be slow, repetitive, and error-prone.\n", "\n", "It is often better to write Python code that assembles a query for you. One useful tool for that is the [string `format` method](https://www.w3schools.com/python/ref_string_format.asp).\n", "\n", "As an example, we'll divide the previous query into two parts; a list of column names and a \"base\" for the query that contains everything except the column names.\n", "\n", "Here's the list of columns we'll select. " ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "columns = 'source_id, ra, dec, pmra, pmdec, parallax'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here's the base; it's a string that contains at least one format specifier in curly brackets (braces)." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "query3_base = \"\"\"SELECT \n", "TOP 10 \n", "{columns}\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1\n", " AND bp_rp BETWEEN -0.75 AND 2\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This base query contains one format specifier, `{columns}`, which is a placeholder for the list of column names we will provide.\n", "\n", "To assemble the query, we invoke `format` on the base string and provide a keyword argument that assigns a value to `columns`." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "query3 = query3_base.format(columns=columns)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example, the variable that contains the column names and the variable in the format specifier have the same name.\n", "That's not required, but it is a common style.\n", "\n", "The result is a string with line breaks. If you display it, the line breaks appear as `\\n`." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'SELECT \\nTOP 10 \\nsource_id, ra, dec, pmra, pmdec\\nFROM gaiadr2.gaia_source\\nWHERE parallax < 1\\n AND bp_rp BETWEEN -0.75 AND 2\\n'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "query3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But if you print it, the line breaks appear as... line breaks." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SELECT \n", "TOP 10 \n", "source_id, ra, dec, pmra, pmdec\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1\n", " AND bp_rp BETWEEN -0.75 AND 2\n", "\n" ] } ], "source": [ "print(query3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the format specifier has been replaced with the value of `columns`.\n", "\n", "Let's run it and see if it works:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "
\n", " name dtype unit description \n", "--------- ------- -------- ------------------------------------------------------------------\n", "source_id int64 Unique source identifier (unique within a particular Data Release)\n", " ra float64 deg Right ascension\n", " dec float64 deg Declination\n", " pmra float64 mas / yr Proper motion in right ascension direction\n", " pmdec float64 mas / yr Proper motion in declination direction\n", "Jobid: None\n", "Phase: COMPLETED\n", "Owner: None\n", "Output file: sync_20210315091929.xml.gz\n", "Results: None\n" ] } ], "source": [ "job = Gaia.launch_job(query3)\n", "print(job)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/html": [ "Table length=10\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
source_idradecpmrapmdec
degdegmas / yrmas / yr
int64float64float64float64float64
5895272561481374080213.2606587905109-56.550444015357150.38944388983017151.2299266281737415
5895261875598904576213.5508930114549-56.610377801543480.16203641364393007-4.672602679543312
5895247444506644992213.33215109206796-56.975347759380995-7.474003156859284-3.538080792097856
5895259470417635968213.78815034206346-56.64585047451594-5.287202255231853-0.8163762113468646
5895265925746051584213.17082359534547-56.74540885107754-7.880749306158471-4.8585444120179595
5895260913525974528213.66936020541976-56.66655190442016-4.7820929042428215-1.5566420086447643
5895264212062283008213.7755742121852-56.51570859067397-6.657690998559842-1.7616494482071872
5895253457497979136213.30929960610283-56.78849448744587-5.242106718924749-0.18655636353898095
4143614130253524096269.1749117455479-18.534151399721172.61642745108048261.3244248889980894
4065443904433108992273.26868565443743-24.421651815402857-1.663096652191022-2.6514745376067683
" ], "text/plain": [ "\n", " source_id ra ... pmdec \n", " deg ... mas / yr \n", " int64 float64 ... float64 \n", "------------------- ------------------ ... --------------------\n", "5895272561481374080 213.2606587905109 ... 1.2299266281737415\n", "5895261875598904576 213.5508930114549 ... -4.672602679543312\n", "5895247444506644992 213.33215109206796 ... -3.538080792097856\n", "5895259470417635968 213.78815034206346 ... -0.8163762113468646\n", "5895265925746051584 213.17082359534547 ... -4.8585444120179595\n", "5895260913525974528 213.66936020541976 ... -1.5566420086447643\n", "5895264212062283008 213.7755742121852 ... -1.7616494482071872\n", "5895253457497979136 213.30929960610283 ... -0.18655636353898095\n", "4143614130253524096 269.1749117455479 ... 1.3244248889980894\n", "4065443904433108992 273.26868565443743 ... -2.6514745376067683" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Good so far." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "This query always selects sources with `parallax` less than 1. But suppose you want to take that upper bound as an input.\n", "\n", "Modify `query3_base` to replace `1` with a format specifier like `{max_parallax}`. Now, when you call `format`, add a keyword argument that assigns a value to `max_parallax`, and confirm that the format specifier gets replaced with the value you provide." ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SELECT \n", "TOP 10\n", "source_id, ra, dec, pmra, pmdec\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 0.5 AND \n", "bp_rp BETWEEN -0.75 AND 2\n", "\n" ] } ], "source": [ "# Solution\n", "\n", "query_base = \"\"\"SELECT \n", "TOP 10\n", "{columns}\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < {max_parallax} AND \n", "bp_rp BETWEEN -0.75 AND 2\n", "\"\"\"\n", "\n", "query = query_base.format(columns=columns,\n", " max_parallax=0.5)\n", "print(query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "This notebook demonstrates the following steps:\n", "\n", "1. Making a connection to the Gaia server,\n", "\n", "2. Exploring information about the database and the tables it contains,\n", "\n", "3. Writing a query and sending it to the server, and finally\n", "\n", "4. Downloading the response from the server as an Astropy `Table`.\n", "\n", "In the next lesson we will extend these queries to select a particular region of the sky." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Best practices\n", "\n", "* If you can't download an entire dataset (or it's not practical) use queries to select the data you need.\n", "\n", "* Read the metadata and the documentation to make sure you understand the tables, their columns, and what they mean.\n", "\n", "* Develop queries incrementally: start with something simple, test it, and add a little bit at a time.\n", "\n", "* Use ADQL features like `TOP` and `COUNT` to test before you run a query that might return a lot of data.\n", "\n", "* If you know your query will return fewer than 2000 rows, you can run it synchronously, which might complete faster. If it might return more than 2000 rows, you should run it asynchronously.\n", "\n", "* ADQL and SQL are not case-sensitive, so you don't have to capitalize the keywords, but you should.\n", "\n", "* ADQL and SQL don't require you to break a query into multiple lines, but you should." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter notebooks can be good for developing and testing code, but they have some drawbacks. In particular, if you run the cells out of order, you might find that variables don't have the values you expect.\n", "\n", "To mitigate these problems:\n", "\n", "* Make each section of the notebook self-contained. Try not to use the same variable name in more than one section.\n", "\n", "* Keep notebooks short. Look for places where you can break your analysis into phases with one notebook per phase." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Tags", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 2 }