xpclrs 1.0.0

A high-performance rust implementation of the XP-CLR method.
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*
This module provides the VCF/BCF-specific I/O functions.
*/
use crate::io::{consolidate_list, get_gt_index, gt2gcount, GenoData};
use anyhow::Result;
use counter::Counter;
use itertools::MultiUnzip;
use rust_htslib::bcf::{
    record::{Genotype, GenotypeAllele},
    IndexedReader, Read, Reader,
};
use std::{fmt::Display, path::Path};

// Data structure
// Define multiple readers for the indexed and unindexed XCF file
pub enum XcfReader {
    Indexed(IndexedReader),
    Readthrough(Reader),
}

/// Read an XCF (VCF/BCF) file, either indexed or unindexed.
///
/// # Examples
///
/// ```ignore
/// let reader = xpclrs::xcf::read_xcf("in.bcf", true).unwrap();
/// ```
pub fn read_xcf<P: AsRef<Path> + Display>(path: P, has_index: bool) -> Result<XcfReader> {
    let xcf_reader: XcfReader = if has_index {
        XcfReader::Indexed(
            IndexedReader::from_path(path).expect("Cannot load indexed BCF/VCF file"),
        )
    } else {
        XcfReader::Readthrough(Reader::from_path(path).expect("Cannot load BCF/VCF file"))
    };
    Ok(xcf_reader)
}

