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
/*!
Functions for displaying statistics about a `DataView`.
*/

use std::fmt;

use prettytable as pt;

use access::DataIndex;
use cons::Len;
use label::{StrLabels, StrTypes};
use partial::*;
use stats::*;
use store::NRows;
use view::{AssocDataIndexCons, AssocDataIndexConsOf, DataView};

/// Structure containing general statistics of a `DataView`.
#[derive(Debug, Clone)]
pub struct ViewStats {
    nrows: usize,
    nfields: usize,
    idents: Vec<String>,
    tys: Vec<String>,
    mins: Vec<String>,
    maxs: Vec<String>,
    sums: Vec<String>,
    means: Vec<String>,
    stdevs: Vec<String>,
}

/// Partially-implemented function (implementing [Func](../partial/trait.Func.html) and
/// [FuncDefault](../partial/trait.FuncDefault.html)) for computing the minimum value in a field.
#[derive(Debug)]
pub struct MinFn {
    values: Vec<String>,
}
impl Default for MinFn {
    fn default() -> MinFn {
        MinFn { values: vec![] }
    }
}
impl FuncDefault for MinFn {
    type Output = ();
    fn call(&mut self) -> () {
        self.values.push(String::new());
    }
}

/// Partially-implemented function (implementing [Func](../partial/trait.Func.html) and
/// [FuncDefault](../partial/trait.FuncDefault.html)) for computing the maximum value in a field.
#[derive(Debug)]
pub struct MaxFn {
    values: Vec<String>,
}
impl Default for MaxFn {
    fn default() -> MaxFn {
        MaxFn { values: vec![] }
    }
}
impl FuncDefault for MaxFn {
    type Output = ();
    fn call(&mut self) -> () {
        self.values.push(String::new());
    }
}

/// Partially-implemented function (implementing [Func](../partial/trait.Func.html) and
/// [FuncDefault](../partial/trait.FuncDefault.html)) for computing the sum of values in a field.
#[derive(Debug)]
pub struct SumFn {
    values: Vec<String>,
}
impl Default for SumFn {
    fn default() -> SumFn {
        SumFn { values: vec![] }
    }
}
impl FuncDefault for SumFn {
    type Output = ();
    fn call(&mut self) -> () {
        self.values.push(String::new());
    }
}

/// Partially-implemented function (implementing [Func](../partial/trait.Func.html) and
/// [FuncDefault](../partial/trait.FuncDefault.html)) for computing the arithmetic mean of values
/// in a field.
#[derive(Debug)]
pub struct MeanFn {
    values: Vec<String>,
}
impl Default for MeanFn {
    fn default() -> MeanFn {
        MeanFn { values: vec![] }
    }
}
impl FuncDefault for MeanFn {
    type Output = ();
    fn call(&mut self) -> () {
        self.values.push(String::new());
    }
}

/// Partially-implemented function (implementing [Func](../partial/trait.Func.html) and
/// [FuncDefault](../partial/trait.FuncDefault.html)) for computing the standard deviation of values
/// in a field.
#[derive(Debug)]
pub struct StDevFn {
    values: Vec<String>,
}
impl Default for StDevFn {
    fn default() -> StDevFn {
        StDevFn { values: vec![] }
    }
}
impl FuncDefault for StDevFn {
    type Output = ();
    fn call(&mut self) -> () {
        self.values.push(String::new());
    }
}

