<jupyter_start><jupyter_text>2. Coordinates and UnitsIn the previous lesson, we wrote ADQL queries and used them to select and download data from the Gaia server.In this lesson, we'll pick up where we left off and write a query to select stars from a particular region of the sky.  OutlineWe'll start with an example that does a "cone search"; that is, it selects stars that appear in a circular region of the sky.Then, to select stars in the vicinity of GD-1, we'll:* Use `Quantity` objects to represent measurements with units.* Use Astropy to convert coordinates from one frame to another.* Use the ADQL keywords `POLYGON`, `CONTAINS`, and `POINT` to select stars that fall within a polygonal region.* Submit a query and download the results.* Store the results in a FITS file.After completing this lesson, you should be able to* Use Python string formatting to compose more complex ADQL queries.* Work with coordinates and other quantities that have units.* Download the results of a query and store them in a file.  Installing librariesIf you are running this notebook on Colab, you can run the following cell to install the libraries we'll use.If you are running this notebook on your own computer, you might have to install these libraries yourself.  See the instructions in the preface.<jupyter_code># If we're running on Colab, install libraries

# TODO: When Colab can install gala, switch from astro-gala

import sys
IN_COLAB = 'google.colab' in sys.modules

if IN_COLAB:
    !pip install astroquery astro-gala<jupyter_output><empty_output><jupyter_text>Working with UnitsThe measurements we will work with are physical quantities, which means that they have two parts, a value and a unit.For example, the coordinate $30^{\circ}$ has value 30 and its units are degrees.Until recently, most scientific computation was done with values only; units were left out of the program altogether, [often with catastrophic results](https://en.wikipedia.org/wiki/Mars_Climate_OrbiterCause_of_failure).Astropy provides tools for including units explicitly in computations, which makes it possible to detect errors before they cause disasters.To use Astropy units, we import them like this:<jupyter_code>import astropy.units as u<jupyter_output><empty_output><jupyter_text>`u` is an object that contains most common units and all SI units.You can use `dir` to list them, but you should also [read the documentation](https://docs.astropy.org/en/stable/units/).<jupyter_code>dir(u)<jupyter_output><empty_output><jupyter_text>To create a quantity, we multiply a value by a unit.<jupyter_code>angle = 10 * u.degree
type(angle)<jupyter_output><empty_output><jupyter_text>The result is a `Quantity` object.Jupyter knows how to display `Quantities` like this:<jupyter_code>angle<jupyter_output><empty_output><jupyter_text>Quantities provide a method called `to` that converts to other units.  For example, we can compute the number of arcminutes in `angle`:<jupyter_code>angle_arcmin = angle.to(u.arcmin)
angle_arcmin<jupyter_output><empty_output><jupyter_text>If you add quantities, Astropy converts them to compatible units, if possible:<jupyter_code>angle + 30 * u.arcmin<jupyter_output><empty_output><jupyter_text>If the units are not compatible, you get an error.For example:```angle + 5 * u.second```causes a `UnitConversionError`.  ExerciseCreate a quantity that represents 5 [arcminutes](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) and assign it to a variable called `radius`.Then convert it to degrees.<jupyter_code># Solution goes here<jupyter_output><empty_output><jupyter_text>Selecting a RegionOne of the most common ways to restrict a query is to select stars in a particular region of the sky.For example, here's a query from the [Gaia archive documentation](https://gea.esac.esa.int/archive-help/adql/examples/index.html) that selects objects in a circular region centered at (88.8, 7.4) with a search radius of 5 arcmin (0.08333 deg).<jupyter_code>query_cone = """SELECT 
TOP 10 
source_id
FROM gaiadr2.gaia_source
WHERE 1=CONTAINS(
  POINT(ra, dec),
  CIRCLE(88.8, 7.4, 0.08333333))
"""<jupyter_output><empty_output><jupyter_text>This query uses three keywords that are specific to ADQL (not SQL):* `POINT`: a location in [ICRS coordinates](https://en.wikipedia.org/wiki/International_Celestial_Reference_System), specified in degrees of right ascension and declination.* `CIRCLE`: a circle where the first two values are the coordinates of the center and the third is the radius in degrees.* `CONTAINS`: a function that returns `1` if a `POINT` is contained in a shape and `0` otherwise.Here is the [documentation of `CONTAINS`](http://www.ivoa.net/documents/ADQL/20180112/PR-ADQL-2.1-20180112.htmltth_sEc4.2.12).A query like this is called a cone search because it selects stars in a cone.Here's how we run it.<jupyter_code>from astroquery.gaia import Gaia

job = Gaia.launch_job(query_cone)
job
results = job.get_results()
results<jupyter_output><empty_output><jupyter_text>ExerciseWhen you are debugging queries like this, you can use `TOP` to limit the size of the results, but then you still don't know how big the results will be.An alternative is to use `COUNT`, which asks for the number of rows that would be selected, but it does not return them.In the previous query, replace `TOP 10 source_id` with `COUNT(source_id)` and run the query again.  How many stars has Gaia identified in the cone we searched?<jupyter_code># Solution goes here<jupyter_output><empty_output><jupyter_text>Getting GD-1 DataFrom the Price-Whelan and Bonaca paper, we will try to reproduce Figure 1, which includes this representation of stars likely to belong to GD-1: The axes of this figure are defined so the x-axis is aligned with the stars in GD-1, and the y-axis is perpendicular.* Along the x-axis ($\phi_1$) the figure extends from -100 to 20 degrees.* Along the y-axis ($\phi_2$) the figure extends from about -8 to 4 degrees.Ideally, we would select all stars from this rectangle, but there are more than 10 million of them, so* That would be difficult to work with,* As anonymous Gaia users, we are limited to 3 million rows in a single query, and* While we are developing and testing code, it will be faster to work with a smaller dataset.So we'll start by selecting stars in a smaller rectangle near the center of GD-1, from -55 to -45 degrees $\phi_1$ and -8 to 4 degrees $\phi_2$.But first we let's see how to represent these coordinates with Astropy.  Transforming coordinatesAstropy provides a `SkyCoord` object that represents sky coordinates relative to a specified frame.The following example creates a `SkyCoord` object that represents the approximate coordinates of [Betelgeuse](http://simbad.u-strasbg.fr/simbad/sim-basic?Ident=Betelgeuse) (alf Ori) in the ICRS frame.[ICRS](https://www.iers.org/IERS/EN/Science/ICRS/ICRS.html) is the"International Celestial Reference System", adopted in 1997 by the International Astronomical Union.<jupyter_code>from astropy.coordinates import SkyCoord

ra = 88.8 * u.degree
dec = 7.4 * u.degree
coord_icrs = SkyCoord(ra=ra, dec=dec, frame='icrs')

coord_icrs<jupyter_output><empty_output><jupyter_text>`SkyCoord` provides a function that transforms to other frames.For example, we can transform `coords_icrs` to Galactic coordinates like this:<jupyter_code>coord_galactic = coord_icrs.transform_to('galactic')
coord_galactic<jupyter_output><empty_output><jupyter_text>Notice that in the Galactic frame, the coordinates are called `l` and `b`, not `ra` and `dec`.To transform to and from GD-1 coordinates, we'll use a frame defined by [Gala](https://gala-astro.readthedocs.io/en/latest/), which is an Astropy-affiliated library that provides tools for galactic dynamics.Gala provides [`GD1Koposov10`](https://gala-astro.readthedocs.io/en/latest/_modules/gala/coordinates/gd1.html), which is "a Heliocentric spherical coordinate system defined by the orbit of the GD-1 stream".<jupyter_code>from gala.coordinates import GD1Koposov10

gd1_frame = GD1Koposov10()
gd1_frame<jupyter_output><empty_output><jupyter_text>We can use it to find the coordinates of Betelgeuse in the GD-1 frame, like this:<jupyter_code>coord_gd1 = coord_icrs.transform_to(gd1_frame)
coord_gd1<jupyter_output><empty_output><jupyter_text>Notice that the coordinates are called `phi1` and `phi2`.These are the coordinates shown in the figure from the paper, above.  ExerciseLet's find the location of GD-1 in ICRS coordinates.1. Create a `SkyCoord` object at 0°, 0° in the GD-1 frame.2. Transform it to the ICRS frame.Hint: Because ICRS is built into Astropy, you can specify it by name, `icrs` (as we did with `galactic`).<jupyter_code># Solution goes here<jupyter_output><empty_output><jupyter_text>Notice that the origin of the GD-1 frame maps to `ra=200`, exactly, in ICRS.  That's by design.  Selecting a rectangleNow we'll use these coordinate transformations to define a rectangle in the GD-1 frame and transform it to ICRS. The following variables define the boundaries of the rectangle in $\phi_1$ and $\phi_2$.<jupyter_code>phi1_min = -55 * u.degree
phi1_max = -45 * u.degree
phi2_min = -8 * u.degree
phi2_max = 4 * u.degree<jupyter_output><empty_output><jupyter_text>To create a rectangle, we'll use the following function, which takes the lower and upper bounds as parameters.<jupyter_code>def make_rectangle(x1, x2, y1, y2):
    """Return the corners of a rectangle."""
    xs = [x1, x1, x2, x2, x1]
    ys = [y1, y2, y2, y1, y1]
    return xs, ys<jupyter_output><empty_output><jupyter_text>The return value is a tuple containing a list of coordinates in `phi1` followed by a list of coordinates in `phi2`.<jupyter_code>phi1_rect, phi2_rect = make_rectangle(
    phi1_min, phi1_max, phi2_min, phi2_max)<jupyter_output><empty_output><jupyter_text>`phi1_rect` and `phi2_rect` contains the coordinates of the corners of a rectangle in the GD-1 frame.In order to use them in a Gaia query, we have to convert them to ICRS.  First we'll put them into a `SkyCoord` object.<jupyter_code>corners = SkyCoord(phi1=phi1_rect, phi2=phi2_rect, frame=gd1_frame)
corners<jupyter_output><empty_output><jupyter_text>Now we can use `transform_to` to convert to ICRS coordinates.<jupyter_code>corners_icrs = corners.transform_to('icrs')
corners_icrs<jupyter_output><empty_output><jupyter_text>Notice that a rectangle in one coordinate system is not necessarily a rectangle in another.  In this example, the result is a (non-rectangular) polygon.  Defining a polygonIn order to use this polygon as part of an ADQL query, we have to convert it to a string with a comma-separated list of coordinates, as in this example:```"""POLYGON(143.65, 20.98,         134.46, 26.39,         140.58, 34.85,         150.16, 29.01)"""````SkyCoord` provides `to_string`, which produces a list of strings.<jupyter_code>t = corners_icrs.to_string()
t<jupyter_output><empty_output><jupyter_text>We can use the Python string function `join` to join `t` into a single string (with spaces between the pairs):<jupyter_code>s = ' '.join(t)
s<jupyter_output><empty_output><jupyter_text>That's almost what we need, but we have to replace the spaces with commas.<jupyter_code>s.replace(' ', ', ')<jupyter_output><empty_output><jupyter_text>The following function combines these steps.<jupyter_code>def skycoord_to_string(skycoord):
    """Convert SkyCoord to string."""
    t = skycoord.to_string()
    s = ' '.join(t)
    return s.replace(' ', ', ')<jupyter_output><empty_output><jupyter_text>Here's how we use it.<jupyter_code>point_list = skycoord_to_string(corners_icrs)
point_list<jupyter_output><empty_output><jupyter_text>Assembling the queryNow we're ready to assemble the query. We need `columns` again (as we saw in the previous lesson).<jupyter_code>columns = 'source_id, ra, dec, pmra, pmdec, parallax'<jupyter_output><empty_output><jupyter_text>And here's the query base we used in the previous lesson:<jupyter_code>query3_base = """SELECT 
TOP 10 
{columns}
FROM gaiadr2.gaia_source
WHERE parallax < 1
  AND bp_rp BETWEEN -0.75 AND 2
"""<jupyter_output><empty_output><jupyter_text>Now we'll add a `WHERE` clause to select stars in the polygon we defined.<jupyter_code>query4_base = """SELECT
TOP 10
{columns}
FROM gaiadr2.gaia_source
WHERE parallax < 1
  AND bp_rp BETWEEN -0.75 AND 2 
  AND 1 = CONTAINS(POINT(ra, dec), 
                   POLYGON({point_list}))
"""<jupyter_output><empty_output><jupyter_text>The query base contains format specifiers for `columns` and `point_list`.We'll use `format` to fill in these values.<jupyter_code>query4 = query4_base.format(columns=columns, 
                          point_list=point_list)
print(query4)<jupyter_output><empty_output><jupyter_text>As always, we should take a minute to proof-read the query before we launch it.<jupyter_code>job = Gaia.launch_job_async(query4)
print(job)<jupyter_output><empty_output><jupyter_text>Here are the results.<jupyter_code>results = job.get_results()
results<jupyter_output><empty_output><jupyter_text>Finally, we can remove `TOP 10` run the query again.The result is bigger than our previous queries, so it will take a little longer.<jupyter_code>query5_base = """SELECT
{columns}
FROM gaiadr2.gaia_source
WHERE parallax < 1
  AND bp_rp BETWEEN -0.75 AND 2 
  AND 1 = CONTAINS(POINT(ra, dec), 
                   POLYGON({point_list}))
"""
query5 = query5_base.format(columns=columns, 
                          point_list=point_list)
print(query5)
job = Gaia.launch_job_async(query5)
print(job)
results = job.get_results()
len(results)<jupyter_output><empty_output><jupyter_text>There are more than 100,000 stars in this polygon, but that's a manageable size to work with.  Saving resultsThis is the set of stars we'll work with in the next step.  But since we have a substantial dataset now, this is a good time to save it.Storing the data in a file means we can shut down this notebook and pick up where we left off without running the previous query again.Astropy `Table` objects provide `write`, which writes the table to disk.<jupyter_code>filename = 'gd1_results.fits'
results.write(filename, overwrite=True)<jupyter_output><empty_output><jupyter_text>Because the filename ends with `fits`, the table is written in the [FITS format](https://en.wikipedia.org/wiki/FITS), which preserves the metadata associated with the table.If the file already exists, the `overwrite` argument causes it to be overwritten.We can use `getsize` to confirm that the file exists and check the size:<jupyter_code>from os.path import getsize

MB = 1024 * 1024
getsize(filename) / MB<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08486882663196109, 'fraction_numerical': 0.018014932529625317, 'mean_word_length': 5.445916114790287, 'pattern_counts': {'":': 0, '<': 144, '<?xml version=': 0, '>': 141, 'https://': 9, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '35', 'dir': 'jupyter-structured-clean-dedup', 'id': '128525', 'license': 'MIT', 'n_tokens_mistral': 4729, 'n_tokens_neox': 4450, 'n_words': 1707, 'path': '02_coords.ipynb', 'repo_name': 'Chuly90/AstronomicalData', 'size': '14599'}