Téléverser les fichiers vers "/"
This commit is contained in:
201
main.py
201
main.py
@@ -6,40 +6,6 @@ from mopso import MOPSO
|
||||
from surrogate_handler import SurrogateHandler
|
||||
import pandas as pd
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D # Nécessaire pour la 3D
|
||||
|
||||
def plot_pareto_3d(archive, model_type:str):
|
||||
fig = plt.figure(figsize=(12, 8))
|
||||
ax = fig.add_subplot(111, projection='3d')
|
||||
|
||||
# Extraction des scores depuis l'archive
|
||||
# f_best[0] = Coût, f_best[1] = Insatisfaction, f_best[2] = Stress Réseau
|
||||
f1 = [p.f_best[0] for p in archive]
|
||||
f2 = [p.f_best[1] for p in archive]
|
||||
f3 = [p.f_best[2] for p in archive]
|
||||
|
||||
# Création du nuage de points
|
||||
img = ax.scatter(f1, f2, f3, c=f3, cmap='viridis', s=60, edgecolors='black')
|
||||
|
||||
ax.set_xlabel('Coût (€)')
|
||||
ax.set_ylabel('Insatisfaction (SoC manquant)')
|
||||
ax.set_zlabel('Pic Réseau (kW)')
|
||||
ax.set_title(f'Front de Pareto des Solutions Non-Dominées ({model_type})')
|
||||
|
||||
# Barre de couleur
|
||||
cbar = fig.colorbar(img, ax=ax, pad=0.1)
|
||||
cbar.set_label('Intensité du Pic Réseau (kW)')
|
||||
|
||||
# Sauvegarde et affichage
|
||||
filename = f"{model_type}_pareto_3d.png"
|
||||
plt.savefig(filename)
|
||||
print(f"Graphique sauvegardé sous : {filename}")
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
class SmartMOPSO(MOPSO):
|
||||
def __init__(self, model_type=None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
@@ -53,18 +19,7 @@ class SmartMOPSO(MOPSO):
|
||||
for p in self.particles:
|
||||
self.surrogate_handler.add_data(p.x, p.f_current[1])
|
||||
|
||||
def iterate(self):
|
||||
train_freq = 10 # Retrain every 10 iterations
|
||||
|
||||
# Check if retraining is needed
|
||||
if self.use_surrogate and (self.t % train_freq == 0):
|
||||
self.surrogate_handler.train()
|
||||
|
||||
# Determine if AI prediction should be used
|
||||
use_ai = (self.use_surrogate and
|
||||
self.surrogate_handler.is_trained and
|
||||
self.t % train_freq != 0)
|
||||
|
||||
def iterate(self, prediction_freq:int=10):
|
||||
# Main loop (overriding original logic to manage control flow)
|
||||
for t in range(self.t):
|
||||
self.select_leader()
|
||||
@@ -75,7 +30,7 @@ class SmartMOPSO(MOPSO):
|
||||
self.particles[i].update_position()
|
||||
self.particles[i].keep_boudaries(self.A_max)
|
||||
|
||||
if use_ai:
|
||||
if (t % (prediction_freq) != 0) and self.use_surrogate:
|
||||
# Fast exact calculation (f1, f3)
|
||||
f1 = self.particles[i].f1(self.prices)
|
||||
f3 = self.particles[i].f3()
|
||||
@@ -91,15 +46,34 @@ class SmartMOPSO(MOPSO):
|
||||
self.particles[i].updating_socs(self.socs, self.capacities)
|
||||
self.particles[i].evaluate(self.prices, self.socs, self.socs_req, self.times)
|
||||
|
||||
# Capture data for AI training
|
||||
if self.use_surrogate:
|
||||
self.surrogate_handler.add_data(self.particles[i].x, self.particles[i].f_current[1])
|
||||
|
||||
self.particles[i].update_best()
|
||||
|
||||
self.update_archive()
|
||||
|
||||
|
||||
# Run Classic MOPSO, collect data and run training for the model
|
||||
def train_surrogate_model(self):
|
||||
# Generation of data
|
||||
for t in range(self.t):
|
||||
self.select_leader()
|
||||
|
||||
for i in range(self.n):
|
||||
# Movement
|
||||
self.particles[i].update_velocity(self.leader.x, self.c1, self.c2, self.w)
|
||||
self.particles[i].update_position()
|
||||
self.particles[i].keep_boudaries(self.A_max)
|
||||
# Standard Calculation (Slow and Exact)
|
||||
self.particles[i].updating_socs(self.socs, self.capacities)
|
||||
self.particles[i].evaluate(self.prices, self.socs, self.socs_req, self.times)
|
||||
|
||||
# Capture data for AI training
|
||||
self.surrogate_handler.add_data(self.particles[i].x, self.particles[i].f_current[1])
|
||||
|
||||
# End of dataset generation (based on classic MOPSO)
|
||||
self.surrogate_handler.train()
|
||||
|
||||
|
||||
|
||||
def calculate_elec_prices(csv_file:str, sep:str=';'):
|
||||
elec_df = pd.read_csv(filepath_or_buffer=csv_file, sep=sep, skipinitialspace=True)
|
||||
|
||||
@@ -156,6 +130,9 @@ def run_scenario(scenario_name, capacities:list, price_mean:float, price_std:flo
|
||||
# Instantiate extended class
|
||||
optimizer = SmartMOPSO(model_type=model_type, **params)
|
||||
|
||||
if(model_type is not None):
|
||||
optimizer.train_surrogate_model()
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# Run simulation
|
||||
@@ -174,64 +151,7 @@ def run_scenario(scenario_name, capacities:list, price_mean:float, price_std:flo
|
||||
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
def plot_time_benchmark(nb_particles_list, results_dict):
|
||||
|
||||
t_mopso = [item[0] for item in results_dict['MOPSO']]
|
||||
t_mlp = [item[0] for item in results_dict['MLP']]
|
||||
t_rf = [item[0] for item in results_dict['RF']]
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
|
||||
plt.plot(nb_particles_list, t_mopso, 'o-', label='Sans IA (MOPSO)', color='#1f77b4', linewidth=2)
|
||||
plt.plot(nb_particles_list, t_mlp, 's--', label='Avec MLP', color='#ff7f0e', linewidth=2)
|
||||
plt.plot(nb_particles_list, t_rf, '^-.', label='Avec Random Forest', color='#2ca02c', linewidth=2)
|
||||
|
||||
plt.title("Temps d'exécution selon le nombre de particules", fontsize=14, fontweight='bold')
|
||||
plt.xlabel("Nombre de Particules", fontsize=12)
|
||||
plt.ylabel("Temps (s)", fontsize=12)
|
||||
plt.grid(True, linestyle=':', alpha=0.7)
|
||||
plt.legend(fontsize=11)
|
||||
|
||||
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def plot_f2_benchmark(nb_particles_list, results_dict):
|
||||
s_mopso = [item[1] for item in results_dict['MOPSO']]
|
||||
s_mlp = [item[1] for item in results_dict['MLP']]
|
||||
s_rf = [item[1] for item in results_dict['RF']]
|
||||
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
|
||||
plt.plot(nb_particles_list, s_mopso, 'o-', label='Sans IA (MOPSO)', color='#1f77b4', linewidth=2)
|
||||
plt.plot(nb_particles_list, s_mlp, 's--', label='Avec MLP', color='#ff7f0e', linewidth=2)
|
||||
plt.plot(nb_particles_list, s_rf, '^-.', label='Avec Random Forest', color='#2ca02c', linewidth=2)
|
||||
|
||||
plt.title("Meilleur Score F2 (Convergence) selon le nombre de particules", fontsize=14, fontweight='bold')
|
||||
plt.xlabel("Nombre de Particules (log scale)", fontsize=12)
|
||||
plt.ylabel("Meilleur F2 Score", fontsize=12)
|
||||
plt.grid(True, linestyle=':', alpha=0.7)
|
||||
plt.legend(fontsize=11)
|
||||
|
||||
plt.xscale('log')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# CSV files
|
||||
elec_price_csv = 'data/elec_prices.csv'
|
||||
@@ -256,7 +176,7 @@ def main():
|
||||
'MLP': [],
|
||||
'RF': []
|
||||
}
|
||||
nb_particles = [20,50,500,1000,10000]
|
||||
nb_particles = [20,50,100,500]
|
||||
|
||||
for k in range(len(nb_particles)):
|
||||
# 1. Without Surrogate (Baseline)
|
||||
@@ -294,9 +214,9 @@ def main():
|
||||
n=nb_particles[k]
|
||||
)
|
||||
results['RF'].append((d3, f3_score))
|
||||
|
||||
|
||||
# --- DISPLAY RESULTS ---
|
||||
|
||||
|
||||
print("\n=== SUMMARY ===")
|
||||
print(f"{'Mode':<15} | {'Time (s)':<10} | {'Best f2':<10}")
|
||||
print("-" * 45)
|
||||
@@ -304,9 +224,60 @@ def main():
|
||||
for i in range(len(nb_particles)):
|
||||
print(f"{k:<15}_{nb_particles[i]:<15} | {v[i][0]:<10.2f} | {v[i][1]:<10.4f}")
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
def plot_time_benchmark(nb_particles_list, results_dict):
|
||||
|
||||
t_mopso = [item[0] for item in results_dict['MOPSO']]
|
||||
t_mlp = [item[0] for item in results_dict['MLP']]
|
||||
t_rf = [item[0] for item in results_dict['RF']]
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
|
||||
plt.plot(nb_particles_list, t_mopso, 'o-', label='Sans IA (MOPSO)', color='#1f77b4', linewidth=2)
|
||||
plt.plot(nb_particles_list, t_mlp, 's--', label='Avec MLP', color='#ff7f0e', linewidth=2)
|
||||
plt.plot(nb_particles_list, t_rf, '^-.', label='Avec Random Forest', color='#2ca02c', linewidth=2)
|
||||
|
||||
plt.title("Temps d'exécution selon le nombre de particules", fontsize=14, fontweight='bold')
|
||||
plt.xlabel("Nombre de Particules", fontsize=12)
|
||||
plt.ylabel("Temps (s)", fontsize=12)
|
||||
plt.grid(True, linestyle=':', alpha=0.7)
|
||||
plt.legend(fontsize=11)
|
||||
|
||||
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
plot_time_benchmark(nb_particles, results)
|
||||
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def plot_f2_benchmark(nb_particles_list, results_dict):
|
||||
s_mopso = [item[1] for item in results_dict['MOPSO']]
|
||||
s_mlp = [item[1] for item in results_dict['MLP']]
|
||||
s_rf = [item[1] for item in results_dict['RF']]
|
||||
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
|
||||
plt.plot(nb_particles_list, s_mopso, 'o-', label='Sans IA (MOPSO)', color='#1f77b4', linewidth=2)
|
||||
plt.plot(nb_particles_list, s_mlp, 's--', label='Avec MLP', color='#ff7f0e', linewidth=2)
|
||||
plt.plot(nb_particles_list, s_rf, '^-.', label='Avec Random Forest', color='#2ca02c', linewidth=2)
|
||||
|
||||
plt.title("Meilleur Score F2 (Convergence) selon le nombre de particules", fontsize=14, fontweight='bold')
|
||||
plt.xlabel("Nombre de Particules (log scale)", fontsize=12)
|
||||
plt.ylabel("Meilleur F2 Score", fontsize=12)
|
||||
plt.grid(True, linestyle=':', alpha=0.7)
|
||||
plt.legend(fontsize=11)
|
||||
|
||||
plt.xscale('log')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
plot_f2_benchmark(nb_particles, results)
|
||||
|
||||
|
||||
|
||||
main()
|
||||
Reference in New Issue
Block a user