{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# **Lab 3 Plotting Script**"
      ],
      "metadata": {
        "id": "LjK3BPbJfLkR"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Run the block below, if you want to connect to your Google Drive for the files. Otherwise, skip this block and upload your output files to the temporary session storage."
      ],
      "metadata": {
        "id": "3siH93iIcOTG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import drive\n",
        "drive.mount('/content/drive')"
      ],
      "metadata": {
        "id": "nfJ-bzU-KBcA"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Connect to a runtime, if not done so automatically. Then run the next block to import everything we will need."
      ],
      "metadata": {
        "id": "qHKM2JNAfWAR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install mesa_reader\n",
        "import matplotlib.pyplot as plt\n",
        "import mesa_reader as mr\n",
        "import numpy as np\n",
        "from matplotlib.collections import LineCollection"
      ],
      "metadata": {
        "id": "Y767TtUPtql0"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Next, drag and drop your output files into Colab. Then set the path for this folder below."
      ],
      "metadata": {
        "id": "IP7AreBMfpil"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "output_file_path = \"/content/drive/MyDrive/M10_Omega0p75/\" # ex. ./M05_Omega0p60/"
      ],
      "metadata": {
        "id": "ZQF-Nx2EgHZX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Now, you can grab all the necessary variables from the profile and history data, below"
      ],
      "metadata": {
        "id": "NkeP0-9_giyH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Basic Parameters\n",
        "# Load the MESA profile data\n",
        "load_dir = mr.MesaLogDir(output_file_path)\n",
        "profile = load_dir.profile_data()\n",
        "history = mr.MesaData(output_file_path + \"history.data\")\n",
        "\n",
        "extra_jdot = profile.extra_jdot\n",
        "radii = profile.radius\n",
        "max_r_polar = profile.r_polar[0]\n",
        "log_dJ_over_J = profile.log_dJ_over_J\n",
        "omega_core = history.center_omega\n",
        "omega_surf = history.surf_avg_omega\n",
        "hydrogen_core = history.center_h1\n",
        "initial_hydrogen_core = history.center_h1[0]\n",
        "mass = history.star_mass[0]\n",
        "\n",
        "age_ms = history.star_age - history.star_age[0]\n",
        "surf_omega_over_c = history.surf_avg_omega_div_omega_crit\n",
        "log_g = history.log_g\n",
        "v_eq = history.surf_avg_v_rot"
      ],
      "metadata": {
        "id": "sQMHKz-hBrAP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Plot log(dJ)/J over radius (colored red if extra_jdot is negative, green if extra_jdot is positive)"
      ],
      "metadata": {
        "id": "-63PPeB5gy1-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = radii / max_r_polar\n",
        "y = log_dJ_over_J\n",
        "\n",
        "points = np.array([x, y]).T.reshape(-1, 1, 2)\n",
        "segments = np.concatenate([points[:-1], points[1:]], axis=1)\n",
        "\n",
        "# Assign colors based on sign of the average of each segment\n",
        "segment_values = extra_jdot\n",
        "colors = ['red' if v < 0 else 'green' for v in segment_values]\n",
        "\n",
        "lc = LineCollection(segments, colors=colors, linewidths=1)\n",
        "lc.set_array(x[:-1])\n",
        "fig, ax = plt.subplots(figsize=(8, 4))\n",
        "fig.set_dpi(300)\n",
        "ax.add_collection(lc)\n",
        "ax.set_xlim(-0.01, max(x)+0.01)\n",
        "ax.set_ylim(y.min() - 0.5, y.max() + 0.5)\n",
        "ax.set_xlabel(r\"$r/r_{polar}$\")\n",
        "ax.set_ylabel(\"$Log(abs(\\dot{J}_{extra}) * dt / J)$\")\n",
        "ax.set_title(\"\")\n",
        "plt.grid(True)\n",
        "plt.tight_layout()\n",
        "plt.show()"
      ],
      "metadata": {
        "id": "0n0qrlV2Ap9Z"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Next, copy the plots from [Mombarg et al., 2024](https://www.aanda.org/articles/aa/pdf/2024/03/aa48466-23.pdf), Figure 3, [omega/omega_crit vs time] [omega/omega_crit vs Xcore/Xini] [V_eq over log(g)]"
      ],
      "metadata": {
        "id": "Io7stQDDmetu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "fig, ((ax1), (ax2), (ax3)) = plt.subplots(3, 1, figsize=(4, 8))\n",
        "fig.set_dpi(300)\n",
        "\n",
        "if mass == 5:\n",
        "  col = 'red'\n",
        "elif mass == 6:\n",
        "  col = 'green'\n",
        "elif mass == 8:\n",
        "  col = 'blue'\n",
        "else:\n",
        "  col = 'black'\n",
        "\n",
        "if \"75\" in output_file_path:\n",
        "  lnstyle = 'solid'\n",
        "elif \"60\" in output_file_path:\n",
        "  lnstyle = 'dashed'\n",
        "\n",
        "x1 = np.array([])\n",
        "x2 = np.array([])\n",
        "x3 = np.array([])\n",
        "y1 = np.array([])\n",
        "y3 = np.array([])\n",
        "\n",
        "for i, omega in enumerate(surf_omega_over_c):\n",
        "  if omega <= 1e-8:\n",
        "    continue\n",
        "\n",
        "  x1 = np.append(x1, age_ms[i]/1e6)\n",
        "  x2 = np.append(x2, hydrogen_core[i]/initial_hydrogen_core)\n",
        "  y1 = np.append(y1, surf_omega_over_c[i] )\n",
        "\n",
        "  x3 = np.append(x3, log_g[i])\n",
        "  y3 = np.append(y3, v_eq[i])\n",
        "\n",
        "\n",
        "ax1.plot(x1, y1, color = col, linestyle = lnstyle, linewidth = 1)\n",
        "ax2.plot(x2, y1, color = col, linestyle = lnstyle, linewidth = 1)\n",
        "ax3.plot(x3, y3, color = col, linestyle = lnstyle, linewidth = 1 )\n",
        "\n",
        "ax1.set_xlim(0.0, 90)\n",
        "ax1.set_ylim(0.4, 1.0)\n",
        "ax1.set_xlabel(r\"$t_{MS} [Myr]$\")\n",
        "ax1.set_ylabel(\"$\\u03A9_{eq}/\\u03A9_{c}$\")\n",
        "\n",
        "ax2.set_xlim(0.0, 1.0)\n",
        "ax2.set_ylim(0.4, 1.0)\n",
        "ax2.set_xlabel(r\"$X_{core}/X_{ini}$\")\n",
        "ax2.set_ylabel(\"$\\u03A9_{eq}/\\u03A9_{c}$\")\n",
        "ax2.invert_xaxis()\n",
        "\n",
        "ax3.set_xlim(3.5, 4.4)\n",
        "ax3.set_ylim(200, 550)\n",
        "ax3.set_xlabel(r\"$log(g_{pole}/cms^{-2})$\")\n",
        "ax3.set_ylabel(\"$V_{eq}$\")\n",
        "ax3.invert_xaxis()\n",
        "\n",
        "ax1.minorticks_on()\n",
        "ax2.minorticks_on()\n",
        "ax3.minorticks_on()\n",
        "ax1.grid(True)\n",
        "ax2.grid(True)\n",
        "ax3.grid(True)\n",
        "plt.tight_layout()\n",
        "plt.show()"
      ],
      "metadata": {
        "id": "1_DwAOxlmxjG"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Now, make a run with no extra torque, upload those files as well and save this path below"
      ],
      "metadata": {
        "id": "SXwYrLfAjtTZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "no_torque_files = \"/content/drive/MyDrive/M10_Omega0p60_nojdot/\" # ex. \"./M05_Omega0p60_nojdot/\""
      ],
      "metadata": {
        "id": "WbalC1nlj0b_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Now, lets get values from these plots"
      ],
      "metadata": {
        "id": "Yv1jpusRj3q1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load the second run's MESA history data\n",
        "no_torque_mesa = mr.MesaLogDir(no_torque_files)\n",
        "history2 = mr.MesaData(no_torque_files + \"history.data\")\n",
        "\n",
        "omega_core_no_extra_torque = history2.center_omega\n",
        "omega_surf_no_extra_torque = history2.surf_avg_omega\n",
        "hydrogen_core_no_extra_torque = history2.center_h1\n",
        "initial_hydrogen_core_no_extra_torque = history2.center_h1[0]"
      ],
      "metadata": {
        "id": "cwbxf9kLkDay"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Then, we can plot the difference between these runs, below"
      ],
      "metadata": {
        "id": "lfuo1V6_kD4A"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "fig, ax = plt.subplots(figsize=(8, 4))\n",
        "fig.set_dpi(300)\n",
        "\n",
        "x = np.array([])\n",
        "y = np.array([])\n",
        "\n",
        "for i, omega in enumerate(omega_surf_no_extra_torque):\n",
        "  if omega <= 1e-8:\n",
        "    continue\n",
        "\n",
        "  x = np.append(x, hydrogen_core_no_extra_torque[i]/initial_hydrogen_core_no_extra_torque)\n",
        "  y = np.append(y, omega_core_no_extra_torque[i]/omega_surf_no_extra_torque[i])\n",
        "\n",
        "\n",
        "plt.plot(x, y, color='red', linestyle='dashed', linewidth=1, label='No Extra Torque')\n",
        "\n",
        "x = np.array([])\n",
        "y = np.array([])\n",
        "\n",
        "for i, omega in enumerate(omega_surf):\n",
        "  if omega <= 1e-8:\n",
        "    continue\n",
        "\n",
        "  x = np.append(x, hydrogen_core[i]/initial_hydrogen_core)\n",
        "  y = np.append(y, omega_core[i]/omega_surf[i])\n",
        "\n",
        "plt.plot(x, y, color='black', linewidth=1, label = 'Extra Torque')\n",
        "\n",
        "\n",
        "ax.set_xlim(0.0, 1.0)\n",
        "ax.set_xlabel(r\"$X_{c}'$\")\n",
        "ax.set_ylabel(\"$\\u03A9_{core}/\\u03A9_{surf}$\")\n",
        "ax.invert_xaxis()\n",
        "ax.minorticks_on()\n",
        "ax.set_title(\"\")\n",
        "plt.grid(True)\n",
        "ax.set_box_aspect(0.7)\n",
        "plt.legend(loc = 'upper left')\n",
        "plt.tight_layout()\n",
        "plt.show()"
      ],
      "metadata": {
        "id": "vMFeTnNeM90N"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}