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
//! Principal Component Analysis Module
//!
//! Contains implementation of PCA.
//!
//! # Examples
//!
//! ```
//! use rusty_machine::learning::pca::PCA;
//! use rusty_machine::learning::UnSupModel;
//!
//! use rusty_machine::linalg::Matrix;
//! let mut pca = PCA::default();
//!
//! let inputs = Matrix::new(3, 2, vec![1., 0.1,
//!                                     3., 0.2,
//!                                     4., 0.2]);
//! // Train the model
//! pca.train(&inputs).unwrap();
//!
//! // Mapping a new point to principal component space
//! let new_data = Matrix::new(1, 2, vec![2., 0.1]);
//! let output = pca.predict(&new_data).unwrap();
//!
//! assert_eq!(output, Matrix::new(1, 2, vec![-0.6686215718235227, 0.042826190364433595]));
//! ```

use linalg::{Matrix, BaseMatrix, Axes};
use linalg::Vector;

use learning::{LearningResult, UnSupModel};
use learning::error::{Error, ErrorKind};

/// Principal Component Analysis
///
/// - PCA uses rulinalg SVD which is experimental (not yet work for large data)
#[derive(Debug)]
pub struct PCA {
    /// number of componentsc considered
    n: Option<usize>,
    /// Flag whether to centering inputs
    center: bool,

    // Number of original input
    n_features: Option<usize>,
    // Center of inputs
    centers: Option<Vector<f64>>,
    // Principal components
    components: Option<Matrix<f64>>,
    // Whether components is inversed (trained with number of rows < cols data)
    inv: bool
}

impl PCA {

    /// Constructs untrained PCA model.
    ///
    /// # Parameters
    ///
    /// - `n` : number of principal components
    /// - `center` : flag whether centering inputs to be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use rusty_machine::learning::pca::PCA;
    ///
    /// let model = PCA::new(3, true);
    /// ```
    pub fn new(n: usize, center: bool) -> PCA {

        PCA {
            // accept n as usize, user should know the number of columns
            n: Some(n),
            center: center,

            n_features: None,
            centers: None,
            components: None,
            inv: false
        }
    }

    /// Returns principal components (matrix which contains eigenvectors as columns)
    pub fn components(&self) -> LearningResult<&Matrix<f64>>  {
        match self.components {
            None => Err(Error::new_untrained()),
            Some(ref rot) => { Ok(rot) }
        }
    }
}

/// The default PCA.
///
/// Parameters:
///
/// - `n` = `None` (keep all components)
/// - `center` = `true`
///
/// # Examples
///
/// ```
/// use rusty_machine::learning::pca::PCA;
///
/// let model = PCA::default();
/// ```
impl Default for PCA {
    fn default() -> Self {
        PCA {
            // because number of columns is unknown,
            // return all components by default
            n: None,
            center: true,

            n_features: None,
            centers: None,
            components: None,
            inv: false
        }
    }
}

/// Train the model and predict the model output from new data.
impl UnSupModel<Matrix<f64>, Matrix<f64>> for PCA {

    fn predict(&self, inputs: &Matrix<f64>) -> LearningResult<Matrix<f64>>  {

        match self.n_features {
            None => { return Err(Error::new_untrained()); },
            Some(f) => {
                if f != inputs.cols() {
                    return Err(Error::new(ErrorKind::InvalidData,
                               "Input data must have the same number of columns as training data"));
                }
            }
        };

        match self.components {
            // this can't happen
            None => { return Err(Error::new_untrained()); },
            Some(ref comp) => {
                if self.center == true {
                    match self.centers {
                        // this can't happen
                        None => return Err(Error::new_untrained()),
                        Some(ref centers) => {
                            let data = unsafe { centering(inputs, &centers) };
                            if self.inv == true {
                                Ok(data * comp.transpose())
                            } else {
                                Ok(data * comp)
                            }
                        }
                    }
                } else {
                    if self.inv == true {
                        Ok(inputs * comp.transpose())
                    } else {
                        Ok(inputs * comp)
                    }
                }
            }
        }
    }

    fn train(&mut self, inputs: &Matrix<f64>) -> LearningResult<()> {
        match self.n {
            None => {},
            Some(n) => {
                if n > inputs.cols() {
                    return Err(Error::new(ErrorKind::InvalidData,
                               "Input data must have equal or larger number of columns than n"));
                }
            }
        }

        let data = if self.center == true {
            let centers = inputs.mean(Axes::Row);
            let m = unsafe { centering(inputs, &centers) };
            self.centers = Some(centers);
            m
        } else {
            inputs.clone()
        };
        let (_, _, mut v) = data.svd().unwrap();
        if inputs.cols() > inputs.rows() {
            v = v.transpose();
            self.inv = true;
        }

        self.components = match self.n {
            Some(c) => {
                let slicer: Vec<usize> = (0..c).collect();
                Some(v.select_cols(&slicer))
            },
            None => Some(v)
        };
        self.n_features = Some(inputs.cols());
        Ok(())
    }
}

/// Subtract center Vector from each rows
unsafe fn centering(inputs: &Matrix<f64>, centers: &Vector<f64>) -> Matrix<f64> {
    // Number of inputs columns and centers length must be the same
    Matrix::from_fn(inputs.rows(), inputs.cols(),
                    |c, r| inputs.get_unchecked([r, c]) - centers.data().get_unchecked(c))
}

#[cfg(test)]
mod tests {

    use linalg::{Matrix, Axes, Vector};
    use super::centering;

    #[test]
    fn test_centering() {
        let m = Matrix::new(2, 3, vec![1., 2., 3.,
                                       2., 4., 4.]);
        let centers = m.mean(Axes::Row);
        assert_vector_eq!(centers, Vector::new(vec![1.5, 3., 3.5]), comp=abs, tol=1e-8);

        let centered = unsafe { centering(&m, &centers) };
        let exp = Matrix::new(2, 3, vec![-0.5, -1., -0.5,
                                         0.5, 1., 0.5]);
        assert_matrix_eq!(centered, exp, comp=abs, tol=1e-8);
    }
}