macro_rules! impl_stats_fns {
    ($($dtype:ty)*) => {$(

        impl Func<$dtype> for MinFn {
            type Output = ();
            fn call<DI>(&mut self, data: &DI) -> ()
            where
                DI: DataIndex<DType=$dtype>
            {
                self.values.push(data.min().map_or(String::new(), ToString::to_string));
            }
        }
        impl IsImplemented<MinFn> for $dtype {
            type IsImpl = Implemented;
        }

        impl Func<$dtype> for MaxFn {
            type Output = ();
            fn call<DI>(&mut self, data: &DI) -> ()
            where
                DI: DataIndex<DType=$dtype>
            {
                self.values.push(data.max().map_or(String::new(), ToString::to_string));
            }
        }
        impl IsImplemented<MaxFn> for $dtype {
            type IsImpl = Implemented;
        }

        impl Func<$dtype> for SumFn {
            type Output = ();
            fn call<DI>(&mut self, data: &DI) -> ()
            where
                DI: DataIndex<DType=$dtype>
            {
                self.values.push(data.sum().to_string());
            }
        }
        impl IsImplemented<SumFn> for $dtype {
            type IsImpl = Implemented;
        }

        impl Func<$dtype> for MeanFn {
            type Output = ();
            fn call<DI>(&mut self, data: &DI) -> ()
            where
                DI: DataIndex<DType=$dtype>
            {
                self.values.push(data.mean().to_string());
            }
        }
        impl IsImplemented<MeanFn> for $dtype {
            type IsImpl = Implemented;
        }

        impl Func<$dtype> for StDevFn {
            type Output = ();
            fn call<DI>(&mut self, data: &DI) -> ()
            where
                DI: DataIndex<DType=$dtype>
            {
                self.values.push(data.stdev().to_string());
            }
        }
        impl IsImplemented<StDevFn> for $dtype {
            type IsImpl = Implemented;
        }

    )*}
}

impl_stats_fns![f64 f32 u64 u32 usize i64 i32 isize];

macro_rules! impl_stats_fns_nonimpl {
    ($($dtype:ty)*) => {$(

        impl IsImplemented<MinFn> for $dtype {
            type IsImpl = Unimplemented;
        }
        impl IsImplemented<MaxFn> for $dtype {
            type IsImpl = Unimplemented;
        }
        impl IsImplemented<SumFn> for $dtype {
            type IsImpl = Unimplemented;
        }
        impl IsImplemented<MeanFn> for $dtype {
            type IsImpl = Unimplemented;
        }
        impl IsImplemented<StDevFn> for $dtype {
            type IsImpl = Unimplemented;
        }

    )*}
}

impl_stats_fns_nonimpl![bool String];

impl<Labels, Frames> DataView<Labels, Frames>
where
    Frames: Len + NRows + AssocDataIndexCons<Labels>,
    AssocDataIndexConsOf<Labels, Frames>: DeriveCapabilities<MinFn>,
    AssocDataIndexConsOf<Labels, Frames>: DeriveCapabilities<MaxFn>,
    AssocDataIndexConsOf<Labels, Frames>: DeriveCapabilities<SumFn>,
    AssocDataIndexConsOf<Labels, Frames>: DeriveCapabilities<MeanFn>,
    AssocDataIndexConsOf<Labels, Frames>: DeriveCapabilities<StDevFn>,
    Labels: Len + StrLabels + StrTypes,
{
    /// Compute and return general statistics for this `DataView`.
    pub fn view_stats(&self) -> ViewStats {
        let mut min_fn = MinFn::default();
        DeriveCapabilities::<MinFn>::derive(self.frames.assoc_data()).map(&mut min_fn);
        let mut max_fn = MaxFn::default();
        DeriveCapabilities::<MaxFn>::derive(self.frames.assoc_data()).map(&mut max_fn);
        let mut sum_fn = SumFn::default();
        DeriveCapabilities::<SumFn>::derive(self.frames.assoc_data()).map(&mut sum_fn);
        let mut mean_fn = MeanFn::default();
        DeriveCapabilities::<MeanFn>::derive(self.frames.assoc_data()).map(&mut mean_fn);
        let mut stdev_fn = StDevFn::default();
        DeriveCapabilities::<StDevFn>::derive(self.frames.assoc_data()).map(&mut stdev_fn);

        let view_stats = ViewStats {
            nrows: self.nrows(),
            nfields: self.nfields(),
            idents: <Labels as StrLabels>::labels()
                .iter()
                .map(|s| s.to_string())
                .collect(),
            tys: <Labels as StrTypes>::str_types()
                .iter()
                .map(|s| s.to_string())
                .collect(),
            mins: min_fn.values,
            maxs: max_fn.values,
            sums: sum_fn.values,
            means: mean_fn.values,
            stdevs: stdev_fn.values,
        };

        view_stats
    }
}

impl fmt::Display for ViewStats {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(
            f,
            "DataView with {} rows, {} fields",
            self.nrows, self.nfields
        )?;

        let mut table = pt::Table::new();
        table.set_titles(
            ["Field", "Type", "Min", "Max", "Sum", "Mean", "StDev"]
                .iter()
                .into(),
        );

