bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
first_visit_mc.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2024 <copyright holder> <email>
2// SPDX-License-Identifier: Apache-2.0
3
4#ifndef FIRST_VISIT_MC_H
5#define FIRST_VISIT_MC_H
6
7#include "bitrl/base/bitrl_config.h"
9
14
15#ifdef CUBEAI_PRINT_DBG_MSGS
17#endif
18
19#include <algorithm>
20#include <string>
21#include <tuple>
22#include <vector>
23
24namespace bitrl
25{
27{
28
40
44template <typename EnvType, typename TrajectoryGenerator, typename DecayLRSchedule,
45 typename DiscountGenerator>
47{
48 public:
53 typedef EnvType env_type;
54
58 typedef TrajectoryGenerator trajectory_generator_type;
59
63 typedef DecayLRSchedule decay_lr_schedule_type;
64
68 typedef DiscountGenerator discount_generator_type;
69
74 typedef typename env_type::time_step_type time_step_type;
75
80 FirstVisitMCSolver(FirstVisitMCSolverConfig solver_config, TrajectoryGenerator &trajectory_gen,
81 DecayLRSchedule &decay_lr_schedule,
82 discount_generator_type &discount_generator);
83
89
95
99 void actions_before_episode_begins(env_type &, uint_t /*episode_idx*/) {}
100
105 const EpisodeInfo & /*einfo*/)
106 {
107 }
108
113
118 void save(const std::string &filename) const;
119
123 DynVec<real_t> value_function() const { return v_; }
124
125 private:
131
137
142 TrajectoryGenerator trajectory_gen_;
143
148 DecayLRSchedule decay_lr_schedule_;
149
154 discount_generator_type discount_generator_;
155};
156
157template <typename EnvType, typename TrajectoryGenerator, typename DecayLRSchedule,
158 typename DiscountGenerator>
160 FirstVisitMCSolver(FirstVisitMCSolverConfig solver_config, TrajectoryGenerator &trajectory_gen,
161 DecayLRSchedule &decay_lr_schedule,
162 discount_generator_type &discount_generator)
163 : v_(), config_(solver_config), trajectory_gen_(trajectory_gen),
164 decay_lr_schedule_(decay_lr_schedule), discount_generator_(discount_generator)
165{
166}
167
168template <typename EnvType, typename TrajectoryGenerator, typename DecayLRSchedule,
169 typename DiscountGenerator>
170void FirstVisitMCSolver<EnvType, TrajectoryGenerator, DecayLRSchedule,
172{
173
174 v_.resize(env.n_states());
175 std::for_each(v_.begin(), v_.end(), [](auto &item) { item = 0.0; });
176}
177
178template <typename EnvType, typename TrajectoryGenerator, typename DecayLRSchedule,
179 typename DiscountGenerator>
180EpisodeInfo FirstVisitMCSolver<EnvType, TrajectoryGenerator, DecayLRSchedule,
181 DiscountGenerator>::on_training_episode(env_type &env,
182 uint_t episode_idx)
183{
184
185 // start timing the training on this episode
186 auto start = std::chrono::steady_clock::now();
187
188 // generate the trajectory for the environment
189 // for this episode
190 auto trajectory = trajectory_gen_(env, config_.max_steps);
191
192 const auto trajectory_size = std::distance(trajectory.begin(), trajectory.end());
193
194#ifdef CUBEAI_PRINT_DBG_MSGS
195 if (trajectory_size == 0)
196 {
197 BITRL_LOG_WARN << "Trajectory size=" << trajectory_size << std::endl;
198 }
199#endif
200
201 // accummulate the rewards in an array
202 // we need this in order to take the dot product
203 // with the discounts
204 std::vector<real_t> rewards;
205 rewards.reserve(trajectory_size);
206
207 auto time_step_itr = trajectory.begin();
208 for (; time_step_itr != trajectory.end(); ++time_step_itr)
209 {
210 auto time_step = *time_step_itr;
211 rewards.push_back(time_step.reward());
212 }
213
214 // compute the discounts for the generated trajectory
215 auto discounts = discount_generator_(trajectory, config_.max_steps);
216
217 // calculate learning rate
218 auto alpha = decay_lr_schedule_(config_.init_alpha, episode_idx);
219
220 std::vector<bool> visited(env.n_states(), false);
221 time_step_itr = trajectory.begin();
222 for (uint_t count = 0; time_step_itr != trajectory.end(); ++time_step_itr, ++count)
223 {
224
225 auto time_step = *time_step_itr;
226
227 if (visited[time_step.observation()])
228 continue;
229
230 visited[time_step.observation()] = true;
231
232 // find the steps from the current time_step to the end
233 // of the trajectory
234 auto n_steps = std::distance(time_step_itr, trajectory.end());
235
236 // calculate the return. First extract up to n_steps
237 // from the discounts
238 auto trajectory_discounts = bitrl::maths::extract_subvector(discounts, n_steps);
239 auto trajectory_rewards = bitrl::maths::extract_subvector(rewards, count, false);
240 auto G = bitrl::maths::dot_product(trajectory_discounts, trajectory_rewards);
241 auto mc_error = G - v_[time_step.observation()];
242
243 // update the state value
244 v_[time_step.observation()] += alpha * mc_error;
245 }
246
247 auto end = std::chrono::steady_clock::now();
248 std::chrono::duration<real_t> elapsed_seconds = end - start;
249 auto episode_info = EpisodeInfo();
250 episode_info.episode_index = episode_idx;
251 episode_info.total_time = elapsed_seconds;
252 episode_info.episode_iterations = std::distance(trajectory.begin(), trajectory.end());
253 return episode_info;
254}
255
256template <typename EnvType, typename TrajectoryGenerator, typename DecayLRSchedule,
257 typename DiscountGenerator>
259 const std::string &filename) const
260{
261
262 bitsim::utils::io::CSVWriter file_writer(filename, ',');
263 file_writer.open();
264 file_writer.write_column_names({"state_index", "value_function"});
265
266 for (uint_t s = 0; s < static_cast<uint_t>(v_.size()); ++s)
267 {
268 auto row = std::make_tuple(s, v_[s]);
269 file_writer.write_row(row);
270 }
271}
272
273} // namespace rl::algos::mc
274} // namespace bitrl
275#endif // FIRST_VISIT_MC_H
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_WARN
Definition bitrl_log.h:37
Definition first_visit_mc.h:47
void actions_before_episode_begins(env_type &, uint_t)
actions_before_training_episode
Definition first_visit_mc.h:99
TrajectoryGenerator trajectory_generator_type
Definition first_visit_mc.h:58
DecayLRSchedule decay_lr_schedule_type
Definition first_visit_mc.h:63
void actions_before_training_begins(env_type &env)
actions_before_training_begins. Execute any actions the algorithm needs before starting the iteration...
Definition first_visit_mc.h:171
void actions_after_episode_ends(env_type &, uint_t, const EpisodeInfo &)
actions_after_training_episode
Definition first_visit_mc.h:104
void save(const std::string &filename) const
save the results
Definition first_visit_mc.h:258
env_type::time_step_type time_step_type
The time step type used by the environment.
Definition first_visit_mc.h:74
DynVec< real_t > value_function() const
The value of every state, as the solver has it now.
Definition first_visit_mc.h:123
void actions_after_training_ends(env_type &)
actions_after_training_ends. Actions to execute after the training iterations have finisehd
Definition first_visit_mc.h:94
DiscountGenerator discount_generator_type
Definition first_visit_mc.h:68
FirstVisitMCSolver(FirstVisitMCSolverConfig solver_config, TrajectoryGenerator &trajectory_gen, DecayLRSchedule &decay_lr_schedule, discount_generator_type &discount_generator)
Constructor.
Definition first_visit_mc.h:160
EpisodeInfo on_training_episode(env_type &env, uint_t episode_idx)
on_episode Do one on_episode of the algorithm
Definition first_visit_mc.h:181
EnvType env_type
The environment type.
Definition first_visit_mc.h:53
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
void write_row(const std::vector< T > &vals)
Write a row of the file.
Definition csv_file_writer.h:89
void write_column_names(const std::vector< std::string > &col_names, bool write_header=true)
Write the column names.
Definition csv_file_writer.cpp:16
virtual void open() override
Open the file for writing.
Definition file_writer_base.cpp:21
std::iterator_traits< IteratorType >::value_type dot_product(IteratorType bv1, IteratorType ev1, IteratorType bv2, IteratorType ev2)
Definition vector_math.h:577
std::vector< T > extract_subvector(const std::vector< T > &vec, uint_t end, bool up_to=true)
Definition vector_math.h:447
Definition first_visit_mc.h:27
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
const std::string INVALID_STR
Invalid string.
Definition bitsim_consts.h:21
Definition line_segment_link.h:11
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
The EpisodeInfo struct.
Definition episode_info.h:21
real_t alpha_decay_ratio
Definition first_visit_mc.h:35
uint_t n_episodes
Definition first_visit_mc.h:37
real_t min_alpha
Definition first_visit_mc.h:34
uint_t max_steps
Definition first_visit_mc.h:36
real_t init_alpha
Definition first_visit_mc.h:33
real_t gamma
Definition first_visit_mc.h:31
std::string save_path
Definition first_visit_mc.h:38
real_t tolerance
Definition first_visit_mc.h:32