/// Process an indexed XCF file into `GenoData`.
///
/// # Examples
///
/// ```ignore
/// let data = xpclrs::xcf::indexed_xcf("in.bcf".to_string(), &s1, &s2, "1", 0, None, (None, None, None, 1)).unwrap();
/// ```
pub fn indexed_xcf(
    xcf_fn: String,
    s1: &[String],
    s2: &[String],
    chrom: &str,
    start: u64,
    end: Option<u64>,
    (phased, rrate, gdistkey, n_threads): (Option<bool>, Option<f64>, Option<String>, usize),
) -> Result<GenoData> {
    log::info!("Indexed reader.");
    // Prepare the indexed reader
    let mut reader = IndexedReader::from_path(xcf_fn).expect("Cannot load indexed BCF/VCF file");
    reader
        .set_threads(n_threads)
        .expect("Failed to set threads");
    let rrate = rrate.unwrap_or(1e-8);
    // Resolve options once to avoid per-record branching.
    let phased = phased.unwrap_or(false);

    // Load the XCF file
    let xcf_header = reader.header().clone();
    log::info!("Samples in VCF: {}", xcf_header.sample_count());

    // Load sample lists as an u8 array
    let s1 = consolidate_list(&xcf_header.samples(), s1).expect("Failed to subset sampleA");
    let s2 = consolidate_list(&xcf_header.samples(), s2).expect("Failed to subset sampleB");

    // Fetch the indices of each sample in each list
    let i1 = get_gt_index(&xcf_header.samples(), &s1).expect("Failed to get indeces of sampleA");
    let i2 = get_gt_index(&xcf_header.samples(), &s2).expect("Failed to get indeces of sampleB");

    // Print number of samples
    log::info!("Samples A: {}", i1.len());
    log::info!("Samples B: {}", i2.len());

    // Dies if no samples are retained
    if s1.is_empty() || s2.is_empty() {
        eprintln!("No samples found in the lists.");
        std::process::exit(1);
    }

    // Start loading the genotypes here
    // First, find the sequence index
    let rid = reader
        .header()
        .name2rid(chrom.as_bytes())
        .expect("RID not found");
    log::info!("Chromosome {chrom} (ID: {rid})");

    // Jump to target position in place
    let _ = reader.fetch(rid, start, end);
    // Load the records, defining the counters of how many sites we skip
    let mut multiallelic = 0;
    let mut monom_gt2 = 0;
    let mut miss_gt1 = 0;
    let mut miss_gt2 = 0;
    let mut pass = 0;
    let mut skipped = 0;
    let mut tot = 0;

    let (positions, gt1_data, gt2_data, gd_data): (Vec<_>, Vec<_>, Vec<_>, Vec<_>) = if phased {
        reader
            .records()
            .filter_map(|r| {
                let record = r.ok()?;
                tot += 1;
                let genotypes = record.genotypes().expect("Cannot fetch the genotypes");
                let gt1_g = i1
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();
                let gt2_g = i2
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();

                // Count alleles from both populations in a single pass
                let mut alleles1: Counter<u32> = Counter::new();
                let mut alleles2: Counter<u32> = Counter::new();

                for g in &gt1_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles1[&a] += 1;
                    }
                }
                for g in &gt2_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles2[&a] += 1;
                    }
                }

                // Union both sets
                let all_alleles: Counter<u32> = alleles1
                    .iter()
                    .chain(alleles2.iter())
                    .map(|(&k, &v)| (k, v))
                    .collect();

                // Define genetic position
                let gd = match &gdistkey {
                    Some(key) => record
                        .info(key.as_bytes())
                        .float()
                        .ok()
                        .flatten()
                        .expect("Missing info field for genetic position")[0]
                        as f64,
                    None => record.pos() as f64 * rrate,
                };

                // Perform filtering and counting
                if all_alleles.len() > 2 {
                    skipped += 1;
                    multiallelic += 1;
                    None
                } else if alleles1.is_empty() || alleles2.is_empty() {
                    skipped += 1;
                    if alleles1.is_empty() {
                        miss_gt1 += 1;
                    };
                    if alleles2.is_empty() {
                        miss_gt2 += 1;
                    };
                    None
                } else if alleles2.len() == 1 || alleles2.values().min().copied()? == 1 {
                    skipped += 1;
                    monom_gt2 += 1;
                    None
                } else {
                    pass += 1;
                    // Define reference allele as the minimum allele index (consistent with methods)
                    let ref_ix = *all_alleles
                        .keys()
                        .min()
                        .expect("Can't compute reference allele index");
                    // Encode genotypes to compact i8 counts relative to ref allele
                    let mut gt1 = Vec::with_capacity(gt1_g.len());
                    for gt in gt1_g {
                        gt1.push(gt2gcount(gt, ref_ix));
                    }
                    // If phased, store haplotypes in gt2; else store dosages
                    let mut gt2 = Vec::with_capacity(gt2_g.len() * 2);
                    for gt in &gt2_g {
                        for a in gt.iter() {
                            gt2.push(match a {
                                GenotypeAllele::PhasedMissing => -9_i8,
                                GenotypeAllele::UnphasedMissing => -9_i8,
                                _ => a.index().unwrap() as i8,
                            });
                        }
                    }
                    Some((record.pos() as usize, gt1, gt2, gd))
                }
            })
            .multiunzip()
    } else {
        reader
            .records()
            .filter_map(|r| {
                let record = r.ok()?;
                tot += 1;
                let genotypes = record.genotypes().expect("Cannot fetch the genotypes");
                let gt1_g = i1
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();
                let gt2_g = i2
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();

                // Count alleles from both populations in a single pass
                let mut alleles1: Counter<u32> = Counter::new();
                let mut alleles2: Counter<u32> = Counter::new();

                for g in &gt1_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles1[&a] += 1;
                    }
                }
                for g in &gt2_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles2[&a] += 1;
                    }
                }

                // Union both sets
                let all_alleles: Counter<u32> = alleles1
                    .iter()
                    .chain(alleles2.iter())
                    .map(|(&k, &v)| (k, v))
                    .collect();

                // Define genetic position
                let gd = match &gdistkey {
                    Some(key) => record
                        .info(key.as_bytes())
                        .float()
                        .ok()
                        .flatten()
                        .expect("Missing info field for genetic position")[0]
                        as f64,
                    None => record.pos() as f64 * rrate,
                };

                // Perform filtering and counting
                if all_alleles.len() > 2 {
                    skipped += 1;
                    multiallelic += 1;
                    None
                } else if alleles1.is_empty() || alleles2.is_empty() {
                    skipped += 1;
                    if alleles1.is_empty() {
                        miss_gt1 += 1;
                    };
                    if alleles2.is_empty() {
                        miss_gt2 += 1;
                    };
                    None
                } else if alleles2.len() == 1 || alleles2.values().min().copied()? == 1 {
                    skipped += 1;
                    monom_gt2 += 1;
                    None
                } else {
                    pass += 1;
                    // Define reference allele as the minimum allele index (consistent with methods)
                    let ref_ix = *all_alleles
                        .keys()
                        .min()
                        .expect("Can't compute reference allele index");
                    // Encode genotypes to compact i8 counts relative to ref allele
                    let mut gt1 = Vec::with_capacity(gt1_g.len());
                    for gt in gt1_g {
                        gt1.push(gt2gcount(gt, ref_ix));
                    }
                    // If phased, store haplotypes in gt2; else store dosages
                    let mut gt2 = Vec::with_capacity(gt2_g.len());
                    for gt in gt2_g {
                        gt2.push(gt2gcount(gt, ref_ix));
                    }
                    Some((record.pos() as usize, gt1, gt2, gd))
                }
            })
            .multiunzip()
    };

    // Assess everything looks good
    if gt1_data.len() != gt2_data.len() {
        panic!("Inconsistent data")
    };
    if positions.len() != gt2_data.len() {
        panic!("Inconsistent data")
    };
    if positions.len() as i32 != pass {
        panic!("Inconsistent data")
    };
    if tot != (pass + skipped) {
        panic!("Inconsistent counts")
    }
    // Print some info
    log::info!("Processed {tot} variants");
    log::info!("Loaded {pass} variants");
    log::info!("Skipped {skipped} variants because:");
    log::info!(" - {multiallelic} multiallelic");
    log::info!(" - {monom_gt2} monomorphic/singleton in pop B");
    log::info!(" - {miss_gt1} all-missing in pop A");
    log::info!(" - {miss_gt2} all-missing in pop B");
    Ok(GenoData {
        positions,
        gt1: gt1_data,
        gt2: gt2_data,
        gdistances: gd_data,
    })
}

