bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
expected_sarsa.h
Go to the documentation of this file.
1#ifndef EXPECTED_SARSA_H
2#define EXPECTED_SARSA_H
3
12
13#include <chrono>
14#include <concepts>
15#include <string>
16#include <vector>
17
18namespace bitrl
19{
20namespace rl::algos::td
21{
22
59
65template <typename PolicyType>
66concept epsilon_greedy_policy_concept = requires(PolicyType policy, const PolicyType cpolicy,
67 const DynMat<real_t> &q, uint_t state)
68{
69 {
70 policy(q, state)
71 } -> std::convertible_to<uint_t>;
72 {
73 cpolicy.eps_value()
74 } -> std::convertible_to<real_t>;
75 policy.on_episode(state);
76};
77
93template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
94class ExpectedSarsaSolver final : public TDAlgoBase<EnvType>
95{
96 public:
100 typedef PolicyType policy_type;
101
105 ExpectedSarsaSolver(const ExpectedSarsaConfig &config, const PolicyType &policy);
106
111
116
117 virtual void actions_before_episode_begins(env_type &, uint_t /*episode_idx*/) {}
118
122 virtual void actions_after_episode_ends(env_type &, uint_t episode_idx,
123 const EpisodeInfo & /*einfo*/)
124 {
125 policy_.on_episode(episode_idx);
126 }
127
131 virtual EpisodeInfo on_training_episode(env_type &, uint_t episode_idx);
132
136 void save(const std::string &filename) const;
137
142
146 const DynMat<real_t> &q_table() const noexcept { return q_table_; }
147
152 real_t expected_value(const state_type &state) const;
153
154 private:
155 ExpectedSarsaConfig config_;
156 policy_type policy_;
157 DynMat<real_t> q_table_;
158};
159
160template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
162 const PolicyType &policy)
163 : TDAlgoBase<EnvType>(), config_(config), policy_(policy)
164{
165}
166
167template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
169{
170 q_table_ = DynMat<real_t>::Zero(env.n_states(), env.n_actions());
171}
172
173template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
175{
176 if (config_.path != bitsim::consts::INVALID_STR)
177 {
178 save(config_.path);
179 }
180}
181
182template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
184{
185 const DynVec<real_t> values = maths::get_row(q_table_, state);
186 const auto n_actions = static_cast<real_t>(values.size());
187 const real_t eps = policy_.eps_value();
188
189 // the greedy action, picked the way the policy picks it
190 const auto greedy = bitrl::rl::policies::MaxTabularPolicy::get_action(values);
191 return eps * values.sum() / n_actions + (1.0 - eps) * values[greedy];
192}
193
194template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
196 uint_t episode_idx)
197{
198 auto start = std::chrono::steady_clock::now();
199 EpisodeInfo info;
200
201 auto episode_score = 0.0;
202 auto state = env.reset().observation();
203
204 uint_t itr = 0;
205 for (; itr < config_.max_num_iterations_per_episode; ++itr)
206 {
207 const auto action = policy_(q_table_, state);
208 auto time_step = env.step(action);
209 const auto next_state = time_step.observation();
210 const auto reward = time_step.reward();
211 const auto done = time_step.done();
212 episode_score += reward;
213
214 // nothing follows the step that ends the episode
215 const auto target = done ? reward : reward + config_.gamma * expected_value(next_state);
216 q_table_(state, action) += config_.eta * (target - q_table_(state, action));
217
218 if (done)
219 {
220 break;
221 }
222 state = next_state;
223 }
224
225 auto end = std::chrono::steady_clock::now();
226 std::chrono::duration<real_t> elapsed_seconds = end - start;
227
228 info.episode_index = episode_idx;
229 info.episode_reward = episode_score;
230 info.episode_iterations = itr;
231 info.total_time = elapsed_seconds;
232 return info;
233}
234
235template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
236void ExpectedSarsaSolver<EnvType, PolicyType>::save(const std::string &filename) const
237{
238 bitsim::utils::io::CSVWriter file_writer(filename, ',');
239 file_writer.open();
240
241 std::vector<std::string> col_names(1 + q_table_.cols());
242 col_names[0] = "state_index";
243 for (uint_t i = 0; i < static_cast<uint_t>(q_table_.cols()); ++i)
244 {
245 col_names[i + 1] = "action_" + std::to_string(i);
246 }
247 file_writer.write_column_names(col_names);
248
249 // a tuple with a DynVec in it would write the values in one column, so
250 // every row is a vector of numbers
251 std::vector<real_t> row(1 + q_table_.cols());
252 for (uint_t s = 0; s < static_cast<uint_t>(q_table_.rows()); ++s)
253 {
254 row[0] = static_cast<real_t>(s);
255 for (uint_t a = 0; a < static_cast<uint_t>(q_table_.cols()); ++a)
256 {
257 row[1 + a] = q_table_(s, a);
258 }
259 file_writer.write_row(row);
260 }
261}
262
263template <envs::discrete_world_concept EnvType, epsilon_greedy_policy_concept PolicyType>
271
272} // namespace rl::algos::td
273} // namespace bitrl
274
275#endif // EXPECTED_SARSA_H
virtual void actions_after_episode_ends(env_type &, uint_t episode_idx, const EpisodeInfo &)
Lets the policy adjust itself, for example decay its epsilon.
Definition expected_sarsa.h:122
PolicyType policy_type
Definition expected_sarsa.h:100
TDAlgoBase< EnvType >::env_type env_type
Definition expected_sarsa.h:97
void save(const std::string &filename) const
Writes the table to a CSV file, one row per state.
Definition expected_sarsa.h:236
const DynMat< real_t > & q_table() const noexcept
The value of every state and action.
Definition expected_sarsa.h:146
ExpectedSarsaSolver(const ExpectedSarsaConfig &config, const PolicyType &policy)
Constructor.
Definition expected_sarsa.h:161
virtual void actions_before_episode_begins(env_type &, uint_t)
actions_before_training_episode
Definition expected_sarsa.h:117
virtual EpisodeInfo on_training_episode(env_type &, uint_t episode_idx)
Plays one episode and updates the table after every step.
Definition expected_sarsa.h:195
virtual void actions_after_training_ends(env_type &)
Saves the table if the configuration gives a path.
Definition expected_sarsa.h:174
TDAlgoBase< EnvType >::state_type state_type
Definition expected_sarsa.h:99
real_t expected_value(const state_type &state) const
The value the policy expects at the given state: every action weighed with the probability the policy...
Definition expected_sarsa.h:183
bitrl::rl::policies::MaxTabularPolicy build_policy() const
The greedy policy of the table.
Definition expected_sarsa.h:264
TDAlgoBase< EnvType >::action_type action_type
Definition expected_sarsa.h:98
virtual void actions_before_training_begins(env_type &)
Sets every entry of the table to zero.
Definition expected_sarsa.h:168
env_type::action_type action_type
action_t
Definition td_algo_base.h:27
env_type::state_type state_type
state_t
Definition td_algo_base.h:32
EnvType env_type
env_t
Definition td_algo_base.h:22
TDAlgoBase()=default
DPAlgoBase.
class MaxTabularPolicy
Definition max_tabular_policy.h:33
static output_type get_action(const MatType &q_map, uint_t state_idx)
get_action. Given a
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
What ExpectedSarsaSolver needs from its policy: it picks an action from the table and a state,...
Definition expected_sarsa.h:66
DynVec< T > get_row(const DynMat< T > &matrix, uint_t row_idx)
Extract the cidx-th column from the matrix.
Definition matrix_utilities.h:132
Definition double_q_learning.h:26
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
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
Eigen::MatrixX< T > DynMat
Dynamically sized matrix to use around the library.
Definition bitsim_types.h:51
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
The configuration of ExpectedSarsaSolver.
Definition expected_sarsa.h:27
std::string path
Where to save the table when training ends; nothing is saved if it is not set.
Definition expected_sarsa.h:57
uint_t max_num_iterations_per_episode
The most steps an episode can take.
Definition expected_sarsa.h:51
real_t eta
The learning rate.
Definition expected_sarsa.h:46
uint_t n_episodes
Not used; the trainer decides how many episodes to run.
Definition expected_sarsa.h:31
real_t tolerance
Not used; the trainer decides when training stops.
Definition expected_sarsa.h:36
real_t gamma
The discount factor.
Definition expected_sarsa.h:41
Definition max_tabular_policy.h:131
void build_from_state_action_function(const DynMat< real_t > &q, MaxTabularPolicy &policy)