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
use approximators::*;
use core::*;
use geometry::{Card, Space, Matrix};
use std::{collections::HashMap, marker::PhantomData};

/// Linear function approximator.
#[derive(Clone, Serialize, Deserialize)]
pub struct LFA<I: ?Sized, P: Projector<I>, A: Approximator<Projection>> {
    pub projector: P,
    pub approximator: A,

    phantom: PhantomData<I>,
}

impl<I: ?Sized, P: Projector<I>, A: Approximator<Projection>> LFA<I, P, A> {
    pub fn new(projector: P, approximator: A) -> Self {
        LFA {
            projector: projector,
            approximator: approximator,

            phantom: PhantomData,
        }
    }
}

impl<I: ?Sized, P: Projector<I>> LFA<I, P, ScalarFunction> {
    pub fn scalar_valued(projector: P) -> Self {
        let approximator = ScalarFunction::new(projector.dim());

        Self::new(projector, approximator)
    }
}

impl<I: ?Sized, P: Projector<I>> LFA<I, P, VectorFunction> {
    pub fn vector_valued(projector: P, n_outputs: usize) -> Self {
        let approximator = VectorFunction::new(projector.dim(), n_outputs);

        Self::new(projector, approximator)
    }
}

impl<I, P: Projector<I>, A: Approximator<Projection>> Space for LFA<I, P, A> {
    type Value = Projection;

    fn dim(&self) -> usize {
        self.projector.dim()
    }

    fn card(&self) -> Card {
        self.projector.card()
    }
}

impl<I, P, A> Projector<I> for LFA<I, P, A>
where
    P: Projector<I>,
    A: Approximator<Projection>,
{
    fn project(&self, input: &I) -> Projection {
        self.projector.project(input)
    }
}

impl<I, P, A> Approximator<I> for LFA<I, P, A>
where
    I: ?Sized,
    P: Projector<I>,
    A: Approximator<Projection>,
{
    type Value = A::Value;

    fn evaluate(&self, input: &I) -> EvaluationResult<Self::Value> {
        let primal = self.projector.project(input);

        self.approximator.evaluate(&primal)
    }

    fn update(&mut self, input: &I, update: Self::Value) -> UpdateResult<()> {
        let primal = self.projector.project(input);

        self.approximator.update(&primal, update)
    }

    fn adapt(&mut self, new_features: &HashMap<IndexT, IndexSet>) -> AdaptResult<usize> {
        self.approximator.adapt(new_features)
    }
}

impl<I, P, A> Parameterised for LFA<I, P, A>
where
    I: ?Sized,
    P: Projector<I>,
    A: Approximator<Projection> + Parameterised,
{
    fn weights(&self) -> Matrix<f64> { self.approximator.weights() }
}