/// Process an unindexed XCF file into `GenoData`.
///
/// # Examples
///
/// ```ignore
/// let data = xpclrs::xcf::readthrough_xcf("in.bcf".to_string(), &s1, &s2, "1", 0, None, (None, None, None, 1)).unwrap();
/// ```
pub fn readthrough_xcf(
    xcf_fn: String,
    s1: &[String],
    s2: &[String],
    chrom: &str,
    start: u64,
    end: Option<u64>,
    (phased, rrate, gdistkey, n_threads): (Option<bool>, Option<f64>, Option<String>, usize),
) -> Result<GenoData> {
    log::info!("Streamed reader.");
    log::info!("This is substantially slower than the indexed one.");
    log::info!("Consider generating an index for your BCF/VCF file.");
    // Prepare the indexed reader
    let mut reader =
        Reader::from_path(xcf_fn).expect("Cannot load unindexed/streamed BCF/VCF file");
    reader
        .set_threads(n_threads)
        .expect("Failed to set threads");
    let end = end.unwrap_or(999999999);
    let rrate = rrate.unwrap_or(1e-8);
    // Resolve options once to avoid per-record branching.
    let phased = phased.unwrap_or(false);

    // Load the XCF file
    let xcf_header = reader.header().clone();
    log::info!("Samples in VCF: {}", xcf_header.sample_count());

    // Load sample lists as an u8 array
    let s1 = consolidate_list(&xcf_header.samples(), s1).expect("Failed to subset sampleA");
    let s2 = consolidate_list(&xcf_header.samples(), s2).expect("Failed to subset sampleB");

    // Fetch the indices of each sample in each list
    let i1 = get_gt_index(&xcf_header.samples(), &s1).expect("Failed to get indeces of sampleA");
    let i2 = get_gt_index(&xcf_header.samples(), &s2).expect("Failed to get indeces of sampleB");

    // Print number of samples
    log::info!("Samples A: {}", s1.len());
    log::info!("Samples B: {}", s2.len());

    // Dies if no samples are retained
    if s1.is_empty() || s2.is_empty() {
        eprintln!("No samples found in the lists.");
        std::process::exit(1);
    }

    // Start loading the genotypes here
    // First, find the sequence index
    let rid = reader
        .header()
        .name2rid(chrom.as_bytes())
        .unwrap_or_else(|_| panic!("Chromosome ID not found {chrom}"));
    log::info!("Chromosome {chrom} (ID: {rid})");

    // Load the records, defining the counters of how many sites we skip
    let mut multiallelic = 0;
    let mut monom_gt2 = 0;
    let mut miss_gt1 = 0;
    let mut miss_gt2 = 0;
    let mut pass = 0;
    let mut skipped = 0;
    let mut tot = 0;
    let (positions, gt1_data, gt2_data, gd_data): (Vec<_>, Vec<_>, Vec<_>, Vec<_>) = if phased {
        reader
            .records()
            .filter(|r| {
                let record = r.as_ref().unwrap();
                let pos = record.pos() as u64;
                record.rid().unwrap() == rid && (pos >= start && pos < end)
            })
            .filter_map(|r| {
                let record = r.ok()?;
                tot += 1;
                let genotypes = record.genotypes().expect("Cannot fetch the genotypes");
                let gt1_g = i1
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();
                let gt2_g = i2
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();

                // Count alleles from both populations in a single pass
                let mut alleles1: Counter<u32> = Counter::new();
                let mut alleles2: Counter<u32> = Counter::new();

                for g in &gt1_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles1[&a] += 1;
                    }
                }
                for g in &gt2_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles2[&a] += 1;
                    }
                }

                // Union both sets
                let all_alleles: Counter<u32> = alleles1
                    .iter()
                    .chain(alleles2.iter())
                    .map(|(&k, &v)| (k, v))
                    .collect();

                // Define genetic position
                let gd = match &gdistkey {
                    Some(key) => record
                        .info(key.as_bytes())
                        .float()
                        .ok()
                        .flatten()
                        .expect("Missing info field for genetic position")[0]
                        as f64,
                    None => record.pos() as f64 * rrate,
                };

                // Perform filtering and counting
                if all_alleles.len() > 2 {
                    skipped += 1;
                    multiallelic += 1;
                    None
                } else if alleles1.is_empty() || alleles2.is_empty() {
                    skipped += 1;
                    if alleles1.is_empty() {
                        miss_gt1 += 1;
                    };
                    if alleles2.is_empty() {
                        miss_gt2 += 1;
                    };
                    None
                } else if alleles2.len() == 1 || alleles2.values().min().copied()? == 1 {
                    skipped += 1;
                    monom_gt2 += 1;
                    None
                } else {
                    pass += 1;
                    // Define reference allele as the minimum allele index
                    let ref_ix = *all_alleles
                        .keys()
                        .min()
                        .expect("Can't compute reference allele index");
                    // Encode genotypes to compact i8 counts relative to ref allele
                    let mut gt1 = Vec::with_capacity(gt1_g.len());
                    for gt in gt1_g {
                        gt1.push(gt2gcount(gt, ref_ix));
                    }
                    // If phased, store haplotypes in gt2; else store dosages
                    let mut gt2 = Vec::with_capacity(gt2_g.len() * 2);
                    for gt in &gt2_g {
                        for a in gt.iter() {
                            gt2.push(match a {
                                GenotypeAllele::PhasedMissing => -9_i8,
                                GenotypeAllele::UnphasedMissing => -9_i8,
                                _ => a.index().unwrap() as i8,
                            });
                        }
                    }
                    Some((record.pos() as usize, gt1, gt2, gd))
                }
            })
            .multiunzip()
    } else {
        reader
            .records()
            .filter(|r| {
                let record = r.as_ref().unwrap();
                let pos = record.pos() as u64;
                record.rid().unwrap() == rid && (pos >= start && pos < end)
            })
            .filter_map(|r| {
                let record = r.ok()?;
                tot += 1;
                let genotypes = record.genotypes().expect("Cannot fetch the genotypes");
                let gt1_g = i1
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();
                let gt2_g = i2
                    .iter()
                    .map(|i| genotypes.get(*i))
                    .collect::<Vec<Genotype>>();

                // Count alleles from both populations in a single pass
                let mut alleles1: Counter<u32> = Counter::new();
                let mut alleles2: Counter<u32> = Counter::new();

                for g in &gt1_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles1[&a] += 1;
                    }
                }
                for g in &gt2_g {
                    for a in g.iter().filter_map(|a| a.index()) {
                        alleles2[&a] += 1;
                    }
                }

                // Union both sets
                let all_alleles: Counter<u32> = alleles1
                    .iter()
                    .chain(alleles2.iter())
                    .map(|(&k, &v)| (k, v))
                    .collect();

                // Define genetic position
                let gd = match &gdistkey {
                    Some(key) => record
                        .info(key.as_bytes())
                        .float()
                        .ok()
                        .flatten()
                        .expect("Missing info field for genetic position")[0]
                        as f64,
                    None => record.pos() as f64 * rrate,
                };

                // Perform filtering and counting
                if all_alleles.len() > 2 {
                    skipped += 1;
                    multiallelic += 1;
                    None
                } else if alleles1.is_empty() || alleles2.is_empty() {
                    skipped += 1;
                    if alleles1.is_empty() {
                        miss_gt1 += 1;
                    };
                    if alleles2.is_empty() {
                        miss_gt2 += 1;
                    };
                    None
                } else if alleles2.len() == 1 || alleles2.values().min().copied()? == 1 {
                    skipped += 1;
                    monom_gt2 += 1;
                    None
                } else {
                    pass += 1;
                    // Define reference allele as the minimum allele index
                    let ref_ix = *all_alleles
                        .keys()
                        .min()
                        .expect("Can't compute reference allele index");
                    // Encode genotypes to compact i8 counts relative to ref allele
                    let mut gt1 = Vec::with_capacity(gt1_g.len());
                    for gt in gt1_g {
                        gt1.push(gt2gcount(gt, ref_ix));
                    }
                    // If phased, store haplotypes in gt2; else store dosages
                    let mut gt2 = Vec::with_capacity(gt2_g.len());
                    for gt in gt2_g {
                        gt2.push(gt2gcount(gt, ref_ix));
                    }
                    Some((record.pos() as usize, gt1, gt2, gd))
                }
            })
            .multiunzip()
    };

    // Assess everything looks good
    if gt1_data.len() != gt2_data.len() {
        panic!("Inconsistent data")
    };
    if positions.len() != gt2_data.len() {
        panic!("Inconsistent data")
    };
    if positions.len() as i32 != pass {
        panic!("Inconsistent data")
    };
    if tot != (pass + skipped) {
        panic!("Inconsistent counts")
    }
    // Print some info

    log::info!("Processed {tot} variants");
    log::info!("Loaded {pass} variants");
    log::info!("Skipped {skipped} variants because:");
    log::info!(" - {multiallelic} multiallelic");
    log::info!(" - {monom_gt2} monomorphic/singleton in pop B");
    log::info!(" - {miss_gt1} all-missing in pop A");
    log::info!(" - {miss_gt2} all-missing in pop B");
    Ok(GenoData {
        positions,
        gt1: gt1_data,
        gt2: gt2_data,
        gdistances: gd_data,
    })
}