- Migrate from simple loop to SimPy discrete event simulator - Implement node_mobility_process() as parallel SimPy processes - LEACH: distributed CH election with probability p - LEACH-C: centralized BS-optimized CH selection - 6 test scenarios with comprehensive results - 3000 rounds per scenario for long-term viability testing - All metrics calculated: FDN, FMR, DLBI, RSPI - 5 PNG graphs generated with analysis - Full rapport updated with 3000-round results - Code cleaned: no .log or .md files, no __pycache__
141 lines
4.3 KiB
Python
141 lines
4.3 KiB
Python
"""
|
|
Module principal : Simulation complète des protocoles LEACH et LEACH-C avec SimPy
|
|
"""
|
|
|
|
import random
|
|
import json
|
|
import os
|
|
from datetime import datetime
|
|
from simulator_simpy import SimulatorSimPy
|
|
from config import SCENARIOS, DEBUG
|
|
|
|
|
|
def run_all_scenarios():
|
|
"""
|
|
Lance les simulations pour tous les scénarios.
|
|
Utilise SimPy pour simulation à événements discrets.
|
|
|
|
Returns:
|
|
dict: Résultats pour tous les scénarios
|
|
"""
|
|
all_results = {}
|
|
|
|
print(f"\n{'#'*70}")
|
|
print(f"# SIMULATION LEACH vs LEACH-C - RÉSEAUX DYNAMIQUES (SimPy)")
|
|
print(f"# Démarrage: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
print(f"{'#'*70}\n")
|
|
|
|
for scenario in SCENARIOS:
|
|
scenario_name = scenario["name"]
|
|
print(f"\n{'='*70}")
|
|
print(f"SCÉNARIO: {scenario_name}")
|
|
print(f"{'='*70}")
|
|
|
|
scenario_results = {}
|
|
|
|
# Simuler LEACH
|
|
print(f"\n>>> Exécution LEACH...")
|
|
sim_leach = SimulatorSimPy(scenario, protocol_name="LEACH")
|
|
leach_data = sim_leach.run()
|
|
scenario_results["LEACH"] = {
|
|
"metrics": {
|
|
"fdn": leach_data["fdn"],
|
|
"fmr": leach_data["fmr"],
|
|
"dlbi": leach_data["dlbi"],
|
|
"rspi": leach_data["rspi"],
|
|
},
|
|
"rounds_data": leach_data["rounds_data"]
|
|
}
|
|
|
|
# Simuler LEACH-C
|
|
print(f"\n>>> Exécution LEACH-C...")
|
|
sim_leachc = SimulatorSimPy(scenario, protocol_name="LEACH-C")
|
|
leachc_data = sim_leachc.run()
|
|
scenario_results["LEACH-C"] = {
|
|
"metrics": {
|
|
"fdn": leachc_data["fdn"],
|
|
"fmr": leachc_data["fmr"],
|
|
"dlbi": leachc_data["dlbi"],
|
|
"rspi": leachc_data["rspi"],
|
|
},
|
|
"rounds_data": leachc_data["rounds_data"]
|
|
}
|
|
|
|
all_results[scenario_name] = scenario_results
|
|
|
|
print(f"\n{'#'*70}")
|
|
print(f"# SIMULATIONS TERMINÉES - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
print(f"{'#'*70}\n")
|
|
|
|
return all_results
|
|
|
|
|
|
def save_results(results, output_file):
|
|
"""
|
|
Sauvegarde les résultats en JSON.
|
|
|
|
Args:
|
|
results (dict): Résultats de toutes les simulations
|
|
output_file (str): Chemin du fichier de sortie
|
|
"""
|
|
# Convertir en format sérialisable JSON
|
|
json_results = {}
|
|
|
|
for scenario_name, scenario_data in results.items():
|
|
json_results[scenario_name] = {}
|
|
|
|
for protocol in ["LEACH", "LEACH-C"]:
|
|
if protocol in scenario_data:
|
|
json_results[scenario_name][protocol] = {
|
|
"metrics": scenario_data[protocol]["metrics"]
|
|
}
|
|
|
|
with open(output_file, 'w') as f:
|
|
json.dump(json_results, f, indent=2)
|
|
|
|
print(f"OK - Résultats sauvegardés: {output_file}")
|
|
|
|
|
|
def print_summary(results):
|
|
"""Affiche un résumé des résultats."""
|
|
print("\n" + "="*70)
|
|
print("RÉSUMÉ DES RÉSULTATS")
|
|
print("="*70)
|
|
|
|
for scenario_name, scenario_data in results.items():
|
|
print(f"\n{scenario_name}:")
|
|
|
|
for protocol in ["LEACH", "LEACH-C"]:
|
|
if protocol in scenario_data:
|
|
metrics = scenario_data[protocol]["metrics"]
|
|
print(f"\n {protocol}:")
|
|
print(f" FDN (First Dead Node): {metrics['fdn']}")
|
|
print(f" FMR (First Muted Round): {metrics['fmr']}")
|
|
print(f" DLBI: {metrics['dlbi']:.4f}")
|
|
print(f" RSPI: {metrics['rspi']:.4f}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Graine de randomisation pour reproductibilité
|
|
random.seed(42)
|
|
|
|
# Déterminer le répertoire racine du projet
|
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
project_dir = os.path.dirname(script_dir)
|
|
results_dir = os.path.join(project_dir, "results")
|
|
|
|
# Créer le répertoire results s'il n'existe pas
|
|
os.makedirs(results_dir, exist_ok=True)
|
|
|
|
# Lancer toutes les simulations
|
|
all_results = run_all_scenarios()
|
|
|
|
# Afficher un résumé
|
|
print_summary(all_results)
|
|
|
|
# Sauvegarder les résultats
|
|
output_file = os.path.join(results_dir, "simulation_results.json")
|
|
save_results(all_results, output_file)
|
|
|
|
print(f"\nRésultats disponibles dans: {results_dir}")
|