{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Welcome to plotter\n",
    "#### 1. Select ``Run`` from top left toolbar\n",
    "#### 2. Select ``Run All Cells`` from the dropdown menu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as wg\n",
    "from IPython.display import display\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.lines import Line2D\n",
    "from matplotlib.offsetbox import AnchoredText\n",
    "from ipywidgets import HBox, VBox, Checkbox, ToggleButton\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "from matplotlib import cm\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "from matplotlib import cm\n",
    "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
    "%matplotlib widget\n",
    "%run libraries.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2900c280abd443a4ba064151627a1e37",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(VBox(children=(Label(value='Material :'), Label(value='Anisotropy constant $K_u$ [kJ/m3] :'), L…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "caa846c9873844578e48da393df0e565",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Button(description='Save', style=ButtonStyle(), tooltip='The values saved will be used for further calculation…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f5cd522e614e444b8832f1c1c6a18c43",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Output()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "Material = wg.Text(value='Material', placeholder='Type material', disabled=False, layout=wg.Layout(width='100px', height='30px'))\n",
    "Ku     = wg.BoundedFloatText(value=48, min=-430, max=6600, step=0.1, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "Kuout  = wg.Output()\n",
    "Ms     = wg.BoundedFloatText(value=1711, min=1, max=2000, step=0.1, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "Msout  = wg.Output()\n",
    "rho    = wg.BoundedFloatText(value=7.87, min=1e-3, max=1e3, step=1e-3, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "rhoout = wg.Output()\n",
    "dpar   = wg.BoundedFloatText(value=9.95, min=1, max=60, step=0.01, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "dparout= wg.Output()\n",
    "\n",
    "Medium = wg.Text(value='Medium', placeholder='Type medium', disabled=False, layout=wg.Layout(width='100px', height='30px'))\n",
    "eta    = wg.BoundedFloatText(value=1e-3, min=1e-4, max=1e3, step=1e-4, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "etaout = wg.Output()\n",
    "ds     = wg.BoundedFloatText(value=15, min=0, max=20, step=0.01, disabled=False, layout=wg.Layout(width='100px', height='25px'))\n",
    "dsout  = wg.Output()\n",
    "\n",
    "Mattext = wg.Label('Material :')\n",
    "Kutext  = wg.Label(r'Anisotropy constant $K_u$ [kJ/m3] :')\n",
    "Mstext  = wg.Label(r'Saturation magnetization $M_s$ [kA/m] :')\n",
    "rhotext = wg.Label(r'Density of material $\\rho$  [g/cm3] :')\n",
    "dpartext= wg.Label(r'Particle diameter $d_p$ [nm] :')\n",
    "\n",
    "space  = wg.Label(r'$\\quad$')\n",
    "\n",
    "Medtext= wg.Label('Medium :')\n",
    "etatext= wg.Label(r'Viscosity $\\eta$ [Ns/m2] :')\n",
    "dstext  = wg.Label(r'Surfactant layer thickness $d_s$  [nm] :')\n",
    "\n",
    "display(HBox((VBox((Mattext, Kutext, Mstext, rhotext, dpartext)),\n",
    "              VBox((Material, Ku, Kuout, Ms, Msout, rho, rhoout, dpar, dparout)),\n",
    "              space,\n",
    "              VBox((Medtext, etatext, dstext)),\n",
    "              VBox((Medium, eta, etaout, ds, dsout)) )) )\n",
    "\n",
    "savebutton = wg.Button(description='Save', tooltip='The values saved will be used for further calculation')\n",
    "saveout = wg.Output()\n",
    "display(savebutton, saveout)\n",
    "\n",
    "colorcode = ['b', 'g', 'r', 'm', 'k']\n",
    "\n",
    "\n",
    "def on_button_clicked(save):\n",
    "    with saveout:\n",
    "        siKu  = float(Ku.value   * unit['Factor']['Anisotropy constant'])\n",
    "        siMs  = float(Ms.value   * unit['Factor']['Saturation magnetization'])\n",
    "        sirho = float(rho.value  * unit['Factor']['Density'])\n",
    "        sieta = float(eta.value  * unit['Factor']['Viscosity'])\n",
    "        sidp  = float(dpar.value * unit['Factor']['Surfactant layer thickness'])\n",
    "        sids  = float(ds.value   * unit['Factor']['Surfactant layer thickness'])\n",
    "        \n",
    "        if sidp > ((6 * kb * T * np.log(1e50)) / (siKu * np.pi))**(1/3):\n",
    "            maxdp = ((6 * kb * T * np.log(1e50)) / (siKu * np.pi))**(1/3)\n",
    "            warningtext = wg.Label(f'Particle diameter exceeded maximum. Relaxation time has reached infinity.\\n Max particle diameter for the given anisotropy constant is {round(maxdp * 1e9, 2)} nm')\n",
    "            display(warningtext)\n",
    "        else:\n",
    "            tau_n = tau0 * np.exp((siKu * np.pi * sidp**3) / (6 * kb * T))\n",
    "            tau_b = (sieta * np.pi * (sidp + sids)**3) / (2 * kb * T)\n",
    "            tau_tot = (tau_n * tau_b) / (tau_n + tau_b)\n",
    "#             fmax = 1 / (2 * np.pi * tau_tot)\n",
    "#             print(f\"fmax = {round(fmax / unit['Factor']['Frequency'])} kHz\")\n",
    "            \n",
    "            def plotdropdown(Axes):\n",
    "                if Axes == 'select axes':\n",
    "                    None\n",
    "                elif Axes == 'frequency - SAR':\n",
    "                    fieldtext = wg.Label('Field H [G] :', layout=wg.Layout(width='120px', height='30px'))\n",
    "                    field0 = wg.BoundedIntText(value=100, min=1, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    fieldout0 = wg.Output()\n",
    "                    field1 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    fieldout1 = wg.Output()\n",
    "                    field2 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    fieldout2 = wg.Output()\n",
    "                    field3 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    fieldout3 = wg.Output()\n",
    "                    field4 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    fieldout4 = wg.Output()\n",
    "                    display(HBox((fieldtext, field0,fieldout0,field1,fieldout1,field2,fieldout2,field3,fieldout3,field4,fieldout4)))\n",
    "\n",
    "                    saveff = wg.Button(description='Compute', tooltip='The values saved will be used for further calculation')\n",
    "                    saveffout = wg.Output()\n",
    "                    display(saveff, saveffout)\n",
    "                    def on_button_clicked2(save2):\n",
    "                        with saveffout:\n",
    "                            \n",
    "                            fields = [field0.value, field1.value, field2.value, field3.value, field4.value]\n",
    "\n",
    "                            while 0 in fields:\n",
    "                                fields.remove(0)\n",
    "                            labels = [f'H = {fields[i]} G' for i in range(len(fields))]\n",
    "                            fields = np.array(fields) * unit['Factor']['Field']\n",
    "\n",
    "                            freqslider = wg.IntSlider(value=10, min=10, max=1000, description='f [kHz]')\n",
    "                            fig, ax = plt.subplots()\n",
    "                            ax.set_xlabel('f [kHz]')\n",
    "                            ax.set_ylabel('SAR [W/g]')\n",
    "#                             ax.add_artist(AnchoredText(f\"{Material.value} \\n{Medium.value}\", loc=2))\n",
    "                            ax.add_artist(AnchoredText(f\"{Material.value} \\n{Medium.value} \\no $\\leq$ Atkinson Limit \\nx  > Atkinson Limit\", loc='upper left'))                         \n",
    "                            legend_elements = [Line2D([0], [0], marker='.', color=colorcode[i], linestyle='None', label=labels[i]) for i in range(len(fields))]\n",
    "                            ax.legend(handles=legend_elements, loc='center left', fontsize=8)\n",
    "#                             ax.set_yscale('log')\n",
    "                            \n",
    "                            \n",
    "                            def freqSAR(freqslider):\n",
    "\n",
    "                                for h in range(len(fields)):\n",
    "                                    P = ((np.pi**3 * vacuumpermeability**2 * fields[h]**2 * siMs**2 * sidp**3 * (freqslider * unit['Factor']['Frequency'])**2 * tau_tot) / \\\n",
    "                                        (9 * kb * T * sirho * (1 + (2 * np.pi * freqslider * unit['Factor']['Frequency'] * tau_tot)**2))) * 1e-3\n",
    "                                    if fields[h] * freqslider * unit['Factor']['Frequency'] <= 4.85e8:\n",
    "                                        ax.scatter(freqslider, P, marker='o', s=15, color=colorcode[h])\n",
    "                                    else:\n",
    "                                        ax.scatter(freqslider, P, marker='x', s=10, color=colorcode[h])\n",
    "\n",
    "                            wg.interact(freqSAR, freqslider=freqslider)\n",
    "                            \n",
    "                            x = np.arange(10, 1000, 1)\n",
    "                            y = []\n",
    "                            for h in range(len(fields)):\n",
    "                                P = ((np.pi**3 * vacuumpermeability**2 * fields[h]**2 * siMs**2 * sidp**3 * (x * unit['Factor']['Frequency'])**2 * tau_tot) / \\\n",
    "                                    (9 * kb * T * sirho * (1 + (2 * np.pi * x * unit['Factor']['Frequency'] * tau_tot)**2))) * 1e-3\n",
    "                                y.append(P)\n",
    "                            X = np.array(x).reshape(len(x), 1)\n",
    "                            Y = np.hstack(([np.array(y[h]).reshape(len(y[h]),1) for h in range(len(fields))]))\n",
    "                            export(X, Y, Material.value, Medium.value, Axes)\n",
    "                            \n",
    "                    saveff.on_click(on_button_clicked2)\n",
    "         \n",
    "                elif Axes == 'field - SAR':\n",
    "                    freqtext = wg.Label('Frequency f [kHz] :', layout=wg.Layout(width='120px', height='30px'))\n",
    "                    freq0 = wg.BoundedIntText(value=100, min=1, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    freqout0 = wg.Output()\n",
    "                    freq1 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    freqout1 = wg.Output()\n",
    "                    freq2 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    freqout2 = wg.Output()\n",
    "                    freq3 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    freqout3 = wg.Output()\n",
    "                    freq4 = wg.BoundedIntText(value=0, min=0, max=500, disabled=False, layout=wg.Layout(width='70px'))\n",
    "                    freqout4 = wg.Output()\n",
    "                    display(HBox((freqtext, freq0,freqout0,freq1,freqout1,freq2,freqout2,freq3,freqout3,freq4,freqout4)))\n",
    "                    \n",
    "                    saveff = wg.Button(description='Compute', tooltip='The values saved will be used for further calculation')\n",
    "                    saveffout = wg.Output()\n",
    "                    display(saveff, saveffout)\n",
    "\n",
    "                    \n",
    "                    def on_button_clicked2(save2):\n",
    "                        with saveffout:\n",
    "                            freq = [freq0.value, freq1.value, freq2.value, freq3.value, freq4.value]\n",
    "\n",
    "                            while 0 in freq:\n",
    "                                freq.remove(0)\n",
    "                            labels = [f'f = {freq[i]} kHz' for i in range(len(freq))]\n",
    "                            freq = np.array(freq) * unit['Factor']['Frequency']\n",
    "                            fieldslider = wg.IntSlider(value=10, min=10, max=1000, description='H [G]')\n",
    "                            fig, ax = plt.subplots()\n",
    "                            ax.set_xlabel('H [G]')\n",
    "                            ax.set_ylabel('SAR [W/g]')\n",
    "                            ax.add_artist(AnchoredText(f\"{Material.value} \\n{Medium.value} \\no $\\leq$ Atkinson Limit \\nx  > Atkinson Limit\", loc='upper left'))\n",
    "\n",
    "                            legend_elements = [Line2D([0], [0], marker='.', color=colorcode[i], linestyle='None', label=labels[i]) for i in range(len(freq))]\n",
    "                            ax.legend(handles=legend_elements, loc='center left', fontsize=8)\n",
    "                            \n",
    "                            \n",
    "                            def fieldSAR(fieldslider):\n",
    "#                                 print(f\"field={fieldslider * unit['Factor']['Field']}, freq420={freq[0]}, Ms={siMs}, dp={sidp}, Ku={siKu}, eta={sieta}, rho={sirho}\")\n",
    "                                for f in range(len(freq)): \n",
    "                                    P = ((np.pi**3 * vacuumpermeability**2 * (fieldslider * unit['Factor']['Field'])**2 * siMs**2 * sidp**3 * freq[f]**2 * tau_tot) / \\\n",
    "                                         (9 * kb * T * sirho * (1 + (2 * np.pi * freq[f] * tau_tot)**2))) * 1e-3\n",
    "                                    if fieldslider * freq[f] * unit['Factor']['Frequency'] <= 4.85e8:\n",
    "                                        ax.scatter(fieldslider, P, marker='o', s=15, color=colorcode[f])\n",
    "                                    else:\n",
    "                                        ax.scatter(fieldslider, P, marker='x', s=10, color=colorcode[f])\n",
    "                            wg.interact(fieldSAR, fieldslider=fieldslider)\n",
    "                            \n",
    "                            x = np.arange(10, 1000, 1)\n",
    "                            y = []\n",
    "                            for f in range(len(freq)):\n",
    "                                P = ((np.pi**3 * vacuumpermeability**2 * (x * unit['Factor']['Field'])**2 * siMs**2 * sidp**3 * freq[f]**2 * tau_tot) / \\\n",
    "                                    (9 * kb * T * sirho * (1 + (2 * np.pi * freq[f] * tau_tot)**2))) * 1e-3\n",
    "                                y.append(P)\n",
    "                            X = np.array(x).reshape(len(x), 1)\n",
    "                            Y = np.hstack(([np.array(y[h]).reshape(len(y[f]),1) for h in range(len(freq))]))\n",
    "                            export(X, Y, Material.value, Medium.value, Axes)\n",
    "                            \n",
    "                    saveff.on_click(on_button_clicked2)\n",
    "                elif Axes == 'f - H - SAR':\n",
    "                    fig = plt.figure()\n",
    "                    ax = fig.gca(projection='3d')\n",
    "                    plt.tight_layout()\n",
    "                    ax.set_xlabel('Frequency f [kHz]')\n",
    "                    ax.set_ylabel('Field H [G]')\n",
    "                    ax.set_zlabel('SAR [W/g]')\n",
    "                    ax.invert_yaxis()\n",
    "                    ax.view_init(elev=18, azim=-27)\n",
    "                    ax.text2D(0.0, 0.98, f\"{Material.value}, {Medium.value}\", transform=ax.transAxes)\n",
    "                    ax.text2D(0.0, 0.94, f\"Ms: {Ms.value} kA/m, Ku: {Ku.value} kJ/m3, rho: {rho.value} g/cm3, eta: {eta.value} Ns/m2\", transform=ax.transAxes, fontsize=8)\n",
    "                    ax.text2D(0.0, 0.90, f\"Particle diameter: {dpar.value} nm\", transform=ax.transAxes, fontsize=8)\n",
    "                    \n",
    "                    # Make data.\n",
    "                    X = np.arange(1, 500, 1) # f\n",
    "                    Y = np.arange(1, 500, 1) # H\n",
    "                    X, Y = np.meshgrid(X, Y)\n",
    "                    Z = ((np.pi**3 * vacuumpermeability**2 * (Y * unit['Factor']['Field'])**2 * siMs**2 * sidp**3 * (X * unit['Factor']['Frequency'])**2 * tau_tot) / \\\n",
    "                        (9 * kb * T * sirho * (1 + (2 * np.pi * X * unit['Factor']['Frequency'] * tau_tot)**2))) * 1e-3\n",
    "\n",
    "                    # Plot the surface.\n",
    "                    surf = ax.plot_surface(X, Y, Z, cmap=cm.jet)#, rstride=1, cstride=1, linewidth=0, antialiased=False)\n",
    "\n",
    "    #####################################################################################################################################\n",
    "                \n",
    "#####################################################################################################################################\n",
    "                        \n",
    "            wg.interact(plotdropdown, Axes=simulation)\n",
    "        \n",
    "savebutton.on_click(on_button_clicked)\n"
   ]
  },
  {
   "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": "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
