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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::fmt::{self, Display, Formatter};
use std::iter::FromIterator;
use indexmap::IndexMap;
use indexmap::map::Keys;
use serde::ser::{self, Serialize, Serializer, SerializeMap};
use prettytable as pt;
use access::DataIndex;
use frame::{DataFrame, FramedMap, FramedTMap, FramedMapExt, Framed, FramedFunc, SerializedField};
use filter::Filter;
use field::{Value};
use join::{Join, sort_merge_join, compute_merged_frames, compute_merged_field_list, MergedFields};
use field::{FieldIdent, RFieldIdent};
use error;
use store::{DataStore, CopyIntoFn};
use data_types::*;
use apply::sort::{DtOrd, SortOrderFn};
use select::{SelectField, Field};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ViewField {
pub rident: RFieldIdent,
pub frame_idx: usize,
}
#[derive(Debug, Clone, Default)]
pub struct DataView<DTypes>
where DTypes: DTypeList
{
pub(crate) frames: Vec<DataFrame<DTypes>>,
pub(crate) fields: IndexMap<FieldIdent, ViewField>,
}
impl<DTypes> DataView<DTypes>
where DTypes: DTypeList
{
pub fn v<L: IntoFieldList>(&self, s: L) -> DataView<DTypes> {
let mut sub_fields = IndexMap::new();
for ident in &s.into_field_list() {
if let Some(field) = self.fields.get(ident) {
sub_fields.insert(ident.clone(), field.clone());
}
}
DataView {
frames: self.frames.clone(),
fields: sub_fields,
}
}
pub fn subview<L: IntoFieldList>(&self, s: L) -> error::Result<DataView<DTypes>> {
let mut sub_fields = IndexMap::new();
for ident in &s.into_field_list() {
if let Some(field) = self.fields.get(ident) {
sub_fields.insert(ident.clone(), field.clone());
} else {
return Err(error::AgnesError::FieldNotFound(ident.clone()));
}
}
Ok(DataView {
frames: self.frames.clone(),
fields: sub_fields,
})
}
pub fn nrows(&self) -> usize
where DTypes::Storage: MaxLen<DTypes>
{
if self.frames.is_empty() { 0 } else { self.frames[0].nrows() }
}
pub fn is_empty(&self) -> bool
where DTypes::Storage: MaxLen<DTypes>
{
self.nrows() == 0
}
pub fn nfields(&self) -> usize {
self.fields.len()
}
pub fn fieldnames(&self) -> Vec<&FieldIdent> {
self.fields.keys().collect()
}
pub(crate) fn get_field_type(&self, ident: &FieldIdent) -> Option<DTypes::DType> {
self.fields.get(ident).and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].get_field_type(&view_field.rident.ident)
})
}
pub fn has_field(&self, s: &FieldIdent) -> bool {
self.fields.contains_key(s)
}
pub fn rename<T, U>(&mut self, orig: T, new: U) -> error::Result<()> where
T: Into<FieldIdent>,
U: Into<FieldIdent>
{
let (orig, new) = (orig.into(), new.into());
if self.fields.contains_key(&new) {
return Err(error::AgnesError::FieldCollision(vec![new]));
}
let new_vf = if let Some(ref orig_vf) = self.fields.get(&orig) {
ViewField {
rident: RFieldIdent {
ident: orig_vf.rident.ident.clone(),
rename: Some(new.to_string())
},
frame_idx: orig_vf.frame_idx,
}
} else {
return Err(error::AgnesError::FieldNotFound(orig));
};
self.fields.insert(new_vf.rident.to_renamed_field_ident(), new_vf);
self.fields.swap_remove(&orig);
Ok(())
}
pub fn merge(&self, other: &DataView<DTypes>) -> error::Result<DataView<DTypes>>
where DTypes::Storage: MaxLen<DTypes>
{
if self.nrows() != other.nrows() {
return Err(error::AgnesError::DimensionMismatch(
"number of rows mismatch in merge".into()));
}
let (new_frames, other_store_indices) = compute_merged_frames(self, other);
let MergedFields { mut new_fields, .. } =
compute_merged_field_list(self, other, &other_store_indices, None)?;
let new_fields = IndexMap::from_iter(new_fields.drain(..));
Ok(DataView {
frames: new_frames,
fields: new_fields
})
}
pub fn join<'b, T>(&'b self, other: &'b DataView<DTypes>, join: &Join)
-> error::Result<DataStore<DTypes>>
where T: 'static + DataType<DTypes> + DtOrd + PartialEq + Default,
DTypes: 'b,
DTypes::Storage: MaxLen<DTypes> + TypeSelector<DTypes, T> + CreateStorage
+ for<'c> FramedMapExt<DTypes, CopyIntoFn<'c, DTypes>, ()>
{
match join.predicate {
_ => {
sort_merge_join::<DTypes, T>(self, other, join)
}
}
}
pub fn idents(&self) -> Keys<FieldIdent, ViewField> {
self.fields.keys()
}
pub fn map<F, FOut, I>(&self, ident: I, f: F)
-> error::Result<FOut>
where DTypes::Storage: FramedMap<DTypes, F, FOut>,
I: Into<FieldIdent>
{
let ident = ident.into();
self.fields.get(&ident)
.ok_or_else(|| error::AgnesError::FieldNotFound(ident))
.and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].map(&view_field.rident.ident, f)
})
}
pub fn tmap<T, F, I>(&self, ident: I, f: F)
-> error::Result<F::Output>
where F: Func<DTypes, T>,
T: DataType<DTypes>,
DTypes::Storage: MaxLen<DTypes> + FramedTMap<DTypes, T, F>,
I: Into<FieldIdent>,
{
let ident = ident.into();
self.fields.get(&ident)
.ok_or_else(|| error::AgnesError::FieldNotFound(ident))
.and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].tmap(&view_field.rident.ident, f)
})
}
pub fn map_ext<F, FOut, I>(&self, ident: I, f: F)
-> error::Result<FOut>
where DTypes::Storage: FramedMapExt<DTypes, F, FOut>,
I: Into<FieldIdent>
{
let ident = ident.into();
self.fields.get(&ident)
.ok_or_else(|| error::AgnesError::FieldNotFound(ident))
.and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].map_ext(&view_field.rident.ident, f)
})
}
pub fn map_partial<F, I>(&self, ident: I, f: F)
-> error::Result<Option<F::Output>>
where DTypes::Storage: MapPartial<DTypes, F> + MaxLen<DTypes>,
F: FuncPartial<DTypes>,
I: Into<FieldIdent>
{
let ident = ident.into();
self.fields.get(&ident)
.ok_or_else(|| error::AgnesError::FieldNotFound(ident))
.and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].map_partial(&view_field.rident.ident, f)
})
}
pub fn sort_by<'a>(&'a mut self, ident: &FieldIdent) -> error::Result<Vec<usize>>
where DTypes::Storage: FramedMap<DTypes, SortOrderFn, Vec<usize>>,
{
match self.fields.get(ident) {
Some(view_field) => {
let sorted = self.frames[view_field.frame_idx].sort_by(&view_field.rident.ident)?;
for frame_idx in 0..self.frames.len() {
if frame_idx != view_field.frame_idx {
self.frames[frame_idx].update_permutation(&sorted);
}
}
Ok(sorted)
},
None => Err(error::AgnesError::FieldNotFound(ident.clone()))
}
}
}
impl<DTypes> Field<DTypes> for DataView<DTypes>
where DTypes: DTypeList
{}
impl<'a, DTypes, T> SelectField<'a, T, DTypes>
for DataView<DTypes>
where T: 'static + DataType<DTypes>,
DTypes: 'a + DTypeList,
DTypes::Storage: MaxLen<DTypes>
{
type Output = Framed<'a, DTypes, T>;
fn select(&'a self, ident: FieldIdent) -> error::Result<Framed<'a, DTypes, T>>
where DTypes: AssocTypes,
DTypes::Storage: TypeSelector<DTypes, T>
{
self.fields.get(&ident)
.ok_or_else(|| error::AgnesError::FieldNotFound(ident.clone()))
.and_then(|view_field: &ViewField| {
self.frames[view_field.frame_idx].select(view_field.rident.ident.clone())
})
}
}
impl<DTypes, T> Filter<DTypes, T> for DataView<DTypes>
where DataFrame<DTypes>: Filter<DTypes, T> + Field<DTypes>,
DTypes: DTypeList,
DTypes::Storage: MaxLen<DTypes> + TypeSelector<DTypes, T>,
T: 'static + DataType<DTypes>
{
fn filter<I: Into<FieldIdent>, F: Fn(&T) -> bool>(&mut self, ident: I, pred: F)
-> error::Result<Vec<usize>>
{
let ident = ident.into();
match self.fields.get(&ident) {
Some(view_field) => {
let filter = self.frames[view_field.frame_idx].filter(
&view_field.rident.ident, pred)?;
for frame_idx in 0..self.frames.len() {
if frame_idx != view_field.frame_idx {
self.frames[frame_idx].update_permutation(&filter);
}
}
Ok(filter)
},
None => Err(error::AgnesError::FieldNotFound(ident.clone()))
}
}
}
impl<DTypes> From<DataStore<DTypes>> for DataView<DTypes>
where DTypes: DTypeList
{
fn from(store: DataStore<DTypes>) -> DataView<DTypes> {
let mut fields = IndexMap::new();
for ident in store.fields() {
fields.insert(ident.clone(), ViewField {
rident: RFieldIdent {
ident: ident.clone(),
rename: None
},
frame_idx: 0,
});
}
DataView {
frames: vec![store.into()],
fields
}
}
}
const MAX_DISP_ROWS: usize = 1000;
impl<DTypes> Display for DataView<DTypes>
where DTypes: DTypeList,
DTypes::Storage: MaxLen<DTypes>
+ for<'a, 'b> Map<DTypes, FramedFunc<'a, DTypes, AddCellToRowFn<'b>>, ()>
{
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
if self.frames.is_empty() || self.fields.is_empty() {
return write!(f, "Empty DataView");
}
let nrows = self.frames[0].nrows();
let mut table = pt::Table::new();
table.set_titles(self.fields.keys().into());
let mut rows = vec![pt::row::Row::empty(); nrows.min(MAX_DISP_ROWS)];
for view_field in self.fields.values() {
match self.frames[view_field.frame_idx].map(
&view_field.rident.ident,
AddCellToRowFn {
rows: &mut rows,
},
) {
Ok(_) => {},
Err(e) => { return write!(f, "view display error: {}", e); },
}
}
for row in rows.drain(..) {
table.add_row(row);
}
table.set_format(*pt::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
Display::fmt(&table, f)
}
}
pub struct AddCellToRowFn<'a> {
rows: &'a mut Vec<pt::row::Row>,
}
impl<'a, DTypes, T> Func<DTypes, T> for AddCellToRowFn<'a>
where DTypes: DTypeList,
T: 'a + DataType<DTypes>,
for<'b> Value<&'b T>: ToString
{
type Output = ();
fn call(
&mut self,
type_data: &dyn DataIndex<DTypes, DType=T>,
)
{
for i in 0..type_data.len().min(MAX_DISP_ROWS) {
self.rows[i].add_cell(cell!(type_data.get_datum(i).unwrap()));
}
}
}
impl<DTypes> Serialize for DataView<DTypes>
where DTypes: DTypeList,
DTypes::Storage: MaxLen<DTypes> + FieldSerialize<DTypes>
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
let mut map = serializer.serialize_map(Some(self.fields.len()))?;
for field in self.fields.values() {
map.serialize_entry(&field.rident.to_string(), &SerializedField::new(
field.rident.ident.clone(),
&self.frames[field.frame_idx]
))?;
}
map.end()
}
}
pub trait SerializeAsVec: Serialize {}
impl<T> SerializeAsVec for Vec<T> where T: Serialize {}
#[derive(Debug, Clone)]
pub struct FieldView<DTypes>
where DTypes: DTypeList
{
frame: DataFrame<DTypes>,
field: RFieldIdent,
}
impl<DTypes> Serialize for FieldView<DTypes>
where DTypes: DTypeList,
DTypes::Storage: MaxLen<DTypes> + FieldSerialize<DTypes>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
if self.frame.has_field(&self.field.ident) {
SerializedField::new(
self.field.to_renamed_field_ident(),
&self.frame
).serialize(serializer)
} else {
Err(ser::Error::custom(format!("missing field: {}", self.field.to_string())))
}
}
}
impl<DTypes> SerializeAsVec for FieldView<DTypes>
where DTypes: DTypeList,
DTypes::Storage: MaxLen<DTypes> + FieldSerialize<DTypes>
{}
impl<DTypes> DataView<DTypes>
where DTypes: DTypeList
{
pub fn as_fieldview(&self) -> Option<FieldView<DTypes>> {
if self.fields.is_empty() {
None
} else {
let field = self.fields.values().next().unwrap();
Some(FieldView {
frame: self.frames[field.frame_idx].clone(),
field: field.rident.clone(),
})
}
}
}
pub trait IntoFieldList {
fn into_field_list(self) -> Vec<FieldIdent>;
}
impl IntoFieldList for FieldIdent {
fn into_field_list(self) -> Vec<FieldIdent> {
vec![self]
}
}
impl<'a> IntoFieldList for &'a FieldIdent {
fn into_field_list(self) -> Vec<FieldIdent> {
vec![self.clone()]
}
}
impl IntoFieldList for Vec<FieldIdent> {
fn into_field_list(self) -> Vec<FieldIdent> {
self
}
}
impl<'a> IntoFieldList for Vec<&'a FieldIdent> {
fn into_field_list(self) -> Vec<FieldIdent> {
#[allow(unknown_lints, map_clone)]
self.iter().map(|&fi| fi.clone()).collect()
}
}
impl<'a> IntoFieldList for &'a str {
fn into_field_list(self) -> Vec<FieldIdent> {
vec![FieldIdent::Name(self.to_string())]
}
}
impl<'a> IntoFieldList for Vec<&'a str> {
fn into_field_list(mut self) -> Vec<FieldIdent> {
self.drain(..).map(|s| FieldIdent::Name(s.to_string())).collect()
}
}
macro_rules! impl_into_field_list_str_arr {
($($val:expr),*) => {$(
impl<'a> IntoFieldList for [&'a str; $val] {
fn into_field_list(self) -> Vec<FieldIdent> {
self.iter().map(|s| FieldIdent::Name(s.to_string())).collect()
}
}
)*}
}
impl_into_field_list_str_arr!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
impl IntoFieldList for String {
fn into_field_list(self) -> Vec<FieldIdent> {
vec![FieldIdent::Name(self)]
}
}
impl IntoFieldList for Vec<String> {
fn into_field_list(mut self) -> Vec<FieldIdent> {
self.drain(..).map(FieldIdent::Name).collect()
}
}
macro_rules! impl_into_field_list_string_arr {
($($val:expr),*) => {$(
impl IntoFieldList for [String; $val] {
fn into_field_list(self) -> Vec<FieldIdent> {
self.iter().map(|s| FieldIdent::Name(s.clone())).collect()
}
}
)*}
}
impl_into_field_list_string_arr!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
#[cfg(test)]
mod tests {
use test_utils::*;
use super::{FieldIdent, Filter};
use error::*;
use data_types::standard::*;
use access::{DataIndex, DataIterator};
#[test]
fn merge() {
let ds1 = sample_emp_table();
let ds2 = sample_emp_table_extra();
let (dv1, dv2): (DataView, DataView) = (ds1.into(), ds2.into());
println!("{}", dv1);
println!("{}", dv2);
let merged_dv: DataView = dv1.merge(&dv2).expect("merge failed");
println!("{}", merged_dv);
assert_eq!(merged_dv.nrows(), 7);
assert_eq!(merged_dv.nfields(), 6);
for (left, right) in merged_dv.fieldnames().iter()
.zip(vec!["EmpId", "DeptId", "EmpName", "SalaryOffset", "DidTraining", "VacationHrs"]
.iter().map(|&s| FieldIdent::Name(s.into())))
{
assert_eq!(left, &&right);
}
}
#[test]
fn merge_dimension_mismatch() {
let ds1 = sample_emp_table();
let ds2 = sample_dept_table();
let (dv1, dv2): (DataView, DataView) = (ds1.into(), ds2.into());
println!("{}", dv1);
println!("{}", dv2);
match dv1.merge(&dv2) {
Ok(_) => { panic!("Merge was expected to fail (dimension mismatch), but succeeded"); },
Err(AgnesError::DimensionMismatch(_)) => { },
Err(e) => { panic!("Incorrect error: {:?}", e); },
};
}
#[test]
fn merge_field_collision() {
let ds1 = sample_emp_table();
let ds2 = sample_emp_table();
let (dv1, dv2): (DataView, DataView) = (ds1.into(), ds2.into());
println!("{}", dv1);
println!("{}", dv2);
match dv1.merge(&dv2) {
Ok(_) => { panic!("Merge expected to fail (field collision), but succeeded"); },
Err(AgnesError::FieldCollision(fields)) => {
assert_eq!(fields, vec!["EmpId", "DeptId", "EmpName"]
.iter().map(|&s| FieldIdent::Name(s.into())).collect::<Vec<_>>());
},
Err(e) => { panic!("Incorrect error: {:?}", e); }
}
}
#[test]
fn rename() {
let ds = sample_emp_table();
let mut dv: DataView = ds.into();
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
dv.rename("DeptId", "Department Id").expect("rename failed");
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "Department Id", "EmpName"]);
dv.rename("Department Id", "DeptId").expect("rename failed");
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
}
#[test]
fn rename_field_collision() {
let ds = sample_emp_table();
let mut dv: DataView = ds.into();
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
match dv.rename("DeptId", "EmpId") {
Ok(_) => { panic!("Rename expected to fail (field collision), but succeeded"); },
Err(AgnesError::FieldCollision(fields)) => {
assert_eq!(fields, vec!["EmpId"]
.iter().map(|&s| FieldIdent::Name(s.into())).collect::<Vec<_>>());
},
Err(e) => { panic!("Incorrect error: {:?}", e); }
}
}
#[test]
fn rename_field_not_found() {
let ds = sample_emp_table();
let mut dv: DataView = ds.into();
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
match dv.rename("Department Id", "DepartmentId") {
Ok(_) => { panic!("Rename expected to fail (field not found), but succeeded"); },
Err(AgnesError::FieldNotFound(field)) => {
assert_eq!(field, FieldIdent::Name("Department Id".to_string()));
},
Err(e) => { panic!("Incorrect error: {:?}", e); }
}
}
#[test]
fn subview() {
let ds = sample_emp_table();
let dv: DataView = ds.into();
assert_eq!(dv.frames[0].store_ref_count(), 1);
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
let subdv1 = dv.v("EmpId");
assert_eq!(dv.frames[0].store_ref_count(), 2);
assert_eq!(subdv1.nrows(), 7);
assert_eq!(subdv1.nfields(), 1);
let subdv1 = dv.subview("EmpId").expect("subview failed");
assert_eq!(dv.frames[0].store_ref_count(), 3);
assert_eq!(subdv1.nrows(), 7);
assert_eq!(subdv1.nfields(), 1);
let subdv2 = dv.v(vec!["EmpId", "DeptId"]);
assert_eq!(dv.frames[0].store_ref_count(), 4);
assert_eq!(subdv2.nrows(), 7);
assert_eq!(subdv2.nfields(), 2);
let subdv2 = dv.subview(vec!["EmpId", "DeptId"]).expect("subview failed");
assert_eq!(dv.frames[0].store_ref_count(), 5);
assert_eq!(subdv2.nrows(), 7);
assert_eq!(subdv2.nfields(), 2);
let subdv3 = dv.v(vec!["EmpId", "DeptId", "EmpName"]);
assert_eq!(dv.frames[0].store_ref_count(), 6);
assert_eq!(subdv3.nrows(), 7);
assert_eq!(subdv3.nfields(), 3);
let subdv3 = dv.subview(vec!["EmpId", "DeptId", "EmpName"]).expect("subview failed");
assert_eq!(dv.frames[0].store_ref_count(), 7);
assert_eq!(subdv3.nrows(), 7);
assert_eq!(subdv3.nfields(), 3);
let subdv4 = subdv2.v("DeptId");
assert_eq!(dv.frames[0].store_ref_count(), 8);
assert_eq!(subdv4.nrows(), 7);
assert_eq!(subdv4.nfields(), 1);
let subdv4 = subdv2.subview("DeptId").expect("subview failed");
assert_eq!(dv.frames[0].store_ref_count(), 9);
assert_eq!(subdv4.nrows(), 7);
assert_eq!(subdv4.nfields(), 1);
}
#[test]
fn subview_fail() {
let ds = sample_emp_table();
let dv: DataView = ds.into();
assert_eq!(dv.frames[0].store_ref_count(), 1);
assert_field_lists_match(dv.fieldnames(), vec!["EmpId", "DeptId", "EmpName"]);
let subdv1 = dv.v(vec!["EmpId", "DeptId", "Employee Name"]);
assert_eq!(dv.frames[0].store_ref_count(), 2);
assert_eq!(subdv1.nrows(), 7);
assert_eq!(subdv1.nfields(), 2);
match dv.subview(vec!["EmpId", "DeptId", "Employee Name"]) {
Ok(_) => { panic!("expected error (field not found), but succeeded"); },
Err(AgnesError::FieldNotFound(field)) => {
assert_eq!(field, FieldIdent::Name("Employee Name".into()));
},
Err(e) => { panic!("Incorrect error: {:?}", e); }
}
let subdv2 = dv.v("Nonexistant");
assert_eq!(dv.frames[0].store_ref_count(), 3);
assert_eq!(subdv2.nrows(), 7);
assert_eq!(subdv2.nfields(), 0);
match dv.subview(vec!["Nonexistant"]) {
Ok(_) => { panic!("expected error (field not found), but succeeded"); },
Err(AgnesError::FieldNotFound(field)) => {
assert_eq!(field, FieldIdent::Name("Nonexistant".into()));
},
Err(e) => { panic!("Incorrect error: {:?}", e); }
}
}
#[test]
fn filter() {
let ds = sample_emp_table();
let orig_dv: DataView = ds.into();
assert_eq!(orig_dv.nrows(), 7);
let mut dv1 = orig_dv.clone();
dv1.filter("DeptId", |val: &u64| *val == 1).unwrap();
println!("{}", dv1);
assert_eq!(dv1.nrows(), 3);
text::assert_dv_sorted_eq(&dv1, &"EmpName".into(), vec!["Sally", "Bob", "Cara"]);
dv1.filter("EmpId", |val: &u64| *val >= 6).unwrap();
assert_eq!(dv1.nrows(), 1);
text::assert_dv_sorted_eq(&dv1, &"EmpName".into(), vec!["Cara"]);
let mut dv2 = orig_dv.clone();
dv2.filter("EmpId", |val: &u64| *val >= 6).unwrap();
assert_eq!(dv2.nrows(), 4);
text::assert_dv_sorted_eq(&dv2, &"EmpName".into(), vec!["Cara", "Louis", "Louise", "Ann"]);
dv2.filter("DeptId", |val: &u64| *val == 4).unwrap();
assert_eq!(dv2.nrows(), 2);
text::assert_dv_sorted_eq(&dv2, &"EmpName".into(), vec!["Louise", "Ann"]);
}
#[test]
fn sort() {
let orig_dv = sample_merged_emp_table();
assert_eq!(orig_dv.nrows(), 7);
let mut dv1 = orig_dv.clone();
dv1.sort_by(&"EmpName".into()).unwrap();
text::assert_dv_eq_vec(&dv1, &"EmpName".into(),
vec!["Ann", "Bob", "Cara", "Jamie", "Louis", "Louise", "Sally"]
);
unsigned::assert_dv_eq_vec(&dv1, &"EmpId".into(),
vec![10u64, 5, 6, 2, 8, 9, 0]);
let mut dv2 = dv1.clone();
dv2.sort_by(&"EmpId".into()).unwrap();
text::assert_dv_eq_vec(&dv2, &"EmpName".into(),
vec!["Sally", "Jamie", "Bob", "Cara", "Louis", "Louise", "Ann"]
);
unsigned::assert_dv_eq_vec(&dv2, &"EmpId".into(),
vec![0u64, 2, 5, 6, 8, 9, 10]);
text::assert_dv_eq_vec(&dv1, &"EmpName".into(),
vec!["Ann", "Bob", "Cara", "Jamie", "Louis", "Louise", "Sally"]
);
unsigned::assert_dv_eq_vec(&dv1, &"EmpId".into(),
vec![10u64, 5, 6, 2, 8, 9, 0]);
let mut dv3 = dv1.clone();
dv3.sort_by(&"VacationHrs".into()).unwrap();
text::assert_dv_eq_vec(&dv3, &"EmpName".into(),
vec!["Louis", "Louise", "Cara", "Ann", "Sally", "Jamie", "Bob"]
);
unsigned::assert_dv_eq_vec(&dv3, &"EmpId".into(),
vec![8u64, 9, 6, 10, 0, 2, 5]);
}
#[test]
fn filter_sort() {
let orig_dv = sample_merged_emp_table();
assert_eq!(orig_dv.nrows(), 7);
let mut dv1 = orig_dv.clone();
dv1.filter("VacationHrs", |&val: &f64| val >= 0.0).unwrap();
assert_eq!(dv1.nrows(), 6);
text::assert_dv_eq_vec(&dv1, &"EmpName".into(),
vec!["Sally", "Jamie", "Bob", "Cara", "Louise", "Ann"]
);
let mut dv2 = dv1.clone();
dv2.sort_by(&"EmpName".into()).unwrap();
text::assert_dv_eq_vec(&dv2, &"EmpName".into(),
vec!["Ann", "Bob", "Cara", "Jamie", "Louise", "Sally"]
);
let mut dv3 = dv2.clone();
dv3.filter("DeptId", |&val: &u64| val == 1).unwrap();
assert_eq!(dv3.nrows(), 3);
text::assert_dv_eq_vec(&dv3, &"EmpName".into(), vec!["Bob", "Cara", "Sally"]);
text::assert_dv_eq_vec(&dv1, &"EmpName".into(),
vec!["Sally", "Jamie", "Bob", "Cara", "Louise", "Ann"]
);
dv1.filter("DeptId", |&val: &u64| val == 1).unwrap();
assert_eq!(dv1.nrows(), 3);
text::assert_dv_eq_vec(&dv1, &"EmpName".into(), vec!["Sally", "Bob", "Cara"]);
text::assert_dv_eq_vec(&dv2, &"EmpName".into(),
vec!["Ann", "Bob", "Cara", "Jamie", "Louise", "Sally"]
);
}
#[test]
fn tmap_closure() {
let orig_dv = sample_merged_emp_table();
let has_jamie = orig_dv.tmap(
"EmpName",
|data: &dyn DataIndex<Types, DType=String>|
DataIterator::new(data).any(|emp_name| emp_name == "Jamie".to_string())
).unwrap();
assert_eq!(has_jamie, true);
let has_james = orig_dv.tmap(
"EmpName",
|data: &dyn DataIndex<Types, DType=String>|
DataIterator::new(data).any(|emp_name| emp_name == "James".to_string())
).unwrap();
assert_eq!(has_james, false);
}
#[test]
fn tmap_incorrect_field_type() {
let orig_dv = sample_merged_emp_table();
match orig_dv.tmap(
"EmpName",
|data: &dyn DataIndex<Types, DType=u64>|
DataIterator::new(data).any(|emp_id| emp_id == 1)
) {
Err(AgnesError::IncompatibleTypes { .. }) => {},
Err(_) => { panic!["wrong error when calling tmap() with incorrect type"]; },
Ok(_) => { panic!["expected error when calling tmap() with incorrect type, but \
received Ok"]; }
}
}
}