bustools 0.14.0

Interacting with the kallisto/bus format of scRNAseq data
Documentation
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
//! Advanced iterators over busrecords, grouping records by cell or molecule.
//! 
//! Allows to iterate over 
//! * cells (CB)
//! * mRNAs (CB+UMI)
//! * CB+UMI+gene: in case some CB/UMI collision
//! 
//! To iterate over a **sorted** busfile, grouping all records by CB:
//! ```rust, no_run
//! # use bustools::io::BusReader;
//! use bustools::iterators::CellGroupIterator; //need to bring that trait into scope
//! 
//! let breader = BusReader::new("/path/to/some.bus");
//! for (cb, vector_of_records) in breader.groupby_cb() {
//!     // Example: the number of records in that cell
//!     let n_molecules: usize = vector_of_records.len();
//! }
//! ```
//! 
//! To iterate over a **sorted** busfile, grouping all records by CB+UMI:
//! ```rust, no_run
//! # use bustools::io::BusReader; 
//! use bustools::iterators::CbUmiGroupIterator; //need to bring that trait into scope
//! 
//! let breader = BusReader::new("/path/to/some.bus");
//! for ((cb, umi), vector_of_records) in breader.groupby_cbumi() {
//!     // Example: the number of reads of that molecule (CB/UMI)
//!     let n_reads: u32 = vector_of_records.iter().map(|r| r.COUNT).sum();
//! }
//! ```
use crate::{
    consistent_genes::{groubygene, CUGset, Ec2GeneMapper},
    io::{BusRecord, CUGIterator},
};

/// groups an iterator over BusRecords by cell+umi
pub struct CbUmiGroup<I: CUGIterator> {
    iter: I,
    last_record: Option<BusRecord>, //option needed to mark the final element of the iteration
}

impl<I> Iterator for CbUmiGroup<I>
where I: CUGIterator,
{
    type Item = ((u64, u64), Vec<BusRecord>);
    fn next(&mut self) -> Option<Self::Item> {
        // let mut busrecords: Vec<BusRecord> = Vec::with_capacity(10); // storing the result to be emitted; capacity is small, since we dont expect many records for the same CB/UMI
        let mut busrecords: Vec<BusRecord> = Vec::new(); // storing the result to be emitted; capacity is small, since we dont expect many records for the same CB/UMI

        loop {
            // anything left in the basic iterator (if not, just emit whatever is stored in self.last_element)
            if let Some(new_record) = self.iter.next() {
                // the newly seen record
                let (new_cb, new_umi) = (new_record.CB, new_record.UMI);

                // take ownership of self.last_record, which we're goign to emit now (since we have a new item)
                // replace by the new item
                let last_record =
                    std::mem::replace(&mut self.last_record, Some(new_record)).unwrap();

                let (current_cb, current_umi) = (last_record.CB, last_record.UMI);

                busrecords.push(last_record); // the stored element from the previous iteration

                // now we just need to decide if we want to emit, or continue growing
                if new_cb > current_cb || (new_cb == current_cb && new_umi > current_umi) {
                    // we ran into a new CB/UMI and its records
                    // println!("\tyielding {:?}", (current_cb, &busrecords));

                    return Some(((current_cb, current_umi), busrecords));
                } else if new_cb == current_cb && new_umi == current_umi {
                    // nothing happens, just keep growing busrecords
                } else {
                    // the new cb is smaller then the current state: this is a bug due to an UNOSORTED busfile
                    panic!(
                        "Unsorted busfile: {}/{} -> {}/{}",
                        current_cb, current_umi, new_cb, new_umi
                    )
                }
            } else {
                // emit whatever is left in last element
                // we get the ownership and replace with None (which in the next iterator will trigger the end of the entire iterator)
                // to mark the end of iteration and all items emitted, set last_item to None
                // let last_record = std::mem::replace(&mut self.last_record, None);
                let last_record = self.last_record.take(); // swaps the current value for None; clippy suggestion to std::mem::replace
                                                           // get the last element and emit
                if let Some(r) = last_record {
                    // we ran pas the last entry of the file
                    // FINALize the last emit
                    let current_cb = r.CB;
                    let current_umi = r.UMI;
                    busrecords.push(r);
                    return Some(((current_cb, current_umi), busrecords));
                } else {
                    return None;
                }
            }
        }
    }
}

