chainfile 0.4.0

A crate for working with genomics chain files.
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
//! A machine for lifting over coordinates within a reference genome.

use std::collections::HashMap;

use omics::coordinate::Contig;
use omics::coordinate::Strand;
use omics::coordinate::interval::interbase::Interval;
use omics::coordinate::position::Number;
use rust_lapper as lapper;

use crate::alignment::section::header::Record as Header;
use crate::liftover::stepthrough::interval_pair::ContiguousIntervalPair;

pub mod builder;

pub use builder::Builder;

/// A dictionary of chromosome names and their size.
pub type ChromosomeDictionary = HashMap<String, Number>;

/// A mapping segment annotated with the chain ID from which it originated.
#[derive(Clone, Debug, Eq, PartialEq)]
struct AnnotatedPair {
    /// The chain ID from which this segment originated.
    chain_id: usize,

    /// The mapping segment.
    pair: ContiguousIntervalPair,
}

/// The liftover results from a single chain.
///
/// Each chain produces one or more contiguous mapping segments. When a
/// query interval spans a gap within a chain, the chain contributes
/// multiple segments (one per aligned block that overlaps the query).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LiftoverResult {
    /// The chain from which these liftover results originated.
    chain: Header,

    /// The mapping segments from this chain that overlap the query.
    segments: Vec<ContiguousIntervalPair>,
}

impl LiftoverResult {
    /// Gets the chain from which these liftover results originated.
    pub fn chain(&self) -> &Header {
        &self.chain
    }

    /// Gets the mapping segments.
    pub fn segments(&self) -> &[ContiguousIntervalPair] {
        &self.segments
    }

    /// Consumes `self` and returns the mapping segments.
    pub fn into_segments(self) -> Vec<ContiguousIntervalPair> {
        self.segments
    }
}

/// A machine for lifting over coordinates from a reference genome to a query
/// genome.
///
/// Generally, you will want to use a [`builder::Builder`] to construct one of
/// these.
#[derive(Debug)]
pub struct Machine {
    /// The inner lookup table of positions in the reference genome to positions
    /// in the query genome for each contig in the reference genome.
    inner: HashMap<Contig, lapper::Lapper<Number, AnnotatedPair>>,

    /// A lookup table from chain ID to the chain header.
    chains: HashMap<usize, Header>,

    /// The reference chromosome corpus.
    reference_chromosomes: ChromosomeDictionary,

    /// The query chromosome corpus.
    query_chromosomes: ChromosomeDictionary,
}

impl Machine {
    /// Gets all of the contigs of the reference genome along with the start and
    /// end positions for each contig.
    pub fn reference_chromosomes(&self) -> &ChromosomeDictionary {
        &self.reference_chromosomes
    }

    /// Gets all of the contigs of the query genome along with the start and
    /// end positions for each contig.
    pub fn query_chromosomes(&self) -> &ChromosomeDictionary {
        &self.query_chromosomes
    }

    /// Performs a liftover from the specified `interval` to the query genome.
    ///
    /// Results are grouped by the chain from which each mapping segment
    /// originated. Each [`LiftoverResult`] contains one or more contiguous
    /// segments from a single chain, along with the chain's header.
    ///
    /// The returned `Vec<LiftoverResult>` is sorted by score descending
    /// (best chain first), with chain ID ascending as a tiebreaker. Within
    /// each result, `segments()` are sorted by reference interval start
    /// position ascending, with end position as a tiebreaker.
    pub fn liftover(&self, interval: Interval) -> Option<Vec<LiftoverResult>> {
        let entry = self.inner.get(interval.contig())?;

        let (start, stop) = match interval.strand() {
            Strand::Positive => (
                interval.start().position().get(),
                interval.end().position().get(),
            ),
            Strand::Negative => (
                interval.end().position().get(),
                interval.start().position().get(),
            ),
        };

        let strand = interval.strand();

        let mut hits = Vec::<(usize, ContiguousIntervalPair)>::new();

        for e in entry.find(start, stop) {
            if e.val.pair.reference().strand() != strand {
                continue;
            }

            // SAFETY: the lapper guarantees that `e.val.pair` overlaps
            // `interval`, so `clamp()` will always succeed.
            let pair = e.val.pair.clone().clamp(interval.clone()).unwrap();
            hits.push((e.val.chain_id, pair));
        }

        if hits.is_empty() {
            return None;
        }

        // Sort by chain ID so that consecutive entries with the same ID are
        // adjacent, then group them.
        hits.sort_by_key(|(id, _)| *id);

        let mut results = Vec::<LiftoverResult>::new();

        for (chain_id, pair) in hits {
            match results.last_mut() {
                Some(last) if last.chain().id() == chain_id => {
                    last.segments.push(pair);
                }
                _ => {
                    let chain = self.chains[&chain_id].clone();
                    results.push(LiftoverResult {
                        chain,
                        segments: vec![pair],
                    });
                }
            }
        }

        // Within each chain group, ensure segments are sorted by reference
        // start position.
        for result in &mut results {
            result.segments.sort_by(|a, b| {
                a.reference()
                    .start()
                    .cmp(b.reference().start())
                    .then_with(|| a.reference().end().cmp(b.reference().end()))
            });
        }

        // Sort results by score descending so the best chain comes first,
        // with chain ID ascending as a tiebreaker.
        results.sort_by(|a, b| {
            b.chain()
                .score()
                .cmp(&a.chain().score())
                .then_with(|| a.chain().id().cmp(&b.chain().id()))
        });

        Some(results)
    }
}

