OptimizerBase.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #pragma once
  2. #include "IOptimizer.h"
  3. #include "exprtk.hpp"
  4. #include <thread>
  5. namespace mdd {
  6. ////////////////////////////////////////////////////////////
  7. //
  8. //Optimization is always minimization!
  9. //
  10. ////////////////////////////////////////////////////////////
  11. class OptimizerBase
  12. : public IOptimizer
  13. {
  14. protected:
  15. json _base_config;
  16. std::string key;
  17. const std::string type = "optimizer";
  18. std::shared_ptr<IModule> _module;
  19. std::vector<std::shared_ptr<IInput>> _inputs;
  20. std::vector<std::shared_ptr<IOutput>> _outputs;
  21. std::vector<double> _output_vals;
  22. exprtk::expression<double> _func_expr;
  23. std::function<json(const json&)> _callback;
  24. std::shared_ptr<std::thread> _thread_ptr;
  25. int step = -1;
  26. struct opt_state {
  27. state module_state = state::STATE_ERROR;
  28. double opt_value = 0;
  29. };
  30. opt_state updateOutputs();
  31. OptimizerBase(const std::string& base_config = "{}");
  32. bool configureChild(const json& config) override;
  33. public:
  34. struct Permutation {
  35. public:
  36. std::vector<std::vector<double>> dna;
  37. double fitness = 0;
  38. bool operator== (const Permutation& ind) {
  39. return (dna == ind.dna);
  40. };
  41. static bool same(Permutation const& a, Permutation const& b) {
  42. bool check1 = (a.dna == b.dna);
  43. bool check2 = true;
  44. if (a.dna.size() != b.dna.size())
  45. {
  46. check2 = false;
  47. }
  48. else {
  49. for (size_t i = 0; i < a.dna.size(); i++)
  50. {
  51. if (a.dna[i].size() != b.dna[i].size())
  52. {
  53. check2 = false;
  54. }
  55. else
  56. {
  57. for (size_t j = 0; j < a.dna[i].size(); j++)
  58. {
  59. if (a.dna[i][j] != b.dna[i][j])
  60. {
  61. check2 = false;
  62. }
  63. }
  64. }
  65. }
  66. }
  67. if (check1 != check2)
  68. {
  69. int test = 0;
  70. }
  71. return check1;
  72. }
  73. static bool smaller(Permutation const& a, Permutation const& b) {
  74. return (a.dna < b.dna);
  75. }
  76. };
  77. bool connect(std::shared_ptr<IModule> module) override;
  78. void updateLayout();
  79. bool setEvaluation(std::string func) override;
  80. bool configure(const json& config) override;
  81. const json& getConfiguration() override;
  82. //virtual std::string getGeneratorID() = 0;
  83. void load(const json& j);
  84. json dump();
  85. json getIdentifier() override;
  86. void attachCallback(std::function<json(const json&)> callback) override;
  87. //state update() override;
  88. void callback_add_step(const std::vector<Permutation>& pers);
  89. void callback_evaluate_opt(const opt_state& state, const Permutation& per);
  90. ~OptimizerBase();
  91. };
  92. }