impl<I> CbUmiGroup<I>
where I: CUGIterator,
{
    pub fn new(mut iter: I) -> Self {
        let last_record = iter.next(); //initilize with the first record in the file
        Self { iter, last_record }
    }
}

pub struct CbUmiGroupFaster<I: CUGIterator> {
    iter: I,
    current_records: Vec<BusRecord>, //option needed to mark the final element of the iteration
    current_cbumi: (u64, u64),
}
impl<I> CbUmiGroupFaster<I>
where I: CUGIterator,
{
    pub fn new(mut iter: I) -> Self {
        let last_record = iter.next().expect("min one item needed"); //initilize with the first record in the file
        let current_cbumi = (last_record.CB, last_record.UMI);
        let current_records = vec![last_record];
        Self { iter, current_records, current_cbumi }
    }
}
impl<I> Iterator for CbUmiGroupFaster<I>
where I: CUGIterator,
{
    type Item = ((u64, u64), Vec<BusRecord>);
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // anything left in the basic iterator (if not, just emit whatever is stored in self.last_element)
            if let Some(new_record) = self.iter.next() {
                // the newly seen record
                let new_cbumi = (new_record.CB, new_record.UMI);

                match new_cbumi.cmp(&self.current_cbumi){
                    std::cmp::Ordering::Equal => { self.current_records.push(new_record); },// the stored element from the previous iteration
                    std::cmp::Ordering::Less => {panic!("Unsorted busfile: {:?} -> {:?}", self.current_cbumi, new_cbumi)},
                    std::cmp::Ordering::Greater => {
                        let new_records = vec![new_record];
                        let to_emit = std::mem::replace(&mut self.current_records, new_records);
                        let current_cbumi = std::mem::replace(&mut self.current_cbumi, new_cbumi);
                        return Some((current_cbumi, to_emit));  
                    },
                }
            } else {
                // note: this is the last iteration, but next() will be called once more, expected to yield None!
                let to_emit = std::mem::take(&mut self.current_records);
                let result = if !to_emit.is_empty() {
                    let current_cbumi = std::mem::take(&mut self.current_cbumi);
                    Some((current_cbumi, to_emit))        
                } else {
                    None // truely done now
                };
                return result    
            }
        }
    }
}

/// gets iterator chaining working! Just a wrapper around CbUmiGroupIterator::new()
pub trait CbUmiGroupIterator: CUGIterator + Sized {
    fn groupby_cbumi(self) -> CbUmiGroupFaster<Self> {
        CbUmiGroupFaster::new(self)
    }
}
// implements the .groupby_cbumi() synthax for any `CUGIterator`
impl<I: CUGIterator> CbUmiGroupIterator for I {}

//=================================================================================
/// groups an iterator over BusRecords by cell
pub struct CellGroup<I: CUGIterator> {
    iter: I,
    last_record: Option<BusRecord>, //option needed to mark the final element of the iteration
}

impl<I> Iterator for CellGroup<I>
where I: CUGIterator,
{
    type Item = (u64, Vec<BusRecord>);
    fn next(&mut self) -> Option<Self::Item> {
        // TODO: allocated every .next() call. maybe move into the struct?
        
        let mut busrecords: Vec<BusRecord> = Vec::new(); // storing the result to be emitted
        // let mut busrecords: Vec<BusRecord> = Vec::with_capacity(self.buffersize); // storing the result to be emitted

        loop {
            if let Some(new_record) = self.iter.next() {
                // the newly seen record
                let new_cb = new_record.CB;

                // take ownership of self.last_record, which we're goign to emit now (since we have a new item)
                // replace by the new item
                // note that before this line, self.last_record CANNOT logically be None, hence the unwrap.
                // If it is somethings wrong with my logic
                let last_record =
                    std::mem::replace(&mut self.last_record, Some(new_record)).unwrap();

                let current_cb = last_record.CB;

                busrecords.push(last_record); // the stored element from the previous iteration

                // now we just need to decide if we want to emit, or continue growing
                match new_cb.cmp(&current_cb) {
                    std::cmp::Ordering::Equal => {} //nothing happens, just keep growing busrecords
                    std::cmp::Ordering::Greater => {
                        return Some((current_cb, busrecords));
                    }
                    std::cmp::Ordering::Less => {
                        panic!("Unsorted busfile: {} -> {}", current_cb, new_cb)
                    }
                }
            } else {
                // get the last element and emit

                // we get the ownership and replace with None (which in the next iterator will trigger the end of the entire iterator)
                // to mark the end of iteration and all items emitted, set last_item to None
                // let last_record = std::mem::replace(&mut self.last_record, None);
                let last_record = self.last_record.take(); // swaps the current value for None; clippy suggestion to std::mem::replace

                if let Some(r) = last_record {
                    // we ran pas the last entry of the file
                    // FINALize the last emit
                    let current_cb = r.CB;
                    busrecords.push(r);
                    return Some((current_cb, busrecords));
                } else {
                    return None;
                }
            }
        }
    }
}

