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
use crate::approximators::Approximator;
use crate::basis::Projection;
use crate::core::*;
use crate::geometry::{norms::l1, Matrix, Vector};
use std::{collections::HashMap, mem::replace};

/// Weight-`Projection` evaluator with scalar `f64` output.
#[derive(Clone, Serialize, Deserialize)]
pub struct ScalarFunction {
    pub weights: Vector<f64>,
}

impl ScalarFunction {
    pub fn new(n_features: usize) -> Self {
        ScalarFunction {
            weights: Vector::zeros((n_features,)),
        }
    }

    fn extend_weights(&mut self, new_weights: Vec<f64>) {
        let mut weights =
            unsafe { replace(&mut self.weights, Vector::uninitialized((0,))).into_raw_vec() };

        weights.extend(new_weights);

        self.weights = Vector::from_vec(weights);
    }
}

impl Approximator<Projection> for ScalarFunction {
    type Value = f64;

    fn n_outputs(&self) -> usize { 1 }

    fn evaluate(&self, p: &Projection) -> EvaluationResult<f64> { Ok(p.dot(&self.weights)) }

    fn update(&mut self, p: &Projection, error: f64) -> UpdateResult<()> {
        Ok(match p {
            &Projection::Dense(ref activations) => {
                let scaled_error = error / l1(activations.as_slice().unwrap());

                self.weights.scaled_add(scaled_error, activations)
            },
            &Projection::Sparse(ref indices) => {
                let scaled_error = error / indices.len() as f64;

                for idx in indices {
                    self.weights[*idx] += scaled_error;
                }
            },
        })
    }

    fn adapt(&mut self, new_features: &HashMap<IndexT, IndexSet>) -> AdaptResult<usize> {
        let n_nfs = new_features.len();
        let max_index = self.weights.len() + n_nfs - 1;

        let new_weights: Result<Vec<f64>, _> = new_features
            .into_iter()
            .map(|(&i, idx)| {
                if i > max_index {
                    Err(AdaptError::Failed)
                } else {
                    Ok(idx.iter().fold(0.0, |acc, j| acc + self.weights[*j]) / (idx.len() as f64))
                }
            })
            .collect();

        self.extend_weights(new_weights?);

        Ok(n_nfs)
    }
}

impl Parameterised for ScalarFunction {
    fn weights(&self) -> Matrix<f64> {
        let n_rows = self.weights.len();

        self.weights.clone().into_shape((n_rows, 1)).unwrap()
    }
}

#[cfg(test)]
mod tests {
    extern crate seahash;

    use crate::approximators::{Approximator, ScalarFunction};
    use crate::basis::fixed::{Fourier, TileCoding};
    use crate::LFA;
    use std::{
        collections::{BTreeSet, HashMap},
        hash::BuildHasherDefault,
    };

    type SHBuilder = BuildHasherDefault<seahash::SeaHasher>;

    #[test]
    fn test_sparse_update_eval() {
        let p = TileCoding::new(SHBuilder::default(), 4, 100);
        let mut f = LFA::scalar_output(p);
        let input = vec![5.0];

        let _ = f.update(&input, 50.0);
        let out = f.evaluate(&input).unwrap();

        assert!((out - 50.0).abs() < 1e-6);
    }

    #[test]
    fn test_dense_update_eval() {
        let p = Fourier::new(3, vec![(0.0, 10.0)]);
        let mut f = LFA::scalar_output(p);

        let input = vec![5.0];

        let _ = f.update(input.as_slice(), 50.0);
        let out = f.evaluate(input.as_slice()).unwrap();

        assert!((out - 50.0).abs() < 1e-6);
    }

    #[test]
    fn test_adapt() {
        let mut f = ScalarFunction::new(100);

        let mut new_features = HashMap::new();
        new_features.insert(100, {
            let mut idx = BTreeSet::new();

            idx.insert(10);
            idx.insert(90);

            idx
        });

        match f.adapt(&new_features) {
            Ok(n) => {
                assert_eq!(n, 1);
                assert_eq!(f.weights.len(), 101);
                assert_eq!(f.weights[100], f.weights[10] / 2.0 + f.weights[90] / 2.0);
            },
            Err(err) => panic!("ScalarFunction::adapt failed with AdaptError::{:?}", err),
        }
    }
}