bascet 0.4.0

Bascet is a tool to preprocess single-cell data, handling barcode detection, trimming, QC, and managing the execution of custom tools for each cell
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
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::sync::Arc;
use std::fmt;

use super::ZipBascetShardReader;
use super::TirpBascetShardReader;
use super::DetectedFileformat;


/////////////////////////////// 
/// Type: Cell ID
pub type CellID = String;

/////////////////////////////// 
/// Type: UMI (unique molecular identifier)
pub type CellUMI = Vec<u8>;

type ListReadWithBarcode = Arc<(CellID,Arc<Vec<ReadPair>>)>;


///////////////////////////////
/// One pair of reads with a UMI
#[derive(Debug,Clone)]
pub struct ReadPair {
    pub r1: Vec<u8>,
    pub r2: Vec<u8>,
    pub q1: Vec<u8>,
    pub q2: Vec<u8>,
    pub umi: Vec<u8>
}
impl fmt::Display for ReadPair {

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {}, {})", 
            String::from_utf8_lossy(self.r1.as_slice()), 
            String::from_utf8_lossy(self.r2.as_slice()) ,
            String::from_utf8_lossy(self.umi.as_slice()) 
        )
    }
}



///////////////////////////////
/// A constructor of objects given a path (a type of factory)
pub trait ConstructFromPath<R> where Self: Clone { ///+Sized added later
    fn new_from_path(&self, fname: &PathBuf) -> anyhow::Result<R> where Self: Sized;
}


///////////////////////////////
/// A writer of pairs of reads for a cell
pub trait ReadPairWriter {

    /////////////////////////////// 
    /// Write all read pairs for a given cell
    fn write_reads_for_cell(
        &mut self, 
        cell_id: &CellID, 
        list_reads: &Arc<Vec<ReadPair>>
    );

    fn writing_done(&mut self) -> anyhow::Result<()>;
}

///////////////////////////////
/// A random reader of pairs of reads from a cell
pub trait ReadPairReader { 

    /////////////////////////////// 
    /// Read all read pairs for a given cell
    fn get_reads_for_cell(
        &mut self, 
        cell_id: &CellID
    ) -> anyhow::Result<Arc<Vec<ReadPair>>>;

}

///////////////////////////////
/// A streaming reader of pairs of reads from a cell
pub trait StreamingReadPairReader { 

    /// Read all read pairs for the next cell being streamed
    fn get_reads_for_next_cell(
        &mut self
    ) -> anyhow::Result<Option<ListReadWithBarcode>>;

}


///////////////////////////////
/// A file that can return which cells are present in it
pub trait ShardCellDictionary {

    /////////////////////////////// 
    /// Get list of cells in this file
    fn get_cell_ids(&mut self) -> anyhow::Result<Vec<CellID>>;

    /////////////////////////////// 
    /// Check if a cell is present
    fn has_cell(&mut self, cellid: &CellID) -> bool;

}

/////////////////////////////// 
/// Common shard reader trait  -- random I/O
pub trait ShardRandomFileExtractor { 

    /////////////////////////////// 
    /// Extract requested files to a directory
    fn extract_to_outdir (
        &mut self, 
        cell_id: &CellID, 
        needed_files: &Vec<String>,
        fail_if_missing: bool,
        out_directory: &PathBuf
    ) -> anyhow::Result<bool>;

    /////////////////////////////// 
    /// Return a list of files associated with given cell
    fn get_files_for_cell(
        &mut self, 
        cell_id: &CellID
    ) -> anyhow::Result<Vec<String>>;

    /////////////////////////////// 
    /// Extract specified file to path
    fn extract_as(
        &mut self, 
        cell_id: &String, 
        file_name: &String,
        path_outfile: &PathBuf
    ) -> anyhow::Result<()>;

}


/////////////////////////////// 
/// Common shard reader trait   -- streaming I/O
pub trait ShardStreamingFileExtractor  { //Or CellFileExtractor, make common to above

    /////////////////////////////// 
    /// Move to the next cell in the stream
    fn next_cell (
        &mut self, 
    ) -> anyhow::Result<Option<CellID>>;

    /////////////////////////////// 
    /// Extract requested files to a directory
    fn extract_to_outdir (
        &mut self, 
        needed_files: &Vec<String>,
        fail_if_missing: bool,
        out_directory: &PathBuf
    ) -> anyhow::Result<bool>;

    /////////////////////////////// 
    /// Return a list of files associated with given cell
    fn get_files_for_cell(
        &mut self
    ) -> anyhow::Result<Vec<String>>;

}






///////////////////////////////
/// An enum holding the type of readers that Bascet supports.
/// instead of dyn, an enum might be a better choice to cover all the different traits being implemented, since not every reader has every property!
pub enum DynShardReader {
    TirpBascetShardReader(TirpBascetShardReader),
    ZipBascetShardReader(ZipBascetShardReader)
}
impl ShardCellDictionary for DynShardReader {

    fn get_cell_ids(&mut self) -> anyhow::Result<Vec<CellID>> {
        match self {
            DynShardReader::TirpBascetShardReader(r) => r.get_cell_ids(),
            DynShardReader::ZipBascetShardReader(r) => r.get_cell_ids()
        }
    }
    fn has_cell(&mut self, cellid: &CellID) -> bool {
        match self {
            DynShardReader::TirpBascetShardReader(r) => r.has_cell(&cellid),
            DynShardReader::ZipBascetShardReader(r) => r.has_cell(&cellid)
        }
    }

}
impl ShardRandomFileExtractor for DynShardReader {

