SimulatedAnnealingForKnapsack.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace MetaheuristicsPCL
  5. {
  6. public class SimulatedAnnealingForKnapsack : SimulatedAnnealingAlgorithm
  7. {
  8. int nbIterationsWithoutUpdate = 1;
  9. int nbIterations = 1;
  10. private const int MAX_ITERATIONS_WITHOUT_UPDATE = 30;
  11. private const int MAX_ITERATIONS = 100;
  12. protected override void UpdateTemperature()
  13. {
  14. temperature *= 0.9;
  15. }
  16. protected override void InitTemperature()
  17. {
  18. temperature = 5;
  19. }
  20. protected override bool Done()
  21. {
  22. return nbIterationsWithoutUpdate >= MAX_ITERATIONS_WITHOUT_UPDATE && nbIterations >= MAX_ITERATIONS;
  23. }
  24. protected override void UpdateSolution(ISolution _bestSolution)
  25. {
  26. double seuil = 0.0;
  27. if (_bestSolution.Value < currentSolution.Value)
  28. {
  29. seuil = Math.Exp(-1 * (currentSolution.Value - _bestSolution.Value) / currentSolution.Value / temperature);
  30. }
  31. if (_bestSolution.Value > currentSolution.Value || KnapsackProblem.randomGenerator.NextDouble() < seuil)
  32. {
  33. currentSolution = _bestSolution;
  34. if (_bestSolution.Value > bestSoFarSolution.Value)
  35. {
  36. bestSoFarSolution = _bestSolution;
  37. nbIterationsWithoutUpdate = 0;
  38. }
  39. }
  40. }
  41. protected override void Increment()
  42. {
  43. nbIterationsWithoutUpdate++;
  44. nbIterations++;
  45. }
  46. protected override void SendResult()
  47. {
  48. ihm.PrintMessage(bestSoFarSolution.ToString());
  49. }
  50. }
  51. }