genomicframe-core 0.2.0

High-performance genomics I/O and interoperability layer
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
//! VCF (Variant Call Format) reader
//!
//! VCF is a text-based format for representing genetic variants.
//! This module provides efficient, streaming-first parsing with gzip support.
//!
//! # Design Philosophy
//!
//! - **Streaming by default**: Records are never buffered unless explicitly requested
//! - **Zero-copy parsing**: Where possible, records borrow from the input buffer
//! - **Automatic compression detection**: Handles `.vcf` and `.vcf.gz` transparently
//! - **Lazy evaluation**: Process millions of variants with O(1) memory
//!
//! # Examples
//!
//! ```no_run
//! use genomicframe_core::formats::vcf::VcfReader;
//! use genomicframe_core::core::GenomicRecordIterator;
//!
//! // Streaming: O(1) memory, processes one record at a time
//! let mut reader = VcfReader::from_path("large.vcf.gz")?;
//! let mut high_quality_count = 0;
//!
//! while let Some(record) = reader.next_record()? {
//!     if record.is_pass() && record.qual.unwrap_or(0.0) > 30.0 {
//!         high_quality_count += 1;
//!     }
//! }
//!
//! // Chunked: Process in fixed-size batches
//! let reader = VcfReader::from_path("large.vcf.gz")?;
//! for chunk_result in reader.chunks(10_000) {
//!     let chunk = chunk_result?;
//!     // Process 10k variants at a time, then discard
//! }
//! # Ok::<(), genomicframe_core::error::Error>(())
//! ```

use crate::core::{GenomicPosition, GenomicReader, GenomicRecordIterator};
use crate::error::{Error, Result};
use crate::io::Compression;
use crate::interval::annotation::AnnotationIndex;
use crate::formats::vcf::annotated::AnnotatedVcfRecord;
use flate2::read::MultiGzDecoder;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

/// A single VCF record (variant)
#[derive(Debug, Clone)]
pub struct VcfRecord {
    /// Chromosome
    pub chrom: String,
    /// Position (1-based)
    pub pos: u64,
    /// Variant ID (e.g., rs number)
    pub id: String,
    /// Reference allele
    pub reference: String,
    /// Alternate allele(s)
    pub alt: Vec<String>,
    /// Quality score
    pub qual: Option<f64>,
    /// Filter status
    pub filter: String,
    /// INFO field (key-value annotations)
    pub info: String,
    /// FORMAT field
    pub format: Option<String>,
    /// Sample genotypes
    pub samples: Vec<String>,
}

impl VcfRecord {
    /// Get the genomic position of this variant
    pub fn position(&self) -> GenomicPosition {
        GenomicPosition::new(self.chrom.clone(), self.pos)
    }

    /// Check if this variant passed all filters
    pub fn is_pass(&self) -> bool {
        self.filter == "PASS" || self.filter == "."
    }

    /// Check if this variant is a SNP (single nucleotide polymorphism)
    ///
    /// Returns true if both REF and all ALT alleles are single nucleotides.
    pub fn is_snp(&self) -> bool {
        // REF must be single nucleotide
        if self.reference.len() != 1 {
            return false;
        }

        // All ALT alleles must be single nucleotides
        self.alt.iter().all(|alt| alt.len() == 1 && alt != ".")
    }

    /// Check if this variant is an indel (insertion/deletion)
    ///
    /// Returns true if REF or any ALT allele has length != 1.
    pub fn is_indel(&self) -> bool {
        // If REF is not single nucleotide, it's an indel
        if self.reference.len() != 1 {
            return true;
        }

        // If any ALT is not single nucleotide (excluding missing "."), it's an indel
        self.alt.iter().any(|alt| alt.len() != 1 && alt != ".")
    }

    /// Check if this variant is a transition (A↔G or C↔T)
    ///
    /// Returns true if the variant is a SNP and all ALT alleles are transitions.
    pub fn is_transition(&self) -> bool {
        if !self.is_snp() {
            return false;
        }

        let ref_base = self.reference.chars().next().unwrap();

        self.alt.iter().all(|alt| {
            if let Some(alt_base) = alt.chars().next() {
                matches!(
                    (ref_base, alt_base),
                    ('A', 'G') | ('G', 'A') | ('C', 'T') | ('T', 'C')
                )
            } else {
                false
            }
        })
    }