    fn extract_to_outdir (
        &mut self, 
        cell_id: &CellID, 
        needed_files: &Vec<String>,
        fail_if_missing: bool,
        out_directory: &PathBuf
    ) -> anyhow::Result<bool> {
        match self {
            DynShardReader::TirpBascetShardReader(r) => r.extract_to_outdir(&cell_id, &needed_files, fail_if_missing, &out_directory),
            DynShardReader::ZipBascetShardReader(r) => r.extract_to_outdir(&cell_id, &needed_files, fail_if_missing, &out_directory),
        }
    }

    fn get_files_for_cell(
        &mut self, 
        cell_id: &CellID
    ) -> anyhow::Result<Vec<String>> {
        match self {
            DynShardReader::TirpBascetShardReader(r) => r.get_files_for_cell(&cell_id),
            DynShardReader::ZipBascetShardReader(r) => r.get_files_for_cell(&cell_id)
        }
    }

    fn extract_as(
        &mut self, 
        cell_id: &String, 
        file_name: &String,
        path_outfile: &PathBuf
    ) -> anyhow::Result<()> {
        match self {
            DynShardReader::TirpBascetShardReader(r) => r.extract_as(&cell_id, &file_name, &path_outfile),
            DynShardReader::ZipBascetShardReader(r) => r.extract_as(&cell_id, &file_name, &path_outfile),
        }
    }

}




///////////////////////////////
/// Given a path, get a suitable shard reader
pub fn get_shard_reader_for_path(p: &PathBuf) -> anyhow::Result<DynShardReader> {
    match crate::fileformat::detect_shard_format(&p) {
        DetectedFileformat::TIRP => {
            Ok(DynShardReader::TirpBascetShardReader(TirpBascetShardReader::new(p).expect(format!("Failed to read {}",p.display()).as_str())))
        },
        DetectedFileformat::ZIP => {
            Ok(DynShardReader::ZipBascetShardReader(ZipBascetShardReader::new(p).expect(format!("Failed to read {}",p.display()).as_str())))
        },
        _ => { 
            anyhow::bail!("File format for {} does not support listing of cell IDs", p.display()) 
        }
    }
}




///////////////////////////////
/// Given a path to a shard file, get a dictionary that can return which cells are in it
pub fn get_dyn_celldict(
    p: &PathBuf
) -> anyhow::Result<Box<dyn ShardCellDictionary>> {

    match crate::fileformat::detect_shard_format(&p) {
        DetectedFileformat::TIRP => {
            Ok(Box::new(TirpBascetShardReader::new(p).expect(format!("Unable to read cell list for {}",p.display()).as_str())))
        },
        DetectedFileformat::ZIP => {
            Ok(Box::new(ZipBascetShardReader::new(p).expect(format!("Unable to read cell list for {}",p.display()).as_str())))
        },
        _ => { 
            anyhow::bail!("File format for {} does not support listing of cell IDs", p.display()) 
        }
    }

}


///////////////////////////////
/// Try to figure out what cells are present in an input file.           
/// If we cannot list the cells for this file then it will have to stream all the content
pub fn try_get_cells_in_file(
    p: &PathBuf
) -> anyhow::Result<Option<Vec<CellID>>> {

    let mut cell_dict = get_dyn_celldict(p).
        expect(format!("Unable to read cell list for {}",p.display()).as_str());
    Ok(Some(cell_dict.get_cell_ids().unwrap()))
    
}






























/////////////////////////////// 
/// Row in a histogram for cell barcode counting (used for serialization)
#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
struct BarcodeHistogramRow {
    bc: String,
    cnt: u64
}

/////////////////////////////// 
/// Histogram for cell barcode counting
pub struct BarcodeHistogram {
    histogram: HashMap<CellID, u64>
}
impl BarcodeHistogram {

    /// Create a new empty histogram
    pub fn new() -> BarcodeHistogram {
        BarcodeHistogram {
            histogram: HashMap::new()
        }
    }

    /// Increment the count of one cell by 1
    pub fn inc(
        &mut self, 
        cellid: &CellID
    ){        
        let counter = self.histogram.entry(cellid.clone()).or_insert(0);
        *counter += 1;
    }

    /// Increment the count of one cell
    pub fn inc_by(
        &mut self, 
        cellid: &CellID, 
        cnt: &u64
    ){        
        let counter = self.histogram.entry(cellid.clone()).or_insert(0);
        *counter += cnt;
    }

    /// Add a histogram to this histogram
    pub fn add_histogram(
        &mut self, 
        other: &BarcodeHistogram
    ) {
        for (cellid,v) in other.histogram.iter() {
            let counter = self.histogram.entry(cellid.clone()).or_insert(0);
            *counter += v;    
        }
    }

    /// Read histogram from file
    pub fn from_file(
        fname: &PathBuf
    ) -> anyhow::Result<BarcodeHistogram> {

        //Open file
        let file = File::open(fname)?;
        let reader= BufReader::new(file);

        //Read it as a CSV file
        let mut hist = BarcodeHistogram::new();
        let mut reader = csv::ReaderBuilder::new()
            .delimiter(b'\t')
            .from_reader(reader);
        for result in reader.deserialize() {
            let record: BarcodeHistogramRow = result.unwrap();
            hist.histogram.insert(record.bc, record.cnt);
        }
        Ok(hist)
    }

    /// Write histogram to file
    pub fn write_file(
        &self, 
        fname: &PathBuf
    ) -> anyhow::Result<()> {

            //Open file
            let mut writer = csv::WriterBuilder::new()
                .delimiter(b'\t')
                .from_path(fname)
                .expect("Could not open histogram file for writing");

            for (bc, cnt) in self.histogram.iter() {
                let _ = writer.serialize(BarcodeHistogramRow {
                    bc: bc.to_string(),
                    cnt: *cnt
                });
            }

            let _ = writer.flush();
        Ok(())
    }


}