OptimizerEvolutionary.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #include "OptimizerEvolutionary.h"
  2. namespace mdd {
  3. void OptimizerEvolutionary::evaluate(size_t ignore_len)
  4. {
  5. _mutex.lock();
  6. //clear duplicates
  7. //std::sort(_children.begin(), _children.end(), Permutation::smaller);
  8. //_children.erase(std::unique(_children.begin(), _children.end(), Permutation::same), _children.end());
  9. std::vector<Permutation> save = _children;
  10. _children.clear();
  11. for (size_t i = 0; i < save.size(); i++)
  12. {
  13. bool found = false;
  14. for (size_t j = 0; j < _children.size(); j++)
  15. {
  16. if (save[i] == _children[j])
  17. {
  18. found = true;
  19. break;
  20. }
  21. }
  22. if (!found)
  23. {
  24. _children.push_back(save[i]);
  25. }
  26. }
  27. //print Modules which are not evaluated again
  28. opt_state def_state;
  29. def_state.module_state = state::UNCHANGED;
  30. for (int i = 0; i < ignore_len; ++i)
  31. {
  32. callback_evaluate_opt(_children[i]);
  33. }
  34. //calculate fitness
  35. for (auto it = _children.begin() + ignore_len; it != _children.end(); ++it)
  36. {
  37. auto per = findPermutation(it->dna);
  38. if (per == nullptr)
  39. {
  40. for (size_t j = 0; j < _inputs.size(); j++)
  41. {
  42. //std::cout << "set: " << j << ": " << it->dna[j] << std::endl;
  43. _inputs[j]->setValue() = it->dna[j];
  44. }
  45. // Start timer
  46. auto start = std::chrono::steady_clock::now();
  47. // Update Module
  48. opt_state opt = updateOutputs();
  49. // Stop timer
  50. auto end = std::chrono::steady_clock::now();
  51. std::chrono::duration<double> elapsed_seconds = end - start;
  52. it->time = elapsed_seconds.count();
  53. it->status = opt.module_state;
  54. it->fitness = opt.opt_value;
  55. callback_evaluate_opt(*it);
  56. if (opt.module_state == state::STATE_ERROR) {
  57. _children.erase(it);
  58. }
  59. }
  60. else{
  61. callback_evaluate_opt(*per);
  62. }
  63. }
  64. //find fitest
  65. double min = _children[0].fitness;
  66. _bests.clear();
  67. _bests.push_back(_children[0]);
  68. for (size_t i = 1; i < _children.size(); i++)
  69. {
  70. if (round(min/_precision)*_precision > round(_children[i].fitness / _precision) * _precision) {
  71. min = _children[i].fitness;
  72. _bests.clear();
  73. _bests.push_back(_children[i]);
  74. }
  75. else if(round(min / _precision) * _precision == round(_children[i].fitness / _precision) * _precision)
  76. {
  77. bool found = false;
  78. for (size_t j = 0; j < _bests.size(); j++)
  79. {
  80. if (_children[i] == _bests[j])
  81. {
  82. found = true;
  83. break;
  84. }
  85. }
  86. if (!found)
  87. {
  88. _bests.push_back(_children[i]);
  89. }
  90. }
  91. }
  92. _mutex.unlock();
  93. callback_autosave();
  94. }
  95. OptimizerEvolutionary::OptimizerEvolutionary()
  96. :OptimizerBase(R"JSON(
  97. {
  98. "converges":
  99. {
  100. "value": 0
  101. },
  102. "grow generation":
  103. {
  104. "value": 20
  105. },
  106. "max fitness":
  107. {
  108. "value": 0.0
  109. },
  110. "min generations":
  111. {
  112. "value": -1
  113. },
  114. "precission":
  115. {
  116. "value": 0.001
  117. }
  118. })JSON")
  119. {
  120. key = "OptimizerEvolutionary";
  121. _converges = 0;
  122. _grow_generation = 20;
  123. _max_fitness = 0.0;
  124. _min_generations = -1;
  125. _precision = 0.001;
  126. }
  127. bool OptimizerEvolutionary::configureChild(const json& config) {
  128. bool found = false;
  129. auto jit = config.find("converges");
  130. if (jit != config.end())
  131. {
  132. json jval = jit.value()["value"];
  133. if (jval.is_string())
  134. {
  135. jval = json::parse(jval.get<std::string>());
  136. }
  137. _converges = jval.get<int>();
  138. _base_config["configure"]["converges"]["value"] = _converges;
  139. found = true;
  140. }
  141. jit = config.find("grow generation");
  142. if (jit != config.end())
  143. {
  144. json jval = jit.value()["value"];
  145. if (jval.is_string())
  146. {
  147. jval = json::parse(jval.get<std::string>());
  148. }
  149. _grow_generation = jval.get<int>();
  150. _base_config["configure"]["grow generation"]["value"] = _grow_generation;
  151. found = true;
  152. }
  153. jit = config.find("max fitness");
  154. if (jit != config.end())
  155. {
  156. json jval = jit.value()["value"];
  157. if (jval.is_string())
  158. {
  159. jval = json::parse(jval.get<std::string>());
  160. }
  161. _max_fitness = jval.get<double>();
  162. _base_config["configure"]["max fitness"]["value"] = _max_fitness;
  163. found = true;
  164. }
  165. jit = config.find("min generations");
  166. if (jit != config.end())
  167. {
  168. json jval = jit.value()["value"];
  169. if (jval.is_string())
  170. {
  171. jval = json::parse(jval.get<std::string>());
  172. }
  173. _min_generations = jval.get<int>();
  174. _base_config["configure"]["min generations"]["value"] = _min_generations;
  175. found = true;
  176. }
  177. jit = config.find("precision");
  178. if (jit != config.end())
  179. {
  180. json jval = jit.value()["value"];
  181. if (jval.is_string())
  182. {
  183. jval = json::parse(jval.get<std::string>());
  184. }
  185. _precision = jval.get<double>();
  186. _base_config["configure"]["precision"]["value"] = _precision;
  187. found = true;
  188. }
  189. return found;
  190. }
  191. bool OptimizerEvolutionary::loadStepDB(const json& j) {
  192. bool ret = true;
  193. for (size_t i = 0; i < j.size(); i++)
  194. {
  195. json jstep = j.at(i);
  196. int counter = json::parse(jstep["step"].get<std::string>()).get<int>();
  197. json dna = json::parse(jstep["dna"].get<std::string>());
  198. ret = ret && addStep(counter, dna);
  199. if (this->step != counter)
  200. {
  201. ++this->step;
  202. _children.clear();
  203. }
  204. std::shared_ptr<Permutation> per_ptr = getPermutation(counter, dna);
  205. _children.push_back(*per_ptr);
  206. }
  207. return ret;
  208. }
  209. bool OptimizerEvolutionary::loadDB(const json& j) {
  210. bool ret = OptimizerBase::loadDB(j);
  211. if (step == -1)
  212. {
  213. return ret;
  214. }
  215. _bests = findBest(step -1);
  216. return ret;
  217. }
  218. void OptimizerEvolutionary::reset() {
  219. OptimizerBase::reset();
  220. _children.clear();
  221. _bests.clear();
  222. _same_counter = 0;
  223. _old_best = Permutation();
  224. }
  225. bool OptimizerEvolutionary::reachAbort(const std::vector<Permutation>& pers) {
  226. bool check;
  227. check = step < _min_generations || pers[0].fitness > _max_fitness;
  228. if (!check && _converges > 0)
  229. {
  230. bool found = false;
  231. for (size_t i = 0; i < pers.size(); i++)
  232. {
  233. Permutation p_container = pers.at(i);
  234. if (p_container == _old_best)
  235. {
  236. found = true;
  237. break;
  238. }
  239. }
  240. if (found)
  241. {
  242. ++_same_counter;
  243. }
  244. else
  245. {
  246. _old_best = pers[0];
  247. _same_counter = 0;
  248. }
  249. if (_same_counter < _converges)
  250. {
  251. check = true;
  252. }
  253. }
  254. return !check;
  255. }
  256. double OptimizerEvolutionary::update()
  257. {
  258. if (_inputs.size() == 0)
  259. {
  260. std::cout << "ERROR: No optimizable inputs detected!" << std::endl;
  261. return -1.0;
  262. }
  263. do
  264. {
  265. ++step;
  266. std::cout << _children.size() << " | " << step << std::endl;
  267. evolve();
  268. } while (!reachAbort(_bests));
  269. return _bests[0].fitness;
  270. }
  271. std::vector<double> OptimizerEvolutionary::mutateGene(std::shared_ptr<IInput> input, std::vector<double> seed)
  272. {
  273. const limits limit = *(input->getLimits());
  274. auto ret = seed;
  275. if (!limit.elements.empty())
  276. {
  277. int i = (int)random_num(0, limit.elements.size() - 1);
  278. ret = limit.elements[i];
  279. return ret;
  280. }
  281. if (!limit.min.empty() && !limit.max.empty()) {
  282. bool check = true;
  283. do {
  284. if (!ret.empty())
  285. {
  286. int i = (int)random_num(0, limit.min.size() - 1);
  287. if (!limit.step.empty()) {
  288. //randomly generate step dx in [min, max]
  289. /*std::cout << limit["min"][i].get<double>() << " | ";
  290. std::cout << limit["max"][i].dump() << " | ";
  291. std::cout << limit["step"][i].dump() << " | ";*/
  292. ret[i] = random_num(limit.min[i], limit.max[i], limit.step[i]);
  293. }
  294. else {
  295. int m = (int)random_num(0, 1);
  296. if (m == 0)
  297. {
  298. ret[i] = limit.min[i];
  299. }
  300. else {
  301. ret[i] = limit.max[i];
  302. }
  303. }
  304. }
  305. else
  306. {
  307. for (size_t i = 0; i < limit.min.size(); i++)
  308. {
  309. if (!limit.step.empty()) {
  310. //randomly generate step dx in [min, max]
  311. ret.push_back(random_num(limit.min[i], limit.max[i], limit.step[i]));
  312. }
  313. else {
  314. int m = (int)random_num(0, 1);
  315. if (m == 0)
  316. {
  317. ret.push_back(limit.min[i]);
  318. }
  319. else {
  320. ret.push_back(limit.max[i]);
  321. }
  322. }
  323. }
  324. }
  325. if (!limit.rule.empty()) {
  326. //use rule to check
  327. exprtk::symbol_table<double> symbol_table;
  328. symbol_table.add_vector("val", ret);
  329. symbol_table.add_constants();
  330. exprtk::expression<double> func_expr;
  331. func_expr.register_symbol_table(symbol_table);
  332. exprtk::parser<double> parser;
  333. parser.compile(limit.rule, func_expr);
  334. double func_val = func_expr.value();
  335. if (func_val < 0.5)
  336. {
  337. check = false;
  338. }
  339. else {
  340. check = true;
  341. }
  342. }
  343. } while (!check);
  344. return ret;
  345. }
  346. std::cout << "ERROR in GENE elements! (END)" << std::endl;
  347. return input->getValue();//ERROR
  348. }
  349. void OptimizerEvolutionary::evolve()
  350. {
  351. _mutex.lock();
  352. if (_children.empty())
  353. {
  354. for (size_t i = 0; i < _grow_generation * 2; i++)
  355. {
  356. bool not_found = true;
  357. Permutation per;
  358. while (not_found)
  359. {
  360. per = generatePermutation();
  361. not_found = false;
  362. for (size_t i = 0; i < _children.size(); i++)
  363. {
  364. if (_children[i].dna == per.dna)
  365. {
  366. not_found = true;
  367. break;
  368. }
  369. }
  370. }
  371. _children.push_back(per);
  372. }
  373. }
  374. else {
  375. ////fittest should breed more
  376. //detect lower border
  377. double max = _children[0].fitness;
  378. for (size_t i = 1; i < _children.size(); i++)
  379. {
  380. if (max < _children[i].fitness) {
  381. max = _children[i].fitness;
  382. }
  383. }
  384. //detect lower border
  385. double sum = 0;
  386. for (size_t i = 0; i < _children.size(); i++)
  387. {
  388. sum += max - _children[i].fitness;
  389. }
  390. if (sum == 0)
  391. {
  392. sum = 1.0;
  393. }
  394. //multiply fitter parents
  395. std::vector<Permutation> gen_pool = _children;
  396. for (size_t i = 0; i < _children.size(); i++)
  397. {
  398. int additional = std::round((max - _children[i].fitness) / sum * 20);
  399. //std::cout << additional << std::endl;
  400. for (size_t j = 1; j < additional; j++)
  401. {
  402. gen_pool.push_back(_children[i]);
  403. }
  404. }
  405. //fittest parents will also be new childrens
  406. _children = _bests;
  407. //breed
  408. for (size_t i = 0; i < _grow_generation; i++)
  409. {
  410. bool not_found = true;
  411. Permutation per;
  412. int try_counter = 0;
  413. while (not_found && try_counter < 20)
  414. {
  415. int p1 = (int)random_num(0, gen_pool.size() - 1);
  416. int p2 = (int)random_num(0, gen_pool.size() - 1);
  417. per = combine(gen_pool[p1], gen_pool[p2]);
  418. ++try_counter;
  419. not_found = false;
  420. for (size_t i = 0; i < _children.size(); i++)
  421. {
  422. if (_children[i].dna == per.dna)
  423. {
  424. not_found = true;
  425. break;
  426. }
  427. }
  428. }
  429. _children.push_back(per);
  430. }
  431. }
  432. _mutex.unlock();
  433. callback_add_step(_children);
  434. evaluate(_bests.size());
  435. }
  436. OptimizerEvolutionary::Permutation OptimizerEvolutionary::combine(Permutation par1, Permutation par2, int try_counter)
  437. {
  438. size_t len = par1.dna.size();
  439. Permutation child;
  440. for (size_t i = 0; i < len; i++)
  441. {
  442. double p = random_num(0.0, 100.0, 1.0);
  443. if (p<45.0 - try_counter)
  444. {
  445. child.dna.push_back(par1.dna[i]);
  446. }
  447. else if(p<90.0 - 2*try_counter){
  448. child.dna.push_back(par2.dna[i]);
  449. }
  450. else
  451. {
  452. child.dna.push_back(mutateGene(_inputs[i]));
  453. }
  454. }
  455. return child;
  456. }
  457. OptimizerEvolutionary::Permutation OptimizerEvolutionary::generatePermutation()
  458. {
  459. Permutation ret;
  460. for (size_t i = 0; i < _inputs.size(); i++)
  461. {
  462. ret.dna.push_back(mutateGene(_inputs[i]));
  463. }
  464. return ret;
  465. }
  466. std::vector<OptimizerEvolutionary::Permutation> OptimizerEvolutionary::getBests() {
  467. return _bests;
  468. }
  469. double OptimizerEvolutionary::evaluateFitness(const Permutation& ind) {
  470. for (size_t j = 0; j < _inputs.size(); j++)
  471. {
  472. _inputs[j]->setValue() = ind.dna[j];
  473. }
  474. auto opt = updateOutputs();
  475. return opt.opt_value;
  476. }
  477. }