    /// Check if this variant is a transversion (A↔C, A↔T, G↔C, G↔T)
    ///
    /// Returns true if the variant is a SNP and all ALT alleles are transversions.
    pub fn is_transversion(&self) -> bool {
        if !self.is_snp() {
            return false;
        }

        let ref_base = self.reference.chars().next().unwrap();

        self.alt.iter().all(|alt| {
            if let Some(alt_base) = alt.chars().next() {
                matches!(
                    (ref_base, alt_base),
                    ('A', 'C') | ('A', 'T') | ('C', 'A') | ('C', 'G') | ('G', 'C') | ('G', 'T')
                        | ('T', 'A') | ('T', 'G')
                )
            } else {
                false
            }
        })
    }
}

/// VCF header metadata
#[derive(Debug, Clone, Default)]
pub struct VcfHeader {
    /// File format version
    pub version: String,
    /// Contig/chromosome definitions
    pub contigs: Vec<String>,
    /// Sample names
    pub samples: Vec<String>,
    /// INFO field definitions
    pub info_fields: Vec<String>,
    /// FORMAT field definitions
    pub format_fields: Vec<String>,
    /// Other header lines
    pub other: Vec<String>,
}

/// VCF file reader (streaming, memory-efficient)
///
/// **The only way to create a VcfReader is `VcfReader::from_path()`.**
///
/// This is intentionally simple - there's one obvious way to read a VCF file.
pub struct VcfReader {
    reader: Box<dyn BufRead>,
    header: VcfHeader,
}

/// Iterator that annotates VCF records with genomic context
///
/// Created by calling `VcfReader::annotate_with()`.
pub struct AnnotatingIterator {
    reader: VcfReader,
    index: AnnotationIndex,
}

impl VcfReader {
    /// Open a VCF file - handles .vcf and .vcf.gz automatically
    ///
    /// # Memory Behavior
    ///
    /// - Opens file handle (~8KB buffer)
    /// - Parses header (~1-10KB typically)
    /// - **Does NOT load variants into memory**
    /// - Variants are parsed on-demand as you iterate
    ///
    /// # Example
    ///
    /// ```no_run
    /// use genomicframe_core::formats::vcf::VcfReader;
    /// use genomicframe_core::core::GenomicRecordIterator;
    ///
    /// // Works with multi-GB files using only ~10KB RAM
    /// let mut reader = VcfReader::from_path("variants.vcf.gz")?;
    ///
    /// while let Some(variant) = reader.next_record()? {
    ///     if variant.is_pass() {
    ///         println!("{:?}", variant);
    ///     }
    /// }
    /// # Ok::<(), genomicframe_core::error::Error>(())
    /// ```
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        let file = File::open(path)?;
        let compression = Compression::from_path(path);

        let reader: Box<dyn BufRead> = match compression {
            Compression::Gzip | Compression::Bgzip => {
                Box::new(BufReader::new(MultiGzDecoder::new(file)))
            }
            _ => Box::new(BufReader::new(file)),
        };

