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
//! RavenCol
//!
//! `RavenCol` is a collection of utilities for processing data for data analysis. Up to now it can reads data only from CSV files.
//! 
use std::error::Error;
use std::ffi::OsString;

/// Enum to contain a datum, it can be an Integer, a Float, an String or None.
#[derive(Debug, PartialEq)]
pub enum Datum<'a> {
    Integer(i32),
    Float(f64),
    NotNumber(&'a str),
    None
}

/// Main data struct. It contains a vec of StringRecords and the name of the columns from the CSV file.
/// 
/// The normal way of creating a RawFrame is from a CSV file. This file will be parsed with CSV crate functions.
/// The struct has a creator method using os_strings as path for the CSV file and a creator method form terminal arg in position n.
/// 
/// A RawFrame is similir to a DataFrame. It is a tabular data structure. 
/// It is possible to operate over columns which are created with methods.
/// All the column extraction methods return iterators, the main objective extracting a column is to operate with it.
/// The intention is ti produce an iterator which is consumed in the column calculation.
/// 
/// In order to computo over columns it is important to decide the type of datum to use in the calculation and if the operation
/// needs full columns or only parsed valid columns for the required type.
/// 
/// Once the type of the column is decided it is necessary to decide what to do with the data which is not possible to parse to this type.
/// Three options are provided. Keep it blank through Option types, impute it with a none_value or filter them out of the column.
#[derive(Debug)]
pub struct RawFrame {
    pub records: Vec<csv::StringRecord>,
    pub columns: csv::StringRecord,
}

impl RawFrame {
    /// Creates a RawFrame from an os_string.
    /// 
    /// # Arguments
    ///
    /// * `file_path` - An OsString that holds the path of CSV file
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use std::ffi::OsString;
    ///
    /// let path = OsString::from("./datos_test/test.csv");
    /// let datos = RawFrame::from_os_string(path).unwrap();
    /// ```
    pub fn from_os_string(file_path: OsString) -> Result<crate::RawFrame, Box<dyn Error>> {

        let (columns,records) = crate::reading::get_data_src_h(file_path)?;

        Ok(crate::RawFrame{columns, records})

    }

    /// Creates a RawFrame from terminal argument in position n.
    /// 
    /// # Arguments
    ///
    /// * `n` - A usize that holds the position of the terminal argument on which is the path of CSV file
    pub fn from_arg(n: usize) -> Result<crate::RawFrame, Box<dyn Error>> {

        let ruta = crate::reading::read_arg(n)?;
        let datos = crate::RawFrame::from_os_string(ruta)?;

        Ok(datos)

    }

    pub fn concat(&mut self, cola: crate::RawFrame) -> Result<(), Box<dyn Error>> {

        if &self.columns.len() != &cola.columns.len() {
            return Err(From::from("El número de columnas no es el mismo"))
        }

        self.records.extend(cola.records);

        Ok(())
    }

    /// Returns the position index for column in RawFrame or None if column does not exists.
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// assert_eq!(datos.col_index("col_b"),Some(1));
    /// ```
    pub fn col_index(&self, column: &str) -> Option<usize> {
        let cadena = String::from(column);
        self.columns.iter().position(|col| col == cadena)
    }

    /// Returns the position index for column in RawFrame or Error if column does not exists.
    fn col_position(&self, column: &str) -> Result<usize,Box<dyn Error>> {
        match self.col_index(column) {
            Some(n) => Ok(n),
            None => Err(From::from("No existe la columna"))
        }
    }

    /// Returns a full column of Datum. 
    /// The column is in a consumible iterator. Each element has Datum type. All the valid rows are included.
    /// The Datum type mixes several posibilities of types, this generates a general column.
    /// For simple operations or plotting use specific type columns.
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<Datum> = datos.column("col_a").unwrap().collect();
    /// ```
    pub fn column(&self, column: &str) -> Result<impl Iterator<Item=Datum> + '_,Box<dyn Error>>{
    
        let position = self.col_position(column)?;

