hope_agents 0.3.6

HOPE Agents: Hierarchical Optimizing Policy Engine for AIngle AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Value function approximation for HOPE Agents.
//!
//! Provides different methods for approximating state-value functions (V-functions),
//! which estimate how good it is for an agent to be in a given state.
//!
//! - **Tabular:** A simple lookup table, mapping each state to a value.
//! - **Linear:** A linear combination of features extracted from a state.
//!
//! These are typically used in value-based reinforcement learning algorithms.

use crate::learning::engine::StateId;
use crate::observation::Observation;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A trait for state-value function approximators.
pub trait ValueFunction {
    /// Evaluates the estimated value of a given state.
    fn evaluate(&self, state: &StateId) -> f64;

    /// Updates the value function for a state based on a target value and learning rate.
    fn update(&mut self, state: &StateId, target: f64, learning_rate: f64);

    /// Resets the value function to its initial state.
    fn reset(&mut self);

    /// Returns the number of states or features tracked by the function.
    fn size(&self) -> usize;
}

/// A simple tabular value function that uses a `HashMap` as a lookup table.
///
/// This is suitable for environments with a small, discrete number of states.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabularValueFunction {
    /// A map from a `StateId` to its estimated value.
    values: HashMap<StateId, f64>,
    /// The default value to return for states not yet present in the table.
    default_value: f64,
}

impl TabularValueFunction {
    /// Creates a new `TabularValueFunction` with a specified default value.
    pub fn new(default_value: f64) -> Self {
        Self {
            values: HashMap::new(),
            default_value,
        }
    }

    /// Returns a reference to the internal map of all state values.
    pub fn get_all_values(&self) -> &HashMap<StateId, f64> {
        &self.values
    }

    /// Directly sets the value for a specific state.
    pub fn set_value(&mut self, state: &StateId, value: f64) {
        self.values.insert(state.clone(), value);
    }
}

impl Default for TabularValueFunction {
    fn default() -> Self {
        Self::new(0.0)
    }
}

impl ValueFunction for TabularValueFunction {
    fn evaluate(&self, state: &StateId) -> f64 {
        self.values
            .get(state)
            .copied()
            .unwrap_or(self.default_value)
    }

    fn update(&mut self, state: &StateId, target: f64, learning_rate: f64) {
        let current = self.evaluate(state);
        let new_value = current + learning_rate * (target - current);
        self.values.insert(state.clone(), new_value);
    }

    fn reset(&mut self) {
        self.values.clear();
    }

    fn size(&self) -> usize {
        self.values.len()
    }
}

/// A function that extracts a feature vector (`Vec<f64>`) from an `Observation`.
pub type FeatureExtractor = Box<dyn Fn(&Observation) -> Vec<f64> + Send + Sync>;

/// A value function approximator that uses a linear combination of features.
///
/// The value of a state `s` is calculated as `V(s) = w · φ(s)`, where `w` is a weight
/// vector and `φ(s)` is a feature vector extracted from the state.
/// This is useful for environments with large or continuous state spaces.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinearValueFunction {
    /// The vector of weights for the linear function.
    weights: Vec<f64>,
    /// The number of features expected in the feature vector.
    num_features: usize,
    /// The default value to return if features cannot be evaluated.
    default_value: f64,
    /// A count of updates performed for each feature, for statistical purposes.
    #[serde(skip)]
    update_counts: Vec<u64>,
}

impl LinearValueFunction {
    /// Creates a new `LinearValueFunction` with a specified number of features.
    pub fn new(num_features: usize, default_value: f64) -> Self {
        Self {
            weights: vec![0.0; num_features],
            num_features,
            default_value,
            update_counts: vec![0; num_features],
        }
    }

    /// Creates a new `LinearValueFunction` with a predefined set of initial weights.
    pub fn with_weights(weights: Vec<f64>) -> Self {
        let num_features = weights.len();
        Self {
            weights,
            num_features,
            default_value: 0.0,
            update_counts: vec![0; num_features],
        }
    }

    /// Evaluates the value of a state given its feature vector.
    /// This is the dot product of the weights and the features.
    pub fn evaluate_features(&self, features: &[f64]) -> f64 {
        if features.len() != self.num_features {
            return self.default_value;
        }

        // Dot product of weights and features
        self.weights
            .iter()
            .zip(features.iter())
            .map(|(w, f)| w * f)
            .sum()
    }

