first version of demo notebook

This commit is contained in:
2026-01-18 12:14:58 +01:00
parent 05298908e5
commit c71fde5088

226
mopso_demonstrations.ipynb Normal file
View File

@@ -0,0 +1,226 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "dcf378e6",
"metadata": {},
"source": [
"# Optimisation de charge de véhicules électriques par MOPSO assisté par IA\n",
"### Par Amine AIT MOUSSA, Siham DAANOUNI, et Clément DELAMOTTE\n",
"\n",
"---\n",
"\n",
"**Objectif :** Minimiser le coût de charge, l'insatisfaction utilisateur et la tension sur le réseau.\n",
"\n",
"**Méthode :** Utilisation d'un algorithme MOPSO (Multi-Objective Particle Swarm Optimization), couplé à un modèle de régression (Surrogate Model) pour accélérer l'évaluation des particules."
]
},
{
"cell_type": "markdown",
"id": "ea73e020",
"metadata": {},
"source": [
"## 1. Imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cf6f9f8",
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import copy\n",
"from mopso import MOPSO \n",
"from surrogate_handler import SurrogateHandler"
]
},
{
"cell_type": "markdown",
"id": "ee8b04e4",
"metadata": {},
"source": [
"## 2. SmartMOPSO class\n",
"We created a new class that heritate the classic MOPSO, but we added :\n",
"- in the initialization the surrogate type\n",
"- a new implementation to the iteration function, to use the surrogate for predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f783ba32",
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
"class SmartMOPSO(MOPSO):\n",
" def __init__(self, model_type=None, **kwargs):\n",
" super().__init__(**kwargs)\n",
" \n",
" # Initialize Surrogate Handler if model_type is provided\n",
" self.use_surrogate = (model_type is not None)\n",
" if self.use_surrogate:\n",
" self.surrogate_handler = SurrogateHandler(model_type)\n",
"\n",
" # Pre-fill with initial particle data\n",
" for p in self.particles:\n",
" self.surrogate_handler.add_data(p.x, p.f_current[1])\n",
"\n",
" def iterate(self):\n",
" train_freq = 10 # Retrain every 10 iterations\n",
" \n",
" # Check if retraining is needed\n",
" if self.use_surrogate and (self.t % train_freq == 0):\n",
" self.surrogate_handler.train()\n",
"\n",
" # Determine if AI prediction should be used\n",
" use_ai = (self.use_surrogate and \n",
" self.surrogate_handler.is_trained and \n",
" self.t % train_freq != 0)\n",
"\n",
" # Main loop (overriding original logic to manage control flow)\n",
" for t in range(self.t): \n",
" self.select_leader()\n",
" \n",
" for i in range(self.n):\n",
" # Movement \n",
" self.particles[i].update_velocity(self.leader.x, self.c1, self.c2, self.w)\n",
" self.particles[i].update_position()\n",
" self.particles[i].keep_boudaries(self.A_max)\n",
"\n",
" if use_ai:\n",
" # Fast exact calculation (f1, f3)\n",
" f1 = self.particles[i].f1(self.prices)\n",
" f3 = self.particles[i].f3()\n",
" \n",
" # Slow prediction (f2) by using Surrogate\n",
" f2_pred = self.surrogate_handler.predict(self.particles[i].x)\n",
" \n",
" # Inject scores without running the expensive 'updating_socs'\n",
" self.particles[i].f_current = [f1, f2_pred, f3]\n",
" \n",
" else:\n",
" # Standard Calculation (Slow and Exact)\n",
" self.particles[i].updating_socs(self.socs, self.capacities)\n",
" self.particles[i].evaluate(self.prices, self.socs, self.socs_req, self.times)\n",
" \n",
" # Capture data for AI training\n",
" if self.use_surrogate:\n",
" self.surrogate_handler.add_data(self.particles[i].x, self.particles[i].f_current[1])\n",
"\n",
" self.particles[i].update_best()\n",
" \n",
" self.update_archive()"
]
},
{
"cell_type": "markdown",
"id": "a2b510ed",
"metadata": {},
"source": [
"## 3. Execution Function\n",
"Execute the pipeline on a scenario with simulation parameters by using the SmartMOPSO class for the classic MOPSO or for MOPSO and Surrogate. It does the calculation for the functions f1 and f3, and calculate or predict by AI the f2 function"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a8797755",
"metadata": {},
"outputs": [],
"source": [
"def run_scenario(scenario_name, model_type=None):\n",
" print(f\"\\n--- Launching Scenario: {scenario_name} ---\")\n",
" start_time = time.time()\n",
" \n",
" # Simulation parameters\n",
" params = {\n",
" 'f_weights': [1,1,1], 'A_max': 500, 'price_mean': 0.15, 'price_std': 0.05,\n",
" 'capacities': [50]*10, 'n': 20, 't': 50, \n",
" 'w': 0.4, 'c1': 2.0, 'c2': 2.0,\n",
" 'nb_vehicles': 10, 'delta_t': 60, 'nb_of_ticks': 72\n",
" }\n",
" \n",
" # Instantiate extended class\n",
" optimizer = SmartMOPSO(model_type=model_type, **params)\n",
" \n",
" # Run simulation\n",
" optimizer.iterate()\n",
" \n",
" end_time = time.time()\n",
" duration = end_time - start_time\n",
" \n",
" # Retrieve best f2\n",
" best_f2 = min([p.f_current[1] for p in optimizer.archive]) if optimizer.archive else 0\n",
" \n",
" print(f\"Finished in {duration:.2f} seconds.\")\n",
" print(f\"Best f2 found: {best_f2:.4f}\")\n",
" \n",
" return duration, best_f2"
]
},
{
"cell_type": "markdown",
"id": "cdbd5f06",
"metadata": {},
"source": [
"## Scenario comparison\n",
"\n",
"We use here 3 configurations to evaluate our surrogate models :\n",
"1. **No AI (Baseline) :** Exact calculation, without any approximation.\n",
"2. **MLP (Multi-Layer Perceptron) :** Using a neural network to approximate $f_2$.\n",
"3. **RF (Random Forest) :** Using random forest to approximate $f_2$.\n",
"\n",
"The goal is to compare the **execution time** and **solutions quality**"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6cdd4953",
"metadata": {},
"outputs": [],
"source": [
"if __name__ == \"__main__\":\n",
" results = {}\n",
" \n",
" # 1. Without Surrogate (Baseline)\n",
" d1, f1_score = run_scenario(\"No AI\", model_type=None)\n",
" results['No-AI'] = (d1, f1_score)\n",
" \n",
" # 2. With MLP\n",
" d2, f2_score = run_scenario(\"With MLP\", model_type='mlp')\n",
" results['MLP'] = (d2, f2_score)\n",
" \n",
" # 3. With Random Forest\n",
" d3, f3_score = run_scenario(\"With Random Forest\", model_type='rf')\n",
" results['RF'] = (d3, f3_score)\n",
" \n",
" # DISPLAY RESULTS\n",
" print(\"\\n=== SUMMARY ===\")\n",
" print(f\"{'Mode':<15} | {'Time (s)':<10} | {'Best f2':<10}\")\n",
" print(\"-\" * 45)\n",
" for k, v in results.items():\n",
" print(f\"{k:<15} | {v[0]:<10.2f} | {v[1]:<10.4f}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}