        Ok(self.records.iter().map(move |record| {
            match record.get(position) {
                None => Datum::None,
                Some(cadena) => match cadena.parse::<i32>() {
                    Ok(num) => Datum::Integer(num),
                    _ => match cadena.parse::<f64>() {
                        Ok(num) => Datum::Float(num),
                        _ => Datum::NotNumber(cadena)
                    },
                }
            }
        }))
    }

    /// Returns a full column of a generic type. 
    /// The column is in a consumible iterator. Each element has Option<T> type. All the valid rows are included.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method feels repetitive with methods that returns specific type columns because was created after the definition of those.
    /// In the future the specific type columns will dissapear.
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<Option<i32>> = datos.col_type("col_a").unwrap().collect();
    /// ```
    pub fn col_type<T>(&self, column: &str) -> Result<impl Iterator<Item=Option<T>> + '_,Box<dyn Error>>
    where T: std::str::FromStr
    {

        let position = self.col_position(column)?;

        Ok(self.records.iter().map(move |record| {
            match record.get(position) {
                None => None,
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => Some(num),
                    _ => None
                } 
            }
        }))

    }

    /// Returns a filtered column of generic type filtering for only the possible to parse data. 
    /// The column is in a consumible iterator. Each element has T type. Only the valid parsed rows are included.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method has a variable number of elements related to the rows in the RawDataframe, use it with caution.
    /// This method feels repetitive with methods that returns specific type columns because was created after the definition of those.
    /// In the future the specific type columns will dissapear.
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<i32> = datos.col_fil("col_a").unwrap().collect();
    /// ```
    pub fn col_fil<T>(&self, column: &str) -> Result<impl Iterator<Item=T> + '_,Box<dyn Error>>
    where T: std::str::FromStr
    {
        
        let position = self.col_position(column)?;

        Ok(self.records.iter().filter_map(move |record| {
            match record.get(position) {
                None => None,
                Some(cadena) => cadena.parse::<T>().ok()
            }
        }))
    }

    /// Returns a full column of a generic type imputing none_val in the impossible to parse data. 
    /// The column is in a consumible iterator. Each element has T type. All the valid rows are included.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method feels repetitive with methods that returns specific type columns because was created after the definition of those.
    /// In the future the specific type columns will dissapear.
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    /// 
    /// * `none_val` - value for imputing the impossible to parse values
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<i32> = datos.col_imp("col_a",0).unwrap().collect();
    /// ```
    pub fn col_imp<T>(&self, column: &str, none_val:T) -> Result<impl Iterator<Item=T> + '_,Box<dyn Error>>
    where T: std::str::FromStr + Clone + 'static
    {

        let position = self.col_position(column)?;

        Ok(self.records.iter().map(move |record| {
            match record.get(position) {
                None => none_val.clone(),
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => num,
                    _ => none_val.clone()
                }
            }
        })) 

    }

    /// Returns the maximum value of a column. The type is generic for comparable types, in order to compare floats is necessary to define std::cmp::Ord or use ordered-float crate or similar
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let maximo: i32 = datos.max_num_fil("col_a").unwrap();
    /// ```
    pub fn max_num_fil<T>(&self, column: &str) -> Result<T,Box<dyn Error>>
    where T: std::str::FromStr + std::cmp::Ord
    {

        let iter = self.col_fil(column)?;

        match iter.max() {
            None => Err(From::from("No se encontró el máximo")),
            Some(val) => Ok(val)
        }

    }

    /// Returns the minimum value of a column. The type is generic for comparable types, in order to compare floats is necessary to define std::cmp::Ord or use ordered-float crate or similar
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let minimo: i32 = datos.min_num_fil("col_a").unwrap();
    /// ```
    pub fn min_num_fil<T>(&self, column: &str) -> Result<T,Box<dyn Error>>
    where T: std::str::FromStr + std::cmp::Ord
    {

        let iter = self.col_fil(column)?;

        match iter.min() {
            None => Err(From::from("No se encontró el mínimo")),
            Some(val) => Ok(val)
        }

    }

    /// Returns the extent of range of a column. A tuple with minimum and maximum. The type is generic for comparable types, in order to compare floats is necessary to define std::cmp::Ord or use ordered-float crate or similar
    /// 
    /// # Arguments
    ///
    /// * `column` - A string slice that holds the name of the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let extent: (i32,i32) = datos.extent_num_fil("col_a").unwrap();
    /// ```
    pub fn extent_num_fil<T>(&self, column: &str) -> Result<(T,T),Box<dyn Error>>
    where T: std::str::FromStr + std::cmp::Ord
    {
        let maximo = self.max_num_fil(column)?;
        let minimo = self.min_num_fil(column)?;

        Ok((minimo,maximo))
    }

    /// Returns a pair of columns of generic type filtering for rows where both values can be parsed. 
    /// The result is in a consumible iterator. Each element is a tuple of T type.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method has a variable number of elements related to the rows in the RawDataframe, use it with caution.
    /// This method is mainly used for compute operations between two columns and to generate a pair of coordinates to plot.
    /// 
    /// # Arguments
    ///
    /// * `xcolumn` - A string slice that holds the name of first the column
    /// * `ycolumn` - A string slice that holds the name of second the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let pairs: Vec<(f64,f64)> = datos.pair_col_fil("col_a","col_b").unwrap().collect();
    /// ```
    pub fn pair_col_fil<T>(&self, xcolumn: &str, ycolumn: &str) -> Result<impl Iterator<Item=(T,T)> + '_,Box<dyn Error>>
    where T: std::str::FromStr
    {

        let xposition = self.col_position(xcolumn)?;

        let yposition = self.col_position(ycolumn)?;

        Ok(self.records.iter().filter_map(move |record| {
            let xval = match record.get(xposition) {
                None => None,
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => Some(num),
                    _ => None
                } 
            };

            let yval = match record.get(yposition) {
                None => None,
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => Some(num),
                    _ => None
                } 
            };
            
            match (xval,yval) {
                (Some(valx),Some(valy)) => Some((valx,valy)),
                _ => None,
            }
        }))

    }

    /// Returns a pair of columns of generic type imputing in the impossible to parse data none_val_x for the first column and none_val_y for the second column. 
    /// The result is in a consumible iterator. Each element is a tuple of T type. All the valid rows are included.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method is mainly used for compute operations between two columns and to generate a pair of coordinates to plot.
    /// 
    /// # Arguments
    ///
    /// * `xcolumn` - A string slice that holds the name of first the column
    /// * `ycolumn` - A string slice that holds the name of second the column
    /// 
    /// * `none_val_x` - value for imputing the impossible to parse values for the first column
    /// * `none_val_y` - value for imputing the impossible to parse values for the second column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<i32> = datos.col_imp("col_a",0).unwrap().collect();
    /// ```
    pub fn pair_col_imp<T>(&self, xcolumn: &str, ycolumn: &str, none_val_x:T, none_val_y:T) -> Result<impl Iterator<Item=(T,T)> + '_,Box<dyn Error>>
    where T: std::str::FromStr + Clone + 'static
    {

        let xposition = self.col_position(xcolumn)?;

        let yposition = self.col_position(ycolumn)?;

        Ok(self.records.iter().map(move |record| {
            let xval = match record.get(xposition) {
                None => none_val_x.clone(),
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => num,
                    _ => none_val_x.clone()
                } 
            };

            let yval = match record.get(yposition) {
                None => none_val_y.clone(),
                Some(cadena) => match cadena.parse::<T>() {
                    Ok(num) => num,
                    _ => none_val_y.clone()
                } 
            };
            
            (xval,yval)
        }))

    }

    /// Returns a slice of columns of generic type imputing in the impossible to parse data the values in the imp_vals Vec. 
    /// The result is in a consumible iterator. Each element is a vec of T type. All the valid rows are included.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method is mainly used for compute operations between two columns and to generate a pair of coordinates to plot.
    /// 
    /// # Arguments
    ///
    /// * `columns` - A Vec of string slices that holds the names of the columns to get
    /// 
    /// * `imp_vals` - values for imputing the impossible to parse values, it has the same order of columns
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// } 
    /// 
    /// let datos = get_data();
    /// 
    /// let col: Vec<Vec<i32>> = datos.slice_col_imp(vec!["col_a","col_b"],vec![0,0]).unwrap().collect();
    /// ```
    pub fn slice_col_imp<T>(&self, columns: Vec<&str>, imp_vals: Vec<T>) -> Result<impl Iterator<Item=Vec<T>> + '_,Box<dyn Error>> 
    where T: std::str::FromStr + Clone + 'static
    {

        let positions = columns.iter().map(|col| self.col_position(col).unwrap()).collect::<Vec<usize>>();

        Ok(self.records.iter().map(move |record| {
            positions.iter().zip(imp_vals.iter()).map(|tup|{
                match record.get(*tup.0) {
                    None => tup.1.clone(),
                    Some(cadena) => match cadena.parse::<T>() {
                        Ok(num) => num,
                        _ => tup.1.clone()
                    }
                }
            }).collect::<Vec<T>>()
        }))
    }

    /// Returns a slice of columns of generic type filtering for rows where all values can be parsed. 
    /// The result is in a consumible iterator. Each element is a vec of T type.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method has a variable number of elements related to the rows in the RawDataframe, use it with caution.
    /// 
    /// # Arguments
    ///
    /// * `columns` -A Vec of string slices that holds the names of the columns to get
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let pairs: Vec<Vec<f64>> = datos.slice_col_fil(vec!["col_a","col_b"]).unwrap().collect();
    /// ```
    pub fn slice_col_fil<T>(&self, columns: Vec<&str>) -> Result<impl Iterator<Item=Vec<T>> + '_,Box<dyn Error>> 
    where T: std::str::FromStr + Clone
    {

        let positions = columns.iter().map(|col| self.col_position(col).unwrap()).collect::<Vec<usize>>();

        Ok(self.records.iter().filter_map(move |record| {
            let row = positions.iter().map(|pos|{
                match record.get(*pos) {
                    None => None,
                    Some(cadena) => match cadena.parse::<T>() {
                        Ok(num) => Some(num),
                        _ => None
                    }
                }
            }).collect::<Vec<Option<T>>>();

            match row.iter().all(|ele| ele.is_some()) {
                true => Some(row.iter().map(move |val| val.as_ref().cloned().unwrap()).collect::<Vec<T>>()),
                false=> None
            }
        }))

    }

    /// Returns a pair of columns of generic type sorted by values on first column. Imputing in the impossible to parse data none_val_x for the first column and none_val_y for the second column. 
    /// The result is in a consumible iterator. Each element is a tuple of T type.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method has a variable number of elements related to the rows in the RawDataframe, use it with caution.
    /// This method has a different order related to the rows in the RawDataframe, use it with caution.
    /// This method is mainly used for compute operations between two columns and to generate a pair of coordinates to plot.
    /// 
    /// # Arguments
    ///
    /// * `xcolumn` - A string slice that holds the name of first the column
    /// * `ycolumn` - A string slice that holds the name of second the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let pairs: Vec<(f64,f64)> = datos.pair_col_fil_sorted("col_a","col_b").unwrap().collect();
    /// ```
    pub fn pair_col_fil_sorted<T>(&self, xcolumn: &str, ycolumn: &str) -> Result<impl Iterator<Item=(T,T)> + '_,Box<dyn Error>>
    where T: std::str::FromStr + std::cmp::PartialOrd + 'static
    {

        let mut temp_vec: Vec<(T,T)> = self.pair_col_fil(xcolumn, ycolumn).unwrap().collect();
        temp_vec.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        Ok(temp_vec.into_iter())

    }

    /// Returns a pair of columns of generic type sorted by values on first column. Filtering for rows where both values can be parsed. 
    /// The result is in a consumible iterator. Each element is a tuple of T type.
    /// The generic type is specified in the definition of the variable in which the iterator will bind.
    /// This method has a variable number of elements related to the rows in the RawDataframe, use it with caution.
    /// This method has a different order related to the rows in the RawDataframe, use it with caution.
    /// This method is mainly used for compute operations between two columns and to generate a pair of coordinates to plot.
    /// 
    /// # Arguments
    ///
    /// * `xcolumn` - A string slice that holds the name of first the column
    /// * `ycolumn` - A string slice that holds the name of second the column
    ///
    /// # Examples
    ///
    /// ```
    /// use ravencol::RawFrame;
    /// use ravencol::Datum;
    /// use std::ffi::OsString;
    ///
    /// fn get_data() -> ravencol::RawFrame {
    ///     let path = OsString::from("./datos_test/test.csv");
    ///     let datos = RawFrame::from_os_string(path).unwrap();
    ///     datos
    /// }
    /// 
    /// let datos = get_data();
    /// 
    /// let pairs: Vec<(f64,f64)> = datos.pair_col_imp_sorted("col_a","col_b",0.0,0.0).unwrap().collect();
    /// ```
    pub fn pair_col_imp_sorted<T>(&self, xcolumn: &str, ycolumn: &str, none_val_x:T, none_val_y:T) -> Result<impl Iterator<Item=(T,T)> + '_,Box<dyn Error>>
    where T: std::str::FromStr + std::cmp::PartialOrd + Copy + 'static
    {

        let mut temp_vec: Vec<(T,T)> = self.pair_col_imp(xcolumn, ycolumn, none_val_x, none_val_y).unwrap().collect();
        temp_vec.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        Ok(temp_vec.into_iter())

    }


}