impl<I> CellGroup<I>
where I: CUGIterator,
{
    pub fn new(mut iter: I) -> Self {
        let last_record = iter.next(); //initilize with the first record in the file
        Self { iter, last_record }
    }
}

pub struct CellGroupFaster<I: CUGIterator> {
    iter: I,
    current_records: Vec<BusRecord>,
    current_cb: u64,
}
impl<I> CellGroupFaster<I>
where I: CUGIterator,
{
    pub fn new(mut iter: I) -> Self {
        let last_record = iter.next().expect("expected at least one value in iterator"); //initilize with the first record in the file
        let current_cb = last_record.CB;
        let current_records = vec![last_record];
        Self { iter, current_records, current_cb}
    }
}

impl<I> Iterator for CellGroupFaster<I>
where I: CUGIterator,
{
    type Item = (u64, Vec<BusRecord>);
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(new_record) = self.iter.next() {
                // the newly seen record
                let new_cb = new_record.CB;
                match new_cb.cmp(&self.current_cb) {
                    std::cmp::Ordering::Equal => { self.current_records.push(new_record) },  // just another record to add
                    std::cmp::Ordering::Less =>  { panic!("Unsorted busfile: {} -> {}", self.current_cb, new_cb) },
                    std::cmp::Ordering::Greater => {
                        // start a new recordlist, emit the old one
                        let new_records = vec![new_record];
                        let to_emit = std::mem::replace(&mut self.current_records, new_records);
                        let current_cb = std::mem::replace(&mut self.current_cb, new_cb);
                        return Some((current_cb, to_emit));  
                    },
                }
            } else {
                // note: this is the last iteration, but next() will be called once more, expected to yield None!
                let to_emit = std::mem::take(&mut self.current_records);
                let result = if !to_emit.is_empty() {
                    let current_cb = std::mem::take(&mut self.current_cb);
                    Some((current_cb, to_emit))        
                } else {
                    None // truely done now
                };
                return result   
            }
        }
    }
}


/// gets iterator chaining working! Just a wrapper around CellGroupIterator::new()
pub trait CellGroupIterator: CUGIterator + Sized {
    fn groupby_cb(self) -> CellGroupFaster<Self> {
        CellGroupFaster::new(self)
    }
}
impl<I: CUGIterator> CellGroupIterator for I {}

/// enables to group things by gene
/// `CbUmiIterator.iter().group_by_gene()`
/// works for any iterator yielding `Vec<BusRecord>`
pub struct GroupbyGene<I> {
    iter: I,
    ecmapper: Ec2GeneMapper,
}

impl<I> Iterator for GroupbyGene<I>
where
    I: Iterator<Item = Vec<BusRecord>>,
{
    type Item = Vec<CUGset>;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|v| groubygene(v, &self.ecmapper))
    }
}

impl<I> GroupbyGene<I> {
    pub fn new(iter: I, ecmapper: Ec2GeneMapper) -> Self {
        Self { iter, ecmapper }
    }
}