        debug_assert_eq!(self.idents.len(), self.tys.len());
        debug_assert_eq!(self.idents.len(), self.mins.len());
        debug_assert_eq!(self.idents.len(), self.maxs.len());
        debug_assert_eq!(self.idents.len(), self.sums.len());
        debug_assert_eq!(self.idents.len(), self.means.len());
        debug_assert_eq!(self.idents.len(), self.stdevs.len());

        for i in 0..self.mins.len() {
            table.add_row(pt::row::Row::new(vec![
                cell![self.idents[i]],
                cell![self.tys[i]],
                cell![self.mins[i]],
                cell![self.maxs[i]],
                cell![self.sums[i]],
                cell![self.means[i]],
                cell![self.stdevs[i]],
            ]));
        }

        table.set_format(*pt::format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
        table.fmt(f)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use test_utils::*;

    macro_rules! assert_float_eq {
        ($actual:expr, $expected:expr) => {{
            assert!(($actual.clone().parse::<f64>().unwrap() - $expected).abs() < 1e-4);
        }};
    }
    #[test]
    fn view_stats_display() {
        let dv_emp = sample_emp_table().into_view();
        println!("{}", dv_emp);
        let vs1 = dv_emp.view_stats();
        println!("{}", vs1);
        assert_eq!(vs1.nrows, 7);
        assert_eq!(vs1.nfields, 3);
        assert_eq!(vs1.tys[0], "u64".to_string());
        assert_eq!(vs1.tys[1], "u64".to_string());
        assert_eq!(vs1.tys[2], "String".to_string());

        assert_eq!(vs1.mins[0], "0".to_string()); // EmpId min
        assert_eq!(vs1.maxs[0], "10".to_string()); // EmpId max
        assert_eq!(vs1.sums[0], "40".to_string()); // EmpId sum
        assert_float_eq!(vs1.means[0], 5.714286); // EmpId mean
        assert_float_eq!(vs1.stdevs[0], 3.683942); // EmpId stdev

        assert_eq!(vs1.mins[2], "".to_string()); // EmpName shortest len
        assert_eq!(vs1.maxs[2], "".to_string()); // EmpName longest len
        assert_eq!(vs1.sums[2], "".to_string()); // EmpName sum is NA
        assert_eq!(vs1.means[2], "".to_string()); // EmpName mean is NA
        assert_eq!(vs1.stdevs[2], "".to_string()); // EmpName stdev is NA

        println!("{}", vs1);

        let dv_extra = sample_emp_table_extra().into_view();
        println!("{}", dv_extra);
        let vs2 = dv_extra.view_stats();
        println!("{}", vs2);

        assert_eq!(vs2.nrows, 7);
        assert_eq!(vs2.nfields, 3);
        assert_eq!(vs2.tys[0], "i64".to_string());
        assert_eq!(vs2.tys[1], "bool".to_string());
        assert_eq!(vs2.tys[2], "f32".to_string());

        assert_eq!(vs2.mins[0], "-33".to_string()); // SalaryOffset min
        assert_eq!(vs2.maxs[0], "12".to_string()); // SalaryOffset max
        assert_eq!(vs2.sums[0], "-13".to_string()); // SalaryOffset sum (# of true)
        assert_float_eq!(vs2.means[0], -1.857143); // SalaryOffset mean
        assert_float_eq!(vs2.stdevs[0], 15.004761); // SalaryOffset stdev

        assert_eq!(vs2.mins[1], "".to_string()); // DidTraining min
        assert_eq!(vs2.maxs[1], "".to_string()); // DidTraining max
        assert_eq!(vs2.sums[1], "".to_string()); // DidTraining sum
        assert_eq!(vs2.means[1], "".to_string()); // DidTraining mean
        assert_eq!(vs2.stdevs[1], "".to_string()); // DidTraining stdev

        assert_eq!(vs2.mins[2], "-1.2".to_string()); // VacationHrs min
        assert_eq!(vs2.maxs[2], "98.3".to_string()); // VacationHrs max
        assert_float_eq!(vs2.sums[2], 238.6); // VacationHrs sum
        assert_float_eq!(vs2.means[2], 34.0857143); // VacationHrs mean
        assert_float_eq!(vs2.stdevs[2], 35.070948); // VacationHrs stdev
    }
}