{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table width=\"100%\" style=\"padding:0; margin-left:-6px;\">\n",
    "    <tr style=\"padding=0;\" width=\"100%\">\n",
    "        <td width=\"auto\">\n",
    "           <hr style=\"border:2px solid darkblue\">\n",
    "            <h1> nb9. Download data</h1>\n",
    "           <hr style=\"border:2px solid darkblue\">\n",
    "        </td>\n",
    "        <td width=\"60px\">\n",
    "           <img src=\"ALMAsmall.png\" align=\"right\"/> \n",
    "        </td>\n",
    "    </tr>\n",
    "</table>  \n",
    "\n",
    "In this notebook we show how to download ALMA data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:29.631168Z",
     "iopub.status.busy": "2021-11-16T10:27:29.630524Z",
     "iopub.status.idle": "2021-11-16T10:27:30.858423Z",
     "shell.execute_reply": "2021-11-16T10:27:30.858897Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pyvo\n",
    "import pandas as pd\n",
    "import astropy\n",
    "import os\n",
    "from astroquery.alma import Alma\n",
    "\n",
    "service = pyvo.dal.TAPService(\"https://almascience.eso.org/tap\")      # for the EU ALMA TAP service\n",
    "\n",
    "# service = pyvo.dal.TAPService(\"https://almascience.nao.ac.jp/tap\")  # for the EA ALMA TAP service\n",
    "# service = pyvo.dal.TAPService(\"https://almascience.nrao.edu/tap\")   # for the NA ALMA TAP service"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<hr style=\"border:2px solid darkblue\"> </hr>\n",
    "\n",
    "## Using ALMA's Datalink\n",
    "\n",
    "<hr style=\"border:2px solid darkblue\"> </hr>\n",
    "\n",
    "In order to download the data after a query the Member Observations Unit IDs are required.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:30.864906Z",
     "iopub.status.busy": "2021-11-16T10:27:30.864183Z",
     "iopub.status.idle": "2021-11-16T10:27:31.208214Z",
     "shell.execute_reply": "2021-11-16T10:27:31.207697Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List of datasets that match the query uid://A001/X133d/X2f99, uid://A001/X144/X23b, uid://A001/X2fa/X22, uid://A001/X2fa/X24, uid://A001/X2fa/X28\n"
     ]
    }
   ],
   "source": [
    "coordinates = astropy.coordinates.SkyCoord.from_name(\"NGC 3628\")\n",
    "output = service.search(f\"SELECT * FROM ivoa.obscore WHERE INTERSECTS(CIRCLE('ICRS',{coordinates.ra.degree},{coordinates.dec.degree}, 0.06),s_region)=1\").to_table().to_pandas()\n",
    "mous_ids = np.unique(output['member_ous_uid'])\n",
    "print(f\"List of datasets that match the query {', '.join(mous_ids)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Selecting as an example a small dataset from the list above"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:31.214852Z",
     "iopub.status.busy": "2021-11-16T10:27:31.214226Z",
     "iopub.status.idle": "2021-11-16T10:27:37.937256Z",
     "shell.execute_reply": "2021-11-16T10:27:37.937823Z"
    }
   },
   "outputs": [],
   "source": [
    "mous_id = 'uid___A001_X2fa_X28'\n",
    "datalink = pyvo.dal.adhoc.DatalinkResults.from_result_url(f\"https://almascience.eso.org/datalink/sync?ID={mous_id}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the dataset and write it into the current working directory by uncommenting and running the following two lines:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:37.941813Z",
     "iopub.status.busy": "2021-11-16T10:27:37.941163Z",
     "iopub.status.idle": "2021-11-16T10:27:37.943110Z",
     "shell.execute_reply": "2021-11-16T10:27:37.943628Z"
    }
   },
   "outputs": [],
   "source": [
    "#for dl in datalink:    \n",
    "#    dl.cachedataset(filename=os.path.basename(dl['access_url']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<hr style=\"border:2px solid darkblue\"> </hr>\n",
    "\n",
    "## Using astroquery\n",
    "\n",
    "<hr style=\"border:2px solid darkblue\"> </hr>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 9a: Download data for galaxy NGC 3628\n",
    "\n",
    "As above, we first query for the source and obtain the list of Member Observing Units IDs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:37.949014Z",
     "iopub.status.busy": "2021-11-16T10:27:37.948356Z",
     "iopub.status.idle": "2021-11-16T10:27:38.192590Z",
     "shell.execute_reply": "2021-11-16T10:27:38.191838Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List of datasets that match the query uid://A001/X133d/X2f99, uid://A001/X144/X23b, uid://A001/X2fa/X22, uid://A001/X2fa/X24, uid://A001/X2fa/X28\n"
     ]
    }
   ],
   "source": [
    "coordinates = astropy.coordinates.SkyCoord.from_name(\"NGC 3628\")\n",
    "output = service.search(f\"SELECT * FROM ivoa.obscore WHERE INTERSECTS(CIRCLE('ICRS',{coordinates.ra.degree},{coordinates.dec.degree},0.06),s_region)=1\").to_table().to_pandas()\n",
    "mous_ids = np.unique(output['member_ous_uid'])\n",
    "print(f\"List of datasets that match the query {', '.join(mous_ids)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Setting the output directory to the current working directory and selecting a dataset from the list above as example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:38.197315Z",
     "iopub.status.busy": "2021-11-16T10:27:38.196609Z",
     "iopub.status.idle": "2021-11-16T10:27:38.199922Z",
     "shell.execute_reply": "2021-11-16T10:27:38.199075Z"
    }
   },
   "outputs": [],
   "source": [
    "myAlma = Alma()\n",
    "myAlma.cache_location = os.getcwd()    \n",
    "mous_id = 'uid___A001_X2fa_X28'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the dataset and write it into the current working directory by uncommenting and running the following line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-11-16T10:27:38.203893Z",
     "iopub.status.busy": "2021-11-16T10:27:38.203267Z",
     "iopub.status.idle": "2021-11-16T10:27:38.205469Z",
     "shell.execute_reply": "2021-11-16T10:27:38.205978Z"
    }
   },
   "outputs": [],
   "source": [
    "#myAlma.retrieve_data_from_uid(mous_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "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.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