/// gets iterator chaining working! Just a wrapper around GroupbyGene::new() 
pub trait GroupbyGeneIterator<T>: Iterator<Item = T> + Sized {
    fn group_by_gene(self, ecmapper: Ec2GeneMapper) -> GroupbyGene<Self> {
        GroupbyGene::new(self, ecmapper)
    }
}
impl<T, I: Iterator<Item = T>> GroupbyGeneIterator<T> for I {}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};

    use crate::consistent_genes::{Ec2GeneMapper, Genename, EC};
    use crate::io::BusRecord;
    use crate::iterators::{CbUmiGroupIterator, CellGroup, CellGroupIterator};
    use crate::utils::vec2set;

    #[test]
    fn test_cb_single_elem() {
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let records = vec![r1.clone()];
        let mut it = records.into_iter().groupby_cb();

        assert_eq!(
            it.next(),
            Some((0, vec![r1]))
        );

        assert_eq!(
            it.next(),
            None
        );
    }

    #[test]
    fn test_cbumi_single_elem() {
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let records = vec![r1.clone()];
        let mut it = records.into_iter().groupby_cbumi();

        assert_eq!(
            it.next(),
            Some(((0,2), vec![r1]))
        );

        assert_eq!(
            it.next(),
            None
        );
    }

    #[test]
    fn test_cb_iter_last_element1() {
        // make sure everything is emitted, even if the last element is its own group
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 1, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };

        let records = vec![r1.clone(), r2.clone(), r3.clone()];
        let n: Vec<_> = records.clone().into_iter().groupby_cb().map(|(_cb, records)| records).collect();
        assert_eq!(n.len(), 2);

        let rlist = &n[1];
        assert_eq!(rlist.len(), 1);

        // another wayto initialize,  no chaining
        let iter = records.into_iter();
        let n: Vec<_> = CellGroup::new(iter).map(|(_cb, records)| records).collect();
        assert_eq!(n.len(), 2);

        let rlist = &n[1];
        assert_eq!(rlist.len(), 1);
    }

    #[test]
    fn test_cb_iter_last_element2() {
        // make sure everything is emitted, even if the last element has mutiple elements
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 1, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r4 = BusRecord { CB: 1, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let records = vec![r1.clone(), r2.clone(), r3.clone(), r4.clone()];
        let n: Vec<_> = records.into_iter().groupby_cb().collect();
        assert_eq!(n.len(), 2);

        let (_cb, rlist) = &n[1];
        assert_eq!(rlist.len(), 2);
    }

    #[test]
    fn test_cb_iter() {
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 1, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r4 = BusRecord { CB: 2, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };
        let r5 = BusRecord { CB: 2, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r6 = BusRecord { CB: 3, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };

        let records = vec![
            r1.clone(),
            r2.clone(),
            r3.clone(),
            r4.clone(),
            r5.clone(),
            r6.clone(),
        ];
        let n: Vec<(u64, Vec<BusRecord>)> = records.into_iter().groupby_cb().collect();

        assert_eq!(n.len(), 4);
        // println!("{:?}", n);
        // println!("First");
        let c1 = &n[0];
        assert_eq!(*c1, (0, vec![r1, r2]));

        // println!("Second");
        let c2 = &n[1];
        assert_eq!(*c2, (1, vec![r3]));

        // println!("Third");
        let c3 = &n[2];
        assert_eq!(*c3, (2, vec![r4, r5]));

        let c4 = &n[3];
        assert_eq!(*c4, (3, vec![r6]));

        // assert_eq!(n, vec![vec![r1,r2], vec![r3], vec![r4,r5]])
    }

    #[test]
    fn test_cbumi_iter() {
        let r1 = BusRecord { CB: 0, UMI: 1, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r4 = BusRecord { CB: 1, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };
        let r5 = BusRecord { CB: 1, UMI: 2, EC: 1, COUNT: 2, FLAG: 0 };
        let r6 = BusRecord { CB: 2, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };

        let records = vec![
            r1.clone(),
            r2.clone(),
            r3.clone(),
            r4.clone(),
            r5.clone(),
            r6.clone(),
        ];

        let cb_iter = records.into_iter().groupby_cbumi();
        let n: Vec<((u64, u64), Vec<BusRecord>)> = cb_iter.collect();
        // println!("{:?}", n);

        assert_eq!(n.len(), 5);
        // println!("{:?}", n);
        // println!("First");
        let c1 = &n[0];
        assert_eq!(*c1, ((0, 1), vec![r1, r2]));

        // println!("Second");
        let c2 = &n[1];
        assert_eq!(*c2, ((0, 2), vec![r3]));

        // println!("Third");
        let c3 = &n[2];
        assert_eq!(*c3, ((1, 1), vec![r4]));

        let c4 = &n[3];
        assert_eq!(*c4, ((1, 2), vec![r5]));

        let c5 = &n[4];
        assert_eq!(*c5, ((2, 1), vec![r6]));
        // assert_eq!(n, vec![vec![r1,r2], vec![r3], vec![r4,r5]])
    }

    #[test]
    #[should_panic(expected = "Unsorted busfile: 2 -> 0")]
    fn test_panic_on_unsorted() {
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 2, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r4 = BusRecord { CB: 0, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };
        let records = vec![r1, r2, r3, r4];
        records.into_iter().groupby_cb().count();
    }

    #[test]
    #[should_panic(expected = "Unsorted busfile: (2, 2) -> (0, 1)")]
    fn test_panic_on_unsorted_cbumi() {
        let r1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 21, EC: 1, COUNT: 2, FLAG: 0 };
        let r3 = BusRecord { CB: 2, UMI: 2, EC: 0, COUNT: 12, FLAG: 0 };
        let r4 = BusRecord { CB: 0, UMI: 1, EC: 1, COUNT: 2, FLAG: 0 };
        let records = vec![r1, r2, r3, r4];
        records.into_iter().groupby_cbumi().count();
    }

    use crate::iterators::GroupbyGeneIterator;
    #[test]
    fn test_groupby_genes() {
        let ec0: HashSet<Genename> = vec2set(vec![Genename("A".to_string())]);
        let ec1: HashSet<Genename> = vec2set(vec![Genename("B".to_string())]);
        let ec2: HashSet<Genename> =
            vec2set(vec![Genename("A".to_string()), Genename("B".to_string())]);
        let ec3: HashSet<Genename> =
            vec2set(vec![Genename("C".to_string()), Genename("D".to_string())]);

        let ec_dict: HashMap<EC, HashSet<Genename>> = HashMap::from([
            (EC(0), ec0.clone()),
            (EC(1), ec1.clone()),
            (EC(2), ec2.clone()),
            (EC(3), ec3.clone()),
        ]);

        let es = Ec2GeneMapper::new(ec_dict);

        // first sample: two records, with consistent gene A
        let r1 = BusRecord { CB: 0, UMI: 1, EC: 0, COUNT: 2, FLAG: 0 };
        let r2 = BusRecord { CB: 0, UMI: 1, EC: 2, COUNT: 2, FLAG: 0 };

        // second sample: two records, with consistent gene A the other consistent with gene B
        let s1 = BusRecord { CB: 0, UMI: 2, EC: 0, COUNT: 3, FLAG: 0 }; // A
        let s2 = BusRecord { CB: 0, UMI: 2, EC: 1, COUNT: 4, FLAG: 0 }; //B

        let records = vec![r1.clone(), r2.clone(), s1.clone(), s2.clone()];
        let cb_iter = records.into_iter().groupby_cbumi();

        let results: Vec<_> = cb_iter.map(|(_cbumi, r)| r).group_by_gene(es).collect();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].len(), 1);
        assert_eq!(results[1].len(), 2);

        println!("{:?}", results)
    }
}

// use itertools::{GroupBy, Itertools};
//  pub struct CbUmiGroup_GROUP {
//     grouped_iter: Box<dyn Iterator<Item=BusRecord>>,
// }

// impl Iterator for CbUmiGroup_GROUP
// {
//     type Item = ((u64, u64), Vec<BusRecord>);
//     fn next(&mut self) -> Option<Self::Item> {
//         self.grouped_iter.next()
//     }
// }

// impl CbUmiGroup_GROUP
// {
//     pub fn new(mut iter: dyn Iterator<Item=BusRecord> + Sized) -> Self {
//         let grouped_iter = iter.group_by(|r| (r.CB, *r));
//         Self { grouped_iter }
//     }
// }

// pub trait CbUmiGroup_GROUPIterator: CUGIterator + Sized {
//     fn groupby_cbumi(self) -> CbUmiGroup_GROUP {
//         CbUmiGroup_GROUP::new(self)
//     }
// }
// impl<I: CUGIterator> CbUmiGroup_GROUPIterator for I {}