{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Modeling of SgrA* sub-mm bump\n",
    "============================="
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.304984Z",
     "iopub.status.busy": "2021-10-29T13:21:53.304697Z",
     "iopub.status.idle": "2021-10-29T13:21:53.626271Z",
     "shell.execute_reply": "2021-10-29T13:21:53.625995Z"
    }
   },
   "outputs": [],
   "source": [
    "import flaremodel as fm\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "fm.set_rcparams(fs=15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.628810Z",
     "iopub.status.busy": "2021-10-29T13:21:53.628499Z",
     "iopub.status.idle": "2021-10-29T13:21:53.630065Z",
     "shell.execute_reply": "2021-10-29T13:21:53.629830Z"
    }
   },
   "outputs": [],
   "source": [
    "sgrA = fm.SgrA()\n",
    "\n",
    "def radius_from_projected(R_proj):\n",
    "    \"\"\"\n",
    "    Return source radius from projected radius\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    R_proj : float\n",
    "        Projected radius in uas.\n",
    "    \"\"\"\n",
    "    return sgrA.distance*(R_proj*np.pi/648e9)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.633963Z",
     "iopub.status.busy": "2021-10-29T13:21:53.633658Z",
     "iopub.status.idle": "2021-10-29T13:21:53.635414Z",
     "shell.execute_reply": "2021-10-29T13:21:53.635184Z"
    }
   },
   "outputs": [],
   "source": [
    "class ThermalSync(fm.SEDFitLM):\n",
    "    \n",
    "    def __init__(self, data, p0, bounds_l=None, bounds_h=None,\n",
    "                                vary=None, params=None):\n",
    "\n",
    "        self.param_names = [\"log10_ne\", \"R_proj\", \"B\", \"theta_E\"]\n",
    "        super().__init__(data, p0=p0, bounds_l=bounds_l, bounds_h=bounds_h, vary=vary, params=params)\n",
    "        \n",
    "        \n",
    "    def set_models(self):\n",
    "        self.models = []\n",
    "        self.flare = fm.HomogeneousSphere(edist=\"thermal\")\n",
    "        \n",
    "        self.models.append(lambda nu, p : \n",
    "                           self.flare.compute_synchrotron(nu, 10**p[\"log10_ne\"], \n",
    "                                        [radius_from_projected(p[\"R_proj\"]), -1], \n",
    "                                        p['B'], [p['theta_E']])) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.637920Z",
     "iopub.status.busy": "2021-10-29T13:21:53.637638Z",
     "iopub.status.idle": "2021-10-29T13:21:53.638809Z",
     "shell.execute_reply": "2021-10-29T13:21:53.639028Z"
    }
   },
   "outputs": [],
   "source": [
    "sgrA = fm.SgrA()\n",
    "data = [[sgrA.submmSED[0], sgrA.submmSED[1], sgrA.submmSED[2]]]\n",
    "p0 =       [5.5, 40., 10., 30.]\n",
    "bounds_l = [4, 30, 1, 5]\n",
    "bounds_h = [10, 50, 300, 1000]\n",
    "vary=      [True, True, True, True]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.643088Z",
     "iopub.status.busy": "2021-10-29T13:21:53.642758Z",
     "iopub.status.idle": "2021-10-29T13:21:53.644458Z",
     "shell.execute_reply": "2021-10-29T13:21:53.644694Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table><tr><th> name </th><th> value </th><th> initial value </th><th> min </th><th> max </th><th> vary </th></tr><tr><td> log10_ne </td><td>  5.50000000 </td><td> 5.5 </td><td>  4.00000000 </td><td>  10.0000000 </td><td> True </td></tr><tr><td> R_proj </td><td>  40.0000000 </td><td> 40.0 </td><td>  30.0000000 </td><td>  50.0000000 </td><td> True </td></tr><tr><td> B </td><td>  10.0000000 </td><td> 10.0 </td><td>  1.00000000 </td><td>  300.000000 </td><td> True </td></tr><tr><td> theta_E </td><td>  30.0000000 </td><td> 30.0 </td><td>  5.00000000 </td><td>  1000.00000 </td><td> True </td></tr></table>"
      ],
      "text/plain": [
       "Parameters([('log10_ne', <Parameter 'log10_ne', value=5.5, bounds=[4:10]>), ('R_proj', <Parameter 'R_proj', value=40.0, bounds=[30:50]>), ('B', <Parameter 'B', value=10.0, bounds=[1:300]>), ('theta_E', <Parameter 'theta_E', value=30.0, bounds=[5:1000]>)])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "submm = ThermalSync(data=data, p0=p0, vary=vary, bounds_l=bounds_l, bounds_h=bounds_h)\n",
    "submm.params"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:53.653859Z",
     "iopub.status.busy": "2021-10-29T13:21:53.650934Z",
     "iopub.status.idle": "2021-10-29T13:21:54.114164Z",
     "shell.execute_reply": "2021-10-29T13:21:54.113867Z"
    },
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 0, 'Frequency [Hz]')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 35176 characters]\n",
      "text/plain": [
       "<Figure size 1152x648 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "submm.plot_initial_guess(ylim=[1e31, 1e35], show=False)\n",
    "plt.ylabel(\"Luminosity [erg/s]\")\n",
    "plt.xlabel(\"Frequency [Hz]\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.138001Z",
     "iopub.status.busy": "2021-10-29T13:21:54.137637Z",
     "iopub.status.idle": "2021-10-29T13:21:54.461264Z",
     "shell.execute_reply": "2021-10-29T13:21:54.460972Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[Variables]]\n",
      "    log10_ne:  5.05268927 +/- 1.06568127 (21.09%) (init = 5.5)\n",
      "    R_proj:    45.4387726 +/- 2.48467967 (5.47%) (init = 40)\n",
      "    B:         25.0314694 +/- 79.5735308 (317.89%) (init = 10)\n",
      "    theta_E:   103.734801 +/- 2.21192395 (2.13%) (init = 30)\n",
      "\n",
      "\n",
      "red. Chi^2: 14.023246080016753\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 32664 characters]\n",
      "text/plain": [
       "<Figure size 1152x648 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "submm.fit()\n",
    "submm.plot_fit(ylim=(1e31, 1e35), show=False)\n",
    "plt.ylabel(\"Luminosity [erg/s]\")\n",
    "plt.xlabel(\"Frequency [Hz]\")\n",
    "submm.report_fit(show_correl=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.464163Z",
     "iopub.status.busy": "2021-10-29T13:21:54.463879Z",
     "iopub.status.idle": "2021-10-29T13:21:54.465084Z",
     "shell.execute_reply": "2021-10-29T13:21:54.465305Z"
    }
   },
   "outputs": [],
   "source": [
    "get_theta_E = lambda T_e: T_e*fm.k_b/(fm.M_e*fm.c**2)\n",
    "te = get_theta_E(1.5e11)\n",
    "p0 =       [5.5, 40., 30, te]\n",
    "bounds_l = [4, 30, 1, 5]\n",
    "bounds_h = [10, 50, 300, 1000]\n",
    "vary=      [True, False, True, False]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.468349Z",
     "iopub.status.busy": "2021-10-29T13:21:54.468068Z",
     "iopub.status.idle": "2021-10-29T13:21:54.469364Z",
     "shell.execute_reply": "2021-10-29T13:21:54.469585Z"
    }
   },
   "outputs": [],
   "source": [
    "submm = ThermalSync(data=data, p0=p0, vary=vary, bounds_l=bounds_l, bounds_h=bounds_h)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.477541Z",
     "iopub.status.busy": "2021-10-29T13:21:54.477178Z",
     "iopub.status.idle": "2021-10-29T13:21:54.480229Z",
     "shell.execute_reply": "2021-10-29T13:21:54.480583Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[Variables]]\n",
      "    log10_ne:  5.02526840 +/- 0.94451789 (18.80%) (init = 5.5)\n",
      "    R_proj:    40 (fixed)\n",
      "    B:         39.6753007 +/- 76.4450283 (192.68%) (init = 30)\n",
      "    theta_E:   25.29259 (fixed)\n",
      "\n",
      "\n",
      "red. Chi^2: 52.91853376430094\n"
     ]
    }
   ],
   "source": [
    "submm.fit()\n",
    "submm.report_fit(show_correl=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.482261Z",
     "iopub.status.busy": "2021-10-29T13:21:54.481822Z",
     "iopub.status.idle": "2021-10-29T13:21:54.506006Z",
     "shell.execute_reply": "2021-10-29T13:21:54.506401Z"
    }
   },
   "outputs": [],
   "source": [
    "geo = fm.HomogeneousSphere(edist=\"thermal\")\n",
    "params = submm.MinimizerResult.params\n",
    "nus = np.logspace(10, 20, 100)\n",
    "ssc = geo.compute_SSC(nus, 10**params[\"log10_ne\"],\n",
    "                             [radius_from_projected(params[\"R_proj\"]), -1], \n",
    "                            params[\"B\"], [params[\"theta_E\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-10-29T13:21:54.507982Z",
     "iopub.status.busy": "2021-10-29T13:21:54.507612Z",
     "iopub.status.idle": "2021-10-29T13:21:54.880258Z",
     "shell.execute_reply": "2021-10-29T13:21:54.879948Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 46004 characters]\n",
      "text/plain": [
       "<Figure size 1152x648 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(sgrA.submmSED[0], sgrA.submmSED[1],\"o\", color=\"black\")\n",
    "ax.errorbar(sgrA.submmSED[0], sgrA.submmSED[1], sgrA.submmSED[2], fmt=\"o\", ms=10, color=\"black\")\n",
    "ax.loglog(sgrA.firSED[0], sgrA.firSED[1], \"o\", color=\"black\", ms=10)\n",
    "ax.loglog([sgrA.firSED[0][0], sgrA.firSED[0][0]], [sgrA.firSED[1][0], sgrA.firSED[1][3]] , \":\", color=\"black\", )\n",
    "ax.loglog([sgrA.firSED[0][1], sgrA.firSED[0][1]], [sgrA.firSED[1][1], sgrA.firSED[1][4]] , \":\", color=\"black\", )\n",
    "ax.loglog([sgrA.firSED[0][2], sgrA.firSED[0][2]], [sgrA.firSED[1][2], sgrA.firSED[1][5]] , \":\", color=\"black\", )\n",
    "ax.loglog(nus, ssc*nus, \"r-\")\n",
    "\n",
    "ax.set_ylabel(\"Luminosity [erg/s]\")\n",
    "ax.set_xlabel(\"Frequency [Hz]\")\n",
    "    \n",
    "submm.plot_fit(ax=ax, ylim=[1e31, 5e35])"
   ]
  }
 ],
 "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.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
