forked from KuMiShi/Optim_Metaheuristique
Compare commits
2 Commits
sihamdaano
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b172e93a85 | |||
| 7d55ba0840 |
121
main.py
121
main.py
@@ -1,121 +1,6 @@
|
|||||||
import time
|
def main():
|
||||||
import numpy as np
|
print("Hello from optim-meta!")
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
import copy
|
|
||||||
from mopso import MOPSO
|
|
||||||
from surrogate_handler import SurrogateHandler
|
|
||||||
|
|
||||||
# --- EXTENDED CLASS (Inheritance) ---
|
|
||||||
|
|
||||||
class SmartMOPSO(MOPSO):
|
|
||||||
def __init__(self, model_type=None, **kwargs):
|
|
||||||
super().__init__(**kwargs)
|
|
||||||
|
|
||||||
# Initialize Surrogate Handler if model_type is provided
|
|
||||||
self.use_surrogate = (model_type is not None)
|
|
||||||
if self.use_surrogate:
|
|
||||||
self.surrogate_handler = SurrogateHandler(model_type)
|
|
||||||
|
|
||||||
# Pre-fill with initial particle data
|
|
||||||
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)
|
|
||||||
|
|
||||||
# Main loop (overriding original logic to manage control flow)
|
|
||||||
for t in range(self.t):
|
|
||||||
self.select_leader()
|
|
||||||
|
|
||||||
for i in range(self.n):
|
|
||||||
# Movement (unchanged)
|
|
||||||
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)
|
|
||||||
|
|
||||||
# --- MODIFIED PART: EVALUATION ---
|
|
||||||
if use_ai:
|
|
||||||
# 1. Fast exact calculation (f1, f3)
|
|
||||||
f1 = self.particles[i].f1(self.prices)
|
|
||||||
f3 = self.particles[i].f3()
|
|
||||||
|
|
||||||
# 2. Slow prediction (f2) via AI
|
|
||||||
f2_pred = self.surrogate_handler.predict(self.particles[i].x)
|
|
||||||
|
|
||||||
# 3. Inject scores without running the expensive 'updating_socs'
|
|
||||||
self.particles[i].f_current = [f1, f2_pred, f3]
|
|
||||||
|
|
||||||
else:
|
|
||||||
# Standard Calculation (Slow & 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
|
|
||||||
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()
|
|
||||||
|
|
||||||
# --- EXECUTION FUNCTION ---
|
|
||||||
def run_scenario(scenario_name, model_type=None):
|
|
||||||
print(f"\n--- Launching Scenario: {scenario_name} ---")
|
|
||||||
start_time = time.time()
|
|
||||||
|
|
||||||
# Simulation parameters
|
|
||||||
params = {
|
|
||||||
'f_weights': [1,1,1], 'A_max': 500, 'price_mean': 0.15, 'price_std': 0.05,
|
|
||||||
'capacities': [50]*10, 'n': 20, 't': 50,
|
|
||||||
'w': 0.4, 'c1': 2.0, 'c2': 2.0,
|
|
||||||
'nb_vehicles': 10, 'delta_t': 60, 'nb_of_ticks': 72
|
|
||||||
}
|
|
||||||
|
|
||||||
# Instantiate extended class
|
|
||||||
optimizer = SmartMOPSO(model_type=model_type, **params)
|
|
||||||
|
|
||||||
# Run simulation
|
|
||||||
optimizer.iterate()
|
|
||||||
|
|
||||||
end_time = time.time()
|
|
||||||
duration = end_time - start_time
|
|
||||||
|
|
||||||
# Retrieve best f2 (e.g., from archive)
|
|
||||||
best_f2 = min([p.f_current[1] for p in optimizer.archive]) if optimizer.archive else 0
|
|
||||||
|
|
||||||
print(f"Finished in {duration:.2f} seconds.")
|
|
||||||
print(f"Best f2 found: {best_f2:.4f}")
|
|
||||||
|
|
||||||
return duration, best_f2
|
|
||||||
|
|
||||||
# --- MAIN ---
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
results = {}
|
main()
|
||||||
|
|
||||||
# 1. Without Surrogate (Baseline)
|
|
||||||
d1, f1_score = run_scenario("No AI", model_type=None)
|
|
||||||
results['No-AI'] = (d1, f1_score)
|
|
||||||
|
|
||||||
# 2. With MLP
|
|
||||||
d2, f2_score = run_scenario("With MLP", model_type='mlp')
|
|
||||||
results['MLP'] = (d2, f2_score)
|
|
||||||
|
|
||||||
# 3. With Random Forest
|
|
||||||
d3, f3_score = run_scenario("With Random Forest", model_type='rf')
|
|
||||||
results['RF'] = (d3, f3_score)
|
|
||||||
|
|
||||||
# --- DISPLAY RESULTS ---
|
|
||||||
print("\n=== SUMMARY ===")
|
|
||||||
print(f"{'Mode':<15} | {'Time (s)':<10} | {'Best f2':<10}")
|
|
||||||
print("-" * 45)
|
|
||||||
for k, v in results.items():
|
|
||||||
print(f"{k:<15} | {v[0]:<10.2f} | {v[1]:<10.4f}")
|
|
||||||
|
|||||||
60
mopso.py
60
mopso.py
@@ -1,5 +1,6 @@
|
|||||||
import random as rd
|
import random as rd
|
||||||
from .particle import Particle
|
from .particle import Particle
|
||||||
|
import copy
|
||||||
|
|
||||||
class MOPSO():
|
class MOPSO():
|
||||||
def __init__(self, f_weights:list, A_max:float, price_mean:float, price_std:float, capacities:list, n:int, t:int, w:float, c1:float, c2:float, archive_size:int=10, nb_vehicles:int=10, delta_t:int=60, nb_of_ticks:int=72, x_min=-100, x_max=100, v_alpha=0.1, surrogate=False):
|
def __init__(self, f_weights:list, A_max:float, price_mean:float, price_std:float, capacities:list, n:int, t:int, w:float, c1:float, c2:float, archive_size:int=10, nb_vehicles:int=10, delta_t:int=60, nb_of_ticks:int=72, x_min=-100, x_max=100, v_alpha=0.1, surrogate=False):
|
||||||
@@ -18,16 +19,27 @@ class MOPSO():
|
|||||||
self.A_max = A_max # Network's power limit
|
self.A_max = A_max # Network's power limit
|
||||||
self.socs, self.socs_req = self.generate_state_of_charges(nb_vehicles,nb_of_ticks)
|
self.socs, self.socs_req = self.generate_state_of_charges(nb_vehicles,nb_of_ticks)
|
||||||
self.times = self.generate_times(nb_vehicles, nb_of_ticks, delta_t)
|
self.times = self.generate_times(nb_vehicles, nb_of_ticks, delta_t)
|
||||||
self.prices = self.generates_prices(price_mean,price_std) #TODO: Use RTE France prices for random prices generation according to number of ticks
|
self.prices = self.generates_prices(nb_of_ticks,price_mean,price_std) #TODO: Use RTE France prices for random prices generation according to number of ticks
|
||||||
self.capacities = capacities
|
self.capacities = capacities
|
||||||
|
|
||||||
# Particles of the simulation
|
# Particles of the simulation
|
||||||
self.particles = [Particle(nb_vehicles=nb_vehicles, nb_of_ticks=nb_of_ticks, delta_t=delta_t, x_min=x_min, x_max=x_max, alpha=v_alpha) for _ in range(self.n)]
|
self.particles = [
|
||||||
|
Particle(
|
||||||
|
socs=copy.deepcopy(self.socs),
|
||||||
|
times=self.times, # Ajouté ici
|
||||||
|
nb_vehicles=nb_vehicles,
|
||||||
|
nb_of_ticks=nb_of_ticks,
|
||||||
|
delta_t=delta_t,
|
||||||
|
x_min=x_min,
|
||||||
|
x_max=x_max,
|
||||||
|
alpha=v_alpha
|
||||||
|
) for _ in range(self.n)
|
||||||
|
]
|
||||||
self.archive = []
|
self.archive = []
|
||||||
self.leader = self.particles[0] # it doesnt matter as the first thing done is choosing a new leader
|
self.leader = self.particles[0] # it doesnt matter as the first thing done is choosing a new leader
|
||||||
|
|
||||||
for i in range(self.n):
|
for i in range(self.n):
|
||||||
self.particles[i].evaluate(self.f_weights, self.prices, self.socs, self.socs_req, self.times)
|
self.particles[i].evaluate(self.prices, self.socs, self.socs_req, self.times)
|
||||||
self.update_archive()
|
self.update_archive()
|
||||||
|
|
||||||
def iterate(self):
|
def iterate(self):
|
||||||
@@ -78,46 +90,48 @@ class MOPSO():
|
|||||||
|
|
||||||
# Genrates the coordinated states of charges requested and initial (duplicated initially for other ticks)
|
# Genrates the coordinated states of charges requested and initial (duplicated initially for other ticks)
|
||||||
def generate_state_of_charges(self, nb_vehicles:int, nb_of_ticks:int):
|
def generate_state_of_charges(self, nb_vehicles:int, nb_of_ticks:int):
|
||||||
socs = []
|
# Structure souhaitée : socs[tick][vehicle] pour être cohérent avec self.x[tick][vehicle]
|
||||||
|
socs = [[0.0 for _ in range(nb_vehicles)] for _ in range(nb_of_ticks)]
|
||||||
socs_req = []
|
socs_req = []
|
||||||
# We ensure soc_req is greater than what the soc_init is (percentage transformed into floats)
|
|
||||||
for _ in range(nb_vehicles):
|
|
||||||
soc_init = rd.randrange(0,100,1)
|
|
||||||
soc_req = rd.randrange(soc_init+1, 101,1)
|
|
||||||
|
|
||||||
# Creating states of charges for each tick in time
|
for i in range(nb_vehicles):
|
||||||
for _ in range(nb_of_ticks):
|
soc_init = rd.randrange(0, 100, 1)
|
||||||
socs.append(soc_init/100)
|
soc_req = rd.randrange(soc_init + 1, 101, 1)
|
||||||
|
|
||||||
|
# Remplissage de la matrice 2D
|
||||||
|
for tick in range(nb_of_ticks):
|
||||||
|
socs[tick][i] = soc_init / 100.0
|
||||||
|
|
||||||
|
socs_req.append(soc_req / 100.0)
|
||||||
|
|
||||||
# Adding the requested state of charge
|
|
||||||
socs_req.append(soc_req/100)
|
|
||||||
return socs, socs_req
|
return socs, socs_req
|
||||||
|
|
||||||
# True if a dominates b, else false
|
# True if a dominates b, else false
|
||||||
def dominates(a:Particle, b:Particle):
|
def dominates(self, a:Particle, b:Particle):
|
||||||
dominates = (a.f_current[0] >= b.f_current[0]) and (a.f_current[1] >= b.f_current[1]) and (a.f_current[2] >= b.f_current[2])
|
dominates = (a.f_current[0] <= b.f_current[0]) and (a.f_current[1] <= b.f_current[1]) and (a.f_current[2] <= b.f_current[2])
|
||||||
if dominates:
|
if dominates:
|
||||||
# Not strict superiority yet
|
# Not strict superiority yet
|
||||||
dominates = (a.f_current[0] > b.f_current[0]) or (a.f_current[1] > b.f_current[1]) or (a.f_current[2] > b.f_current[2])
|
dominates = (a.f_current[0] < b.f_current[0]) or (a.f_current[1] < b.f_current[1]) or (a.f_current[2] < b.f_current[2])
|
||||||
return dominates
|
return dominates
|
||||||
|
|
||||||
|
|
||||||
def update_archive(self):
|
def update_archive(self):
|
||||||
candidates = self.archive + self.particles
|
candidates = self.archive + self.particles
|
||||||
length = len(candidates)
|
length = len(candidates)
|
||||||
|
|
||||||
non_dominated = []
|
non_dominated = []
|
||||||
|
|
||||||
for i in range(length):
|
for i in range(length):
|
||||||
candidate_i = candidates[i]
|
candidate_i = candidates[i]
|
||||||
dominates = True
|
is_dominated = False
|
||||||
|
|
||||||
for j in range(length):
|
for j in range(length):
|
||||||
if i!=j:
|
if i != j:
|
||||||
candidate_j = candidates[j]
|
candidate_j = candidates[j]
|
||||||
dominates = dominates and self.dominates(candidate_i, candidate_j)
|
if self.dominates(candidate_j, candidate_i):
|
||||||
if dominates:
|
is_dominated = True
|
||||||
|
break
|
||||||
|
if not is_dominated:
|
||||||
non_dominated.append(candidate_i)
|
non_dominated.append(candidate_i)
|
||||||
|
|
||||||
# Keeping only a certain number of solutions depending on archive_size (to avoid overloading the number of potential directions for particles)
|
|
||||||
if len(non_dominated) > self.archive_size:
|
if len(non_dominated) > self.archive_size:
|
||||||
final_non_dominated = []
|
final_non_dominated = []
|
||||||
while len(final_non_dominated) < self.archive_size:
|
while len(final_non_dominated) < self.archive_size:
|
||||||
|
|||||||
36
particle.py
36
particle.py
@@ -1,12 +1,14 @@
|
|||||||
import random as rd
|
import random as rd
|
||||||
|
import copy
|
||||||
|
|
||||||
class Particle():
|
class Particle():
|
||||||
def __init__(self,socs:list, nb_vehicles:int=10, delta_t:int=60, nb_of_ticks:int=72, x_min=-100, x_max=100, alpha=0.1):
|
def __init__(self, socs:list, times:list, nb_vehicles:int=10, delta_t:int=60, nb_of_ticks:int=72, x_min=-100, x_max=100, alpha=0.1):
|
||||||
# Problem specific attributes
|
# Problem specific attributes
|
||||||
self.nb_vehicles = nb_vehicles # Number of vehicles handles for the generations of position x
|
self.nb_vehicles = nb_vehicles # Number of vehicles handles for the generations of position x
|
||||||
self.delta_t = delta_t # delta_t for update purposes
|
self.delta_t = delta_t # delta_t for update purposes
|
||||||
self.nb_of_ticks = nb_of_ticks # Accounting for time evolution of the solution (multiplied by delta_t)
|
self.nb_of_ticks = nb_of_ticks # Accounting for time evolution of the solution (multiplied by delta_t)
|
||||||
self.socs = socs # States of charges for the particle current position (self.x)
|
self.socs = socs # States of charges for the particle current position (self.x)
|
||||||
|
self.times = times
|
||||||
|
|
||||||
# Minima and maxima of a position value
|
# Minima and maxima of a position value
|
||||||
self.x_min = x_min
|
self.x_min = x_min
|
||||||
@@ -62,11 +64,8 @@ class Particle():
|
|||||||
if self.x[tick][i] > 0:
|
if self.x[tick][i] > 0:
|
||||||
self.x[tick][i] = self.x[tick][i] * 0.9
|
self.x[tick][i] = self.x[tick][i] * 0.9
|
||||||
current_power = self.get_current_grid_stress(tick)
|
current_power = self.get_current_grid_stress(tick)
|
||||||
|
|
||||||
def update_socs(self, capacities):
|
|
||||||
for tick in range(self.nb_of_ticks):
|
|
||||||
for i in range(self.nb_vehicles-1):
|
|
||||||
self.socs[tick][i+1] = self.socs[tick][i] + (self.x[tick][i] / capacities[i])
|
|
||||||
|
|
||||||
def generate_position(self):
|
def generate_position(self):
|
||||||
pos = []
|
pos = []
|
||||||
@@ -91,7 +90,7 @@ class Particle():
|
|||||||
# Function objective
|
# Function objective
|
||||||
def evaluate(self,elec_prices,socs,socs_req,times):
|
def evaluate(self,elec_prices,socs,socs_req,times):
|
||||||
f1 = self.f1(elec_prices)
|
f1 = self.f1(elec_prices)
|
||||||
f2 = self.f2(socs,socs_req,times)
|
f2 = self.f2(self.socs,socs_req,times)
|
||||||
f3 = self.f3()
|
f3 = self.f3()
|
||||||
|
|
||||||
# Keeping in memory evaluation of each objective for domination evaluation
|
# Keeping in memory evaluation of each objective for domination evaluation
|
||||||
@@ -103,13 +102,13 @@ class Particle():
|
|||||||
self.f_current = f_current
|
self.f_current = f_current
|
||||||
|
|
||||||
def update_best(self):
|
def update_best(self):
|
||||||
current_better = (self.f_current[0] >= self.f_best[0]) and (self.f_current[1] >= self.f_best[1]) and (self.f_current[2] >= self.f_best[2])
|
current_better = (self.f_current[0] <= self.f_best[0]) and (self.f_current[1] <= self.f_best[1]) and (self.f_current[2] <= self.f_best[2])
|
||||||
if current_better:
|
if current_better:
|
||||||
# Not strict superiority yet
|
# Not strict superiority yet
|
||||||
current_dominates = (self.f_current[0] > self.f_best[0]) or (self.f_current[1] > self.f_best[1]) or (self.f_current[2] > self.f_best[2])
|
current_dominates = (self.f_current[0] < self.f_best[0]) or (self.f_current[1] < self.f_best[1]) or (self.f_current[2] < self.f_best[2])
|
||||||
if current_dominates:
|
if current_dominates:
|
||||||
self.p_best = self.x
|
self.p_best = copy.deepcopy(self.x)
|
||||||
self.f_best = self.f_current
|
self.f_best = self.f_current[:]
|
||||||
|
|
||||||
# Calculate the price of the electricity consumption in the grid SUM(1_to_T)(Epsilon_t * A_t * delta_t)
|
# Calculate the price of the electricity consumption in the grid SUM(1_to_T)(Epsilon_t * A_t * delta_t)
|
||||||
def f1(self,elec_prices):
|
def f1(self,elec_prices):
|
||||||
@@ -142,5 +141,16 @@ class Particle():
|
|||||||
current_grid_stress += self.x[tick][i]
|
current_grid_stress += self.x[tick][i]
|
||||||
return current_grid_stress
|
return current_grid_stress
|
||||||
|
|
||||||
def updating_socs(self, socs, capacities):
|
def updating_socs(self, initial_socs, capacities):
|
||||||
pass
|
|
||||||
|
# Calcul de l'évolution temporelle
|
||||||
|
for tick in range(self.nb_of_ticks - 1): # On s'arrête à l'avant-dernier pour calculer le suivant
|
||||||
|
for i in range(self.nb_vehicles):
|
||||||
|
# SoC(t+1) = SoC(t) + (Puissance(t) * delta_t / Capacité)
|
||||||
|
energy_added = (self.x[tick][i] * (self.delta_t / 60))
|
||||||
|
|
||||||
|
# Mise à jour du tick suivant basé sur le tick actuel
|
||||||
|
# On utilise initial_socs comme base si c'est une liste de listes [tick][vehicule]
|
||||||
|
self.socs[tick+1][i] = self.socs[tick][i] + (energy_added / capacities[i])
|
||||||
|
|
||||||
|
self.socs[tick+1][i] = max(0.0, min(1.0, self.socs[tick+1][i]))
|
||||||
Reference in New Issue
Block a user