ml.inl.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. #ifndef OPENCV_ML_INL_HPP
  5. #define OPENCV_ML_INL_HPP
  6. namespace cv { namespace ml {
  7. // declared in ml.hpp
  8. template<class SimulatedAnnealingSolverSystem>
  9. int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem,
  10. double initialTemperature, double finalTemperature, double coolingRatio,
  11. size_t iterationsPerStep,
  12. CV_OUT double* lastTemperature,
  13. cv::RNG& rngEnergy
  14. )
  15. {
  16. CV_Assert(finalTemperature > 0);
  17. CV_Assert(initialTemperature > finalTemperature);
  18. CV_Assert(iterationsPerStep > 0);
  19. CV_Assert(coolingRatio < 1.0f);
  20. double Ti = initialTemperature;
  21. double previousEnergy = solverSystem.energy();
  22. int exchange = 0;
  23. while (Ti > finalTemperature)
  24. {
  25. for (size_t i = 0; i < iterationsPerStep; i++)
  26. {
  27. solverSystem.changeState();
  28. double newEnergy = solverSystem.energy();
  29. if (newEnergy < previousEnergy)
  30. {
  31. previousEnergy = newEnergy;
  32. exchange++;
  33. }
  34. else
  35. {
  36. double r = rngEnergy.uniform(0.0, 1.0);
  37. if (r < std::exp(-(newEnergy - previousEnergy) / Ti))
  38. {
  39. previousEnergy = newEnergy;
  40. exchange++;
  41. }
  42. else
  43. {
  44. solverSystem.reverseState();
  45. }
  46. }
  47. }
  48. Ti *= coolingRatio;
  49. }
  50. if (lastTemperature)
  51. *lastTemperature = Ti;
  52. return exchange;
  53. }
  54. }} //namespace
  55. #endif // OPENCV_ML_INL_HPP