bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
mc_tree_search_solver.h
Go to the documentation of this file.
1#ifndef MC_TREE_SEARCH_SOLVER_H
2#define MC_TREE_SEARCH_SOLVER_H
3
6
7#include <concepts>
8#include <memory>
9#include <random>
10#include <utility>
11#include <vector>
12
13namespace bitrl
14{
15namespace rl
16{
17namespace algos
18{
19namespace mc
20{
21
27template <typename EnvTp>
28concept mcts_env_concept = std::copy_constructible<EnvTp> &&
29 requires(EnvTp env, typename EnvTp::action_type a)
30{
31 typename EnvTp::state_type;
32 {
33 env.n_actions()
34 } -> std::convertible_to<uint_t>;
35 {
36 env.step(a).reward()
37 } -> std::convertible_to<real_t>;
38 {
39 env.step(a).done()
40 } -> std::convertible_to<bool>;
41};
42
48{
49 template <typename EnvTp>
50 typename EnvTp::action_type operator()(const EnvTp &env, std::mt19937 &generator) const
51 {
52 std::uniform_int_distribution<uint_t> action(0, static_cast<uint_t>(env.n_actions()) - 1);
53 return static_cast<typename EnvTp::action_type>(action(generator));
54 }
55};
56
61{
66
72
78
83
89};
90
114template <mcts_env_concept EnvTp, typename RolloutPolicy = UniformRolloutPolicy> class MCTSSolver
115{
116 public:
117 typedef EnvTp env_type;
118 typedef typename env_type::action_type action_type;
119 typedef typename env_type::state_type state_type;
121
122 explicit MCTSSolver(const MCTSConfig &config, RolloutPolicy rollout_policy = RolloutPolicy())
123 : config_(config), rollout_policy_(std::move(rollout_policy)), generator_(config.seed)
124 {
125 }
126
132 action_type plan(const env_type &env);
133
137 std::shared_ptr<const node_type> root() const noexcept { return root_; }
138
139 const MCTSConfig &config() const noexcept { return config_; }
140
141 private:
142 MCTSConfig config_;
143 RolloutPolicy rollout_policy_;
144 std::mt19937 generator_;
145 std::shared_ptr<node_type> root_;
146
147 void simulate_(const env_type &env);
148 void expand_(const std::shared_ptr<node_type> &node, uint_t n_actions);
149};
150
151template <mcts_env_concept EnvTp, typename RolloutPolicy>
154{
155 root_ = std::make_shared<node_type>(nullptr, action_type{});
156 expand_(root_, static_cast<uint_t>(env.n_actions()));
157
158 for (uint_t i = 0; i < config_.n_simulations; ++i)
159 {
160 simulate_(env);
161 }
162
163 // the most visited child is the most reliable choice; ties go to the
164 // larger mean return
165 std::shared_ptr<node_type> best;
166 for (uint_t c = 0; c < root_->n_children(); ++c)
167 {
168 auto child = root_->get_child(c);
169 if (!best || child->total_visits() > best->total_visits() ||
170 (child->total_visits() == best->total_visits() && child->total_visits() > 0 &&
171 child->win_pct() > best->win_pct()))
172 {
173 best = child;
174 }
175 }
176 return best->get_action();
177}
178
179template <mcts_env_concept EnvTp, typename RolloutPolicy>
180void MCTSSolver<EnvTp, RolloutPolicy>::expand_(const std::shared_ptr<node_type> &node,
181 uint_t n_actions)
182{
183 for (uint_t a = 0; a < n_actions; ++a)
184 {
185 node->add_child(node, static_cast<action_type>(a));
186 }
187 // try the children in a random order, so that ties do not always go to
188 // the first action
189 node->shuffle_children(generator_);
190}
191
192template <mcts_env_concept EnvTp, typename RolloutPolicy>
193void MCTSSolver<EnvTp, RolloutPolicy>::simulate_(const env_type &env)
194{
195 env_type sim(env);
196 const auto n_actions = static_cast<uint_t>(sim.n_actions());
197
198 // the nodes the simulation goes through, from the root, and the reward
199 // of the step into each of them
200 std::vector<std::shared_ptr<node_type>> path{root_};
201 std::vector<real_t> rewards;
202 bool done = false;
203
204 // Selection: down the tree while every child of the node was tried
205 auto node = root_;
206 while (!done && path.size() <= config_.max_depth && node->has_children() &&
207 node->n_explored_children() == node->n_children())
208 {
209 node = node->max_ucb_child(config_.temperature);
210 auto time_step = sim.step(node->get_action());
211 rewards.push_back(time_step.reward());
212 done = time_step.done();
213 path.push_back(node);
214 }
215
216 // Expansion: try a child the node has not tried yet
217 if (!done && path.size() <= config_.max_depth)
218 {
219 if (!node->has_children())
220 {
221 expand_(node, n_actions);
222 }
223 auto child = node->get_child(node->n_explored_children());
224 node->update_explored_children();
225 auto time_step = sim.step(child->get_action());
226 rewards.push_back(time_step.reward());
227 done = time_step.done();
228 path.push_back(child);
229 }
230
231 // Rollout: the rollout policy to the end of the episode or of the look ahead
232 real_t rollout_return = 0.0;
233 real_t discount = 1.0;
234 for (auto depth = path.size() - 1; !done && depth < config_.max_depth; ++depth)
235 {
236 auto time_step = sim.step(rollout_policy_(sim, generator_));
237 rollout_return += discount * time_step.reward();
238 discount *= config_.gamma;
239 done = time_step.done();
240 }
241
242 // Backpropagation: every node scores the reward of the step into it and
243 // the discounted return that followed, which is what its parent compares
244 // its children by. After the last node comes the rollout
245 real_t g = rollout_return;
246 for (auto i = path.size(); i-- > 1;)
247 {
248 g = rewards[i - 1] + config_.gamma * g;
249 path[i]->update_visits();
250 path[i]->update_total_score(g);
251 }
252 // the root scores the whole return of the simulation
253 root_->update_visits();
254 root_->update_total_score(g);
255}
256
257} // namespace mc
258} // namespace algos
259} // namespace rl
260} // namespace bitrl
261
262#endif // MC_TREE_SEARCH_SOLVER_H
Base class for Nodes in a MC tree search.
Definition mcts_node.h:31
MCTSSolver(const MCTSConfig &config, RolloutPolicy rollout_policy=RolloutPolicy())
Definition mc_tree_search_solver.h:122
std::shared_ptr< const node_type > root() const noexcept
The root of the tree of the last plan(), or null before the first.
Definition mc_tree_search_solver.h:137
MCTSNodeBase< action_type, state_type > node_type
Definition mc_tree_search_solver.h:120
action_type plan(const env_type &env)
plan. Runs config().n_simulations simulations from copies of env and returns the action that is best ...
Definition mc_tree_search_solver.h:153
EnvTp env_type
Definition mc_tree_search_solver.h:117
const MCTSConfig & config() const noexcept
Definition mc_tree_search_solver.h:139
env_type::action_type action_type
Definition mc_tree_search_solver.h:118
env_type::state_type state_type
Definition mc_tree_search_solver.h:119
What MCTSSolver needs from an environment: it is copied for every simulation, has a fixed number of d...
Definition mc_tree_search_solver.h:28
Definition first_visit_mc.h:27
Definition dp_algo_base.h:15
Definition dummy_agent.h:9
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
bool done
Definition play.py:40
The configuration of MCTSSolver.
Definition mc_tree_search_solver.h:61
real_t temperature
How much UCB favours children that were visited less. It has the units of the returns,...
Definition mc_tree_search_solver.h:77
uint_t n_simulations
How many simulations plan() runs before it picks an action.
Definition mc_tree_search_solver.h:65
uint_t max_depth
The most steps a simulation looks ahead, in the tree and in the rollout after it.
Definition mc_tree_search_solver.h:71
uint_t seed
The seed of the generator of the random rollouts and of the order the children are tried in.
Definition mc_tree_search_solver.h:88
real_t gamma
The discount factor of the returns.
Definition mc_tree_search_solver.h:82
The default rollout policy of MCTSSolver: every action with the same probability.
Definition mc_tree_search_solver.h:48
EnvTp::action_type operator()(const EnvTp &env, std::mt19937 &generator) const
Definition mc_tree_search_solver.h:50