#[cfg(test)]
mod tests {
    use omics::coordinate::Contig;
    use omics::coordinate::interbase::Coordinate;
    use omics::coordinate::position::interbase::Position;

    use super::*;
    use crate::Reader;
    use crate::liftover::machine;

    #[test]
    pub fn test_valid_positive_strand_liftover() -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 + 0 10 seq1 10 + 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 1u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 7u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval).unwrap();

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

        let result = &results[0].segments()[0];

        assert_eq!(result.reference().contig().as_str(), "seq0");
        assert_eq!(result.reference().start().strand(), Strand::Positive);
        assert_eq!(result.reference().start().position(), &Position::new(1));
        assert_eq!(result.reference().end().strand(), Strand::Positive);
        assert_eq!(result.reference().end().position(), &Position::new(7));

        assert_eq!(result.query().contig().as_str(), "seq1");
        assert_eq!(result.query().start().strand(), Strand::Positive);
        assert_eq!(result.query().start().position(), &Position::new(1));
        assert_eq!(result.query().end().strand(), Strand::Positive);
        assert_eq!(result.query().end().position(), &Position::new(7));

        Ok(())
    }

    #[test]
    pub fn test_valid_negative_strand_liftover() -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 - 0 10 seq1 10 - 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 7u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 1u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval).unwrap();

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

        let result = &results[0].segments()[0];

        assert_eq!(result.reference().contig().as_str(), "seq0");
        assert_eq!(result.reference().start().strand(), Strand::Negative);
        assert_eq!(result.reference().start().position(), &Position::new(7));
        assert_eq!(result.reference().end().strand(), Strand::Negative);
        assert_eq!(result.reference().end().position(), &Position::new(1));

        assert_eq!(result.query().contig().as_str(), "seq1");
        assert_eq!(result.query().start().strand(), Strand::Negative);
        assert_eq!(result.query().start().position(), &Position::new(7));
        assert_eq!(result.query().end().strand(), Strand::Negative);
        assert_eq!(result.query().end().position(), &Position::new(1));

        Ok(())
    }

    #[test]
    pub fn test_valid_positive_to_negative_strand_liftover()
    -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 + 0 10 seq1 10 - 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 1u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 7u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval).unwrap();

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

        let result = &results[0].segments()[0];

        assert_eq!(result.reference().contig().as_str(), "seq0");
        assert_eq!(result.reference().start().strand(), Strand::Positive);
        assert_eq!(result.reference().start().position(), &Position::new(1));
        assert_eq!(result.reference().end().strand(), Strand::Positive);
        assert_eq!(result.reference().end().position(), &Position::new(7));

        assert_eq!(result.query().contig().as_str(), "seq1");
        assert_eq!(result.query().start().strand(), Strand::Negative);
        assert_eq!(result.query().start().position(), &Position::new(9));
        assert_eq!(result.query().end().strand(), Strand::Negative);
        assert_eq!(result.query().end().position(), &Position::new(3));

        Ok(())
    }

    #[test]
    pub fn test_valid_negative_to_positive_strand_liftover()
    -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 - 0 10 seq1 10 + 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 7u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 1u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval).unwrap();

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

        let result = &results[0].segments()[0];

        assert_eq!(result.reference().contig().as_str(), "seq0");
        assert_eq!(result.reference().start().strand(), Strand::Negative);
        assert_eq!(result.reference().start().position(), &Position::new(7));
        assert_eq!(result.reference().end().strand(), Strand::Negative);
        assert_eq!(result.reference().end().position(), &Position::new(1));

        assert_eq!(result.query().contig().as_str(), "seq1");
        assert_eq!(result.query().start().strand(), Strand::Positive);
        assert_eq!(result.query().start().position(), &Position::new(3));
        assert_eq!(result.query().end().strand(), Strand::Positive);
        assert_eq!(result.query().end().position(), &Position::new(9));

        Ok(())
    }

    #[test]
    pub fn test_nonexistent_positive_strand_interval_liftover()
    -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 - 0 10 seq1 10 - 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 1u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 7u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval);

        assert_eq!(results, None);

        Ok(())
    }

    #[test]
    pub fn test_nonexistent_negative_strand_interval_liftover()
    -> Result<(), Box<dyn std::error::Error>> {
        let data = b"chain 0 seq0 10 + 0 10 seq1 10 + 0 10 0\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 7u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Negative, 1u64);

        let interval = Interval::try_new(from, to)?;
        let results = machine.liftover(interval);

        assert_eq!(results, None);

        Ok(())
    }

    #[test]
    fn test_grouped_by_chain() -> Result<(), Box<dyn std::error::Error>> {
        // Two chains covering the same region on `seq0`, mapping to
        // `seq1` and `seq2` respectively.
        let data =
            b"chain 100 seq0 10 + 0 10 seq1 10 + 0 10 0\n10\n\nchain 50 seq0 10 + 0 10 seq2 10 + 0 10 1\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 1u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 5u64);
        let interval = Interval::try_new(from, to)?;

        let results = machine.liftover(interval).unwrap();
        assert_eq!(results.len(), 2);

        // Results are sorted by score descending.
        assert_eq!(results[0].chain().score(), 100);
        assert_eq!(results[0].chain().id(), 0);
        assert_eq!(results[0].segments().len(), 1);
        assert_eq!(results[0].segments()[0].query().contig().as_str(), "seq1");

        assert_eq!(results[1].chain().score(), 50);
        assert_eq!(results[1].chain().id(), 1);
        assert_eq!(results[1].segments().len(), 1);
        assert_eq!(results[1].segments()[0].query().contig().as_str(), "seq2");

        Ok(())
    }

    #[test]
    fn test_gapped_chain_returns_multiple_segments() -> Result<(), Box<dyn std::error::Error>> {
        // One chain with a gap: two blocks of 4, separated by a gap of
        // 2 in both reference and query.
        let data = b"chain 0 seq0 10 + 0 10 seq1 10 + 0 10 0\n4\t2\t2\n4";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 0u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 10u64);
        let interval = Interval::try_new(from, to)?;

        let results = machine.liftover(interval).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].segments().len(), 2);
        assert_eq!(results[0].segments()[0].reference().count_entities(), 4);
        assert_eq!(results[0].segments()[1].reference().count_entities(), 4);

        Ok(())
    }

    #[test]
    fn test_liftover_ordering_is_deterministic() -> Result<(), Box<dyn std::error::Error>> {
        // Three chains with IDs 2, 0, 1 (intentionally out of order in the
        // input) covering the same region on `seq0`.
        let data = b"chain 30 seq0 10 + 0 10 seq3 10 + 0 10 2\n10\n\n\
                      chain 100 seq0 10 + 0 10 seq1 10 + 0 10 0\n10\n\n\
                      chain 50 seq0 10 + 0 10 seq2 10 + 0 10 1\n10";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 0u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 10u64);
        let interval = Interval::try_new(from, to)?;

        // Run liftover multiple times and verify ordering is stable.
        for _ in 0..10 {
            let results = machine.liftover(interval.clone()).unwrap();
            assert_eq!(results.len(), 3);

            // Results must be sorted by score descending.
            assert_eq!(results[0].chain().score(), 100);
            assert_eq!(results[1].chain().score(), 50);
            assert_eq!(results[2].chain().score(), 30);
        }

        Ok(())
    }

    #[test]
    fn test_segments_ordered_by_reference_position() -> Result<(), Box<dyn std::error::Error>> {
        // One chain with three blocks separated by gaps, ensuring segments
        // come back in reference-position order. Layout: 5 + gap(2,2) + 5 +
        // gap(2,2) + 6 = 20 reference bases.
        let data = b"chain 0 seq0 20 + 0 20 seq1 20 + 0 20 0\n5\t2\t2\n5\t2\t2\n6";
        let reader = Reader::new(&data[..]);
        let machine = machine::Builder.try_build_from(reader)?;

        let from = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 0u64);
        let to = Coordinate::new(Contig::new_unchecked("seq0"), Strand::Positive, 20u64);
        let interval = Interval::try_new(from, to)?;

        let results = machine.liftover(interval).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].segments().len(), 3);

        // Segments must be sorted by reference start position.
        let starts: Vec<_> = results[0]
            .segments()
            .iter()
            .map(|s| s.reference().start().position().get())
            .collect();
        assert_eq!(starts, vec![0, 7, 14]);

        Ok(())
    }
}