{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1a342e58",
   "metadata": {},
   "source": [
    "# Astrophysics III: galaxy formation & evolution\n",
    "Moodle: https://go.epfl.ch/PHYS-465\n",
    "\n",
    "## Exercise 4\n",
    "Teaching assistant: Lucie Scharré <br>\n",
    "Email: lucie.scharre@epfl.ch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55040aa8",
   "metadata": {},
   "source": [
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3eaf8a3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mlp\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8a092e75",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/luciescharre/opt/anaconda3/lib/python3.9/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.24.3\n",
      "  warnings.warn(f\"A NumPy version >={np_minversion} and <{np_maxversion}\"\n"
     ]
    }
   ],
   "source": [
    "#%% #####################################################################\n",
    "### Luminosity distance from redshift ### \n",
    "\n",
    "# Exact numbers depend on values for H0, and the matter and vacuum density parameters! For our puposes these values are similar enough.\n",
    "# Option 1, requires Astropy, units can be adjusted with u.m, u.km, u.au,...\n",
    "\n",
    "from astropy.cosmology import WMAP9 as cosmo   # https://docs.astropy.org/en/stable/install.html\n",
    "from astropy import units as u\n",
    "z=3\n",
    "d_L = cosmo.luminosity_distance(z).to(u.Mpc).value \n",
    "\n",
    "\n",
    "# Option 2\n",
    "import scipy.integrate as spi\n",
    "def luminosity_distance(z):\n",
    "    c = 3e8  # Speed of light in m/s\n",
    "    H0 = 69.6 *1e3 # in m/s/Mpc\n",
    "    Omega_m = 0.286 # matter \n",
    "    Omega_lambda = 0.714 #vacuum\n",
    "\n",
    "    integrand = lambda z: 1.0 / (Omega_m * (1 + z)**3 + Omega_lambda)**0.5\n",
    "    integral, _ = spi.quad(integrand, 0, z)\n",
    "\n",
    "    d_L = (c / H0) * (1 + z) * integral\n",
    "\n",
    "    return d_L\n",
    "\n",
    "\n",
    "# Luminosity from flux and z\n",
    "def L_calc(F, z):\n",
    "    D = cosmo.luminosity_distance(z).to(u.cm)\n",
    "    L = F*(4*np.pi*D**2)*u.erg*u.s**-1\n",
    "    return L.value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fa2d1fc5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#%% #####################################################################\n",
    "### Useful literature relations ###\n",
    "\n",
    "# Kennicutt+1998 relation to get SFR from Halpha\n",
    "def SFR_Halpha(L_ha):\n",
    "    SFR = 7.9e-42 * L_ha \n",
    "    return SFR\n",
    "\n",
    "\n",
    "## Elbaz SFR-Mstar relation at z =0\n",
    "def Elbaz_SDSS(log10_Mstar, alpha=8.7):\n",
    "    log10_SFR = np.log10(alpha) + 0.77*(log10_Mstar-10) \n",
    "    return log10_SFR\n",
    "\n",
    "\n",
    "### BPT criteria ###\n",
    "\n",
    "# SF criterion, Kewley et al. 2001 \n",
    "def obscrit_OIII_NII_SF(log_n2_ha_ratio):\n",
    "    log_o3_hb_ratio = 0.61/(log_n2_ha_ratio-0.47)+1.19\n",
    "    return log_o3_hb_ratio\n",
    "\n",
    "\n",
    "# AGN criterion, Kauffmann et al. 2003\n",
    "def obscrit_OIII_NII_AGN(log_n2_ha_ratio):\n",
    "    log_o3_hb_ratio = 0.61/(log_n2_ha_ratio-0.05)+1.3\n",
    "    return log_o3_hb_ratio\n",
    "\n",
    "\n",
    "# Lamastra+09 relation to get LAGN from LOIII\n",
    "\n",
    "def LAGN_LOIII(L_o3):\n",
    "    LAGN = np.zeros(len(SDSS_o3))\n",
    "    \n",
    "    #between 1e38 - 1e40\n",
    "    COIII_1 = 87\n",
    "\n",
    "    #between 1e40 - 1e42\n",
    "    COIII_2 = 142\n",
    "\n",
    "    #between 1e42 - 1e44\n",
    "    COIII_3 = 454\n",
    "    \n",
    "    LAGN[L_o3<1e40] = COIII_1 * L_o3[L_o3<1e40]\n",
    "    LAGN[(L_o3>1e40)&(L_o3<1e42)]  = COIII_2 * L_o3[(L_o3>1e40)&(L_o3<1e42)]\n",
    "    LAGN[L_o3>1e42] = COIII_3 * L_o3[L_o3>1e42]\n",
    "    \n",
    "    return LAGN\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "56d36029",
   "metadata": {},
   "outputs": [],
   "source": [
    "#%% #####################################################################\n",
    "### Snippet to plot contours ###\n",
    "\n",
    "from scipy.ndimage.filters import gaussian_filter\n",
    "\n",
    "# sigma (s) signifies standard deviation of the gaussian smoothing \n",
    "\n",
    "\n",
    "def contours(x, y, s=1, bins=100, nlevels = 7, alpha=0.8,cmap=\"Greys_r\"):\n",
    "\n",
    "    hist, xedges, yedges = np.histogram2d(x, y, bins=bins)\n",
    "    \n",
    "    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n",
    "    heatmap = gaussian_filter(hist, sigma=s)\n",
    "    \n",
    "    # logarithmic contours\n",
    "    levels = np.logspace(0,np.log10(heatmap.max()),nlevels)\n",
    "\n",
    "    contourplot = plt.contour(heatmap.T,extent=extent, alpha=0.8,cmap=cmap,levels=levels)\n",
    "\n",
    "\n",
    "def plot_2dhist(x, y, bins=100, cmap = \"Greys_r\"):\n",
    "    hist,xedges,yedges = np.histogram2d(x,y,bins=bins)\n",
    "    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n",
    "    hist_plot = plt.imshow(hist.T, norm=mlp.colors.LogNorm(), cmap =cmap,extent = extent, interpolation=None,origin='lower',aspect='auto')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "177f178e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#%% #####################################################################\n",
    "### Snippet to read in SDSS data ###\n",
    "\n",
    "SDSS_data = np.loadtxt(\"/Users/luciescharre/Documents/Astro-III_Exercises/Exercises4_SDSS_EL (L - in process)/SDSS_DR7.txt\", comments='#').T\n",
    "\n",
    "\n",
    "SDSS_Mstar = 10 ** SDSS_data[-1]\n",
    "SDSS_z = SDSS_data[1]\n",
    "\n",
    "scaling = 1e-16\n",
    "\n",
    "SDSS_ha = SDSS_data[8]*scaling \n",
    "SDSS_hb = SDSS_data[2]*scaling\n",
    "SDSS_o3 = SDSS_data[4]*scaling\n",
    "SDSS_n2 = SDSS_data[12]*scaling\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c384b484",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