    /// Updates the weights using gradient descent.
    /// The update rule is: `w = w + α * error * features`.
    pub fn update_features(&mut self, features: &[f64], target: f64, learning_rate: f64) {
        if features.len() != self.num_features {
            return;
        }

        let prediction = self.evaluate_features(features);
        let error = target - prediction;

        // Gradient descent update
        for (i, &feature) in features.iter().enumerate() {
            self.weights[i] += learning_rate * error * feature;
            self.update_counts[i] += 1;
        }
    }

    /// Returns a slice of the current weights.
    pub fn get_weights(&self) -> &[f64] {
        &self.weights
    }

    /// Returns a slice of the update counts for each feature.
    pub fn get_update_counts(&self) -> &[u64] {
        &self.update_counts
    }

    /// Returns the number of features the function is configured for.
    pub fn num_features(&self) -> usize {
        self.num_features
    }
}

impl Default for LinearValueFunction {
    fn default() -> Self {
        Self::new(10, 0.0)
    }
}

impl ValueFunction for LinearValueFunction {
    fn evaluate(&self, _state: &StateId) -> f64 {
        // Linear value function needs features, which we don't have from StateId alone.
        // Users should call `evaluate_features` directly with a feature vector.
        self.default_value
    }

    fn update(&mut self, _state: &StateId, _target: f64, _learning_rate: f64) {
        // This method is here to satisfy the trait but is a no-op.
        // Users should call `update_features` directly.
    }

    fn reset(&mut self) {
        self.weights.fill(0.0);
        self.update_counts.fill(0);
    }

    fn size(&self) -> usize {
        self.num_features
    }
}

/// A collection of simple, common feature extractor functions.
pub mod feature_extractors {
    use super::*;

    /// Extracts the numeric value from an observation as a single feature.
    pub fn numeric_value(obs: &Observation) -> Vec<f64> {
        vec![obs.value.as_f64().unwrap_or(0.0)]
    }

    /// Extracts the numeric value and confidence score as two features.
    pub fn value_and_confidence(obs: &Observation) -> Vec<f64> {
        vec![
            obs.value.as_f64().unwrap_or(0.0),
            obs.confidence.value() as f64,
        ]
    }

    /// Extracts the numeric value, confidence, and age as three features.
    pub fn value_confidence_age(obs: &Observation) -> Vec<f64> {
        vec![
            obs.value.as_f64().unwrap_or(0.0),
            obs.confidence.value() as f64,
            obs.age_secs() as f64,
        ]
    }

    /// Creates polynomial features (1, x, x^2, x^3) for a numeric observation value.
    /// Useful for approximating non-linear functions.
    pub fn polynomial_features(obs: &Observation) -> Vec<f64> {
        let x = obs.value.as_f64().unwrap_or(0.0);
        vec![1.0, x, x * x, x * x * x]
    }

    /// Creates a feature extractor that normalizes a numeric value to a [0, 1] range.
    pub fn normalized_value(min: f64, max: f64) -> impl Fn(&Observation) -> Vec<f64> {
        move |obs: &Observation| {
            let value = obs.value.as_f64().unwrap_or(0.0);
            let normalized = if max > min {
                ((value - min) / (max - min)).clamp(0.0, 1.0)
            } else {
                0.0
            };
            vec![normalized]
        }
    }

    /// Creates a feature extractor that returns a binary feature (1.0 or 0.0)
    /// based on whether a value is above a threshold.
    pub fn threshold_feature(threshold: f64) -> impl Fn(&Observation) -> Vec<f64> {
        move |obs: &Observation| {
            let value = obs.value.as_f64().unwrap_or(0.0);
            vec![if value > threshold { 1.0 } else { 0.0 }]
        }
    }

