{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Match truth and object catalogs for DC2 Run 1.2i\n", "Owner: Yao-Yuan Mao, Scott Daniel (with help from Anže Slosar, Bhairav Valera, HyeYun Park)
\n", "Last Verified to Run: 2018-11-19\n", "\n", "**Notes:**\n", "- Follow this [step-by-step guide](https://confluence.slac.stanford.edu/x/Xgg4Dg) if you don't know how to run this notebook.\n", "- If you need more information about the Generic Catalog Reader (GCR), see [this diagram](https://github.com/yymao/generic-catalog-reader/blob/master/README.md#concept) and [more examples](https://github.com/LSSTDESC/gcr-catalogs/blob/master/examples/GCRCatalogs%20Demo.ipynb).\n", "\n", "## Learning objectives\n", "After completing and studying this Notebook, you should be able to:\n", " 1. Use GCR to load object catalog and truth catalog\n", " 2. Use `filters` and `native_filters` appropriately\n", " 3. Use `add_quantity_modifier` and `get_quantity_modifier`\n", " 4. Use `FoFCatalogMatching` to do Friends-of-friends catalog matching\n", " 5. Learn some cool Numpy tricks for binning, masking, and reshaping [Advanced]\n", " 6. Learn use pandas to match truth catalog object id back to the galaxy id in extragalactic catalog [advanced]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from astropy.coordinates import SkyCoord\n", "import FoFCatalogMatching\n", "import GCRCatalogs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# load object catalog (for a single tract)\n", "object_cat = GCRCatalogs.load_catalog('dc2_object_run1.2i_all_columns')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's first visually inspect the footprint of one tract of the object catalog.\n", "# When `return_iterator` is turned on, the method `get_quantities` will return an \n", "# iterator, and each element in the iterator will be the quantities we requested in \n", "# different chunks of the dataset. \n", "\n", "# For object catalogs, the different chunks happen to be different patches, \n", "# resulting in a different color for each patch in the scatter plot below.\n", "\n", "for object_data in object_cat.get_quantities(['ra', 'dec'], native_filters=['tract == 4850'], return_iterator=True):\n", " plt.scatter(object_data['ra'], object_data['dec'], s=1, rasterized=True);\n", "\n", "plt.xlabel('RA');\n", "plt.ylabel('Dec');" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Let's choose a small RA and Dec range to do the matching so that it won't take too long!\n", "ra_min, ra_max = 55.5, 56.0\n", "dec_min, dec_max = -29.0, -28.5\n", "\n", "coord_filters = [\n", " 'ra >= {}'.format(ra_min),\n", " 'ra < {}'.format(ra_max),\n", " 'dec >= {}'.format(dec_min),\n", " 'dec < {}'.format(dec_max),\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's also define a magnitude cut\n", "mag_filters = [\n", " (np.isfinite, 'mag_i'),\n", " 'mag_i < 24.5',\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# let's add total ellipticity for later use (not needed for now)\n", "object_cat.add_derived_quantity('shape_hsm_regauss_etot', np.hypot, 'ext_shapeHSM_HsmShapeRegauss_e1', 'ext_shapeHSM_HsmShapeRegauss_e2')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load ra and dec from object, using both of the filters we just defined.\n", "object_data = object_cat.get_quantities(['ra', 'dec', 'mag_i_cModel', 'shape_hsm_regauss_etot'], filters=(coord_filters + mag_filters), native_filters=['tract == 4850'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Let's now turn to the truth catalog\n", "truth_cat = GCRCatalogs.load_catalog('dc2_truth_run1.2_static')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# for a reason that we will soon see, let's inspect the quantities in truth catalog\n", "\n", "print(sorted(truth_cat.list_all_quantities()))\n", "print('---')\n", "print(sorted(truth_cat.list_all_native_quantities()))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# so we see there is no mag_i, but only mag_true_i (i.e., magnitude before lensing)\n", "# to make our `mag_filters` work, let's define mag_i for the truth catalog\n", "truth_cat.add_quantity_modifier('mag_i', truth_cat.get_quantity_modifier('mag_true_i'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# get ra and dec from truth catalog\n", "# note that we add i < 24.5 to the native filter to speed up load time\n", "truth_native_filters = (coord_filters + ['i < 24.5'])\n", "truth_data = truth_cat.get_quantities(['ra', 'dec', 'object_id', 'star', 'sprinkled'], filters=mag_filters, native_filters=truth_native_filters)\n", "\n", "# We will use the object_id, star, and sprinkled columns when cross-referencing truth information with the extragalactic catalog." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# now we can really do the matching!\n", "# FoFCatalogMatching.match takes a dictionary of catalogs to match, a friends-of-friends linking length. \n", "# Because our \"catalog\" is not an astropy table or pandas dataframe, \n", "# `len(truth_coord)` won't give the actual length of the table\n", "# so we need to specify `catalog_len_getter` so that the code knows how to get the length of the catalog.\n", "\n", "results = FoFCatalogMatching.match(\n", " catalog_dict={'truth': truth_data, 'object': object_data},\n", " linking_lengths=1.0,\n", " catalog_len_getter=lambda x: len(x['ra']),\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# return of FoFCatalogMatching.match is an astropy table\n", "results" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# now we want to count the number of truth and object objects *for each group*\n", "# but instead of looping over groups, we can do this in a smart (and very fast) way\n", "\n", "# first we need to know which rows are from the truth catalog and which are from the object\n", "truth_mask = results['catalog_key'] == 'truth'\n", "object_mask = ~truth_mask\n", "\n", "# then np.bincount will give up the number of id occurrences (like historgram but with integer input)\n", "n_groups = results['group_id'].max() + 1\n", "n_truth = np.bincount(results['group_id'][truth_mask], minlength=n_groups)\n", "n_object = np.bincount(results['group_id'][object_mask], minlength=n_groups)\n", "\n", "# now n_truth and n_object are the number of truth/object objects in each group\n", "# we want to make a 2d histrogram of (n_truth, n_object). \n", "n_max = max(n_truth.max(), n_object.max()) + 1\n", "hist_2d = np.bincount(n_object * n_max + n_truth, minlength=n_max*n_max).reshape(n_max, n_max)\n", "\n", "plt.imshow(np.log10(hist_2d+1), extent=(-0.5, n_max-0.5, -0.5, n_max-0.5), origin='lower');\n", "plt.xlabel('Number of truth objects');\n", "plt.ylabel('Number of object objects');\n", "plt.colorbar(label=r'$\\log(N_{\\rm groups} \\, + \\, 1)$');" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's further inspect the objects in the groups that have 1-to-1 truth/object match.\n", "\n", "# first, let's find our the IDs of the groups that have 1-to-1 truth/object match:\n", "one_to_one_group_mask = np.in1d(results['group_id'], np.flatnonzero((n_truth == 1) & (n_object == 1)))\n", "\n", "# and then we can find the row indices in the *original* truth/object catalogs for those 1-to-1 groups\n", "truth_idx = results['row_index'][one_to_one_group_mask & truth_mask]\n", "object_idx = results['row_index'][one_to_one_group_mask & object_mask]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "truth_sc = SkyCoord(truth_data['ra'][truth_idx], truth_data['dec'][truth_idx], unit=\"deg\")\n", "object_sc = SkyCoord(object_data['ra'][object_idx], object_data['dec'][object_idx], unit=\"deg\")\n", "\n", "delta_ra = (object_sc.ra.arcsec - truth_sc.ra.arcsec) * np.cos(np.deg2rad(0.5*(truth_sc.dec.deg + object_sc.dec.deg)))\n", "delta_dec = object_sc.dec.arcsec - truth_sc.dec.arcsec\n", "delta_arcsec = object_sc.separation(truth_sc).arcsec" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(7.3, 6)) # Pick a figuresize that will result in a square equal-axis plus colorbar\n", "plt.hist2d(delta_ra, delta_dec, bins=40, range=((-0.5, +0.5), (-0.5, +0.5)));\n", "plt.xlabel(r'$\\Delta$ RA [arcsec]');\n", "plt.ylabel(r'$\\Delta$ Dec [arcsec]');\n", "plt.colorbar();\n", "plt.xlim(-0.5, +0.5)\n", "plt.ylim(-0.5, +0.5)\n", "plt.axis('equal');" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Plotting Delta angle for the outputs\n", "plt.hist(delta_arcsec, bins=80);\n", "plt.xlim(0, 0.4);\n", "plt.xlabel(r'$\\Delta$ angle [arcsec]');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Going one step further\n", "\n", "Most of the astrophysical truth information about the objects in DC2 is actually stored in the extragalactic catalog. The truth catalog only contains the positions and magnitudes that we believe should have been produced by the image simulators. To access further truth information (redshift, shape parameters, mass), we must cross-reference the truth catalog with the extragalactic catalog. This can be done via the column `object_id` in the truth catalog, which maps directly to `galaxy_id` in the extragalactic catalog.\n", "\n", "Let's use pandas for this part to make our lives a bit easier :) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# convert truth_data and object_data to pandas dataframe and select the matched one\n", "truth_matched = pd.DataFrame(truth_data).iloc[truth_idx].reset_index(drop=True)\n", "object_matched = pd.DataFrame(object_data).iloc[object_idx].reset_index(drop=True)\n", "matched = pd.merge(truth_matched, object_matched, left_index=True, right_index=True, suffixes=('_truth', '_object'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Select only those truth objects that are galaxies which were not sprinkled\n", "# (stars and sprinkled objects do not occur in the extragalactic catalog)\n", "matched_gals = matched.query('~star').query('~sprinkled')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First, load the extragalactic catalog that was used for this simulation (using _test to skip md5 check)\n", "extragalactic_cat = GCRCatalogs.load_catalog('proto-dc2_v3.0_test')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# load redshift and shear parameters from the extragalactic catalog, only for galaxise that are already in `matched_gals`\n", "extragalactic_data = extragalactic_cat.get_quantities(\n", " ['galaxy_id', 'mag_i_lsst', 'ellipticity_true', 'shear_1', 'shear_2'],\n", " filters=[(lambda x: np.in1d(x, matched_gals['object_id'].values, True), 'galaxy_id')]\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# merge extragalactic_data to matched_gals\n", "matched_gals = pd.merge(matched_gals, pd.DataFrame(extragalactic_data), 'left', left_on='object_id', right_on='galaxy_id')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.testing.assert_array_equal(matched_gals['object_id'], matched_gals['galaxy_id'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# check out the table \n", "matched_gals" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# compare the magnitude\n", "plt.figure(figsize=(5,5));\n", "plt.scatter(matched_gals['mag_i_lsst'], matched_gals['mag_i_cModel'], s=1);\n", "lims = [14, 25]\n", "plt.plot(lims, lims, c='k', lw=0.5);\n", "plt.xlabel('extragalactic $i$-mag');\n", "plt.ylabel('object $i$-mag (cModel)');\n", "plt.xlim(lims);\n", "plt.ylim(lims);" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# compare the ellipticity\n", "plt.figure(figsize=(5,5));\n", "plt.scatter(matched_gals['ellipticity_true'], matched_gals['shape_hsm_regauss_etot'], s=1);\n", "lims = [0, 1]\n", "plt.plot(lims, lims, c='k', lw=0.5);\n", "plt.xlabel('extragalactic ellipticity');\n", "plt.ylabel('object ellipticity');\n", "plt.xlim(lims);\n", "plt.ylim(lims);" ] } ], "metadata": { "kernelspec": { "display_name": "desc-python", "language": "python", "name": "desc-python" }, "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.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }