{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **Import all functions and libraries**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from src.Functions_General import *\n",
    "from src.Functions_Energy_Model import *\n",
    "from src.Functions_Financial_Model import *\n",
    "from src.Functions_Load_Emulator_and_DSM import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **External inputs to set before to run the simulation**\n",
    "\n",
    "Before to run the simulation be sure to have set correctly the following input files:\n",
    "        \n",
    "- config.yml [[link yaml](config.yml)]\n",
    "\n",
    "- users CACER.xlsx [[link excel](users%20CACER.xlsx)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **Initializing CACER configuration**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this part, all the input files needed for the simulation are created."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **1. Generating the calendar file**\n",
    "\n",
    "A csv file is created with the following data:\n",
    "- **datetime**, in format [%Y/%M/%D %h:%m:%s];\n",
    "\n",
    "- **day week**, [1 : monday, 2 : thuesday, etc.];\n",
    "- **holiday**, [True : holiday, False : not holiday];\n",
    "- **fascia**, [1, 2, 3];\n",
    "- **day_flag**, [monday, thuesday, etc.]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv file has the following structure:\n",
    "\n",
    "| datetime  (type DatetimeIndex)| day_week (type int)| holiday (type boolean)| fascia (type int)| day_flag (type string)|      \n",
    "| :----:| :----:| :----:| :----:| :----:|\n",
    "| 01/01/2025  00:00:00| 2| True| 3| Sunday| \n",
    "| 01/01/2025  00:15:00| 2| True| 3| Sunday| \n",
    "| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂  *files/general/calendar.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "generate_calendar()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **2. Generating the yaml and csv files with all the inputs of the CACER configuration**\n",
    "\n",
    "The following files are created:\n",
    "- generate_users_yml() \n",
    "\n",
    "        → files/recap.yml \n",
    "\n",
    "        → files/registry_user_types.yml \n",
    "\n",
    "        → files/registry_users.yml\n",
    "\n",
    "        → files/registry_users.csv\n",
    "\n",
    "- generate_plant_yml() \n",
    "\n",
    "        → files/registry_plant.yml\n",
    "\n",
    "        → files/registry_plant.csv\n",
    "\n",
    "- membership_matrix() \n",
    "\n",
    "        → files/membership_matrix.csv\n",
    "\n",
    "- plant_operation_matrix() \n",
    "\n",
    "        → files/plant_operation_matrix.xlsx\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "initialization_users()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **3. Generating the emulated load profile of the users**\n",
    "\n",
    "A csv file is created with the following data:\n",
    "- **datetime**, in format [%Y/%M/%D %h:%m:%s];\n",
    "\n",
    "- quarterly electrical load of each individual user [kWh/15min]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv file has the following structure:\n",
    "\n",
    "| datetime  (type DatetimeIndex)| user_1 (type float)| user_2 (type float)| ...|      \n",
    "| :----:| :----:| :----: | :----: |\n",
    "| 01/01/2025  00:00:00| 0.109| 0.109| ...| \n",
    "| 01/01/2025  00:15:00| 0.098| 0.098| ...| \n",
    "| ...| ...| ...| ...| \n",
    "\n",
    "**emultated users only*\n",
    "\n",
    "📂 *files/input/emulated_load_profile.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "flag_last_dict = False # if false we create the appliance start time dictionary; if true we import the last one created (default: False)\n",
    "flag_optDSM = False # if true we simulate the optimized DSM case (default: False)\n",
    "flag_all_appliance = True # if true we use all appliance for the load profile emulation (default: True)\n",
    "flag_daily_activation = True # if false we dont'use a daily usage activation for some specified appliances (only washing machine at the moment, default: True)\n",
    "flag_multi_use = True # if true we activate the possibility to have multiple activations for the selected appliances during the day (default: True)\n",
    "\n",
    "create_emulated_users(flag_last_dict, flag_optDSM, flag_all_appliance, flag_daily_activation, flag_multi_use)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **4. Generating all load profile of the users (domestic users, commercial users, industrial users, etc.)**\n",
    "\n",
    "A csv file is created with the following data:\n",
    "- **datetime**, in format [%Y/%M/%D %h:%m:%s];\n",
    "\n",
    "- quarterly electrical load of each individual user [kWh/15min]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv file has the following structure (**carichi.csv**):\n",
    "\n",
    "| datetime  (type DatetimeIndex)| user_1 (type float)| user_2 (type float)| ...|      \n",
    "| :----:| :----:| :----: | :----: |\n",
    "| 01/01/2025  00:00:00| 0.109| 0.109| ...| \n",
    "| 01/01/2025  00:15:00| 0.098| 0.098| ...| \n",
    "| ...| ...| ...| ...| \n",
    "\n",
    "**all users*\n",
    "\n",
    "📂 *files/energy/carichi.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "load_profile_all_users()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **5. Generating productivity of the photovoltaic generators**\n",
    "\n",
    "A csv file is created with the following data:\n",
    "- **datetime**, in format [%Y/%M/%D %h:%m:%s];\n",
    "\n",
    "- quarterly electrical productivity of each individual user [kWh/15min]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv file has the following structure:\n",
    "\n",
    "| datetime  (type DatetimeIndex)| user_1 (type float)| user_2 (type float)| ...|      \n",
    "| :----:| :----:| :----: | :----: |\n",
    "| 01/01/2025  00:00:00| 0.109| 0.109| ...| \n",
    "| 01/01/2025  00:15:00| 0.098| 0.098| ...| \n",
    "| ...| ...| ...| ...| \n",
    "\n",
    "**all users*\n",
    "\n",
    "📂 *files/output_gen_pv.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "simulate_configuration_productivity()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **6. Generating all energy flows of the single users**\n",
    "\n",
    "A csv file is created <u>for each users</u> with the following data:\n",
    "- **datetime**, in format [%Y/%M/%D %h:%m:%s];\n",
    "\n",
    "- **Eprel**, quarterly withdrawn energy [kWh/15min];\n",
    "- **Eut**, quarterly consumed energy [kWh/15min];\n",
    "- **Eimm**, quarterly injected energy [kWh/15min];\n",
    "- **Eprod**, quarterly produced energy [kWh/15min];\n",
    "- **Eperdite**, quarterly lost energy [kWh/15min];\n",
    "- **Eaut**, quarterly self-consumed energy [kWh/15min];\n",
    "- **Eaut_PV**, quarterly self-consumed energy from photovoltaic generator [kWh/15min];\n",
    "- **Eaut_batt**, quarterly self-consumed energy from battery [kWh/15min]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv files have the following structure:\n",
    "\n",
    "| datetime  (type DatetimeIndex)| Eprel (type float)| Eut (type float)| Eimm (type float)| Eprod (type float)| Eperdite (type float)| Eaut (type float)| Eaut_PV (type float)| Eaut (type float)|      \n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "| 01/01/2025  00:00:00| 0.0899| 0.0899| 0.0899| 0.0899| 0.0899| 0.0899| 0.0899| 0.0899|  \n",
    "| 01/01/2025  00:15:00| 0.0909| 0.0909| 0.0909| 0.0909| 0.0909| 0.0909| 0.0909| 0.0909| \n",
    "| ...| ...| ...| ...| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/energy/profili_utenti/*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CACER_energy_flows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **Simulate CACER configuration**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this part, all economic cash flows (aggregated for the project, aggregated for the CACER configuratione and for each user types) are simulated. \n",
    "\n",
    "Finally, a Discounted Cash Flow (DCF) is calculated for each \"actor\" (project, CACER configuration, users).\n",
    "\n",
    "Before to run the simulation be sure to have set correctly the following input files:\n",
    "        \n",
    "- input_FM.xlsx [[link excel](files/input_FM.xlsx)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **7. Calculate the electricity bills for each user types**\n",
    "\n",
    "Before to run the simulation be sure to have set correctly the following input files:\n",
    "\n",
    "        → files/mercato.yml\n",
    "\n",
    "A csv file is created <u>for each actor</u> with the following data:\n",
    "- **month**, in format [%Y-%M];\n",
    "\n",
    "- **me_cost**, monthly cost for energy [€/month];\n",
    "- **transport_cost**, monthly cost for transport [€/month];\n",
    "- **ogs_cost**, monthly general system costs [€/month];\n",
    "- **energy_cost**, monthly cost variable with electricity consumption [€/month];\n",
    "- **fixed_cost**, monthly fixed cost [€/month];\n",
    "- **power_cost**, monthly cost variable with contractual power [€/month];\n",
    "- **duty_cost**, monthly cost for duty [€/month];\n",
    "- **vat_cost**, monthly cost for vat [€/month];\n",
    "- **total_bill_cost**, monthly total bill cost [€/month];\n",
    "- **load_active**, monthly consumed energy [kWh/month];\n",
    "- **load_active_corrected**, monthly consumed energy corrected with losses [kWh/month]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The csv files have the following structure:\n",
    "\n",
    "| month  (type DatetimeIndex)| me_cost (type float)| transport_cost (type float)| ogs_cost (type float)| energy_cost (type float)| fixed_cost (type float)| power_cost (type float)| duty_cost (type float)| vat_cost (type float)| total_bill_cost (type float)| load_active (type float)| load_active_corrected (type float)|      \n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "| 2025-01| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56| 71.56|\n",
    "| 2025-02| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89| 58.89|\n",
    "| ...| ...| ...| ...| ...| ...| ...| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/finance/bills/*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "🚨 **PAY ATTENTION:**\n",
    "\n",
    "- For consumers there are two sheets: one with the monthly values in BAU scenario (Business As Usual) and another one with the quarterly values.\n",
    "\n",
    "- For prosumers and producers there are four sheets: monthly BAU scenario (without the photovoltaic generator), quarterly BAU scenario, monthly PV scenario (with the photovoltaic generator) and quarterly PV scenario.\n",
    "\n",
    "- For project and for configuration (the xlsx file name is the same as the primary cabin name indicated in the *user CACER.xlsx* file) there are two sheets: monthly BAU scenario (without the photovoltaic generator) and monthly PV scenario (with the photovoltaic generator)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "create_users_bill()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **8. Setting name and type of the configuration and editing of the incentive repartition**\n",
    "\n",
    "The \"*case_denomination*\" and the \"*type_of_cacer*\" are added to recap.yml file.\n",
    "\n",
    "The \"*case_denomination*\" is used for the final report with results, for the folder with results, etc.\n",
    "\n",
    "The \"*type_of_cacer*\" is necessary for the calculation of the incentives.\n",
    "\n",
    "Finally, the incentive repartition between the members of the CACER configuration (internal and external) is setted in the following file:\n",
    "\n",
    "        → files/inputs_FM.xlsx\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "🚨 **PAY ATTENTION:**\n",
    "\n",
    "The file *input_FM.xlsx* contains all the inputs for financila simulation.\n",
    "\n",
    "It is possible to set the following repartition for the incentives:\n",
    "\n",
    "* Egualitario\n",
    "* Prosumer\n",
    "* PNRR\n",
    "* Equitario\n",
    "* Misto CER\n",
    "* Misto AUC\n",
    "* Misto - ESCo\n",
    "* Social Fund\n",
    "* Misto - Social Fund\n",
    "* Misto - Social Fund 2\n",
    "* Misto - Social Fund PA\n",
    "* Misto - PA\n",
    "* CACER\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "case_denomination = \"prova\"\n",
    "CACER_type = \"CER\" # CER; AUD; AID; NO_CACER\n",
    "repartition_scheme = \"Egualitario\" # Egualitario; Prosumer; PNRR; Equitario; Misto CER; Misto AUC; Misto - ESCo; Social Fund; Misto - Social Fund; Misto - Social Fund 2; Misto - Social Fund PA; Misto - PA; CACER\n",
    "\n",
    "setting_CACER_scenario(case_denomination, CACER_type, repartition_scheme)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **9. Calculate CACER energy shared**\n",
    "\n",
    "📘 **Formula**\n",
    "\n",
    "The energy shared in the CACER configuration is calculated with the following formula:\n",
    "\n",
    "\n",
    "$$ Hourly ~ energy ~ shared  = \\min \\left( \\sum_{n_g=1}^{N_{gens}} ~ E_{inj, ~h, ~n_g}  ; \\sum_{n_c=1}^{N_{consumers}} ~  E_{draw, ~h, ~n_c} \\right) $$\n",
    "\n",
    "\n",
    "🔍 **Meaning of the Terms**\n",
    "\n",
    "- $\n",
    "N_{gens}:~ \\text{Number of energy generators (e.g., photovoltaic systems);}\n",
    "$\n",
    "\n",
    "- $\n",
    "N_{consumers}:~ \\text{Number of consumers in the community;}\n",
    "$\n",
    "\n",
    "- $\n",
    "h:~ \\text{Hour of the month;}\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{inj,h}:~ \\text{Energy injected into the grid by a generator at hour } h;\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{draw,h}:~ \\text{Energy drawn from the grid by a consumer at hour } h.\n",
    "$\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "💾 **Outputs**\n",
    "\n",
    "- In the csv file (*shared_energy_incentive_hourly.csv*) are collected the hourly values for the entire configuration and for each plants.\n",
    "\n",
    "  The csv file has the following structure:\n",
    "\n",
    "| dayhour  (type DatetimeIndex)| Eimm_CACER (type float)| Econd_config_ *Primary Station name* (type float)| Econd_ *user name* (type float)| ...| Econd_cond_CACER (type float)|\n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "| 2025-01-01 00| 0| 0| 0| ...| 0|\n",
    "| 2025-01-01 01| 0| 0| 0| ...| 0|\n",
    "| ...| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/energy/shared_energy_incentive_hourly.csv*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "- In the csv file (*shared_energy_incentive_yearly.csv*) are collected the yearly aggregated values for the entire configuration. \n",
    "\n",
    "  The csv file has the following structure:\n",
    "\n",
    "| year  (type DatetimeIndex)| Eimm (type float)| Econd (type float)| perc_cond_annuale type float|\n",
    "|:----:|:----:|:----:|:----:|\n",
    "| 2025| 24512.54| 2133.47| 0.087|\n",
    "| 2026| 24228.59| 2119.51| 0.087|\n",
    "| ...| ...| ...| ...|\n",
    "\n",
    "📂 *files/energy/shared_energy_incentive_hourly.csv*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "- In the csv file (*shared_energy_valorization_hourly.csv*) are collected the hourly values for the entire configuration and for each generators. The energy shared used for the calculation of the valorization can be different respect that calculated for the incentives (in this case also the \"old\" plants partecipate).\n",
    "\n",
    "  The csv file has the following structure:\n",
    "\n",
    "| dayhour  (type DatetimeIndex)| Econd_VAL (type float)| Econd_bt_VAL (type float)| Econd_mt_VAL (type float)| Econd_CP_VAL (type float)| Econd_CP_bt_VAL (type float)| Econd_CP_mt_VAL (type float)|\n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|:----:| \n",
    "| 2025-01-01 00| 0| 0| 0| 0| 0| 0|\n",
    "| 2025-01-01 01| 0| 0| 0| 0| 0|  0|\n",
    "| ...| ...| ...| ...| ...| ...| ...|\n",
    "\n",
    "📂 *files/energy/shared_energy_valorization_hourly.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CACER_shared_energy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **10. Calculate energy sold revenues**\n",
    "\n",
    "📘 **Formula**\n",
    "\n",
    "The energy sold revenues of the generators are calculated with the following formula:\n",
    "\n",
    "\n",
    "$$ Monthly ~ energy ~ sold ~ revenues = \\sum_{n_g=1}^{N_{gens}} ~ \\sum_{h=1}^{H_{month}} E_{inj, ~h, ~n_g} × PZO_h $$\n",
    "\n",
    "\n",
    "🔍 **Meaning of the Terms**\n",
    "\n",
    "- $\n",
    "N_{gens}:~ \\text{Number of energy generators (e.g., photovoltaic systems);}\n",
    "$\n",
    "\n",
    "- $\n",
    "h:~ \\text{Hour of the month;}\n",
    "$\n",
    "\n",
    "- $\n",
    "H_{month}:~ \\text{Total hours of the month;}\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{inj,h}:~ \\text{Energy injected into the grid by a generator at hour } h;\n",
    "$\n",
    "\n",
    "- $\n",
    "PZO_h:~ \\text{Energy cost for the market zone at hour } h.\n",
    "$\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "📝 **Inputs**\n",
    "\n",
    "The inputs for the RID calculation are listed in:\n",
    "\n",
    "        → files/RID/RID_input.yml\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "💾 **Outputs**\n",
    "\n",
    "- The first csv file (*output_RID.csv*) has the following structure:\n",
    "\n",
    "| month  (type int)| *plant_id_1* (type float)| *plant_id_2* (type float)| ...|\n",
    "|:----:|:----:|:----:|:----:|\n",
    "| 2025-01| 107.32| 107.32| ...|\n",
    "| 2025-02| 146.81| 146.81| ...| \n",
    "| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/RID/output_RID.csv*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "- In the csv file (*output_GSE_RID_fees.csv*) are collected the monthly fees cost for the RID accounting for each generators of the configuration.\n",
    "  \n",
    "  The csv file has the following structure:\n",
    "\n",
    "| month  (type int)| *plants_id_1* (type float)| *plant_id_2* (type float)| ...|\n",
    "|:----:|:----:|:----:|:----:|\n",
    "| GSE_fees| 14| 14| ...|\n",
    "\n",
    "📂 *files/RID/output_GSE_RID_fees.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "RID_calculation()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **11. Aggregate bills costs and energy sold revenues for the entire CACER configuration**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All the bills costs and energy sold revenues are aggregated for the entire configuration. In particular:\n",
    "\n",
    "- The function **aggregate_CACER_bills()** create a csv file (*CACER_incentivi_per_configuration.csv*) with the following structure:\n",
    "\n",
    "| month  (type DatetimeIndex)| incentivo (type float)| valorizzazione (type float)| incentivo_totale (type float)| surplus (type float)| social_fund (type float)|\n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "| 2025-01| 17.61| 1.43| 17.61| 0| 0|\n",
    "| 2025-02| 18.90| 1.53| 18.90| 0| 0|\n",
    "| ...| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/incentivi/CACER_incentivi_per_configuration.csv*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "- The function **aggregate_CACER_RID()** create a csv file (*output_RID_active_CACER.csv*) with the following structure:\n",
    "\n",
    "| month  (type int)| *plant_id_1* (type float)| *plant_id_2* (type float)| ...| CER (type float)|\n",
    "|:----:|:----:|:----:|:----:|:----:|\n",
    "| 2025-01| 107.32| 107.32| ...| 1065.31|\n",
    "| 2025-02| 146.81| 146.81| ...| 1854.54|\n",
    "| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/RID/output_RID_active_CACER.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "aggregate_CACER_bills()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "aggregate_CACER_RID()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **12. Generating the xlsx and csv files with all the financial inputs of the CACER configuration**\n",
    "\n",
    "The following files are created:\n",
    "\n",
    "        → files/finance/FM_template.csv\n",
    "\n",
    "        → files/finance/investment_matrix.csv\n",
    "\n",
    "        → files/finance/ownership_matrix.xlsx\n",
    "\n",
    "        → files/finance/repartition_matrix.xlsx\n",
    "\n",
    "        → files/finance/subscription_matrix.csv\n",
    "\n",
    "        → files/finance/subscription_matrix.xlsx\n",
    "\n",
    "        → files/finance/user_entry_matrix.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "FM_initialization()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **13. Calculate incentives revenues**\n",
    "\n",
    "📘 **Formula incentives**\n",
    "\n",
    "The incentives revenues of the configuration are calculated with the following formula:\n",
    "\n",
    "\n",
    "$$ Monthly ~ incentives ~ revenues = \\sum_{h=1}^{H_{month}} E_{shared, ~FIP, ~h} × FIP_h $$\n",
    "\n",
    "\n",
    "🔍 **Meaning of the Terms**\n",
    "\n",
    "- $\n",
    "h:~ \\text{Hour of the month;}\n",
    "$\n",
    "\n",
    "- $\n",
    "H_{month}:~ \\text{Total hours of the month;}\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{shared,FIP,h}:~ \\text{Energy shared into the CACER configuration at hour } h;\n",
    "$\n",
    "\n",
    "- $\n",
    "FIP_h:~ \\text{Feed In Premium at hour } h.\n",
    "$\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "📘 **Formula valorization**\n",
    "\n",
    "The valorization revenues of the configuration are calculated with the following formula:\n",
    "\n",
    "$$ Monthly ~ valorization ~ revenues = CU_{Afa, m} × E_{ACV} + CU_{Afb), m} × E_{ACVC} + \\sum_{i} (E_{ACV, ~i} × CP_{PR, ~i} × Pz) $$\n",
    "\n",
    "🔍 **Meaning of the Terms**\n",
    "\n",
    "- $\n",
    "CU_{Afa, m}:~ \\text{flat-rate monthly self-consumption unit fee }(TRAS_{E});\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{ACV}:~ \\text{Monthly self-consumed energy;}\n",
    "$\n",
    "\n",
    "- $\n",
    "CU_{Afb), m}:~ \\text{flat-rate monthly self-consumption unit fee (BTAU)};\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{ACVC}:~ \\text{Monthly self-consumed energy for voltage level i}\n",
    "$\n",
    "\n",
    "- $\n",
    "E_{ACV, ~i}:~ \\text{Hourly self-consumed energy for voltage level i}\n",
    "$\n",
    "\n",
    "- $\n",
    "CP_{PR, ~i}:~ \\text{coefficient of avoided losses (1.2\\% for medium voltage and 2.6\\% for low voltage)}\n",
    "$\n",
    "\n",
    "- $\n",
    "Pz:~ \\text{Hourly market price}\n",
    "$\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "💾 **Outputs**\n",
    "\n",
    "The csv file (*CACER_incentivi.csv*) has the following structure:\n",
    "\n",
    "| month_number  (type int)| incentivo (type float)| valorizzazione (type float)| incentivo_totale (type float)| surplus (type float)| social_fund (type float)|\n",
    "|:----:|:----:|:----:|:----:|:----:|:----:|\n",
    "| 1| 17.61| 1.43| 17.61| 0| 0|\n",
    "| 2| 18.90| 1.53| 18.90| 0| 0|\n",
    "| ...| ...| ...| ...| ...| ...| \n",
    "\n",
    "📂 *files/incentivi/CACER_incentivi.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "incentives()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **14. All the economic cash flows for each users and for each stakeholders are calculated**\n",
    "\n",
    "The function **cash_flows_for_all_plants()** calculate all the economic invoicse for the generators of the configuration.\n",
    "\n",
    "A csv file (*plants_id.xlsx*) for each generators are created with the following sheets:\n",
    "\n",
    "- Capex;\n",
    "\n",
    "- D&A;\n",
    "\n",
    "- Debt;\n",
    "\n",
    "- Opex;\n",
    "\n",
    "- Revenues;\n",
    "\n",
    "- Totals.\n",
    "\n",
    "📂 *files/finance/plants/*\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "The function **cash_flows_for_all_users()** calculate all the economic cash flows for the users of the configuration, for the social fund and for the entire CACER configuration.\n",
    "\n",
    "- A csv file (*user_id.xlsx*) for each generators are created with the following sheets:\n",
    "\n",
    "    - plant_id;\n",
    "\n",
    "    - CACER;\n",
    "\n",
    "    - DCF_monthly;\n",
    "\n",
    "    - DCF_yearly;\n",
    "\n",
    "    - Results.\n",
    "\n",
    "- A csv file (*social_fund.xlsx*) for each generators are created with the following economic cash flows:\n",
    "\n",
    "    - month [%Y/%M];\n",
    "\n",
    "    - inflaction_factor;\n",
    "    \n",
    "    - revenues_social_fund\n",
    "\n",
    "- A csv file (*CACER.xlsx*) for each generators are created with the following sheets:\n",
    "\n",
    "    - CACER;\n",
    "\n",
    "    - totals;\n",
    "\n",
    "    - DCF_monthly;\n",
    "\n",
    "    - DCF_yearly;\n",
    "\n",
    "    - Results.\n",
    "\n",
    "📂 *files/finance/users/*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cash_flows_for_all_plants() # plants first..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cash_flows_for_all_users() # ...then users..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **15. All the economic cash flows are aggregated for the project and for the CACER configuration (<u>for single primary station</u>)**\n",
    "\n",
    "A csv file (*project.xlsx*) is created with the following sheets:\n",
    "\n",
    "- plants;\n",
    "\n",
    "- CACER;\n",
    "\n",
    "- totals;\n",
    "\n",
    "- DCF_monthly;\n",
    "\n",
    "- DCF_yearly;\n",
    "\n",
    "- Results.\n",
    "\n",
    "&nbsp;\n",
    "\n",
    "A csv file (*primary_station_id.xlsx*) for each primary stations are created with the following sheets:\n",
    "\n",
    "- plants;\n",
    "\n",
    "- CACER;\n",
    "\n",
    "- totals;\n",
    "\n",
    "- DCF_monthly;\n",
    "\n",
    "- DCF_yearly;\n",
    "\n",
    "- Results.\n",
    "\n",
    "📂 *files/finance/configurations/*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "aggregate_FM() # ...then configurations!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **16.1 The simulation results are organized for the export and for the creation of the report**\n",
    "\n",
    "Different results are added to *files/recap.yml* and the following file is created:\n",
    "\n",
    "        → files/results_finance/results_FM_last_simulation.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "organize_simulation_results_for_reporting()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **16.2 Creating the report with results**\n",
    "\n",
    "A report with the main results is created."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run Reporting.ipynb"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **16.3 Creating the report with results**\n",
    "\n",
    "All the following files and results are collected in a folder.\n",
    "\n",
    "        → all files stored in files/finance/\n",
    "        → files/energy/CACER_energy_monthly.xlsx\n",
    "        → files/incentivi/CACER_incentivi.csv\n",
    "        → files/membership_matrix.csv\n",
    "        → files/plant_operation_matrix.xlsx\n",
    "        → files/inputs_FM.xlsx\n",
    "        → files/registry_plants.yml\n",
    "        → files/registry_user_types.yml\n",
    "        → files/registry_users.yml\n",
    "        → files/results_finance/results_FM_last_simulation.csv\n",
    "        → files/recap.yml\n",
    "        → the report stored in files/results_finance/case_denomination_id.docx\n",
    "\n",
    "📂 *files/results_finance/case_denomination/*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "save_simulation_results(simulation_name = case_denomination)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **17. Killing all excel processes in background**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kill_excel_processes()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\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.10.11"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
