diff --git a/src/lib.rs b/src/lib.rs index 0bc2496..ea36425 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,2 @@ pub mod mankalla; -pub mod rl; +pub mod q_learning; diff --git a/src/mankalla.rs b/src/mankalla.rs index 1ad9b7c..9d067de 100644 --- a/src/mankalla.rs +++ b/src/mankalla.rs @@ -1,8 +1,9 @@ -use crate::rl::Environment; +use crate::q_learning::Environment; use std::fmt::Display; pub struct MankallaGame; +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct MankallaGameState { // 13 12 11 10 9 8 7 // 0 1 2 3 4 5 6 @@ -10,7 +11,7 @@ pub struct MankallaGameState { player_to_move: Player, } -#[derive(PartialEq)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum Player { Player1, Player2, @@ -19,7 +20,10 @@ pub enum Player { impl Environment for MankallaGame { type State = MankallaGameState; type Action = u8; - type Reward = i8; + + fn new() -> MankallaGameState { + Default::default() + } fn actions(state: &Self::State) -> Vec { let start = match state.player_to_move { @@ -35,18 +39,20 @@ impl Environment for MankallaGame { .collect() } - fn step(mut state: Self::State, action: Self::Action) -> (Option, Self::Reward) { + fn step(state: &Self::State, action: &Self::Action) -> (Option, f32) { + let mut state = state.clone(); + let p1_points = state.get_points(&Player::Player1); let p2_points = state.get_points(&Player::Player2); let mut i: usize = match state.player_to_move { Player::Player1 => { - assert!(action < 6); - action as usize + assert!(*action < 6); + *action as usize } Player::Player2 => { - assert!(action < 6); - (action + 7) as usize + assert!(*action < 6); + (*action + 7) as usize } }; @@ -62,10 +68,10 @@ impl Environment for MankallaGame { let finished = state.handle_if_game_finished(); - let mut reward = (state.get_points(&Player::Player1) - p1_points) as i8 - - (state.get_points(&Player::Player2) - p2_points) as i8; + let mut reward = (state.get_points(&Player::Player1) - p1_points) as f32 + - (state.get_points(&Player::Player2) - p2_points) as f32; if state.player_to_move == Player::Player2 { - reward *= -1; + reward *= -1f32; } if finished { @@ -110,12 +116,6 @@ impl Default for MankallaGameState { } } -impl MankallaGame { - pub fn new() -> MankallaGameState { - Default::default() - } -} - impl MankallaGameState { fn get_points(&self, player: &Player) -> u8 { match player { diff --git a/src/q_learning.rs b/src/q_learning.rs new file mode 100644 index 0000000..e654c25 --- /dev/null +++ b/src/q_learning.rs @@ -0,0 +1,117 @@ +use std::collections::HashMap; +use std::hash::Hash; + +pub trait Environment { + type State: Copy + Eq + Hash; + type Action: Copy + Eq + Hash; + fn actions(state: &Self::State) -> Vec; + fn step(state: &Self::State, action: &Self::Action) -> (Option, f32); + fn new() -> Self::State; +} + +pub trait Policy { + fn choose_action(&self, state: &E::State) -> E::Action; + fn improve( + &mut self, + state: &E::State, + action: E::Action, + reward: f32, + next_state: Option<&E::State>, + ); +} + +pub struct QLearning; + +impl QLearning { + pub fn train( + policy: &mut impl Policy, + num_training_episodes: usize, + max_steps: Option, + ) { + for _ in 0..num_training_episodes { + let mut state = E::new(); + + if let Some(m) = max_steps { + for _ in 0..m { + if let Some(next_state) = QLearning::one_iteration(policy, state) { + state = next_state; + } else { + break; + } + } + } else { + loop { + if let Some(next_state) = QLearning::one_iteration(policy, state) { + state = next_state; + } else { + break; + } + } + } + } + } + + fn one_iteration( + policy: &mut impl Policy, + state: E::State, + ) -> Option { + let action = policy.choose_action(&state); + + let (next_state, reward) = E::step(&state, &action); + policy.improve(&state, action, reward, next_state.as_ref()); + next_state + } +} + +pub struct GreedyPolicy { + qtable: HashMap<(E::State, E::Action), f32>, + learning_rate: f32, + gamma: f32, +} + +impl Policy for GreedyPolicy { + fn choose_action(&self, state: &::State) -> ::Action { + let actions = E::actions(state); + *actions.iter() + .max_by(|&a, &b| + self.qtable.get(&(*state, *a)) + .unwrap_or(&0f32) + .total_cmp(self.qtable.get(&(*state, *b)) + .unwrap_or(&0f32)) + ) + .expect( + "The way it is implemented now, there should always be possible actions (might be bad)", + ) + } + fn improve( + &mut self, + state: &::State, + action: ::Action, + reward: f32, + next_state: Option<&::State>, + ) { + let former_value = *self.qtable.get(&(*state, action)).unwrap_or(&0f32); + let target = match next_state { + Some(next_state) => { + reward + + self.gamma + * self + .qtable + .get(&(*next_state, self.choose_action(&next_state))) + .unwrap_or(&0f32) + } + None => 0f32, + }; + self.qtable.insert( + (*state, action), + former_value + self.learning_rate * (target - former_value), + ); + } +} + +pub struct EpsilonGreedyPolicy { + qtable: HashMap<(E::State, E::Action), f32>, + learning_rate: f32, + gamma: f32, + epsilon: f32, +} diff --git a/src/rl.rs b/src/rl.rs deleted file mode 100644 index 5997823..0000000 --- a/src/rl.rs +++ /dev/null @@ -1,37 +0,0 @@ -use std::collections::HashMap; - -pub trait Environment { - type State; - type Action; - type Reward; - fn actions(state: &Self::State) -> Vec; - fn step(state: Self::State, action: Self::Action) -> (Option, Self::Reward); -} - -pub trait ToSaveState: Environment { - type SaveState; - fn to_save_state(state: Self::State) -> Self::SaveState; -} - -trait Policy { - type ActionEvaluator; - fn choose_action(action_evaluator: Self::ActionEvaluator, state: E::State) -> E::Action; - fn train( - action_evaluator: Self::ActionEvaluator, - num_training_episodes: usize, - max_steps: usize, - ) -> Self::ActionEvaluator; -} - -trait SavePolicy: Policy { - fn save_policy(policy: Self::ActionEvaluator); -} - -enum PolicyKind { - Greedy, - EpsilonGreedy, -} - -struct QLearning { - qtable: HashMap, -}