{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# GAMA-12 master catalogue: Flags"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from astropy.table import Table\n",
    "\n",
    "import itertools\n",
    "\n",
    "from herschelhelp_internal.flagging import flag_outliers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "SUFFIX = \"20180218\"\n",
    "FIELD = \"GAMA-12\"\n",
    "catname = \"../../dmu1/dmu1_ml_GAMA-12/data/master_catalogue_gama-12_{}.fits\".format(SUFFIX)\n",
    "master_catalogue = Table.read(catname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "u_bands = [           \"KIDS u\"]\n",
    "g_bands = [\"DECam g\", \"KIDS g\", \"SUPRIME g\", \"GPC1 g\"]\n",
    "r_bands = [\"DECam r\", \"KIDS r\", \"SUPRIME r\", \"GPC1 r\"]\n",
    "i_bands = [           \"KIDS i\", \"SUPRIME i\", \"GPC1 i\"]\n",
    "z_bands = [\"DECam z\",           \"SUPRIME z\", \"GPC1 z\", \"VIRCAM Z\"]\n",
    "y_bands = [                     \"SUPRIME y\", \"GPC1 y\", \"VIRCAM Y\", \"WFCAM Y\"]\n",
    "J_bands = [                                            \"VIRCAM J\", \"WFCAM J\"]\n",
    "H_bands = [                                            \"VIRCAM H\", \"WFCAM H\"]\n",
    "K_bands = [                                            \"VIRCAM K\", \"WFCAM K\"]\n",
    "\n",
    "all_bands = [u_bands, g_bands, r_bands, i_bands, z_bands, y_bands, J_bands, H_bands, K_bands]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Magnitudes and magnitude erros"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def flag_mag(flagcol, mask):\n",
    "    \n",
    "    # Add flag columns if does not exist\n",
    "    if flagcol not in master_catalogue.colnames:\n",
    "        master_catalogue[flagcol] = np.zeros(len(master_catalogue), dtype=bool)\n",
    "    \n",
    "    # Flagged\n",
    "    master_catalogue[flagcol][mask] = np.ones(len(mask), dtype=bool)\n",
    "    print('    Number of flagged objects:', len(master_catalogue[flagcol][mask]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.a Pan-STARRS Aperture and Total magnitude errors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GPC1 g\n",
      "  Aperture magnitude\n",
      "    Number of flagged objects: 555\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 611\n",
      "GPC1 r\n",
      "  Aperture magnitude\n",
      "    Number of flagged objects: 1042\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 1038\n",
      "GPC1 i\n",
      "  Aperture magnitude\n",
      "    Number of flagged objects: 980\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 1036\n",
      "GPC1 z\n",
      "  Aperture magnitude\n",
      "    Number of flagged objects: 781\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 810\n",
      "GPC1 y\n",
      "  Aperture magnitude\n",
      "    Number of flagged objects: 300\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 295\n"
     ]
    }
   ],
   "source": [
    "## dmu0: Pan-STARRS forced photometry cat \n",
    "gpc1_err = 0.0010860000038519502\n",
    "bands = [\"GPC1 g\", \"GPC1 r\", \"GPC1 i\", \"GPC1 z\", \"GPC1 y\"]\n",
    "\n",
    "for i, band in enumerate(bands):\n",
    "    print(band)\n",
    "    basecol = band.replace(\" \", \"_\").lower()\n",
    "    \n",
    "    ecol_ap, ecol_tot = \"merr_ap_{}\".format(basecol), \"merr_{}\".format(basecol)\n",
    "    flagcol_ap, flagcol_tot = \"flag_ap_{}\".format(basecol), \"flag_{}\".format(basecol)\n",
    "    \n",
    "    mask_ap  = np.where(master_catalogue[ecol_ap]  == gpc1_err)[0]\n",
    "    mask_tot = np.where(master_catalogue[ecol_tot] == gpc1_err)[0]\n",
    "    \n",
    "    print('  Aperture magnitude')\n",
    "    flag_mag(flagcol_ap, mask_ap)\n",
    "    print('  Total magnitude')\n",
    "    flag_mag(flagcol_tot, mask_tot)\n",
    "    \n",
    "    master_catalogue[flagcol_tot] = master_catalogue[flagcol_tot] | master_catalogue[flagcol_ap]\n",
    "    master_catalogue.remove_column(flagcol_ap)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.a DECaLS Total magnitudes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DECam g\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/anaconda3/envs/herschelhelp_internal/lib/python3.6/site-packages/astropy/table/column.py:965: RuntimeWarning: invalid value encountered in less\n",
      "  return getattr(self.data, op)(other)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Total magnitude\n",
      "    Number of flagged objects: 126\n",
      "DECam r\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 115\n",
      "DECam z\n",
      "  Total magnitude\n",
      "    Number of flagged objects: 1\n"
     ]
    }
   ],
   "source": [
    "decam_mag = 14.999935\n",
    "bands = [\"DECam g\", \"DECam r\", \"DECam z\"]\n",
    "\n",
    "for i, band in enumerate(bands):\n",
    "    print(band)\n",
    "    basecol = band.replace(\" \", \"_\").lower()\n",
    "    \n",
    "    col = \"m_{}\".format(basecol)\n",
    "    flagcol = \"flag_{}\".format(basecol)\n",
    "    \n",
    "    mask  = np.where((master_catalogue[col]  == decam_mag) | (master_catalogue[col] < 7))[0]\n",
    "    \n",
    "    print('  Total magnitude')\n",
    "    flag_mag(flagcol, mask)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Outliers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "One of m_ap_decam_g and m_ap_kids_g is not present in the catalogue.\n",
      "One of m_decam_g and m_kids_g is not present in the catalogue.\n",
      "SUPRIME g (aperture) - DECam g (aperture):\n",
      "  Number of outliers: 4\n",
      "No sources have both DECam g (total) and SUPRIME g (total) values.\n",
      "\n",
      "GPC1 g (aperture) - DECam g (aperture):\n",
      "  Number of outliers: 1009\n",
      "GPC1 g (total) - DECam g (total):\n",
      "  Number of outliers: 30\n",
      "One of m_ap_kids_g and m_ap_suprime_g is not present in the catalogue.\n",
      "One of m_kids_g and m_suprime_g is not present in the catalogue.\n",
      "One of m_ap_kids_g and m_ap_gpc1_g is not present in the catalogue.\n",
      "One of m_kids_g and m_gpc1_g is not present in the catalogue.\n",
      "GPC1 g (aperture) - SUPRIME g (aperture):\n",
      "  Number of outliers: 0\n",
      "No sources have both SUPRIME g (total) and GPC1 g (total) values.\n",
      "\n",
      "One of m_ap_decam_r and m_ap_kids_r is not present in the catalogue.\n",
      "One of m_decam_r and m_kids_r is not present in the catalogue.\n",
      "SUPRIME r (aperture) - DECam r (aperture):\n",
      "  Number of outliers: 0\n",
      "SUPRIME r (total) - DECam r (total):\n",
      "  Number of outliers: 148\n",
      "GPC1 r (aperture) - DECam r (aperture):\n",
      "  Number of outliers: 2883\n",
      "GPC1 r (total) - DECam r (total):\n",
      "  Number of outliers: 12\n",
      "One of m_ap_kids_r and m_ap_suprime_r is not present in the catalogue.\n",
      "One of m_kids_r and m_suprime_r is not present in the catalogue.\n",
      "One of m_ap_kids_r and m_ap_gpc1_r is not present in the catalogue.\n",
      "One of m_kids_r and m_gpc1_r is not present in the catalogue.\n",
      "GPC1 r (aperture) - SUPRIME r (aperture):\n",
      "  Number of outliers: 0\n",
      "GPC1 r (total) - SUPRIME r (total):\n",
      "  Number of outliers: 5\n",
      "One of m_ap_kids_i and m_ap_suprime_i is not present in the catalogue.\n",
      "One of m_kids_i and m_suprime_i is not present in the catalogue.\n",
      "One of m_ap_kids_i and m_ap_gpc1_i is not present in the catalogue.\n",
      "One of m_kids_i and m_gpc1_i is not present in the catalogue.\n",
      "GPC1 i (aperture) - SUPRIME i (aperture):\n",
      "  Number of outliers: 0\n",
      "GPC1 i (total) - SUPRIME i (total):\n",
      "  Number of outliers: 19\n",
      "SUPRIME z (aperture) - DECam z (aperture):\n",
      "  Number of outliers: 0\n",
      "SUPRIME z (total) - DECam z (total):\n",
      "  Number of outliers: 4\n",
      "GPC1 z (aperture) - DECam z (aperture):\n",
      "  Number of outliers: 1607\n",
      "GPC1 z (total) - DECam z (total):\n",
      "  Number of outliers: 1\n",
      "One of m_ap_decam_z and m_ap_vircam_z is not present in the catalogue.\n",
      "One of m_decam_z and m_vircam_z is not present in the catalogue.\n",
      "GPC1 z (aperture) - SUPRIME z (aperture):\n",
      "  Number of outliers: 0\n",
      "GPC1 z (total) - SUPRIME z (total):\n",
      "  Number of outliers: 6\n",
      "One of m_ap_suprime_z and m_ap_vircam_z is not present in the catalogue.\n",
      "One of m_suprime_z and m_vircam_z is not present in the catalogue.\n",
      "One of m_ap_gpc1_z and m_ap_vircam_z is not present in the catalogue.\n",
      "One of m_gpc1_z and m_vircam_z is not present in the catalogue.\n",
      "GPC1 y (aperture) - SUPRIME y (aperture):\n",
      "  Number of outliers: 0\n",
      "GPC1 y (total) - SUPRIME y (total):\n",
      "  Number of outliers: 2\n",
      "One of m_ap_suprime_y and m_ap_vircam_y is not present in the catalogue.\n",
      "One of m_suprime_y and m_vircam_y is not present in the catalogue.\n",
      "One of m_ap_suprime_y and m_ap_wfcam_y is not present in the catalogue.\n",
      "One of m_suprime_y and m_wfcam_y is not present in the catalogue.\n",
      "One of m_ap_gpc1_y and m_ap_vircam_y is not present in the catalogue.\n",
      "One of m_gpc1_y and m_vircam_y is not present in the catalogue.\n",
      "One of m_ap_gpc1_y and m_ap_wfcam_y is not present in the catalogue.\n",
      "One of m_gpc1_y and m_wfcam_y is not present in the catalogue.\n",
      "One of m_ap_vircam_y and m_ap_wfcam_y is not present in the catalogue.\n",
      "One of m_vircam_y and m_wfcam_y is not present in the catalogue.\n",
      "One of m_ap_vircam_j and m_ap_wfcam_j is not present in the catalogue.\n",
      "One of m_vircam_j and m_wfcam_j is not present in the catalogue.\n",
      "One of m_ap_vircam_h and m_ap_wfcam_h is not present in the catalogue.\n",
      "One of m_vircam_h and m_wfcam_h is not present in the catalogue.\n",
      "One of m_ap_vircam_k and m_ap_wfcam_k is not present in the catalogue.\n",
      "One of m_vircam_k and m_wfcam_k is not present in the catalogue.\n"
     ]
    }
   ],
   "source": [
    "for band_of_a_kind in all_bands:\n",
    "    for band1, band2 in itertools.combinations(band_of_a_kind, 2):\n",
    "        #print(band1, band2)\n",
    "\n",
    "        basecol1, basecol2 = band1.replace(\" \", \"_\").lower(), band2.replace(\" \", \"_\").lower()\n",
    "        \n",
    "        # Aperture mag\n",
    "        col1, col2 = \"m_ap_{}\".format(basecol1), \"m_ap_{}\".format(basecol2)\n",
    "        ecol1, ecol2 = \"merr_ap_{}\".format(basecol1), \"merr_ap_{}\".format(basecol2)\n",
    "        flagcol1, flagcol2 = \"flag_ap_{}\".format(basecol1), \"flag_ap_{}\".format(basecol2)\n",
    "        \n",
    "        try:\n",
    "            master_catalogue = flag_outliers(master_catalogue, col1, col2,\n",
    "                      ecol1, ecol2,\n",
    "                      flagcol1, flagcol2,\n",
    "                      labels=(\"{} (aperture)\".format(band1), \"{} (aperture)\".format(band2)))\n",
    "            \n",
    "        except KeyError:\n",
    "            print(\"One of {} and {} is not present in the catalogue.\".format(col1, col2))\n",
    "            \n",
    "                      \n",
    "        \n",
    "        # Tot mag\n",
    "        col1, col2 = \"m_{}\".format(basecol1), \"m_{}\".format(basecol2)              \n",
    "        ecol1, ecol2 = \"merr_{}\".format(basecol1), \"merr_{}\".format(basecol2)              \n",
    "        flagcol1, flagcol2 = \"flag_{}\".format(basecol1), \"flag_{}\".format(basecol2)\n",
    "              \n",
    "        try:\n",
    "            master_catalogue = flag_outliers(master_catalogue, col1, col2, \n",
    "                      ecol1, ecol2,\n",
    "                      flagcol1, flagcol2,\n",
    "                      labels=(\"{} (total)\".format(band1), \"{} (total)\".format(band2)))   \n",
    "            \n",
    "        except KeyError:\n",
    "            print(\"One of {} and {} is not present in the catalogue.\".format(col1, col2))                    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Save table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#Merge any aperture flags\n",
    "for col in master_catalogue.colnames:\n",
    "    if col.startswith(\"flag_ap_\"):\n",
    "        try:\n",
    "            master_catalogue[col.replace(\"_ap_\", \"_\")] = (master_catalogue[col.replace(\"_ap_\", \"_\")] |\n",
    "                                                          master_catalogue[col])\n",
    "            master_catalogue.remove_column(col)\n",
    "        except KeyError:\n",
    "            print(\"{} only has aperture flags.\".format(col))\n",
    "            master_catalogue.rename_column(col, col.replace(\"_ap_\", \"_\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "flag_cols = [\"help_id\"]\n",
    "for col in master_catalogue.colnames:\n",
    "    if col.startswith(\"flag_\"):\n",
    "        flag_cols += [col]\n",
    "new_catname = \"./data/{}_{}_flags.fits\".format(FIELD.lower(),SUFFIX)\n",
    "master_catalogue[flag_cols].write(new_catname, overwrite = True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (herschelhelp_internal)",
   "language": "python",
   "name": "helpint"
  },
  "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.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