pub mod utils {
    //! Auxiliar module with handy methods.

    /// Allows to filter an iter with an iter of bools.
    /// 
    /// # Arguments
    ///
    /// * `boolean_iter` - Iter of bool. The returned filter will have only wlwmwnts for which this iter has true value.
    /// * `target_iter` - Target iter to filter
    pub fn bool_filter<T>(boolean_iter: impl Iterator<Item=bool>, target_iter: impl Iterator<Item=T>) -> impl Iterator<Item=T>{

        boolean_iter.zip(target_iter).filter(|tup| tup.0).map(|truetup| truetup.1)

    } 

}

pub mod writing {
    //! Auxiliar module for writing CSV files.

    use std::ffi::OsString;
    use std::error::Error;

    /// Write a csv file from an iter. It is necessary that the elements of the iter are vecs of a defined type. In order to write an iter obtained from column producer methods of RawFrame it must be casted to a type first
    pub fn to_csv_iter<T>(path: OsString, columns: Vec<&str>, iterador: impl Iterator<Item=Vec<T>>) -> Result<(), Box<dyn Error>>
    where T: std::convert::AsRef<[u8]>
    {

        let mut wtr = csv::Writer::from_path(path)?;

        wtr.write_record(columns)?;

        for record in iterador {
            wtr.write_record(record)?;
        }

        wtr.flush()?;

        Ok(())

    }
}

