dora_ssr/dora/q_learner.rs
1/* Copyright (c) 2016-2025 Li Jin <dragon-fly@qq.com>
2
3Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
5The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
7THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
8
9extern "C" {
10 fn qlearner_type() -> i32;
11 fn mlqlearner_update(slf: i64, state: i64, action: i32, reward: f64);
12 fn mlqlearner_get_best_action(slf: i64, state: i64) -> i32;
13 fn mlqlearner_visit_matrix(slf: i64, func0: i32, stack0: i64);
14 fn mlqlearner_pack(hints: i64, values: i64) -> i64;
15 fn mlqlearner_unpack(hints: i64, state: i64) -> i64;
16 fn mlqlearner_new(gamma: f64, alpha: f64, max_q: f64) -> i64;
17}
18use crate::dora::IObject;
19/// A simple reinforcement learning framework that can be used to learn optimal policies for Markov decision processes using Q-learning. Q-learning is a model-free reinforcement learning algorithm that learns an optimal action-value function from experience by repeatedly updating estimates of the Q-value of state-action pairs.
20pub struct QLearner { raw: i64 }
21crate::dora_object!(QLearner);
22impl QLearner {
23 pub(crate) fn type_info() -> (i32, fn(i64) -> Option<Box<dyn IObject>>) {
24 (unsafe { qlearner_type() }, |raw: i64| -> Option<Box<dyn IObject>> {
25 match raw {
26 0 => None,
27 _ => Some(Box::new(QLearner { raw: raw }))
28 }
29 })
30 }
31 /// Updates Q-value for a state-action pair based on received reward.
32 ///
33 /// # Arguments
34 ///
35 /// * `state` - An integer representing the state.
36 /// * `action` - An integer representing the action.
37 /// * `reward` - A number representing the reward received for the action in the state.
38 pub fn update(&mut self, state: u64, action: u32, reward: f64) {
39 unsafe { mlqlearner_update(self.raw(), state as i64, action as i32, reward); }
40 }
41 /// Returns the best action for a given state based on the current Q-values.
42 ///
43 /// # Arguments
44 ///
45 /// * `state` - The current state.
46 ///
47 /// # Returns
48 ///
49 /// * `i32` - The action with the highest Q-value for the given state.
50 pub fn get_best_action(&mut self, state: u64) -> i32 {
51 unsafe { return mlqlearner_get_best_action(self.raw(), state as i64); }
52 }
53 /// Visits all state-action pairs and calls the provided handler function for each pair.
54 ///
55 /// # Arguments
56 ///
57 /// * `handler` - A function that is called for each state-action pair.
58 pub fn visit_matrix(&mut self, mut handler: Box<dyn FnMut(u64, u32, f64)>) {
59 let mut stack0 = crate::dora::CallStack::new();
60 let stack_raw0 = stack0.raw();
61 let func_id0 = crate::dora::push_function(Box::new(move || {
62 handler(stack0.pop_i64().unwrap() as u64, stack0.pop_i32().unwrap() as u32, stack0.pop_f64().unwrap())
63 }));
64 unsafe { mlqlearner_visit_matrix(self.raw(), func_id0, stack_raw0); }
65 }
66 /// Constructs a state from given hints and condition values.
67 ///
68 /// # Arguments
69 ///
70 /// * `hints` - A vector of integers representing the byte length of provided values.
71 /// * `values` - The condition values as discrete values.
72 ///
73 /// # Returns
74 ///
75 /// * `i64` - The packed state value.
76 pub fn pack(hints: &Vec<i32>, values: &Vec<i32>) -> u64 {
77 unsafe { return mlqlearner_pack(crate::dora::Vector::from_num(hints), crate::dora::Vector::from_num(values)) as u64; }
78 }
79 /// Deconstructs a state from given hints to get condition values.
80 ///
81 /// # Arguments
82 ///
83 /// * `hints` - A vector of integers representing the byte length of provided values.
84 /// * `state` - The state integer to unpack.
85 ///
86 /// # Returns
87 ///
88 /// * `Vec<i32>` - The condition values as discrete values.
89 pub fn unpack(hints: &Vec<i32>, state: u64) -> Vec<i32> {
90 unsafe { return crate::dora::Vector::to_num(mlqlearner_unpack(crate::dora::Vector::from_num(hints), state as i64)); }
91 }
92 /// Creates a new QLearner object with optional parameters for gamma, alpha, and maxQ.
93 ///
94 /// # Arguments
95 ///
96 /// * `gamma` - The discount factor for future rewards.
97 /// * `alpha` - The learning rate for updating Q-values.
98 /// * `maxQ` - The maximum Q-value. Defaults to 100.0.
99 ///
100 /// # Returns
101 ///
102 /// * `QLearner` - The newly created QLearner object.
103 pub fn new(gamma: f64, alpha: f64, max_q: f64) -> QLearner {
104 unsafe { return QLearner { raw: mlqlearner_new(gamma, alpha, max_q) }; }
105 }
106}