{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4edf6cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import math\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "from lmfit.models import LinearModel, Model\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.patches as patches\n",
    "import glob\n",
    "from scipy import ndimage, signal, interpolate\n",
    "from time import sleep\n",
    "from ennemi import estimate_corr, pairwise_corr, pairwise_mi\n",
    "from matplotlib import ticker, colormaps, colors\n",
    "from datetime import datetime, timedelta\n",
    "from matplotlib import colors as mpl\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
    "import torch\n",
    "import psutil\n",
    "from botorch.models import SingleTaskGP\n",
    "from botorch.models.transforms import Standardize\n",
    "from botorch.acquisition import UpperConfidenceBound\n",
    "from botorch.fit import fit_gpytorch_mll\n",
    "from botorch.optim import optimize_acqf\n",
    "from gpytorch.mlls import ExactMarginalLogLikelihood\n",
    "from torch.utils.data import DataLoader, TensorDataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85ad663a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure visualization - Define original colormaps, matplotlib display settings and configure seaborn theme\n",
    "\n",
    "jurjen_palette = mpl.LinearSegmentedColormap.from_list(\"\", [\"white\",\"midnightblue\",\"orangered\", \"gold\", \"Lemonchiffon\"])\n",
    "etheo = [ '#004F7AFF','#CC3D24FF','#F3C558FF','#30B4CCFF'] #'#6DAE90FF'\n",
    "etheo_palette = mpl.LinearSegmentedColormap.from_list(\"\",etheo)\n",
    "plt.rc('text', usetex=False)\n",
    "pd.set_option('display.max_columns',None)\n",
    "sns.set_theme(style='ticks', context='poster')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4409f6d",
   "metadata": {},
   "source": [
    "# Data preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3095014",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Data preprocessing of first shot day (19.08.2025)\n",
    "\n",
    "# Load input data from first shot day (19.08.2025)\n",
    "raw_models_1908 = pd.read_excel(\n",
    "    './data_2025-08-19 LWFA.xlsx'\n",
    ")\n",
    "\n",
    "# Load shotlog to be able to divide the data into sets of 10 shots\n",
    "shotlog = pd.read_excel(\n",
    "    './Shotlog-2025-08-19.xlsx',\n",
    "    header=1,                # Parameter names\n",
    "    skiprows=[2, 3],         # skip header rows containing nominal values\n",
    "    index_col=0              # Use shot numbers as index columns\n",
    ")\n",
    "\n",
    "# Provide a copy so that the original is not touched\n",
    "models_1908 = raw_models_1908.copy()\n",
    "\n",
    "# Calculate Set number to be able to aggregate sets of 10 shots pertaining to the same input parameter configuration\n",
    "shotnumbers = shotlog.index\n",
    "shotnumbers=shotnumbers[2:]\n",
    "for i in range(1,len(shotnumbers),1):\n",
    "    mask = models_1908['Shot'].between(shotnumbers[i-1],shotnumbers[i])\n",
    "    models_1908.loc[mask, 'Set number'] = i\n",
    "\n",
    "# Convert absolute motor position in y and z to relative quantities by substracting with the nominal motor position of the day\n",
    "models_1908['Relative focus']= models_1908[' bottom\\ntarget\\nz']-39.65      # Nominal z motor position: 39.65 mm\n",
    "models_1908['Laser height']= 15.23-models_1908['bottom\\ntarget\\ny']         # Nominal laser height y: 15.23 mm\n",
    "models_1908['Laser energy']= models_1908['Transmission']*5.76/100           # Nominal laser energy: 5.76 J\n",
    "\n",
    "# Segment data of the whole day into optimization runs of models with different hyperparameters\n",
    "model_slice_charge = models_1908.loc[(models_1908['Shot']>79)&(models_1908['Shot']<350)]\n",
    "model_window_func = models_1908.loc[(models_1908['Shot']>350)&(models_1908['Shot']<610)]\n",
    "model_custom_init = models_1908.loc[(models_1908['Shot']>610)&(models_1908['Shot']<860)]\n",
    "model_growing_acq = models_1908.loc[(models_1908['Shot']>930)&(models_1908['Shot']<1190)]\n",
    "\n",
    "# Aggregate the data into sets of ten shots representing one input parameter configuration\n",
    "summary_vars = ['Relative focus','Relative GVD','Laser energy','Laser height','TOD','B1 pressure','charge in energy window1','charge in energy window2','charge in energy window3','Difference to objective','slice 1 charge']\n",
    "set_model_slice_charge = model_slice_charge.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean', 'std'])\n",
    "set_model_window_func  = model_window_func.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean', 'std'])\n",
    "set_model_custom_init  = model_custom_init.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean', 'std'])\n",
    "set_model_growing_acq  = model_growing_acq.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean', 'std'])\n",
    "set_pivot_1908 = models_1908.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean', 'std'])\n",
    "\n",
    "\n",
    "def flatten_column_names(df):\n",
    "    \"\"\"Flatten column names to reference them more conveniently\"\"\"\n",
    "    cols = df.columns.to_flat_index()\n",
    "    df.columns = cols.str.join('_')\n",
    "    return df\n",
    "\n",
    "set_model_slice_charge = flatten_column_names(set_model_slice_charge)\n",
    "set_model_window_func  = flatten_column_names(set_model_window_func)\n",
    "set_model_custom_init  = flatten_column_names(set_model_custom_init)\n",
    "set_model_growing_acq  = flatten_column_names(set_model_growing_acq)\n",
    "set_pivot_1908 = flatten_column_names(set_pivot_1908)\n",
    "\n",
    "\n",
    "# Normalize slice charge against its maximum value\n",
    "max_charge_per_set = set_pivot_1908['mean_slice 1 charge'].max()\n",
    "\n",
    "set_model_slice_charge['Rel slice charge'] = set_model_slice_charge['mean_slice 1 charge'] / max_charge_per_set\n",
    "set_model_window_func['Rel slice charge']  = set_model_window_func['mean_slice 1 charge']  / max_charge_per_set\n",
    "set_model_custom_init['Rel slice charge']  = set_model_custom_init['mean_slice 1 charge']  / max_charge_per_set\n",
    "set_model_growing_acq['Rel slice charge']  = set_model_growing_acq['mean_slice 1 charge']  / max_charge_per_set\n",
    "\n",
    "# Calculate maximum charge for each iteration step of each hyperparameter configuration\n",
    "for df_name in ['set_model_slice_charge', 'set_model_window_func', 'set_model_custom_init', 'set_model_growing_acq']:\n",
    "    set_df = eval(df_name)\n",
    "    set_df['max charge'] = set_df['Rel slice charge'].shift().expanding().max()\n",
    "    set_df['max charge'] = set_df['max charge'].shift(-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5e5db76",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Data preprocessing of first shot day (04.09.2025)\n",
    "\n",
    "# Load input data from first shot day (19.08.2025)\n",
    "raw_models_0409 = pd.read_excel(\n",
    "    './data_2025-09-04 LWFA.xlsx'\n",
    ")\n",
    "\n",
    "# Load shotlog to be able to divide the data into sets of 10 shots\n",
    "shotlog = pd.read_excel(\n",
    "    './Shotlog-2025-09-04.xlsx',\n",
    "    header=1,                # Parameter names\n",
    "    skiprows=[2, 3],         # skip header rows containing nominal values\n",
    "    index_col=0              # Use shot numbers as index columns\n",
    ")\n",
    "\n",
    "# Provide a copy so that the original is not touched\n",
    "models_0409 = raw_models_0409.copy()\n",
    "\n",
    "# Convert absolute motor position in y and z to relative quantities by substracting with the nominal motor position of the day\n",
    "models_0409['Relative focus']= models_0409[' bottom\\ntarget\\nz']-39.53      # Nominal z motor position: 39.53 mm\n",
    "models_0409['Laser height']= 15.44-models_0409['bottom\\ntarget\\ny']         # Nominal laser height y: 15.44 mm\n",
    "models_0409['Laser energy']= models_0409['Transmission']*5.61/100           # Nominal laser energy: 5.61 J\n",
    "models_0409['Relative GVD']= models_0409['GVD']-38500                       # Nominal GVD: 38500 fs^2\n",
    "\n",
    "# Calculate Set number to be able to aggregate sets of 10 shots pertaining to the same input parameter configuration\n",
    "shotnumbers = shotlog.index\n",
    "shotnumbers=shotnumbers[2:]\n",
    "for i in range(1,len(shotnumbers),1):\n",
    "    mask = models_0409['Shot'].between(shotnumbers[i-1],shotnumbers[i])\n",
    "    models_0409.loc[mask, 'Set number'] = i\n",
    "\n",
    "# Aggregate whole dataset and determine maximum charge\n",
    "summary_vars = ['Relative focus','Relative GVD','Laser energy','Laser height','TOD','B1 pressure','charge in energy window1','charge in energy window2','charge in energy window3','Difference to objective','slice 1 charge']\n",
    "set_pivot_0409 = models_0409.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_pivot_0409.columns = set_pivot_0409.columns.to_flat_index().str.join('_')\n",
    "max_charge_per_set = set_pivot_0409['mean_slice 1 charge'].max()\n",
    "max_set = set_pivot_0409[set_pivot_0409['mean_slice 1 charge'] == set_pivot_0409['mean_slice 1 charge'].max()]\n",
    "\n",
    "\n",
    "# Segment data of the whole day into optimization runs of models with different hyperparameters\n",
    "model_window_5 = models_0409.loc[(models_0409['Shot']>10)&(models_0409['Shot']<260)]\n",
    "model_window_10 = models_0409.loc[(models_0409['Shot']>260)&(models_0409['Shot']<520)]\n",
    "model_window_25_beta_1 = models_0409.loc[(models_0409['Shot']>520)&(models_0409['Shot']<770)]\n",
    "model_window_25_beta_3 = models_0409.loc[(models_0409['Shot']>770)&(models_0409['Shot']<1030)]\n",
    "model_window_25_beta_grow = models_0409.loc[(models_0409['Shot']>1030)&(models_0409['Shot']<1280)]\n",
    "model_jessica = models_0409.loc[(models_0409['Shot']>1280)&(models_0409['Shot']<1530)]\n",
    "\n",
    "# Aggregate the data into sets of ten shots representing one input parameter configuration\n",
    "set_model_window_5 = model_window_5.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_model_window_10 = model_window_10.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_model_window_25_beta_1 = model_window_25_beta_1.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_model_window_25_beta_3 = model_window_25_beta_3.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_model_window_25_beta_grow = model_window_25_beta_grow.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "set_model_jessica = model_jessica.pivot_table(index='Set number', values=summary_vars, aggfunc=['mean','std'])\n",
    "\n",
    "# Flatten column names to reference column names more conveniently\n",
    "def flatten_column_names(df):\n",
    "    \"\"\"Flatten column names to reference them more conveniently\"\"\"\n",
    "    cols = df.columns.to_flat_index()\n",
    "    df.columns = cols.str.join('_')\n",
    "    return df\n",
    "\n",
    "set_model_window_5 = flatten_column_names(set_model_window_5)\n",
    "set_model_window_10 = flatten_column_names(set_model_window_10)\n",
    "set_model_window_25_beta_1 = flatten_column_names(set_model_window_25_beta_1)\n",
    "set_model_window_25_beta_3 = flatten_column_names(set_model_window_25_beta_3)\n",
    "set_model_window_25_beta_grow = flatten_column_names(set_model_window_25_beta_grow)\n",
    "set_model_jessica = flatten_column_names(set_model_jessica)\n",
    "\n",
    "\n",
    "set_model_window_5['Rel slice charge']            = set_model_window_5['mean_slice 1 charge']/max_charge_per_set\n",
    "set_model_window_10['Rel slice charge']           = set_model_window_10['mean_slice 1 charge']/max_charge_per_set\n",
    "set_model_window_25_beta_1['Rel slice charge']    = set_model_window_25_beta_1['mean_slice 1 charge']/max_charge_per_set\n",
    "set_model_window_25_beta_3['Rel slice charge']    = set_model_window_25_beta_3['mean_slice 1 charge']/max_charge_per_set\n",
    "set_model_window_25_beta_grow['Rel slice charge'] = set_model_window_25_beta_grow['mean_slice 1 charge']/max_charge_per_set\n",
    "set_model_jessica['Rel slice charge']             = set_model_jessica['mean_slice 1 charge']/max_charge_per_set\n",
    "\n",
    "\n",
    "for df_name in ['set_model_window_5', 'set_model_window_10', 'set_model_window_25_beta_1', 'set_model_window_25_beta_3', 'set_model_window_25_beta_grow','set_model_jessica']:\n",
    "    set_df = eval(df_name)\n",
    "    set_df['max charge'] = set_df['Rel slice charge'].shift().expanding().max()\n",
    "    set_df['max charge'] = set_df['max charge'].shift(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dcfdec7d",
   "metadata": {},
   "source": [
    "# Hyperparameter tuning - Figures 4 and 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a32e5135",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 4b\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "plt.rcParams[\"figure.figsize\"] = (5,7)\n",
    "sns.lineplot(data=set_model_slice_charge, x=np.arange(0,27,1),y=set_model_slice_charge['max charge']*max_set['mean_slice 1 charge'].iloc[0], label='Charge in energy slice [pC]', color=etheo[0], linewidth=6, ax=ax)\n",
    "sns.pointplot(data=set_model_slice_charge, x=np.arange(0,27,1),y=set_model_slice_charge['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[0], marker='D', markersize=4, alpha=0.6, ax=ax)\n",
    "ax.errorbar(x=np.arange(0,27,1), y=set_model_slice_charge['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_slice_charge['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[0],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['max charge']*max_set['mean_slice 1 charge'].iloc[0], label='Charge in Gaussian window [pC]', color=etheo[1], linewidth=6, ax=ax)\n",
    "sns.pointplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[1], marker='D', markersize=3, alpha=0.6, ax=ax)\n",
    "ax.errorbar(x=np.arange(0,26,1), y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_func['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[1],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_jessica, x=np.arange(0,25,1),y=set_model_jessica['max charge']*max_set['mean_slice 1 charge'].iloc[0],label='Difference to target spectrum [pC]', color=etheo[3], linewidth=6, ax=ax)\n",
    "sns.pointplot(data=set_model_jessica, x=np.arange(0,25,1),y=set_model_jessica['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[3], marker='D', markersize=4, alpha=0.6, ax=ax)\n",
    "ax.errorbar(x=np.arange(0,25,1), y=set_model_jessica['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_jessica['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[3],capsize=3, alpha=0.6)\n",
    "plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.2))\n",
    "plt.ylabel('Charge in energy slice [pC]')\n",
    "plt.xticks(range(0,27,5))\n",
    "plt.xlabel('Iteration')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cfd749f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 5b\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "plt.rcParams[\"figure.figsize\"] = (5,7)\n",
    "sns.lineplot(data=set_model_window_5, x=np.arange(0,25,1),y=set_model_window_5['max charge']*max_set['mean_slice 1 charge'].iloc[0],label=r'Gaussian window ($\\sigma$ = 5 MeV)', color=etheo[0], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_5, x=np.arange(0,25,1),y=set_model_window_5['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[0], marker='D', markersize=4, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,25,1), y=set_model_window_5['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_5['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[0],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_10, x=np.arange(0,26,1),y=set_model_window_10['max charge']*max_set['mean_slice 1 charge'].iloc[0], label=r'Gaussian window ($\\sigma$ = 10 MeV)', color=etheo[1], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_10, x=np.arange(0,26,1),y=set_model_window_10['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[1], marker='D', markersize=4, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,26,1), y=set_model_window_10['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_10['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[1],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['max charge']*max_set['mean_slice 1 charge'].iloc[0], label= r'Gaussian window ($\\sigma$ = 25 MeV)', color=etheo[3], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[3], marker='D', markersize=4, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,26,1), y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_func['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[3],capsize=3, alpha=0.6)\n",
    "plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.2))\n",
    "plt.ylabel('Charge in energy slice [pC]')\n",
    "plt.xticks(range(0,27,5))\n",
    "plt.xlabel('Iteration')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99ae86b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 5a\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "plt.rcParams[\"figure.figsize\"] = (5,7)\n",
    "sns.lineplot(data=set_model_window_25_beta_1, x=np.arange(0,25,1),y=set_model_window_25_beta_1['max charge']*max_set['mean_slice 1 charge'].iloc[0],label=r'Upper confidence bound ($\\beta$ = 1)', color=etheo[0], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_25_beta_1, x=np.arange(0,25,1),y=set_model_window_25_beta_1['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[0], marker='D', markersize=3, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,25,1), y=set_model_window_25_beta_1['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_25_beta_1['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[0],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1),y=set_model_window_25_beta_3['max charge']*max_set['mean_slice 1 charge'].iloc[0], label=r'Upper confidence bound ($\\beta$ = 3)', color=etheo[1], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1),y=set_model_window_25_beta_3['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[1], marker='D', markersize=3, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,26,1), y=set_model_window_25_beta_3['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_25_beta_3['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[1],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_25_beta_grow, x=np.arange(0,25,1),y=set_model_window_25_beta_grow['max charge']*max_set['mean_slice 1 charge'].iloc[0], label= r'Upper confidence bound ($\\beta$ variable)', color=etheo[2], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_25_beta_grow, x=np.arange(0,25,1),y=set_model_window_25_beta_grow['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[2], marker='D', markersize=3, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,25,1), y=set_model_window_25_beta_grow['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_25_beta_grow['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[2],capsize=3, alpha=0.6)\n",
    "sns.lineplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['max charge']*max_set['mean_slice 1 charge'].iloc[0], label=r'Upper confidence bound ($\\beta$=7)', color=etheo[3], linewidth=6)\n",
    "sns.pointplot(data=set_model_window_func, x=np.arange(0,26,1),y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], linestyles='None', color=etheo[3], marker='D', markersize=3, alpha=0.6)\n",
    "ax.errorbar(x=np.arange(0,26,1), y=set_model_window_func['Rel slice charge']*max_set['mean_slice 1 charge'].iloc[0], yerr=set_model_window_func['std_slice 1 charge']/np.sqrt(10),fmt=\"none\",ecolor=etheo[3],capsize=3, alpha=0.6)\n",
    "plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.2))\n",
    "plt.ylabel('Charge in energy slice [pC]')\n",
    "plt.xticks(range(0,27,5))\n",
    "plt.xlabel('Iteration')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b89eea7a",
   "metadata": {},
   "source": [
    "# Parameter tuning - Figure 7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8249ad4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Find parameters to indentify configuration yielding maximum charge\n",
    "\n",
    "set_model_jessica['max laser energy']=set_model_jessica['Laser energy'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max laser energy']=set_model_jessica['max laser energy'].ffill()\n",
    "set_model_jessica['max gvd']=set_model_jessica['Relative GVD'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max gvd']=set_model_jessica['max gvd'].ffill()\n",
    "set_model_jessica['max tod']=set_model_jessica['TOD'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max tod']=set_model_jessica['max tod'].ffill()\n",
    "set_model_jessica['max focus']=set_model_jessica['Relative focus'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max focus']=set_model_jessica['max focus'].ffill()\n",
    "set_model_jessica['max height']=set_model_jessica['Laser height'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max height']=set_model_jessica['max height'].ffill()\n",
    "set_model_jessica['max laser energy']=set_model_jessica['Laser energy'][set_model_jessica['max charge']==set_model_jessica['Rel slice charge']]\n",
    "set_model_jessica['max laser energy']=set_model_jessica['max laser energy'].ffill()\n",
    "\n",
    "set_model_slice_charge['max laser energy']=set_model_slice_charge['Laser energy'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max laser energy']=set_model_slice_charge['max laser energy'].ffill()\n",
    "set_model_slice_charge['max gvd']=set_model_slice_charge['Relative GVD'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max gvd']=set_model_slice_charge['max gvd'].ffill()\n",
    "set_model_slice_charge['max tod']=set_model_slice_charge['TOD'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max tod']=set_model_slice_charge['max tod'].ffill()\n",
    "set_model_slice_charge['max focus']=set_model_slice_charge['Relative focus'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max focus']=set_model_slice_charge['max focus'].ffill()\n",
    "set_model_slice_charge['max height']=set_model_slice_charge['Laser height'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max height']=set_model_slice_charge['max height'].ffill()\n",
    "set_model_slice_charge['max laser energy']=set_model_slice_charge['Laser energy'][set_model_slice_charge['max charge']==set_model_slice_charge['Rel slice charge']]\n",
    "set_model_slice_charge['max laser energy']=set_model_slice_charge['max laser energy'].ffill()\n",
    "\n",
    "set_model_window_func['max laser energy']=set_model_window_func['Laser energy'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max laser energy']=set_model_window_func['max laser energy'].ffill()\n",
    "set_model_window_func['max gvd']=set_model_window_func['Relative GVD'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max gvd']=set_model_window_func['max gvd'].ffill()\n",
    "set_model_window_func['max tod']=set_model_window_func['TOD'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max tod']=set_model_window_func['max tod'].ffill()\n",
    "set_model_window_func['max focus']=set_model_window_func['Relative focus'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max focus']=set_model_window_func['max focus'].ffill()\n",
    "set_model_window_func['max height']=set_model_window_func['Laser height'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max height']=set_model_window_func['max height'].ffill()\n",
    "set_model_window_func['max laser energy']=set_model_window_func['Laser energy'][set_model_window_func['max charge']==set_model_window_func['Rel slice charge']]\n",
    "set_model_window_func['max laser energy']=set_model_window_func['max laser energy'].ffill()\n",
    "\n",
    "set_model_window_25_beta_3['max laser energy']=set_model_window_25_beta_3['Laser energy'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max laser energy']=set_model_window_25_beta_3['max laser energy'].ffill()\n",
    "set_model_window_25_beta_3['max gvd']=set_model_window_25_beta_3['Relative GVD'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max gvd']=set_model_window_25_beta_3['max gvd'].ffill()\n",
    "set_model_window_25_beta_3['max tod']=set_model_window_25_beta_3['TOD'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max tod']=set_model_window_25_beta_3['max tod'].ffill()\n",
    "set_model_window_25_beta_3['max focus']=set_model_window_25_beta_3['Relative focus'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max focus']=set_model_window_25_beta_3['max focus'].ffill()\n",
    "set_model_window_25_beta_3['max height']=set_model_window_25_beta_3['Laser height'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max height']=set_model_window_25_beta_3['max height'].ffill()\n",
    "set_model_window_25_beta_3['max laser energy']=set_model_window_25_beta_3['Laser energy'][set_model_window_25_beta_3['max charge']==set_model_window_25_beta_3['Rel slice charge']]\n",
    "set_model_window_25_beta_3['max laser energy']=set_model_window_25_beta_3['max laser energy'].ffill()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cabcc0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Routine for generating a colored line\n",
    "\n",
    "import warnings\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "from matplotlib.collections import LineCollection\n",
    "from matplotlib import cm\n",
    "\n",
    "def colored_line(x, y, c, ax, **lc_kwargs):\n",
    "    \"\"\"\n",
    "    Plot a line with a color specified along the line by a third value.\n",
    "\n",
    "    It does this by creating a collection of line segments. Each line segment is\n",
    "    made up of two straight lines each connecting the current (x, y) point to the\n",
    "    midpoints of the lines connecting the current point with its two neighbors.\n",
    "    This creates a smooth line with no gaps between the line segments.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    x, y : array-like\n",
    "        The horizontal and vertical coordinates of the data points.\n",
    "    c : array-like\n",
    "        The color values, which should be the same size as x and y.\n",
    "    ax : Axes\n",
    "        Axis object on which to plot the colored line.\n",
    "    **lc_kwargs\n",
    "        Any additional arguments to pass to matplotlib.collections.LineCollection\n",
    "        constructor. This should not include the array keyword argument because\n",
    "        that is set to the color argument. If provided, it will be overridden.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    matplotlib.collections.LineCollection\n",
    "        The generated line collection representing the colored line.\n",
    "    \"\"\"\n",
    "    if \"array\" in lc_kwargs:\n",
    "        warnings.warn('The provided \"array\" keyword argument will be overridden')\n",
    "\n",
    "    # Default the capstyle to butt so that the line segments smoothly line up\n",
    "    default_kwargs = {\"capstyle\": \"butt\"}\n",
    "    default_kwargs.update(lc_kwargs)\n",
    "\n",
    "    # Compute the midpoints of the line segments. Include the first and last points\n",
    "    # twice so we don't need any special syntax later to handle them.\n",
    "    x = np.asarray(x)\n",
    "    y = np.asarray(y)\n",
    "    x_midpts = np.hstack((x[0], 0.5 * (x[1:] + x[:-1]), x[-1]))\n",
    "    y_midpts = np.hstack((y[0], 0.5 * (y[1:] + y[:-1]), y[-1]))\n",
    "\n",
    "    # Determine the start, middle, and end coordinate pair of each line segment.\n",
    "    # Use the reshape to add an extra dimension so each pair of points is in its\n",
    "    # own list. Then concatenate them to create:\n",
    "    # [\n",
    "    #   [(x1_start, y1_start), (x1_mid, y1_mid), (x1_end, y1_end)],\n",
    "    #   [(x2_start, y2_start), (x2_mid, y2_mid), (x2_end, y2_end)],\n",
    "    #   ...\n",
    "    # ]\n",
    "    coord_start = np.column_stack((x_midpts[:-1], y_midpts[:-1]))[:, np.newaxis, :]\n",
    "    coord_mid = np.column_stack((x, y))[:, np.newaxis, :]\n",
    "    coord_end = np.column_stack((x_midpts[1:], y_midpts[1:]))[:, np.newaxis, :]\n",
    "    segments = np.concatenate((coord_start, coord_mid, coord_end), axis=1)\n",
    "\n",
    "    lc = LineCollection(segments, **default_kwargs)\n",
    "    lc.set_array(c)  # set the colors of each segment\n",
    "\n",
    "    return ax.add_collection(lc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adcead4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Figure 7a\n",
    "\n",
    "fig, axs = plt.subplots(5,1, figsize=(10,16))\n",
    "fig.tight_layout()\n",
    "\n",
    "axs[4].errorbar(np.arange(0, 26, 1),set_model_window_25_beta_3['Relative focus'],yerr=0.171, color=etheo[0], capsize=6, linestyle='',marker='s',markersize=4)\n",
    "colored_line(np.arange(0,26,1),set_model_window_25_beta_3['max focus'],set_model_window_25_beta_3['slice 1 charge'], linewidth=3.5, cmap=cut_jurjen,label='Best iteration',  ax=axs[4])\n",
    "axs[4].axvline(x=5, color=etheo[1])\n",
    "axs[4].axvline(x=12, color=etheo[2])\n",
    "axs[4].axvline(x=16, color=etheo[3])\n",
    "axs[4].set_ylabel(r'Focus position'+'\\n'+'[mm]', fontsize=38, rotation=0, loc='center')\n",
    "#axs[1].set_xlabel('Iteration')\n",
    "axs[4].set_xticks(range(0,26,5))\n",
    "#axs[4].get_legend().set_visible(False)\n",
    "axs[4].yaxis.set_label_coords(-0.5, 0.2)\n",
    "axs[4].tick_params(axis='both', which='major', labelsize=38)\n",
    "\n",
    "axs[1].errorbar(np.arange(0, 26, 1),set_model_window_25_beta_3['Laser energy']*0.48,yerr=0.0249, color=etheo[0], capsize=6, linestyle='',marker='s',markersize=4)\n",
    "#sns.lineplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['max laser energy']*0.48, label='Best iteration', color=etheo[0], linewidth=2, ax=axs[1])\n",
    "colored_line(np.arange(0,26,1),set_model_window_25_beta_3['max laser energy']*0.48,set_model_window_25_beta_3['slice 1 charge'], linewidth=4.5, cmap=cut_jurjen,label='Best iteration',  ax=axs[1])\n",
    "\n",
    "axs[1].set_ylabel(r'Laser energy'+'\\n'+'[J]', fontsize=38, rotation=0, loc='center')\n",
    "#axs[0].set_xlabel('Iteration')\n",
    "axs[1].axvline(x=5, color=etheo[1])\n",
    "axs[1].axvline(x=12, color=etheo[2])\n",
    "axs[1].axvline(x=16, color=etheo[3])\n",
    "axs[1].set_xticks(range(0,26,5))\n",
    "axs[1].yaxis.set_label_coords(-0.5, 0.2)\n",
    "axs[1].tick_params(axis='both', which='major', labelsize=38)\n",
    "\n",
    "axs[2].errorbar(np.arange(0, 26, 1),set_model_window_25_beta_3['Laser height'],yerr=0.005, color=etheo[0], capsize=6, linestyle='',marker='s',markersize=4)\n",
    "#sns.pointplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['Laser height'], label='Iteration', color=etheo[0], linewidth=2, ax=axs[2],linestyle='')\n",
    "#sns.lineplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['max height'], label='Best iteration', color=etheo[0], linewidth=2, ax=axs[2])\n",
    "im=colored_line(np.arange(0,26,1),set_model_window_25_beta_3['max height'],set_model_window_25_beta_3['slice 1 charge'], linewidth=4.5, cmap=cut_jurjen,label='Best iteration',  ax=axs[2])\n",
    "\n",
    "axs[2].set_ylabel('Nozzle height'+'\\n'+'[mm]', fontsize=38, rotation=0, loc='center')\n",
    "#axs[2].set_xlabel('Iteration')\n",
    "axs[2].axvline(x=5, color=etheo[1])\n",
    "axs[2].axvline(x=12, color=etheo[2])\n",
    "axs[2].axvline(x=16, color=etheo[3])\n",
    "axs[2].set_xticks(range(0,26,5))\n",
    "axs[2].yaxis.set_label_coords(-0.5, 0.2)\n",
    "axs[2].tick_params(axis='both', which='major', labelsize=38)\n",
    "\n",
    "axs[3].errorbar(np.arange(0, 26, 1),set_model_window_25_beta_3['Relative GVD'],yerr=215, color=etheo[0], capsize=6, linestyle='',marker='s',markersize=4)\n",
    "#sns.pointplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['Relative GVD'], label='Iteration', color=etheo[0], linewidth=2, ax=axs[3],linestyle='')\n",
    "#sns.lineplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['max gvd'], label='Best iteration', color=etheo[0], linewidth=2, ax=axs[3])\n",
    "colored_line(np.arange(0,26,1),set_model_window_25_beta_3['max gvd'],set_model_window_25_beta_3['slice 1 charge'], linewidth=4.5, cmap=cut_jurjen,label='Best iteration',  ax=axs[3])\n",
    "\n",
    "axs[3].set_ylabel(r'Laser GVD'+'\\n'+'$\\mathrm{[fs^2]}$', fontsize=38, rotation=0, loc='center')\n",
    "#axs[3].set_xlabel('Iteration')\n",
    "axs[3].axvline(x=5, color=etheo[1])\n",
    "axs[3].axvline(x=12, color=etheo[2])\n",
    "axs[3].axvline(x=16, color=etheo[3])\n",
    "axs[3].set_xticks(range(0,26,5))\n",
    "#axs[3].get_legend().set_visible(False)\n",
    "axs[3].yaxis.set_label_coords(-0.5, 0.2)\n",
    "axs[3].tick_params(axis='both', which='major', labelsize=38)\n",
    "\n",
    "axs[0].errorbar(np.arange(0, 26, 1),set_model_window_25_beta_3['TOD'],yerr=6256, color=etheo[0], capsize=6, linestyle='',marker='s',markersize=4)\n",
    "#sns.lineplot(data=set_model_window_25_beta_3, x=np.arange(0,26,1), y=set_model_window_25_beta_3['max tod'], label='Best iteration', color=etheo[0], linewidth=2, ax=axs[0])\n",
    "colored_line(np.arange(0,26,1),set_model_window_25_beta_3['max tod'],set_model_window_25_beta_3['slice 1 charge'], linewidth=4.5, cmap=cut_jurjen,label='Best iteration',  ax=axs[0])\n",
    "\n",
    "axs[0].set_ylabel(r'Laser TOD'+'\\n'+'$\\mathrm{[fs^3]}$', fontsize=38, rotation=0, loc='center')\n",
    "axs[4].set_xlabel('Iteration', fontsize=38)\n",
    "axs[0].set_xticks(range(0,26,5))\n",
    "axs[0].axvline(x=5, color=etheo[1])\n",
    "axs[0].axvline(x=12, color=etheo[2])\n",
    "axs[0].axvline(x=16, color=etheo[3])\n",
    "axs[0].yaxis.set_label_coords(-0.5, 0.2)\n",
    "axs[0].legend(loc='upper center', bbox_to_anchor=(0.5,-0.6))\n",
    "axs[0].tick_params(axis='both', which='major', labelsize=38)\n",
    "\n",
    "fig.subplots_adjust(right=0.85)\n",
    "cbar_ax = fig.add_axes([0.90, 0.3, 0.03, 0.3])\n",
    "col=fig.colorbar(im, cax=cbar_ax)\n",
    "cbar_ax.tick_params(labelsize=28)\n",
    "col.set_label(\"Charge in energy slice [pC]\", fontsize=28)\n",
    "plt.savefig('./tuning_parameters_conv_talk.png', bbox_inches=\"tight\", pad_inches=0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16c0835f",
   "metadata": {},
   "source": [
    "# Mutual Information - Table 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9dd7b89a",
   "metadata": {},
   "outputs": [],
   "source": [
    "allpoints = pd.concat([set_pivot_1908,set_pivot_0409],axis=0,ignore_index=True)\n",
    "allpoints.drop(117, inplace=True)\n",
    "allpoints['Laser height'].max()\n",
    "allpoints['Laser energy'] = allpoints['Laser energy']*0.48 # Add transmission factor to convert to real values in chamber\n",
    "\n",
    "mi_selection = allpoints[['Laser height','Laser energy', 'Relative GVD', 'TOD', 'Relative focus', 'Difference to objective', 'slice 1 charge', 'charge in energy window']]\n",
    "mi_selection.rename(columns={'Laser energy':r'Laser energy', 'Relative GVD':r'Laser GVD', 'TOD':r'Laser TOD', 'Relative focus':r'Focus position', 'Difference to objective':'Difference to target spectrum', 'slice 1 charge':'Charge in energy slice','charge in energy window':'Charge in Gaussian window'}, inplace=True)\n",
    "correlation_matrix=pairwise_mi(mi_selection, drop_nan=True)\n",
    "plt.rcParams[\"figure.figsize\"] = (2,4)\n",
    "plot_range = correlation_matrix.iloc[0:5, 6:7]\n",
    "sns.heatmap(plot_range, annot=True, cmap=jurjen_palette, fmt=\".2f\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe2b60fa",
   "metadata": {},
   "source": [
    "# Plot resulting electron spectra end their average - Figure 7b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a173b9f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Load electron spectra of shots pertaining to Iteration 5, 12 and 16\n",
    "\n",
    "# Generate shotnumbers of spectra to be loaded, 10 shots pertaining to one Iteration\n",
    "shotnr5 = np.arange(820,830,1)\n",
    "shotnr12 = np.arange(890,900,1)\n",
    "shotnr16 = np.arange(930,940,1)\n",
    "\n",
    "# method for loading spectra\n",
    "def spectrum(shots):\n",
    "    df = pd.DataFrame()\n",
    "    for i in shots:\n",
    "        spectrum = pd.read_table('./lineout_data_00'+str(i)+'.txt', sep=',')\n",
    "        df = pd.concat([df, spectrum], ignore_index=True, axis=1)\n",
    "    return df\n",
    "\n",
    "#Read in spectra and concatenate them to create a suitable format for sns.lineplot\n",
    "shots5 = spectrum(shotnr5)\n",
    "shots5.dropna(inplace=True)\n",
    "shots5 = shots5[[0,1,3,5,7,9,11,13,15,17,19]]\n",
    "shots5_long = shots5.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")\n",
    "\n",
    "shots12 = spectrum(shotnr12)\n",
    "shots12.dropna(inplace=True)\n",
    "shots12 = shots12[[0,1,3,5,7,9,11,13,15,17,19]]\n",
    "shots12_long = shots12.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")\n",
    "\n",
    "shots16 = spectrum(shotnr16)\n",
    "shots16.dropna(inplace=True)\n",
    "shots16 = shots16[[0,1,3,5,7,9,11,13,15,17,19]]\n",
    "shots16_long = shots16.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b536ffe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 7b\n",
    "fig, ax = plt.subplots()\n",
    "sns.lineplot(data=shots5_long, x=0, y='charge', color=etheo[1], label='Iteration 5', ax=ax, errorbar='sd')\n",
    "sns.lineplot(data=shots13_long, x=0, y='charge', color=etheo[2], label='Iteration 12',ax=ax, errorbar='sd')\n",
    "sns.lineplot(data=shots16_long, x=0, y='charge', color=etheo[3], label='Iteration 16', ax=ax, errorbar='sd')\n",
    "plt.ylim(0,12)\n",
    "plt.xlim(100,250)\n",
    "ax.set_xlabel(r'Electron energy [MeV]')\n",
    "ax.set_ylabel(r'Charge density [pC/MeV]')\n",
    "ax.axvline(x=190, color='grey', linestyle='--', linewidth=2)\n",
    "ax.axvline(x=200, color='grey', linestyle='--', linewidth=2)\n",
    "plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.2))\n",
    "plt.savefig('./electron_sperctra_tuning.png', bbox_inches=\"tight\", pad_inches=0.01)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2133997d",
   "metadata": {},
   "source": [
    "# Plot electron spectra for different window width - Figure 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7510a06",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate shotnumbers of spectra to be loaded, 10 shots pertaining to one Iteration\n",
    "widthnr5 = np.arange(180,190,1)\n",
    "widthnr10 = np.arange(480,490,1)\n",
    "widthnr25 = np.arange(930,940,1)\n",
    "\n",
    "# method for loading spectra\n",
    "def spectrum(shots):\n",
    "    df = pd.DataFrame()\n",
    "    for i in shots:\n",
    "        spectrum = pd.read_table('./lineout_data_00'+str(i)+'.txt', sep=',')\n",
    "        df = pd.concat([df, spectrum], ignore_index=True, axis=1)\n",
    "    return df\n",
    "\n",
    "# Read in spectra and concatenate them to create a suitable format for sns.lineplot\n",
    "width5 = spectrum(widthnr5)\n",
    "width5.dropna(inplace=True)\n",
    "width5 = width5[[0,1,3,5,7,9,11,13,15,17]]\n",
    "width5_long = width5.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")\n",
    "\n",
    "width10 = spectrum(widthnr10)\n",
    "width10.dropna(inplace=True)\n",
    "width10 = width10[[0,1,3,5,7,9,11,13,15,17]]\n",
    "width10_long = width10.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")\n",
    "\n",
    "width25 = spectrum(widthnr25)\n",
    "width25.dropna(inplace=True)\n",
    "width25 = width25[[0,1,3,5,7,9,11,13,15,17,19]]\n",
    "width25_long = width25.melt(id_vars=0, var_name=\"shot\", value_name=\"charge\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccc2a74e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 5c\n",
    "fig, ax = plt.subplots()\n",
    "sns.lineplot(data=width5_long, x=0, y='charge', color=etheo[0], label=r'$\\sigma = 5 $ MeV', ax=ax, errorbar='sd')\n",
    "sns.lineplot(data=width10_long, x=0, y='charge', color=etheo[1], label=r'$\\sigma = 10 $ MeV',ax=ax, errorbar='sd')\n",
    "sns.lineplot(data=width25_long, x=0, y='charge', color=etheo[3], label=r'$\\sigma = 25 $ MeV', ax=ax, errorbar='sd')\n",
    "plt.ylim(0,12.5)\n",
    "plt.xlim(130,250)\n",
    "ax.set_xlabel(r'Electron energy [MeV]')\n",
    "ax.set_ylabel(r'Charge density [pC/MeV]')\n",
    "ax.axvline(x=190, color='grey', linestyle='--', linewidth=2)\n",
    "ax.axvline(x=200, color='grey', linestyle='--', linewidth=2)\n",
    "plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.2))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cecec801",
   "metadata": {},
   "source": [
    "# Scaling comparing to Lu et al - Figure 9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae7db844",
   "metadata": {},
   "outputs": [],
   "source": [
    "allpoints = pd.read_excel('./allpoints_with_noise_for_training.xlsx')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d00417a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calculate Laser power from pulse length measured with online SPIDER\n",
    "allpoints['Laser Power [TW]']=allpoints['Laser Energy [J]']/allpoints['FWHM pulseduration (fs)']*1000\n",
    "\n",
    "# Calculate fit from power law published by Lu et al (10.1103/PhysRevSTAB.10.061301)\n",
    "allpoints['scaling_power']=2.5*1.602e2*np.sqrt(allpoints['Laser Power [TW]']/100)\n",
    "scaling_power=2.5*1.602e2*np.sqrt((power_lin-30)/100)\n",
    "allpoints_pow_filt = allpoints.loc[allpoints['FWHM pulseduration (fs)']<60]\n",
    "power_lin = np.linspace(0,100,1000)\n",
    "\n",
    "# Highlight points whithin one standard deviation of the optimum focus position\n",
    "allpoints_pow_filt_0p5 = allpoints_pow_filt.loc[(allpoints_pow_filt['Z pos real']<0.5+0.171)&(allpoints_pow_filt['Z pos real']>0.5-0.171)] # shots with optimal focus position"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d3bc5b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 9\n",
    "sns.scatterplot(data=allpoints_pow_filt, x='Laser Power [TW]', y='charge over 100 MeV', color=etheo[3], s=10)\n",
    "sns.scatterplot(data=allpoints_pow_filt_0p5, x='Laser Power [TW]', y='charge over 100 MeV', color=etheo[0], s=20, marker='s')\n",
    "plt.plot(power_lin,scaling_power, etheo[1])\n",
    "plt.xlim(0,100)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a39ecbfc",
   "metadata": {},
   "source": [
    "# Noise analysis - Figure 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3283e52f",
   "metadata": {},
   "outputs": [],
   "source": [
    "sets_final = allpoints.pivot_table(index='Set number', values=['Laser Energy [J]', 'real_gvd', 'real_tod', 'Z pos real', 'Pointing'], aggfunc=['mean','std'])\n",
    "sets_final.columns = sets_final.columns.to_flat_index().str.join('_')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b21974bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate Figure 3\n",
    "\n",
    "fig, ax = plt.subplots(1,5, figsize=(25,5))\n",
    "fig.subplots_adjust(wspace=0.4, hspace=0.2)\n",
    "sns.histplot(data=sets_final['std_Laser Energy [J]'], ax=ax[0], color=etheo[0])\n",
    "ax[0].axvline(0.02490612689702056, color=etheo[1])\n",
    "ax[0].set_xlabel('Laser Energy [J]')\n",
    "sns.histplot(data=sets_final['std_real_gvd'], ax=ax[1], color=etheo[0])\n",
    "ax[1].set_xlabel(r'Laser GVD [$\\mathrm{fs^2}$]')\n",
    "ax[1].axvline(sets_final['std_real_gvd'].median(), color=etheo[1])\n",
    "sns.histplot(data=sets_final['std_Pointing'], ax=ax[2], color=etheo[0])\n",
    "ax[2].set_xlabel(r'Nozzle height [$\\mathrm{\\mu}$m]')\n",
    "ax[2].axvline(sets_final['std_Pointing'].median(), color=etheo[1])\n",
    "sns.histplot(data=sets_final['std_Z pos real'], ax=ax[3], color=etheo[0])\n",
    "ax[3].set_xlabel(r'Focus position [mm]')\n",
    "ax[3].axvline(sets_final['std_Z pos real'].median(), color=etheo[1])\n",
    "sns.histplot(data=sets_final['std_real_tod'], ax=ax[4], color=etheo[0])\n",
    "ax[4].set_xlabel(r'Laser TOD [$\\mathrm{fs^3}$]')\n",
    "ax[4].axvline(sets_final['std_real_tod'].median(), color=etheo[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3aa35f52",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Filter out outliers which lie one standard deviation outside of parameter bounds\n",
    "max_foc = allpoints['Relative focus'].max()+sets_final['std_Z pos real'].mean()\n",
    "min_foc = allpoints['Relative focus'].min()-sets_final['std_Z pos real'].mean()\n",
    "max_gvd = allpoints['Relative GVD'].max()+sets_final['std_real_gvd'].mean()\n",
    "min_gvd = allpoints['Relative GVD'].min()-sets_final['std_real_gvd'].mean()\n",
    "max_tod = allpoints['TOD'].max()+sets_final['std_real_tod'].mean()\n",
    "min_tod = allpoints['TOD'].min()-sets_final['std_real_tod'].mean()\n",
    "max_energy = allpoints['Laser Energy [J]'].max()+sets_final['std_Laser Energy [J]'].mean()\n",
    "min_energy = allpoints['Laser Energy [J]'].min()-sets_final['std_Laser Energy [J]'].mean()\n",
    "\n",
    "allpoints_filt=allpoints.loc[(allpoints['Z pos real']<max_foc)&(allpoints['Z pos real']>min_foc)&(allpoints['real_gvd']>min_gvd)&\n",
    "(allpoints['real_gvd']<max_gvd)&(allpoints['real_tod']>min_tod)&(allpoints['real_tod']<max_tod)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6998681c",
   "metadata": {},
   "source": [
    "# Gaussian process parameterspace plotting - Figure 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce9bf86d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Methods for normalizing raw data to be usable for torch and retranslation to the real parameter space\n",
    "def norm_el(a, a_min, a_max):\n",
    "    return (a-a_min)/(a_max-a_min)\n",
    "def rerange(a_norm, a_min, a_max):\n",
    "    return a_min + a_norm*(a_max-a_min)\n",
    "\n",
    "\n",
    "\n",
    "# Parameter ranges of filtered data, limited to 1 standard deviations away from preset parameter bounds\n",
    "defoc_max = 1.671\n",
    "defoc_min = -1.671\n",
    "gvd_max = 825\n",
    "gvd_min = -825\n",
    "tod_max = 26256\n",
    "tod_min = -26256\n",
    "energy_max = 2.5\n",
    "energy_min = 1.5\n",
    "height_max = 2.0\n",
    "height_min = 1.5\n",
    "\n",
    "# Preparation of training data, normalization for torch\n",
    "x_train_all = allpoints_filt\n",
    "x_train_all = x_train_all[['real_tod','Laser Energy [J]','real_gvd','Laser height', 'Z pos real']]\n",
    "x_train_all['real_tod'] = norm_el(x_train_all['real_tod'],tod_min,tod_max)\n",
    "x_train_all['Laser Energy [J]']=norm_el(x_train_all['Laser Energy [J]'], energy_min, energy_max)\n",
    "x_train_all['real_gvd']=norm_el(x_train_all['real_gvd'], gvd_min, gvd_max)\n",
    "x_train_all['Laser height']=norm_el(x_train_all['Laser height'], height_min, height_max)\n",
    "x_train_all['Z pos real']=norm_el(x_train_all['Z pos real'], defoc_min, defoc_max)\n",
    "\n",
    "y_train_all = allpoints_filt['slice 1 charge']\n",
    "y_train_all = y_train_all/200\n",
    "x_train_all = torch.tensor(x_train_all.values)\n",
    "y_train_all = torch.tensor(y_train_all.values)\n",
    "y_train_all = y_train_all.unsqueeze(-1)\n",
    "\n",
    "params_list = [r'Laser TOD [$fs^3$]',r'Laser energy [$J$]', r'Laser GVD [$fs^2$]', r'Nozzle height [$mm$]', r'Focus position [$mm$]']\n",
    "min_values = [-26256, 1.5, -825, 1.5, -1.671]\n",
    "max_values = [26265, 2.5, 825, 2.0, 1.671]\n",
    "batch_size = 8192                                   # batching is needed because of huge tensors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e6bb9b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Training of Gaussian Process\n",
    "model = SingleTaskGP(x_train_all, y_train_all)\n",
    "mll = ExactMarginalLogLikelihood(model.likelihood, model)\n",
    "fit_gpytorch_mll(mll)\n",
    "\n",
    "model.eval()\n",
    "model.likelihood.eval()\n",
    "\n",
    "xi, xj, xk, xl, xm = torch.linspace(0,1, 20, dtype=torch.float64), torch.linspace(0,1, 20, dtype=torch.float64), torch.linspace(0,1,20, dtype=torch.float64), torch.linspace(0,1, 20, dtype=torch.float64), torch.linspace(0,1,20, dtype=torch.float64)\n",
    "X_grid_5d = torch.stack(torch.meshgrid(xi, xj, xk, xl, xm, indexing='ij'), dim=-1)\n",
    "X_5d = X_grid_5d.reshape(-1, 5)\n",
    "print(X_5d.shape)\n",
    "\n",
    "dataset = TensorDataset(X_5d)\n",
    "loader = DataLoader(dataset, batch_size=batch_size, shuffle=False)\n",
    "posterior_mean = []\n",
    "posterior_var = []\n",
    "\n",
    "for batch in loader:            # batching because tensor size is too large to compute otherwise\n",
    "    X_batch = batch[0]\n",
    "    posterior = model.posterior(X_batch)\n",
    "    posterior_mean.append(posterior.mean.detach())\n",
    "    posterior_var.append(posterior.variance.detach())\n",
    "\n",
    "posterior_mean = torch.cat(posterior_mean)          # prediction of slice charge\n",
    "posterior_var = torch.cat(posterior_var)\n",
    "\n",
    "mean_5d = posterior_mean.reshape(20,20,20,20,20).detach().cpu().numpy()   # reshaping\n",
    "lower, upper = posterior.confidence_region()\n",
    "\n",
    "norm = np.sum(mean_5d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d94c52f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generation of Figure 8\n",
    "fig, ax = plt.subplots(5,5, figsize=(20.5, 21))\n",
    "rm_axis = [ax[0,1], ax[0,2],ax[0,3], ax[0,4], ax[1,2], ax[1,3], ax[2,3], ax[1,4],ax[2,4], ax[3,4]]\n",
    "for axs in rm_axis:\n",
    "    fig.delaxes(axs)\n",
    "\n",
    "for i in range(0,5):\n",
    "    for j in range(0,i+1):\n",
    "\n",
    "      # Generation of 1D projections\n",
    "      if i==j:\n",
    "          prodim = (0,1,2,3,4)\n",
    "          prodim = list(prodim)\n",
    "          prodim.remove(i)\n",
    "          prodim = tuple(int(x) for x in prodim)\n",
    "          projection = np.sum(mean_5d, axis=prodim)/norm\n",
    "          xi_v = rerange(xi, min_values[i], max_values[i])\n",
    "          ax[i,j].plot(xi_v, projection, color=etheo[0])\n",
    "          ax[i,j].set_ylim(0,0.15)\n",
    "          ax[i,j].yaxis.set_ticks_position('right')\n",
    "          ax[i,j].tick_params(labelbottom=False,labelleft=False,labelright=True)\n",
    "\n",
    "      # Generation of 2D projections\n",
    "      else:\n",
    "        prodim = (0,1,2,3,4)\n",
    "        prodim = list(prodim)\n",
    "        prodim.remove(i)\n",
    "        prodim.remove(j)\n",
    "        prodim = tuple(int(x) for x in prodim)\n",
    "        projection = np.sum(mean_5d, axis=prodim)/norm\n",
    "          \n",
    "        xi_v = rerange(xi, min_values[i], max_values[i])\n",
    "        xj_v = rerange(xj, min_values[j], max_values[j])\n",
    "\n",
    "        x_train_iv = rerange(x_train_all[:, i], min_values[i], max_values[i])\n",
    "        x_train_jv = rerange(x_train_all[:, j], min_values[j], max_values[j])\n",
    "\n",
    "        left, bottom = 0.25, 0.2\n",
    "        width, height = 0.45, 0.6\n",
    "        im = ax[i,j].pcolormesh(xj_v, xi_v, projection.T, shading='auto', cmap=jurjen_palette, alpha=1.0, vmin=0, vmax=0.01)\n",
    "        ax[i,j].scatter(x_train_jv, x_train_iv, c='k', edgecolors='k', s=3, label='Observed points', marker='D')\n",
    "        \n",
    "        # Cosmetics\n",
    "        if i == 4:\n",
    "            ax[i,j].set_xlabel(params_list[j])\n",
    "        else:\n",
    "            ax[i,j].tick_params(labelbottom=False)\n",
    "        if j==0:\n",
    "            ax[i,j].set_ylabel(params_list[i])\n",
    "        else:\n",
    "            ax[i,j].tick_params(labelleft=False)\n",
    "\n",
    "cbar_ax = fig.add_axes([0.67,0.425,0.01,0.14])\n",
    "fig.colorbar(im,cax=cbar_ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0a0f977",
   "metadata": {},
   "source": [
    "# Reproducibility analysis with dummy Bayesian optimization - Figure 6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "926e5a0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Indices files translating containing indices of Gaussian process dummy measurement\n",
    "bayesian_sets_slice= pd.read_excel('./indices_result_slice_charge.xlsx')\n",
    "bayesian_sets_window1= pd.read_excel('./indices_result_energy_window1.xlsx')\n",
    "bayesian_sets_window2= pd.read_excel('./indices_result_energy_window2.xlsx')\n",
    "bayesian_sets_window3= pd.read_excel('./indices_result_energy_window3.xlsx')\n",
    "bayesian_sets_diff= pd.read_excel('./indices_result_jessica_obj.xlsx')\n",
    "\n",
    "# Create pivot tables for each Iteration of the 100 Models\n",
    "sets = [bayesian_sets_slice, bayesian_sets_window1, bayesian_sets_window2, \n",
    "        bayesian_sets_window3, bayesian_sets_diff]\n",
    "set_names = ['slice', 'window1', 'window2', 'window3', 'diff']\n",
    "pivots = {}\n",
    "\n",
    "for j, set_name in enumerate(sets):\n",
    "    set_name['Setnr'] = (set_name.index / 10).astype(int)\n",
    "    \n",
    "    pivot_name = pd.pivot_table(\n",
    "        set_name, \n",
    "        values=['Laser TOD [$fs^3$]','Laser energy [$J$]','Laser GVD [$fs^2$]',\n",
    "                'Nozzle height [$mm$]','Focus position [$mm$]','slice charge','Modelnumber'], \n",
    "        index=['Setnr'], \n",
    "        aggfunc='mean'\n",
    "    )\n",
    "    for i in range(0, 100, 1):\n",
    "        mask = pivot_name['Modelnumber'] == i\n",
    "        if mask.any():  # Skip empty groups\n",
    "            pivot_name.loc[mask, 'max charge'] = (\n",
    "                pivot_name.loc[mask, 'slice charge'].shift().expanding().max()\n",
    "            ).shift(-1)\n",
    "    pivot_name['Iteration']=pivot_name.index%25\n",
    "    pivot_name.ffill(inplace=True)\n",
    "    pivots[set_names[j] + '_pivot'] = pivot_name\n",
    "\n",
    "# Aggregate data\n",
    "slice_pivot = pd.pivot_table(pivots['slice_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "window1_pivot = pd.pivot_table(pivots['window1_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "window2_pivot = pd.pivot_table(pivots['window2_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "window3_pivot = pd.pivot_table(pivots['window3_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "diff_pivot = pd.pivot_table(pivots['diff_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8fbf7336",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Indices files translating containing indices of Gaussian process dummy measurement\n",
    "bayesian_sets_beta1= pd.read_excel('./window2_beta1.xlsx')\n",
    "bayesian_sets_beta3= pd.read_excel('./window2_beta3.xlsx')\n",
    "bayesian_sets_beta7= pd.read_excel('./indices_result_energy_window2.xlsx')\n",
    "bayesian_sets_betavar= pd.read_excel('./window2_betavar.xlsx')\n",
    "\n",
    "# Create pivot tables for each Iteration of the 100 Models\n",
    "sets = [bayesian_sets_beta1, bayesian_sets_beta3, bayesian_sets_beta7, \n",
    "        bayesian_sets_betavar]\n",
    "set_names = ['beta1', 'beta3', 'beta7', 'betavar']\n",
    "pivots = {}\n",
    "\n",
    "for j, set_name in enumerate(sets):\n",
    "    set_name['Setnr'] = (set_name.index / 10).astype(int)\n",
    "    \n",
    "    pivot_name = pd.pivot_table(\n",
    "        set_name, \n",
    "        values=['Laser TOD [$fs^3$]','Laser energy [$J$]','Laser GVD [$fs^2$]',\n",
    "                'Nozzle height [$mm$]','Focus position [$mm$]','slice charge','Modelnumber'], \n",
    "        index=['Setnr'], \n",
    "        aggfunc='mean'\n",
    "    )\n",
    "    for i in range(0, 100, 1):\n",
    "        mask = pivot_name['Modelnumber'] == i\n",
    "        if mask.any():  # Skip empty groups\n",
    "            pivot_name.loc[mask, 'max charge'] = (\n",
    "                pivot_name.loc[mask, 'slice charge'].shift().expanding().max()\n",
    "            ).shift(-1)\n",
    "    pivot_name['Iteration']=pivot_name.index%25\n",
    "    pivot_name.ffill(inplace=True)\n",
    "    pivots[set_names[j] + '_pivot'] = pivot_name\n",
    "\n",
    "# Aggregate data\n",
    "beta1_pivot = pd.pivot_table(pivots['beta1_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "beta3_pivot = pd.pivot_table(pivots['beta3_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "beta7_pivot = pd.pivot_table(pivots['beta7_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])\n",
    "betavar_pivot = pd.pivot_table(pivots['betavar_pivot'], values=['max charge'], index=['Iteration'], aggfunc=['mean', 'std'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3775eb0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Figure 6a\n",
    "fig = plt.figure(figsize=(11, 6))\n",
    "gs = GridSpec(1, 2, width_ratios=[15, 1])\n",
    "\n",
    "leg_ax = fig.add_subplot(gs[1])\n",
    "plot_ax = fig.add_subplot(gs[0])\n",
    "\n",
    "\n",
    "plt.plot(slice_pivot.index,slice_pivot['mean'], color=etheo[2], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(slice_pivot.index, slice_pivot['mean']-slice_pivot['std'], color=etheo[2], linewidth=2, linestyle=\":\")\n",
    "plt.plot(slice_pivot.index, slice_pivot['mean']+slice_pivot['std'], color=etheo[2], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(window1_pivot.index,window1_pivot['mean']/5, color=etheo[4], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(window1_pivot.index, (window1_pivot['mean']-window1_pivot['std'])/5, color=etheo[4], linewidth=2, linestyle=\":\")\n",
    "plt.plot(window1_pivot.index, (window1_pivot['mean']+window1_pivot['std'])/5, color=etheo[4], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(window2_pivot.index,window2_pivot['mean']/5, color=etheo[3], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(window2_pivot.index, (window2_pivot['mean']-window2_pivot['std'])/5, color=etheo[3], linewidth=2, linestyle=\":\")\n",
    "plt.plot(window2_pivot.index, (window2_pivot['mean']+window2_pivot['std'])/5, color=etheo[3], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(window3_pivot.index,window3_pivot['mean']/5, color=etheo[0], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(window3_pivot.index, (window3_pivot['mean']-window3_pivot['std'])/5, color=etheo[0], linewidth=2, linestyle=\":\")\n",
    "plt.plot(window3_pivot.index, (window3_pivot['mean']+window3_pivot['std'])/5, color=etheo[0], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(diff_pivot.index,diff_pivot['mean']/5, color=etheo[1], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(diff_pivot.index, (diff_pivot['mean']-diff_pivot['std'])/5, color=etheo[1], linewidth=2, linestyle=\":\")\n",
    "plt.plot(diff_pivot.index, (diff_pivot['mean']+diff_pivot['std'])/5, color=etheo[1], linewidth=2, linestyle=\"--\")\n",
    "\n",
    "color_handles = [\n",
    "    Line2D([0], [0], color=etheo[2], lw=4, label=r'Energy slice'),\n",
    "    Line2D([0], [0], color=etheo[4], lw=4, label=r'GW $\\mathrm{\\sigma}$ = 5 MeV'),\n",
    "    Line2D([0], [0], color=etheo[3], lw=4, label=r'GW $\\mathrm{\\sigma}$ = 10 MeV'),\n",
    "    Line2D([0], [0], color=etheo[0], lw=4, label=r'GW $\\mathrm{\\sigma}$ = 25 MeV'),\n",
    "    Line2D([0], [0], color=etheo[1], lw=4, label=r'Difference to objective'),\n",
    "]\n",
    "\n",
    "style_handles = [\n",
    "    Line2D([0], [0], color='black', lw=4, linestyle='-', label='Average'),\n",
    "    Line2D([0], [0], color='black', lw=2, linestyle='--', label='Best Case'),\n",
    "    Line2D([0], [0], color='black', lw=2, linestyle=':', label='Worst Case'),\n",
    "]\n",
    "header_color = Line2D([0], [0], color='none', label=r'$\\bf{Color}$', marker='s', markersize=0, ls='')\n",
    "header_style = Line2D([0], [0], color='none', label=r'$\\bf{Style}$', marker='s', markersize=0, ls='')\n",
    "spacer = Line2D([0], [0], color=(0,0,0,0), label='', lw=0)\n",
    "\n",
    "all_handles = [header_color] + color_handles + [spacer]+[header_style] + style_handles\n",
    "\n",
    "leg_ax.legend(handles=all_handles, frameon=True, loc='center left',\n",
    "              fontsize=18, title_fontsize=20, handlelength=2)\n",
    "leg_ax.axis('off')\n",
    "\n",
    "plot_ax.set_xlabel('Iteration')\n",
    "plot_ax.set_ylabel('Charge in energy slice [pC]')\n",
    "leg_ax.axis('off')\n",
    "plt.tight_layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a92f080",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Figure 6b\n",
    "fig = plt.figure(figsize=(9, 6))\n",
    "gs = GridSpec(1, 2, width_ratios=[15, 1])\n",
    "\n",
    "leg_ax = fig.add_subplot(gs[1])\n",
    "plot_ax = fig.add_subplot(gs[0])\n",
    "\n",
    "plt.plot(beta1_pivot.index,beta1_pivot['mean'], color=etheo[1], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(beta1_pivot.index, beta1_pivot['mean']-beta1_pivot['std'], color=etheo[1], linewidth=2, linestyle=\":\")\n",
    "plt.plot(beta1_pivot.index, beta1_pivot['mean']+beta1_pivot['std'], color=etheo[1], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(beta3_pivot.index,beta3_pivot['mean'], color=etheo[4], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(beta3_pivot.index, (beta3_pivot['mean']-beta3_pivot['std']), color=etheo[4], linewidth=2, linestyle=\":\")\n",
    "plt.plot(beta3_pivot.index, (beta3_pivot['mean']+beta3_pivot['std']), color=etheo[4], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(beta7_pivot.index,beta7_pivot['mean']/5, color=etheo[3], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(beta7_pivot.index, (beta7_pivot['mean']-beta7_pivot['std'])/5, color=etheo[3], linewidth=2, linestyle=\":\")\n",
    "plt.plot(beta7_pivot.index, (beta7_pivot['mean']+beta7_pivot['std'])/5, color=etheo[3], linewidth=2, linestyle=\"--\")\n",
    "plt.plot(betavar_pivot.index,betavar_pivot['mean'], color=etheo[0], linewidth=4, label='Charge in energy slice [pC]')\n",
    "plt.plot(betavar_pivot.index, (betavar_pivot['mean']-betavar_pivot['std']), color=etheo[0], linewidth=2, linestyle=\":\")\n",
    "plt.plot(betavar_pivot.index, (betavar_pivot['mean']+betavar_pivot['std']), color=etheo[0], linewidth=2, linestyle=\"--\")\n",
    "\n",
    "color_handles = [\n",
    "    Line2D([0], [0], color=etheo[1], lw=4, label=r'$\\mathrm{\\beta}$ = 1'),\n",
    "    Line2D([0], [0], color=etheo[4], lw=4, label=r'$\\mathrm{\\beta}$ = 3'),\n",
    "    Line2D([0], [0], color=etheo[3], lw=4, label=r'$\\mathrm{\\beta}$ = 7'),\n",
    "    Line2D([0], [0], color=etheo[0], lw=4, label=r'$\\mathrm{\\beta}$ variable'),\n",
    "]\n",
    "\n",
    "style_handles = [\n",
    "    Line2D([0], [0], color='black', lw=4, linestyle='-', label='Average'),\n",
    "    Line2D([0], [0], color='black', lw=2, linestyle='--', label='Best Case'),\n",
    "    Line2D([0], [0], color='black', lw=2, linestyle=':', label='Worst Case'),\n",
    "]\n",
    "header_color = Line2D([0], [0], color='none', label=r'$\\bf{Color}$', marker='s', markersize=0, ls='')\n",
    "header_style = Line2D([0], [0], color='none', label=r'$\\bf{Style}$', marker='s', markersize=0, ls='')\n",
    "spacer = Line2D([0], [0], color=(0,0,0,0), label='', lw=0)\n",
    "\n",
    "all_handles = [header_color] + color_handles + [spacer]+[header_style] + style_handles\n",
    "\n",
    "leg_ax.legend(handles=all_handles, frameon=True, loc='center left',\n",
    "              fontsize=18, title_fontsize=20, handlelength=2)\n",
    "leg_ax.axis('off')\n",
    "\n",
    "plot_ax.set_xlabel('Iteration')\n",
    "plot_ax.set_ylabel('Charge in energy slice [pC]')\n",
    "leg_ax.axis('off')\n",
    "plt.tight_layout()"
   ]
  }
 ],
 "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.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