        let header = Self::parse_header(reader)?;
        Ok(header)
    }

    /// Get the VCF header metadata
    pub fn header(&self) -> &VcfHeader {
        &self.header
    }

    /// Create an annotating iterator that enriches variants with genomic context
    ///
    /// This is the ergonomic way to annotate variants from BED files, GFF files, etc.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use genomicframe_core::formats::vcf::VcfReader;
    /// use genomicframe_core::interval::annotation::AnnotationIndex;
    ///
    /// // Load gene annotations
    /// let genes = AnnotationIndex::from_bed("genes.bed", |r| {
    ///     r.name.clone().unwrap_or_default()
    /// })?;
    ///
    /// // Annotate variants as they're read
    /// let mut reader = VcfReader::from_path("variants.vcf.gz")?;
    /// for annotated in reader.annotate_with(genes) {
    ///     let annotated = annotated?;
    ///     if annotated.is_annotated() {
    ///         println!("{:?} overlaps {}", annotated.record.position(),
    ///                  annotated.all_annotations().join(", "));
    ///     }
    /// }
    /// # Ok::<(), genomicframe_core::error::Error>(())
    /// ```
    pub fn annotate_with(self, index: AnnotationIndex) -> AnnotatingIterator {
        AnnotatingIterator {
            reader: self,
            index,
        }
    }

    /// Internal: Parse VCF header and return reader positioned at first variant
    fn parse_header(mut reader: Box<dyn BufRead>) -> Result<Self> {
        let mut header = VcfHeader::default();
        let mut line = String::new();

        loop {
            line.clear();
            let bytes_read = reader.read_line(&mut line)?;
            if bytes_read == 0 {
                return Err(Error::Parse("Empty VCF file".to_string()));
            }

            if !line.starts_with('#') {
                // Hit first variant line - done with header
                break;
            }

            // Parse header metadata
            if line.starts_with("##fileformat=") {
                header.version = line.trim_start_matches("##fileformat=").trim().to_string();
            } else if line.starts_with("##contig=") {
                header.contigs.push(line.trim().to_string());
            } else if line.starts_with("##INFO=") {
                header.info_fields.push(line.trim().to_string());
            } else if line.starts_with("##FORMAT=") {
                header.format_fields.push(line.trim().to_string());
            } else if line.starts_with("#CHROM") {
                let parts: Vec<&str> = line.trim().split('\t').collect();
                if parts.len() > 9 {
                    header.samples = parts[9..].iter().map(|s| s.to_string()).collect();
                }
            } else {
                header.other.push(line.trim().to_string());
            }
        }

        Ok(Self { reader, header })
    }

    /// Parse a single VCF record line
    fn parse_record(line: &str) -> Result<VcfRecord> {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() < 8 {
            return Err(Error::Parse(format!(
                "Invalid VCF record: expected at least 8 fields, got {}",
                parts.len()
            )));
        }

        let pos = parts[1]
            .parse::<u64>()
            .map_err(|e| Error::Parse(format!("Invalid position: {}", e)))?;

        let qual = if parts[5] == "." {
            None
        } else {
            Some(
                parts[5]
                    .parse::<f64>()
                    .map_err(|e| Error::Parse(format!("Invalid quality score: {}", e)))?,
            )
        };

        let alt = parts[4].split(',').map(|s| s.to_string()).collect();

        Ok(VcfRecord {
            chrom: parts[0].to_string(),
            pos,
            id: parts[2].to_string(),
            reference: parts[3].to_string(),
            alt,
            qual,
            filter: parts[6].to_string(),
            info: parts[7].to_string(),
            format: parts.get(8).map(|s| s.to_string()),
            samples: parts[9..].iter().map(|s| s.to_string()).collect(),
        })
    }
}

impl GenomicRecordIterator for VcfReader {
    type Record = VcfRecord;

    fn next_raw(&mut self) -> Result<Option<Vec<u8>>> { 
        // TODO: Implement
        Ok(None)
    }

    fn next_record(&mut self) -> Result<Option<Self::Record>> {
        let mut line = String::new();
        loop {
            line.clear();
            let bytes_read = self.reader.read_line(&mut line)?;
            if bytes_read == 0 {
                return Ok(None);
            }

            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            return Ok(Some(Self::parse_record(line)?));
        }
    }
}

impl GenomicReader for VcfReader {
    type Metadata = VcfHeader;

    fn metadata(&self) -> &Self::Metadata {
        &self.header
    }
}

impl Iterator for AnnotatingIterator {
    type Item = Result<AnnotatedVcfRecord>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.reader.next_record() {
            Ok(Some(record)) => {
                let mut annotated = AnnotatedVcfRecord::new(record);
                annotated.annotate_with(&self.index);
                Some(Ok(annotated))
            }
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_vcf_header_parsing() -> Result<()> {
        let vcf_data = "##fileformat=VCFv4.2\n\
                        ##contig=<ID=chr1,length=248956422>\n\
                        #CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample1\n\
                        chr1\t12345\t.\tA\tG\t30\tPASS\t.\tGT\t0/1\n";

        // Write to temp file
        let mut temp_file = NamedTempFile::new()?;
        temp_file.write_all(vcf_data.as_bytes())?;
        temp_file.flush()?;

        let reader = VcfReader::from_path(temp_file.path())?;

        assert_eq!(reader.header().version, "VCFv4.2");
        assert_eq!(reader.header().samples.len(), 1);
        assert_eq!(reader.header().samples[0], "sample1");

        Ok(())
    }

    #[test]
    fn test_vcf_record_parsing() {
        let line = "chr1\t12345\trs123\tA\tG\t30.5\tPASS\tDP=100\tGT\t0/1";
        let record = VcfReader::parse_record(line).unwrap();

        assert_eq!(record.chrom, "chr1");
        assert_eq!(record.pos, 12345);
        assert_eq!(record.id, "rs123");
        assert_eq!(record.reference, "A");
        assert_eq!(record.alt, vec!["G"]);
        assert_eq!(record.qual, Some(30.5));
        assert!(record.is_pass());
    }
}