liblrge 0.3.0

Genome size estimation from long read overlaps
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
//! Data structure for PAF records along with serialization and deserialization methods.
use std::cmp;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Mapping result - i.e., PafRecord
/// See https://lh3.github.io/minimap2/minimap2.html for full details of the PAF format provided by minimap2
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub(crate) struct PafRecord {
    #[serde(
        serialize_with = "serialize_bytes",
        deserialize_with = "deserialize_bytes"
    )]
    pub query_name: Vec<u8>,
    pub query_len: i32,
    /// Query start coordinate (0-based)
    pub query_start: i32,
    /// Query end coordinate (0-based)
    pub query_end: i32,
    /// ‘+’ if query/target on the same strand; ‘-’ if opposite
    pub strand: char,
    #[serde(
        serialize_with = "serialize_bytes",
        deserialize_with = "deserialize_bytes"
    )]
    pub target_name: Vec<u8>,
    pub target_len: i32,
    /// Target start coordinate on the original strand
    pub target_start: i32,
    /// Target end coordinate on the original strand
    pub target_end: i32,
    /// Number of matching bases in the mapping
    pub match_len: i32,
    /// Number bases, including gaps, in the mapping
    pub block_len: i32,
    /// Mapping quality (0-255 with 255 for missing)
    pub mapq: u32,
    /// Type of aln: P/primary, S/secondary and I,i/inversion
    #[serde(serialize_with = "serialize_tp", deserialize_with = "deserialize_tag")]
    pub tp: char,
    /// Number of minimizers on the chain
    #[serde(serialize_with = "serialize_cm", deserialize_with = "deserialize_tag")]
    pub cm: i32,
    /// Number of residues in the matching chain (chaining score)
    #[serde(serialize_with = "serialize_s1", deserialize_with = "deserialize_tag")]
    pub s1: i32,
    /// Approximate per-base sequence divergence
    #[serde(serialize_with = "serialize_dv", deserialize_with = "deserialize_tag")]
    pub dv: f32,
    /// Length of query regions harboring repetitive seeds
    #[serde(serialize_with = "serialize_rl", deserialize_with = "deserialize_tag")]
    pub rl: i32,
}

impl PafRecord {
    /// Checks if the target or query read are internal to the other, within a specified overhang ratio.
    /// This is used to filter out internal reads that are not useful for estimation.
    pub(crate) fn is_internal(&self, max_overhang_ratio: f32) -> bool {
        let overhang = if self.strand == '+' {
            cmp::min(self.query_start, self.target_start)
                + cmp::min(
                    self.query_len - self.query_end,
                    self.target_len - self.target_end,
                )
        } else {
            cmp::min(self.query_start, self.target_len - self.target_end)
                + cmp::min(self.query_len - self.query_end, self.target_start)
        };
        let maplen = cmp::max(
            self.query_end - self.query_start,
            self.target_end - self.target_start,
        );

        let overhang_ratio = overhang as f32 / maplen as f32;
        overhang_ratio < max_overhang_ratio
    }
}

/// Serialize `Vec<u8>` as a UTF-8 string
fn serialize_bytes<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    // remove any null bytes from the end
    let bytes = trim_null_bytes(bytes);
    let s = String::from_utf8_lossy(bytes);
    serializer.serialize_str(&s)
}

fn trim_null_bytes(data: &[u8]) -> &[u8] {
    if let Some(end) = data.iter().rposition(|&byte| byte != 0) {
        &data[..=end] // Slice up to the last non-null byte
    } else {
        &[] // Return an empty slice if all bytes are null
    }
}

/// Deserialize a UTF-8 string into `Vec<u8>`
fn deserialize_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    let s: &str = Deserialize::deserialize(deserializer)?;
    Ok(s.as_bytes().to_vec())
}

/// Serialize the tp tag
fn serialize_tp<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: std::fmt::Display,
{
    serialize_tag_with_name("tp", value, serializer)
}

/// Serialize the cm tag
fn serialize_cm<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: std::fmt::Display,
{
    serialize_tag_with_name("cm", value, serializer)
}

/// Serialize the s1 tag
fn serialize_s1<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: std::fmt::Display,
{
    serialize_tag_with_name("s1", value, serializer)
}