pub mod reading {
    //! Auxiliar module for reading CSV files.

    use std::env;
    use std::error::Error;
    use std::ffi::OsString;
    use std::collections::HashMap;

    /// Returns an OsString for terminal argument in position n or an error if it is not possible to read it
    pub fn read_arg(n: usize) -> Result<OsString, Box<dyn Error>> {
        match env::args_os().nth(n) {
            Some(file_path) => Ok(file_path),
            None => Err(From::from("No se pudo leer el argumento"))
        }
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row is represented as a csv::StringRecord
    pub fn get_data_src(file_path: OsString) -> Result<(csv::StringRecord,Vec<csv::StringRecord>), Box<dyn Error>> {

        let mut vector: Vec<csv::StringRecord> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

        let columns = rdr.headers()?.clone();

        for result in rdr.records() {
            let record = result?;
            vector.push(record);
        }

        Ok((columns,vector))
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row is represented as a Vec<String>
    pub fn get_data_vec(file_path: OsString) -> Result<(csv::StringRecord,Vec<Vec<String>>), Box<dyn Error>> {

        let mut vector: Vec<Vec<String>> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

        let columns = rdr.headers()?.clone();

        for result in rdr.deserialize() {
            let record: Vec<String> = result?;
            vector.push(record);
        }

        Ok((columns,vector))
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row are represented as a HashMap
    pub fn get_data_hsm(file_path: OsString) -> Result<(csv::StringRecord,Vec<HashMap<String, String>>), Box<dyn Error>> {

        let mut vector: Vec<HashMap<String, String>> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

        let columns = rdr.headers()?.clone();

        for result in rdr.deserialize() {
            let record: HashMap<String, String> = result?;
            vector.push(record);
        }

        Ok((columns,vector))
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row are represented as a csv::ByteRecord
    pub fn get_data_brc(file_path: OsString) -> Result<(csv::StringRecord,Vec<csv::ByteRecord>), Box<dyn Error>> {

        let mut vector: Vec<csv::ByteRecord> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

        let columns = rdr.headers()?.clone();

        for result in rdr.byte_records() {
            let record = result?;
            vector.push(record);
        }

        Ok((columns,vector))
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row are represented as a csv::StringRecord
    pub fn get_data_src_h(file_path: OsString) -> Result<(csv::StringRecord,Vec<csv::StringRecord>), Box<dyn Error>> {

        let mut vector: Vec<csv::StringRecord> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

        let columns = rdr.byte_headers()?.clone();
        let columns = csv::StringRecord::from_byte_record_lossy(columns);

        let mut iter = rdr.into_records();

        loop {
            let row = match iter.next() {
                Some(rec) => rec,
                None => break,
            };

            let record = match row {
                Ok(rec) => rec,
                Err(_) => continue,
            };

            vector.push(record);
        }

        Ok((columns,vector))
    }

    /// Returns a tuple with column names and a Vec of rows in a csv file. Each row are represented as a csv::StringRecord
    pub fn get_data_brc_h(file_path: OsString) -> Result<(csv::StringRecord,Vec<csv::StringRecord>), Box<dyn Error>> {

        let mut vector: Vec<csv::StringRecord> = Vec::new();

        let mut rdr = csv::ReaderBuilder::new()
            .flexible(true)
            .trim(csv::Trim::All)
            .from_path(file_path)?;

            let columns = rdr.byte_headers()?.clone();
            let columns = csv::StringRecord::from_byte_record_lossy(columns);

        let mut iter = rdr.into_byte_records();

        loop {
            let row = match iter.next() {
                Some(rec) => rec,
                None => break,
            };

            let record = match row {
                Ok(rec) => csv::StringRecord::from_byte_record_lossy(rec),
                Err(_) => continue,
            };

            vector.push(record);
        }

        Ok((columns,vector))
    }

}