    /// Creates a feature extractor that generates a vector of binary features,
    /// one for each provided threshold.
    pub fn multi_threshold_features(thresholds: Vec<f64>) -> impl Fn(&Observation) -> Vec<f64> {
        move |obs: &Observation| {
            let value = obs.value.as_f64().unwrap_or(0.0);
            thresholds
                .iter()
                .map(|&t| if value > t { 1.0 } else { 0.0 })
                .collect()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::observation::Observation;

    fn create_state_id(name: &str) -> StateId {
        StateId::from_string(name.to_string())
    }

    #[test]
    fn test_tabular_value_function() {
        let mut vf = TabularValueFunction::new(0.0);

        let state = create_state_id("state1");

        // Initial value should be default
        assert_eq!(vf.evaluate(&state), 0.0);

        // Update value
        vf.update(&state, 1.0, 0.1);
        assert!(vf.evaluate(&state) > 0.0);

        // Multiple updates
        vf.update(&state, 1.0, 0.1);
        assert!(vf.evaluate(&state) > 0.0);

        assert_eq!(vf.size(), 1);
    }

    #[test]
    fn test_tabular_value_function_reset() {
        let mut vf = TabularValueFunction::new(0.0);
        let state = create_state_id("state1");

        vf.update(&state, 1.0, 0.1);
        assert!(vf.size() > 0);

        vf.reset();
        assert_eq!(vf.size(), 0);
        assert_eq!(vf.evaluate(&state), 0.0);
    }

    #[test]
    fn test_linear_value_function() {
        let mut vf = LinearValueFunction::new(3, 0.0);

        let features = vec![1.0, 2.0, 3.0];

        // Initial evaluation should be 0
        assert_eq!(vf.evaluate_features(&features), 0.0);

        // Update
        vf.update_features(&features, 10.0, 0.1);

        // Value should change
        let value = vf.evaluate_features(&features);
        assert!(value > 0.0);

        assert_eq!(vf.num_features(), 3);
    }

    #[test]
    fn test_linear_value_function_with_weights() {
        let weights = vec![1.0, 2.0, 3.0];
        let vf = LinearValueFunction::with_weights(weights);

        let features = vec![1.0, 1.0, 1.0];
        // Should be 1*1 + 2*1 + 3*1 = 6
        assert_eq!(vf.evaluate_features(&features), 6.0);
    }

    #[test]
    fn test_feature_extractor_numeric() {
        let obs = Observation::sensor("temp", 25.5);
        let features = feature_extractors::numeric_value(&obs);

        assert_eq!(features.len(), 1);
        assert_eq!(features[0], 25.5);
    }

    #[test]
    fn test_feature_extractor_value_confidence() {
        let obs = Observation::sensor("temp", 25.0).with_confidence(0.9);
        let features = feature_extractors::value_and_confidence(&obs);

        assert_eq!(features.len(), 2);
        assert_eq!(features[0], 25.0);
        // Use approximate comparison for floating point
        assert!((features[1] - 0.9).abs() < 0.001);
    }

    #[test]
    fn test_feature_extractor_polynomial() {
        let obs = Observation::sensor("temp", 2.0);
        let features = feature_extractors::polynomial_features(&obs);

        assert_eq!(features.len(), 4);
        assert_eq!(features[0], 1.0); // constant
        assert_eq!(features[1], 2.0); // x
        assert_eq!(features[2], 4.0); // x^2
        assert_eq!(features[3], 8.0); // x^3
    }

    #[test]
    fn test_feature_extractor_normalized() {
        let extractor = feature_extractors::normalized_value(0.0, 100.0);
        let obs = Observation::sensor("temp", 50.0);
        let features = extractor(&obs);

        assert_eq!(features.len(), 1);
        assert_eq!(features[0], 0.5);
    }

    #[test]
    fn test_feature_extractor_threshold() {
        let extractor = feature_extractors::threshold_feature(30.0);

        let obs_low = Observation::sensor("temp", 20.0);
        let features_low = extractor(&obs_low);
        assert_eq!(features_low[0], 0.0);

        let obs_high = Observation::sensor("temp", 40.0);
        let features_high = extractor(&obs_high);
        assert_eq!(features_high[0], 1.0);
    }

    #[test]
    fn test_feature_extractor_multi_threshold() {
        let extractor = feature_extractors::multi_threshold_features(vec![20.0, 30.0, 40.0]);
        let obs = Observation::sensor("temp", 35.0);
        let features = extractor(&obs);

        assert_eq!(features.len(), 3);
        assert_eq!(features[0], 1.0); // > 20
        assert_eq!(features[1], 1.0); // > 30
        assert_eq!(features[2], 0.0); // < 40
    }
}