/// Serialize the dv tag - format the float with 4 decimal places
fn serialize_dv<S>(value: &f32, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    // format the float with 4 decimal places, or if the value is zero, just serialize it as an integer
    let value = if *value < f32::EPSILON {
        "0".to_string()
    } else {
        format!("{value:.4}",)
    };
    serialize_tag_with_name("dv", &value, serializer)
}

/// Serialize the rl tag
fn serialize_rl<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: std::fmt::Display,
{
    serialize_tag_with_name("rl", value, serializer)
}

/// Generic serialization for fields like `cm:i:123`
fn serialize_tag_with_name<S, T>(name: &str, value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: std::fmt::Display,
{
    let mut prefix = match std::any::type_name::<T>() {
        "char" => "A",
        "i32" => "i",
        "f32" => "f",
        s => s,
    };

    if name == "dv" {
        prefix = "f";
    }

    let formatted = format!("{name}:{prefix}:{value}",);
    serializer.serialize_str(&formatted)
}

/// Generic deserialization for fields like `cm:i:123`
fn deserialize_tag<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: FromStr,
    T::Err: std::fmt::Display,
    D: Deserializer<'de>,
{
    let s: &str = Deserialize::deserialize(deserializer)?;
    s.split(':')
        .next_back()
        .ok_or_else(|| serde::de::Error::custom("Invalid field format"))
        .and_then(|val| val.parse::<T>().map_err(serde::de::Error::custom))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_deserialize_mapping() {
        let buf = b"SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0022\trl:i:56";
        let expected = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0022,
            rl: 56,
        };
        let mut rdr = csv::ReaderBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_reader(&buf[..]);
        for result in rdr.deserialize() {
            // Notice that we need to provide a type hint for automatic
            // deserialization.
            let mapping: PafRecord = result.unwrap();
            assert_eq!(mapping, expected);
        }
    }

    #[test]
    fn test_serialize_mapping() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0022,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0022\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_mapping_null_terminated_qname() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1\0".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0022,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0022\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_mapping_dv_round_down() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0022111,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0022\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_mapping_dv_round_up() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0021999,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0022\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_mapping_dv_fill_to_decimal_places() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.004,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0.0040\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_mapping_dv_zero() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 4402,
            query_start: 40,
            query_end: 237,
            strand: '-',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 5094,
            target_start: 41,
            target_end: 238,
            match_len: 190,
            block_len: 197,
            mapq: 0,
            tp: 'S',
            cm: 59,
            s1: 190,
            dv: 0.0000,
            rl: 56,
        };
        let mut wtr = csv::WriterBuilder::new()
            .delimiter(b'\t')
            .has_headers(false)
            .from_writer(vec![]);
        wtr.serialize(mapping).unwrap();
        let result = wtr.into_inner().unwrap();
        let result = String::from_utf8(result).unwrap();
        let expected = "SRR28370649.1\t4402\t40\t237\t-\tSRR28370649.7311\t5094\t41\t238\t190\t197\t0\ttp:A:S\tcm:i:59\ts1:i:190\tdv:f:0\trl:i:56\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_is_internal() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 390,
            query_start: 46,
            query_end: 317,
            strand: '+',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 278,
            target_start: 4,
            target_end: 275,
            match_len: 260,
            block_len: 271,
            mapq: 0,
            tp: 'S',
            cm: 77,
            s1: 260,
            dv: 0.0,
            rl: 0,
        };
        assert!(mapping.is_internal(0.2));
    }

    #[test]
    fn test_is_internal2() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 298,
            query_start: 1,
            query_end: 297,
            strand: '+',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 398,
            target_start: 54,
            target_end: 350,
            match_len: 276,
            block_len: 296,
            mapq: 0,
            tp: 'S',
            cm: 77,
            s1: 260,
            dv: 0.0,
            rl: 0,
        };
        assert!(mapping.is_internal(0.2));
    }

    #[test]
    fn test_is_internal3() {
        let mapping = PafRecord {
            query_name: b"SRR28370649.1".to_vec(),
            query_len: 390,
            query_start: 0,
            query_end: 355,
            strand: '+',
            target_name: b"SRR28370649.7311".to_vec(),
            target_len: 418,
            target_start: 39,
            target_end: 394,
            match_len: 335,
            block_len: 355,
            mapq: 0,
            tp: 'S',
            cm: 77,
            s1: 260,
            dv: 0.0,
            rl: 0,
        };
        assert!(!mapping.is_internal(0.05));
    }
}