{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "56c93651",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dash import callback, Output, Input, State, html\n",
    "from dash import callback_context\n",
    "import pandas as pd\n",
    "import plotly.graph_objects as go\n",
    "from dash.dependencies import Input, Output\n",
    "import plotly.express as px\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from scipy.interpolate import make_interp_spline\n",
    "import matplotlib.image as mpimg\n",
    "import sys\n",
    "import os\n",
    "dash_dir = os.path.abspath(os.path.join(os.getcwd(), '..'))  # parent of thesis_plot\n",
    "sys.path.append(dash_dir)\n",
    "import functions as functions\n",
    "from plotly.subplots import make_subplots\n",
    "import Thesis_plot.functions as fn\n",
    "import importlib\n",
    "importlib.reload(fn)\n",
    "os.chdir(\"c:/Users/youss/Documents/Tesi/Data/Dash\") "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ab00ca6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "c:\\Users\\youss\\Documents\\Tesi\\Data\\dash\\Thesis_plot\\functions.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n"
     ]
    }
   ],
   "source": [
    "Nominal=1000  #[kW]\n",
    "#Result in MWh\n",
    "combined_energy=fn.energy_analysis(Nominal)\n",
    "combined_energy.rename(columns={\"Gulf_Gabes\": \"Gulf of Gabes\"}, inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "735e1e93",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 69812 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 6 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Load your CSV file\n",
    "df = combined_energy\n",
    "\n",
    "# Convert 'Date' to datetime and extract the month\n",
    "df['Date'] = pd.to_datetime(df['Date'])\n",
    "df['Month'] = df['Date'].dt.month\n",
    "\n",
    "# Define shaded periods (months when system is removed)\n",
    "shaded_periods = {\n",
    "    \"Ceuta\": [1, 2, 3, 4],\n",
    "    \"Jersey\": [11, 12, 1, 2, 3],\n",
    "    \"Zadar\": [11, 12, 1, 2],\n",
    "    \"Gulf of Gabes\": [1, 2, 3, 4]\n",
    "}\n",
    "\n",
    "# Define the locations you want to analyze\n",
    "locations = [\"Ceuta\", \"Gotland\", \"Gulf of Gabes\", \"Pantelleria\", \"Zadar\", \"Jersey\"]\n",
    "\n",
    "# Use a refined color palette\n",
    "colors = [\"#5B8FA8\", \"#C0C0C0\"]  # blue for exploited, grey for not\n",
    "\n",
    "# Create subplots\n",
    "fig, axs = plt.subplots(2, 3, figsize=(12, 6))\n",
    "axs = axs.flatten()\n",
    "\n",
    "# Store wedge references for the legend\n",
    "wedge_refs = None\n",
    "\n",
    "# Plot each location\n",
    "for i, loc in enumerate(locations):\n",
    "    total_energy = df[loc].sum()\n",
    "    \n",
    "    if loc in shaded_periods:\n",
    "        removed_energy = df[df['Month'].isin(shaded_periods[loc])][loc].sum()\n",
    "        exploited_energy = total_energy - removed_energy\n",
    "    else:\n",
    "        removed_energy = 0\n",
    "        exploited_energy = total_energy\n",
    "\n",
    "    wedges, _, autotexts = axs[i].pie(\n",
    "        [exploited_energy, removed_energy],\n",
    "        autopct='%1.2f%%',\n",
    "        startangle=90,\n",
    "        colors=colors,\n",
    "        textprops={'fontsize': 10}\n",
    "    )\n",
    "\n",
    "    axs[i].set_title(loc, fontsize=12)\n",
    "    \n",
    "    # Save wedge references for legend once\n",
    "    if wedge_refs is None:\n",
    "        wedge_refs = wedges\n",
    "\n",
    "# Add a shared legend below the plots\n",
    "fig.legend(wedge_refs, [\"Exploited\", \"Not Exploited\"], loc='lower center', ncol=2, fontsize=12)\n",
    "\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "af60a0b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "               Lost_Energy_Annual_kWh\n",
      "Location                             \n",
      "Ceuta                      647.097304\n",
      "Gotland                      0.000000\n",
      "Gulf of Gabes              617.754398\n",
      "Pantelleria                  0.000000\n",
      "Zadar                      324.225573\n",
      "Jersey                     392.893428\n"
     ]
    }
   ],
   "source": [
    "\n",
    "lost_energy = {}\n",
    "\n",
    "\n",
    "# Calculate lost energy per location\n",
    "for loc in locations:\n",
    "    if loc in shaded_periods:\n",
    "        lost = df[df['Month'].isin(shaded_periods[loc])][loc].sum()\n",
    "    else:\n",
    "        lost = 0  # No removal, no energy loss\n",
    "    lost_energy[loc] = lost\n",
    "\n",
    "# Create DataFrame\n",
    "lost_energy_df = pd.DataFrame.from_dict(lost_energy, orient='index', columns=[\"Lost_Energy_Annual_kWh\"])\n",
    "lost_energy_df.index.name = \"Location\"\n",
    "\n",
    "# Print or save if needed\n",
    "print(lost_energy_df)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2cc99c48",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "141.97314849760002"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "647.097304*0.2194"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "ca520113",
   "metadata": {},
   "outputs": [],
   "source": [
    "shaded_periods = {\n",
    "    \"Ceuta\": [1, 2, 3, 4],          # Jan to Apr\n",
    "    \"Jersey\": [11, 12, 1, 2, 3],    # Nov to Mar\n",
    "    \"Zadar\": [11, 12, 1, 2],        # Nov to Feb\n",
    "    \"Gulf of Gabes\": [1, 2, 3, 4]      # Jan to Apr\n",
    "    # Gotland and Pantelleria are always active\n",
    "}\n",
    "\n",
    "for loc, months in shaded_periods.items():\n",
    "    combined_energy.loc[combined_energy['Month'].isin(months), loc] = 0\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 152192 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 6 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.dates as mdates\n",
    "from matplotlib.ticker import MaxNLocator\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "\n",
    "# List of locations (column names)\n",
    "locations = ['Ceuta', 'Gotland', 'Gulf of Gabes', 'Pantelleria', 'Zadar', 'Jersey']\n",
    "\n",
    "# Shaded periods (months where FPV is removed)\n",
    "shaded_periods = {\n",
    "    \"Ceuta\": [1, 2, 3, 4],          # Jan to Apr\n",
    "    \"Jersey\": [11, 12, 1, 2, 3],    # Nov to Mar\n",
    "    \"Zadar\": [11, 12, 1, 2],        # Nov to Feb\n",
    "    \"Gulf of Gabes\": [1, 2, 3, 4]      # Jan to Apr\n",
    "    # Gotland and Pantelleria are always active\n",
    "}\n",
    "\n",
    "# Convert Date column to datetime if not already\n",
    "combined_energy['Date'] = pd.to_datetime(combined_energy['Date'])\n",
    "combined_energy['Month'] = combined_energy['Date'].dt.month\n",
    "\n",
    "# Create subplots\n",
    "fig, axes = plt.subplots(2, 3, figsize=(12, 6), sharey='row')\n",
    "axes = axes.flatten()\n",
    "\n",
    "for i, loc in enumerate(locations):\n",
    "    ax = axes[i]\n",
    "    \n",
    "    # Plot irradiance\n",
    "    ax.plot(combined_energy['Date'], combined_energy[loc], label=loc, linewidth=0.8, color='goldenrod')\n",
    "    \n",
    "    # Shade days belonging to the removal months\n",
    "    if loc in shaded_periods:\n",
    "        for month in shaded_periods[loc]:\n",
    "            dates_to_shade = combined_energy[combined_energy['Month'] == month]['Date']\n",
    "            for date in dates_to_shade:\n",
    "                ax.axvspan(date, date + pd.Timedelta(days=1), color='grey', alpha=0.1)\n",
    "    \n",
    "    ax.set_title(loc)\n",
    "    ax.set_xlabel(\"Date\")\n",
    "    ax.set_ylabel(r\"$\\overline{P}_h$ [MWh]\")\n",
    "    ax.grid(True)\n",
    "\n",
    "    # Format x-axis to show only months\n",
    "    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))  # %b for abbreviated month name, %m for month number\n",
    "    ax.xaxis.set_major_locator(mdates.MonthLocator())         # One tick per month\n",
    "    ax.xaxis.set_tick_params(rotation=45)\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "507eac7c",
   "metadata": {},
   "source": [
    "YEARLY PRODUCTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "09dd0267",
   "metadata": {},
   "outputs": [],
   "source": [
    "years=20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "id": "640685ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "degraded_data={}\n",
    "locations = ['Ceuta', 'Gulf of Gabes', 'Gotland', 'Jersey', 'Zadar', 'Pantelleria']\n",
    "for loc in locations:\n",
    "    base_energy=combined_energy[loc].sum()\n",
    "    yearly=[base_energy]\n",
    "    for year in range(1,years):\n",
    "        yearly.append(yearly[-1]*(1-0.02))\n",
    "        # Store in dictionary\n",
    "    degraded_data[loc] = yearly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "3e9e91de",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a DataFrame from the dictionary\n",
    "df_yearly_degraded = pd.DataFrame(degraded_data)\n",
    "# Add a Year column for reference (1 to 15)\n",
    "df_yearly_degraded.insert(0, 'Year', range(1, len(df_yearly_degraded)+1))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "id": "9988cb6f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 86512 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 6 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Create subplots\n",
    "fig, axes = plt.subplots(2, 3, figsize=(12, 6), sharey='row')\n",
    "axes = axes.flatten()\n",
    "\n",
    "for i, loc in enumerate(locations):\n",
    "    ax = axes[i]\n",
    "    ax.plot(df_yearly_degraded['Year'], df_yearly_degraded[loc], label=loc, linewidth=2)\n",
    "    ax.set_title(loc)\n",
    "    ax.set_xlabel(\"Date\")\n",
    "    ax.set_ylabel(r\"$E_y$ [MWh]\")\n",
    "    ax.grid(True)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "24fa46dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "#df_yearly_degraded.to_csv(\"PV/df_yearly_production_1mw.csv\", index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "id": "a1519455",
   "metadata": {},
   "outputs": [],
   "source": [
    "def assign_date(df):\n",
    "    date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
    "\n",
    "    # Assign it to a new column\n",
    "    df['Datetime'] = date_range\n",
    "\n",
    "    # Extract Day, Month, and Hour\n",
    "    df['Day'] = df['Datetime'].dt.day\n",
    "    df['Month'] = df['Datetime'].dt.month\n",
    "    df['Hour'] = df['Datetime'].dt.hour\n",
    "    return df "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "f37d263b",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n"
     ]
    }
   ],
   "source": [
    "Gulf_Gabes=pd.read_csv('PV\\Gulf_Gabes.CSV')\n",
    "Gulf_Gabes_2=pd.read_csv('PV\\gulf_gabes_2.CSV')\n",
    "\n",
    "\n",
    "Gulf_Gabes_2=assign_date(Gulf_Gabes_2)\n",
    "Gulf_Gabes=assign_date(Gulf_Gabes)\n",
    "\n",
    "\n",
    "#get the average of each hour over 10 years\n",
    "avg_hourly_energy_Gulf_Gabes_2 = Gulf_Gabes_2.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "avg_hourly_energy_Gulf_Gabes = Gulf_Gabes.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "\n",
    "#some for eeach day\n",
    "daily_energy_Gulf_Gabes_2 = avg_hourly_energy_Gulf_Gabes_2.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "daily_energy_Gulf_Gabes = avg_hourly_energy_Gulf_Gabes.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "\n",
    "#I need this to have the date column to add later \n",
    "daily_energy_Gulf_Gabes_2['Date']=pd.date_range(start='2024-01-01', periods=len(daily_energy_Gulf_Gabes_2), freq='D')\n",
    "# First, assign location names and prepare the 'P' columns\n",
    "daily_energy_Gulf_Gabes['Gulf_Gabes'] = daily_energy_Gulf_Gabes['P']*Nominal/10**6\n",
    "daily_energy_Gulf_Gabes_2['Gulf_Gabes_2'] = daily_energy_Gulf_Gabes_2['P']*Nominal/10**6\n",
    "\n",
    "# Combine into one DataFrame using the Date column from Ceuta\n",
    "combined_energy_gulf_gabes = pd.DataFrame({\n",
    "    'Month':daily_energy_Gulf_Gabes_2['Month'],\n",
    "    'Date': daily_energy_Gulf_Gabes_2['Date'],\n",
    "    'Gulf_Gabes_2': daily_energy_Gulf_Gabes_2['Gulf_Gabes_2'],\n",
    "    'Gulf_Gabes': daily_energy_Gulf_Gabes['Gulf_Gabes'],\n",
    "})\n",
    "\n",
    "# List of locations (column names)\n",
    "locations = [ 'Gulf_Gabes_2', 'Gulf_Gabes']\n",
    "\n",
    "# Shaded periods (months where FPV is removed)\n",
    "shaded_periods = {     \n",
    "    \"Gulf_Gabes\": [1, 2, 3, 4]      # Jan to Apr\n",
    "    # Gotland and Pantelleria are always active\n",
    "}\n",
    "\n",
    "for loc, months in shaded_periods.items():\n",
    "    combined_energy_gulf_gabes.loc[combined_energy_gulf_gabes['Month'].isin(months), loc] = 0\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "id": "e9f5bfce",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n"
     ]
    }
   ],
   "source": [
    "Ceuta = pd.read_csv('PV/Ceuta.CSV')\n",
    "Ceuta_2 = pd.read_csv('PV/Ceuta_2.CSV')\n",
    "\n",
    "# Apply date assignment function\n",
    "Ceuta = assign_date(Ceuta)\n",
    "Ceuta_2 = assign_date(Ceuta_2)\n",
    "\n",
    "# Get the average of each hour over 10 years\n",
    "avg_hourly_energy_Ceuta = Ceuta.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "avg_hourly_energy_Ceuta_2 = Ceuta_2.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "\n",
    "# Sum for each day\n",
    "daily_energy_Ceuta = avg_hourly_energy_Ceuta.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "daily_energy_Ceuta_2 = avg_hourly_energy_Ceuta_2.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "\n",
    "# Create Date column\n",
    "daily_energy_Ceuta_2['Date'] = pd.date_range(start='2024-01-01', periods=len(daily_energy_Ceuta_2), freq='D')\n",
    "\n",
    "# Convert power to energy in MWh using the nominal power\n",
    "daily_energy_Ceuta['Ceuta'] = daily_energy_Ceuta['P'] * Nominal / 10**6\n",
    "daily_energy_Ceuta_2['Ceuta_2'] = daily_energy_Ceuta_2['P'] * Nominal / 10**6\n",
    "\n",
    "# Combine into one DataFrame\n",
    "combined_energy_ceuta = pd.DataFrame({\n",
    "    'Month': daily_energy_Ceuta_2['Month'],\n",
    "    'Date': daily_energy_Ceuta_2['Date'],\n",
    "    'Ceuta_2': daily_energy_Ceuta_2['Ceuta_2'],\n",
    "    'Ceuta': daily_energy_Ceuta['Ceuta'],\n",
    "})\n",
    "\n",
    "# List of locations (column names)\n",
    "locations = ['Ceuta_2', 'Ceuta']\n",
    "\n",
    "# Shaded periods (months where FPV is removed)\n",
    "shaded_periods = {\n",
    "    \"Ceuta\": [1, 2, 3, 4]  # Jan to Apr\n",
    "}\n",
    "\n",
    "# Apply seasonal removal by setting energy to zero for removal months\n",
    "for loc, months in shaded_periods.items():\n",
    "    combined_energy_ceuta.loc[combined_energy_ceuta['Month'].isin(months), loc] = 0\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "e25e17f9",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n"
     ]
    }
   ],
   "source": [
    "Zadar = pd.read_csv('PV/Zadar.CSV')\n",
    "Zadar_2 = pd.read_csv('PV/Zadar_2.CSV')\n",
    "\n",
    "# Apply date assignment function\n",
    "Zadar = assign_date(Zadar)\n",
    "Zadar_2 = assign_date(Zadar_2)\n",
    "\n",
    "# Get the average of each hour over 10 years\n",
    "avg_hourly_energy_Zadar = Zadar.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "avg_hourly_energy_Zadar_2 = Zadar_2.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "\n",
    "# Sum for each day\n",
    "daily_energy_Zadar = avg_hourly_energy_Zadar.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "daily_energy_Zadar_2 = avg_hourly_energy_Zadar_2.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "\n",
    "# Create Date column\n",
    "daily_energy_Zadar_2['Date'] = pd.date_range(start='2024-01-01', periods=len(daily_energy_Zadar_2), freq='D')\n",
    "\n",
    "# Convert power to energy in MWh using the nominal power\n",
    "daily_energy_Zadar['Zadar'] = daily_energy_Zadar['P'] * Nominal / 10**6\n",
    "daily_energy_Zadar_2['Zadar_2'] = daily_energy_Zadar_2['P'] * Nominal / 10**6\n",
    "\n",
    "# Combine into one DataFrame\n",
    "combined_energy_zadar = pd.DataFrame({\n",
    "    'Month': daily_energy_Zadar_2['Month'],\n",
    "    'Date': daily_energy_Zadar_2['Date'],\n",
    "    'Zadar_2': daily_energy_Zadar_2['Zadar_2'],\n",
    "    'Zadar': daily_energy_Zadar['Zadar'],\n",
    "})\n",
    "\n",
    "# List of locations (column names)\n",
    "locations = ['Zadar_2', 'Zadar']\n",
    "\n",
    "# Shaded periods (months where FPV is removed)\n",
    "shaded_periods = {\n",
    "    \"Zadar\": [11, 12, 1, 2]  # Nov to Feb\n",
    "}\n",
    "\n",
    "# Apply seasonal removal by setting energy to zero for removal months\n",
    "for loc, months in shaded_periods.items():\n",
    "    combined_energy_zadar.loc[combined_energy_zadar['Month'].isin(months), loc] = 0\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "id": "c9682786",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n",
      "C:\\Users\\youss\\AppData\\Local\\Temp\\ipykernel_24804\\2539567705.py:2: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  date_range = pd.date_range(start='2010-01-01 00:00', end='2020-12-31 23:00', freq='H')\n"
     ]
    }
   ],
   "source": [
    "\n",
    "Jersey = pd.read_csv('PV/Jersey.CSV')\n",
    "Jersey_2 = pd.read_csv('PV/Jersey_2.CSV')\n",
    "\n",
    "# Apply date assignment function\n",
    "Jersey = assign_date(Jersey)\n",
    "Jersey_2 = assign_date(Jersey_2)\n",
    "\n",
    "# Get the average of each hour over 10 years\n",
    "avg_hourly_energy_Jersey = Jersey.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "avg_hourly_energy_Jersey_2 = Jersey_2.groupby(['Month', 'Day', 'Hour'])['P'].mean().reset_index()\n",
    "\n",
    "# Sum for each day\n",
    "daily_energy_Jersey = avg_hourly_energy_Jersey.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "daily_energy_Jersey_2 = avg_hourly_energy_Jersey_2.groupby(['Month', 'Day'])['P'].sum().reset_index()\n",
    "\n",
    "# Create Date column\n",
    "daily_energy_Jersey_2['Date'] = pd.date_range(start='2024-01-01', periods=len(daily_energy_Jersey_2), freq='D')\n",
    "\n",
    "# Convert power to energy in MWh using the nominal power\n",
    "daily_energy_Jersey['Jersey'] = daily_energy_Jersey['P'] * Nominal / 10**6\n",
    "daily_energy_Jersey_2['Jersey_2'] = daily_energy_Jersey_2['P'] * Nominal / 10**6\n",
    "\n",
    "# Combine into one DataFrame\n",
    "combined_energy_jersey = pd.DataFrame({\n",
    "    'Month': daily_energy_Jersey_2['Month'],\n",
    "    'Date': daily_energy_Jersey_2['Date'],\n",
    "    'Jersey_2': daily_energy_Jersey_2['Jersey_2'],\n",
    "    'Jersey': daily_energy_Jersey['Jersey'],\n",
    "})\n",
    "\n",
    "# List of locations (column names)\n",
    "locations = ['Jersey_2', 'Jersey']\n",
    "\n",
    "# Shaded periods (months where FPV is removed)\n",
    "shaded_periods = {\n",
    "    \"Jersey\": [11, 12, 1, 2]  # Nov to Feb\n",
    "}\n",
    "\n",
    "# Apply seasonal removal by setting energy to zero for removal months\n",
    "for loc, months in shaded_periods.items():\n",
    "    combined_energy_jersey.loc[combined_energy_jersey['Month'].isin(months), loc] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "2ae4a73a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 251520 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Plot configuration: (Title, DataFrame, [Class 1 column, Class 3 column], Shaded months for Class 1)\n",
    "configs = [\n",
    "    (\"Jersey\", combined_energy_jersey, [\"Jersey\", \"Jersey_2\"], [11, 12, 1, 2]),\n",
    "    (\"Zadar\", combined_energy_zadar, [\"Zadar\", \"Zadar_2\"], [11, 12, 1, 2]),\n",
    "    (\"Ceuta\", combined_energy_ceuta, [\"Ceuta\", \"Ceuta_2\"], [1, 2, 3, 4]),\n",
    "    (\"Gulf of Gabes\", combined_energy_gulf_gabes, [\"Gulf_Gabes\", \"Gulf_Gabes_2\"], [1, 2, 3, 4]),\n",
    "]\n",
    "\n",
    "# Create 2x2 subplot\n",
    "fig, axs = plt.subplots(2, 2, figsize=(12, 6))\n",
    "fig.subplots_adjust(hspace=0.3, wspace=0.2)\n",
    "\n",
    "# Plot each configuration\n",
    "for ax, (title, df, cols, shaded_months) in zip(axs.flatten(), configs):\n",
    "    df['Date'] = pd.to_datetime(df['Date'])\n",
    "    df['Month'] = df['Date'].dt.month\n",
    "    \n",
    "    for col in cols:\n",
    "        if \"2\" in col:\n",
    "            label = \"Class 3\" if \"Ceuta\" in col or \"Jersey\" in col else \"Class 1\"\n",
    "        else:\n",
    "            label = \"Class 1\" if \"Ceuta\" in col or \"Jersey\" in col else \"Class 2\"\n",
    "        ax.plot(df['Date'], df[col], label=label, linewidth=1.2)\n",
    "\n",
    "    for month in shaded_months:\n",
    "        dates_to_shade = df[df['Month'] == month]['Date']\n",
    "        for date in dates_to_shade:\n",
    "            ax.axvspan(date, date + pd.Timedelta(days=1), color='grey', alpha=0.1)\n",
    "\n",
    "    ax.set_title(title)\n",
    "    ax.set_xlabel(\"Date\")\n",
    "    ax.set_ylabel(\"Daily Energy [MWh]\")\n",
    "    ax.legend(title=\"Platform Class\")\n",
    "    ax.grid(True)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "id": "d36bc047",
   "metadata": {},
   "outputs": [],
   "source": [
    "annual_energy_lost_gulf=combined_energy_gulf_gabes['Gulf_Gabes_2'].sum()-combined_energy_gulf_gabes['Gulf_Gabes'].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "2df468e3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(1140.6842412121216)"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "annual_energy_lost_gulf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "id": "87290b6d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Gulf_Gabes': np.float64(18957.7174261749),\n",
       " 'Ceuta': np.float64(-2634.921854492306),\n",
       " 'Zadar': np.float64(13355.225787373573),\n",
       " 'Jersey': np.float64(-6160.093836032711)}"
      ]
     },
     "execution_count": 140,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def compute_lifetime_loss(annual_loss, years=20, degradation_rate=0.02):\n",
    "    return sum(annual_loss * ((1 - degradation_rate) ** year) for year in range(years))\n",
    "\n",
    "# Compute annual losses\n",
    "annual_energy_lost = {\n",
    "    'Gulf_Gabes': combined_energy_gulf_gabes['Gulf_Gabes_2'].sum() - combined_energy_gulf_gabes['Gulf_Gabes'].sum(),\n",
    "    'Ceuta': combined_energy_ceuta['Ceuta_2'].sum() - combined_energy_ceuta['Ceuta'].sum(),\n",
    "    'Zadar': combined_energy_zadar['Zadar_2'].sum() - combined_energy_zadar['Zadar'].sum(),\n",
    "    'Jersey': combined_energy_jersey['Jersey_2'].sum() - combined_energy_jersey['Jersey'].sum()\n",
    "}\n",
    "\n",
    "# Compute lifetime losses with 2% annual degradation\n",
    "lifetime_energy_lost = {\n",
    "    location: compute_lifetime_loss(loss)\n",
    "    for location, loss in annual_energy_lost.items()\n",
    "}\n",
    "\n",
    "\n",
    "lifetime_energy_lost\n"
   ]
  }
 ],
 "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.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
