{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from os.path import join\n",
    "\n",
    "import csiborgtools\n",
    "import healpy\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy\n",
    "import scienceplots\n",
    "from cache_to_disk import cache_to_disk, delete_disk_caches_for_function\n",
    "from h5py import File\n",
    "\n",
    "import plt_utils\n",
    "\n",
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache_to_disk(30)\n",
    "def _plot_sky_projected_density(nsim, simname, grid, nside, MAS, survey_name,\n",
    "                                dmin, dmax):\n",
    "    paths = csiborgtools.read.Paths(**csiborgtools.paths_glamdring)\n",
    "    boxsize = csiborgtools.simname2boxsize(simname)\n",
    "\n",
    "    if simname == \"csiborg1\":\n",
    "        reader = csiborgtools.read.CSiBORG1Field(nsim, paths)\n",
    "    elif \"csiborg2\" in simname:\n",
    "        kind = simname.split(\"_\")[-1]\n",
    "        reader = csiborgtools.read.CSiBORG2Field(nsim, kind, paths)\n",
    "    else:\n",
    "        raise ValueError(f\"Unknown simname `{simname}`.\")\n",
    "\n",
    "    field = reader.density_field(MAS, grid)\n",
    "\n",
    "    if survey_name == \"2M++\":\n",
    "        survey = csiborgtools.read.TwoMPPGalaxies()\n",
    "        dist = survey[\"ZCMB\"] * 3e5 / 100\n",
    "        ra, dec = survey[\"RA\"], survey[\"DEC\"]\n",
    "        ra *= numpy.pi / 180\n",
    "        dec *= numpy.pi / 180\n",
    "    elif survey_name == \"SDSS\":\n",
    "        survey = csiborgtools.SDSS()()\n",
    "        dist = survey[\"DIST\"]\n",
    "        ra, dec = survey[\"RA\"], survey[\"DEC\"]\n",
    "        ra *= numpy.pi / 180\n",
    "        dec *= numpy.pi / 180\n",
    "    elif survey_name == \"csiborg2\":\n",
    "        cat = csiborgtools.read.CSiBORG2Catalogue(\n",
    "            nsim, 99, \"main\", paths, bounds={\"totmass\": (1e12, None)})\n",
    "        coord = cat[\"spherical_pos\"]\n",
    "        dist, ra, dec = coord[:, 0], coord[:, 1], coord[:, 2]\n",
    "        ra *= numpy.pi / 180\n",
    "        dec *= numpy.pi / 180\n",
    "    else:\n",
    "        raise ValueError(f\"Unknown survey name `{survey_name}`.\")\n",
    "    \n",
    "    mask = (dist > dmin) & (dist < dmax)\n",
    "    ra = ra[mask]\n",
    "    dec = dec[mask]\n",
    "\n",
    "\n",
    "    angpos = csiborgtools.field.nside2radec(nside)\n",
    "    dist = numpy.linspace(dmin, dmax, 1000)\n",
    "    dmap = csiborgtools.field.make_sky(field, angpos=angpos, dist=dist,\n",
    "                                       boxsize=boxsize)\n",
    "    return dmap, ra, dec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_sky_projected_density(nsim, simname, grid, nside, MAS=\"PCS\",\n",
    "                               dmin=0, dmax=220, survey_name=\"2M++\",\n",
    "                               ext=\"png\", to_save=False):\n",
    "    dmap, ra, dec = _plot_sky_projected_density(\n",
    "        nsim, simname, grid, nside, MAS, survey_name, dmin, dmax)\n",
    "    \n",
    "    with plt.style.context(plt_utils.mplstyle):\n",
    "        healpy.mollview(numpy.log10(dmap), fig=0, title=\"\", unit=\"\", rot=90)\n",
    "\n",
    "        healpy.projscatter(numpy.pi / 2 - dec, ra, s=0.05, c=\"red\",\n",
    "                           label=\"2M++ galaxies\")\n",
    "\n",
    "        if to_save:\n",
    "            fout = join(plt_utils.fout, f\"sky_density_{simname}_{nsim}_from_{dmin}_to_{dmax}.{ext}\")  # noqa\n",
    "            print(f\"Saving to `{fout}`.\")\n",
    "            plt.savefig(fout, dpi=plt_utils.dpi, bbox_inches=\"tight\")\n",
    "        plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'hp' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[3], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mhp\u001b[49m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'hp' is not defined"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 196608/196608 [00:22<00:00, 8765.57it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saving to `../plots/sky_density_csiborg2_main_15517_from_100_to_125.png`.\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 841980 characters]",
      "text/plain": [
       "<Figure size 850x540 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# delete_disk_caches_for_function(\"_plot_sky_projected_density\")\n",
    "plot_sky_projected_density(15517, \"csiborg2_main\", 1024, 128, \"SPH\", dmin=100,\n",
    "                           dmax=125, survey_name=\"csiborg2\", to_save=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv_csiborg",
   "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.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
