MCTSTree.cpp 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "MCTSTree.h"
  7. #include <AK/String.h>
  8. #include <stdlib.h>
  9. MCTSTree::MCTSTree(Chess::Board const& board, MCTSTree* parent)
  10. : m_parent(parent)
  11. , m_board(make<Chess::Board>(board))
  12. , m_last_move(board.last_move())
  13. , m_turn(board.turn())
  14. {
  15. }
  16. MCTSTree::MCTSTree(MCTSTree&& other)
  17. : m_children(move(other.m_children))
  18. , m_parent(other.m_parent)
  19. , m_white_points(other.m_white_points)
  20. , m_simulations(other.m_simulations)
  21. , m_board(move(other.m_board))
  22. , m_last_move(move(other.m_last_move))
  23. , m_turn(other.m_turn)
  24. , m_moves_generated(other.m_moves_generated)
  25. {
  26. other.m_parent = nullptr;
  27. }
  28. MCTSTree& MCTSTree::select_leaf()
  29. {
  30. if (!expanded() || m_children.size() == 0)
  31. return *this;
  32. MCTSTree* node = nullptr;
  33. double max_uct = -double(INFINITY);
  34. for (auto& child : m_children) {
  35. double uct = child.uct(m_turn);
  36. if (uct >= max_uct) {
  37. max_uct = uct;
  38. node = &child;
  39. }
  40. }
  41. VERIFY(node);
  42. return node->select_leaf();
  43. }
  44. MCTSTree& MCTSTree::expand()
  45. {
  46. VERIFY(!expanded() || m_children.size() == 0);
  47. if (!m_moves_generated) {
  48. m_board->generate_moves([&](Chess::Move chess_move) {
  49. auto clone = m_board->clone_without_history();
  50. clone.apply_move(chess_move);
  51. m_children.append(make<MCTSTree>(move(clone), this));
  52. return IterationDecision::Continue;
  53. });
  54. m_moves_generated = true;
  55. if (m_children.size() != 0)
  56. m_board = nullptr; // Release the board to save memory.
  57. }
  58. if (m_children.size() == 0) {
  59. return *this;
  60. }
  61. for (auto& child : m_children) {
  62. if (child.m_simulations == 0) {
  63. return child;
  64. }
  65. }
  66. VERIFY_NOT_REACHED();
  67. }
  68. int MCTSTree::simulate_game() const
  69. {
  70. Chess::Board clone = *m_board;
  71. while (!clone.game_finished()) {
  72. clone.apply_move(clone.random_move());
  73. }
  74. return clone.game_score();
  75. }
  76. int MCTSTree::heuristic() const
  77. {
  78. if (m_board->game_finished())
  79. return m_board->game_score();
  80. double winchance = max(min(double(m_board->material_imbalance()) / 6, 1.0), -1.0);
  81. double random = double(rand()) / RAND_MAX;
  82. if (winchance >= random)
  83. return 1;
  84. if (winchance <= -random)
  85. return -1;
  86. return 0;
  87. }
  88. void MCTSTree::apply_result(int game_score)
  89. {
  90. m_simulations++;
  91. m_white_points += game_score;
  92. if (m_parent)
  93. m_parent->apply_result(game_score);
  94. }
  95. void MCTSTree::do_round()
  96. {
  97. // Note: Limit expansion to spare some memory
  98. // Efficient Selectivity and Backup Operators in Monte-Carlo Tree Search.
  99. // Rémi Coulom.
  100. auto* node_ptr = &select_leaf();
  101. if (node_ptr->m_simulations > s_number_of_visit_parameter)
  102. node_ptr = &select_leaf().expand();
  103. auto& node = *node_ptr;
  104. int result;
  105. if constexpr (s_eval_method == EvalMethod::Simulation) {
  106. result = node.simulate_game();
  107. } else {
  108. result = node.heuristic();
  109. }
  110. node.apply_result(result);
  111. }
  112. Optional<MCTSTree&> MCTSTree::child_with_move(Chess::Move chess_move)
  113. {
  114. for (auto& node : m_children) {
  115. if (node.last_move() == chess_move)
  116. return node;
  117. }
  118. return {};
  119. }
  120. MCTSTree& MCTSTree::best_node()
  121. {
  122. int score_multiplier = (m_turn == Chess::Color::White) ? 1 : -1;
  123. MCTSTree* best_node_ptr = nullptr;
  124. double best_score = -double(INFINITY);
  125. VERIFY(m_children.size());
  126. for (auto& node : m_children) {
  127. double node_score = node.expected_value() * score_multiplier;
  128. if (node_score >= best_score) {
  129. best_node_ptr = &node;
  130. best_score = node_score;
  131. }
  132. }
  133. VERIFY(best_node_ptr);
  134. return *best_node_ptr;
  135. }
  136. Chess::Move MCTSTree::last_move() const
  137. {
  138. return m_last_move.value();
  139. }
  140. double MCTSTree::expected_value() const
  141. {
  142. if (m_simulations == 0)
  143. return 0;
  144. return double(m_white_points) / m_simulations;
  145. }
  146. double MCTSTree::uct(Chess::Color color) const
  147. {
  148. // UCT: Upper Confidence Bound Applied to Trees.
  149. // Kocsis, Levente; Szepesvári, Csaba (2006). "Bandit based Monte-Carlo Planning"
  150. // Fun fact: Szepesvári was my data structures professor.
  151. double expected = expected_value() * ((color == Chess::Color::White) ? 1 : -1);
  152. return expected + s_exploration_parameter * sqrt(log(m_parent->m_simulations) / m_simulations);
  153. }
  154. bool MCTSTree::expanded() const
  155. {
  156. if (!m_moves_generated)
  157. return false;
  158. for (auto& child : m_children) {
  159. if (child.m_simulations == 0)
  160. return false;
  161. }
  162. return true;
  163. }