Skip to main content

optirs_core/schedulers/
constant.rs

1// Constant learning rate scheduler
2//
3// This module provides a simple scheduler that maintains a constant learning rate.
4// It's useful as a base for other schedulers or for testing.
5
6use scirs2_core::ndarray::ScalarOperand;
7use scirs2_core::numeric::Float;
8use std::fmt::Debug;
9
10use super::LearningRateScheduler;
11
12/// A scheduler that maintains a constant learning rate
13#[derive(Debug, Clone, Copy)]
14pub struct ConstantScheduler<A: Float + Debug + ScalarOperand> {
15    /// The constant learning rate
16    learning_rate: A,
17}
18
19impl<A: Float + Debug + ScalarOperand + Send + Sync> ConstantScheduler<A> {
20    /// Create a new constant scheduler with the given learning rate
21    ///
22    /// # Arguments
23    ///
24    /// * `learning_rate` - The constant learning rate to maintain
25    ///
26    /// # Example
27    ///
28    /// ```
29    /// use optirs_core::schedulers::{ConstantScheduler, LearningRateScheduler};
30    ///
31    /// let mut scheduler = ConstantScheduler::new(0.1);
32    /// assert_eq!(scheduler.get_learning_rate(), 0.1);
33    ///
34    /// // Learning rate stays constant after stepping
35    /// scheduler.step();
36    /// assert_eq!(scheduler.get_learning_rate(), 0.1);
37    /// ```
38    pub fn new(learningrate: A) -> Self {
39        Self {
40            learning_rate: learningrate,
41        }
42    }
43}
44
45impl<A: Float + Debug + ScalarOperand + Send + Sync> LearningRateScheduler<A>
46    for ConstantScheduler<A>
47{
48    fn get_learning_rate(&self) -> A {
49        self.learning_rate
50    }
51
52    fn step(&mut self) -> A {
53        self.learning_rate
54    }
55
56    fn reset(&mut self) {
57        // Nothing to reset for a constant scheduler
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_constant_scheduler() {
67        let mut scheduler = ConstantScheduler::new(0.1);
68        assert_eq!(scheduler.get_learning_rate(), 0.1);
69
70        // Step multiple times and check that learning rate remains constant
71        for _ in 0..10 {
72            assert_eq!(scheduler.step(), 0.1);
73        }
74
75        // Reset shouldn't change the learning rate
76        scheduler.reset();
77        assert_eq!(scheduler.get_learning_rate(), 0.1);
78    }
79}