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
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
//! GFF/GTF format support (gene annotations)
//!
//! GFF (General Feature Format) and GTF (Gene Transfer Format) are
//! tab-delimited text formats for genomic annotations.
//!
//! # Design Philosophy
//!
//! - **Streaming by default**: Records are never buffered unless explicitly requested
//! - **Zero-copy where possible**: Minimize allocations during parsing
//! - **Automatic compression detection**: Handles `.gff`, `.gtf`, `.gff.gz`, `.gtf.gz` transparently
//! - **Lazy evaluation**: Process millions of annotations with O(1) memory
//!
//! # Format Specification
//!
//! GFF/GTF files have 9 tab-delimited columns:
//! 1. seqid - chromosome/scaffold name
//! 2. source - annotation source (e.g., "ENSEMBL", "RefSeq")
//! 3. type - feature type (e.g., "gene", "exon", "CDS")
//! 4. start - 1-based start position (inclusive)
//! 5. end - 1-based end position (inclusive)
//! 6. score - floating point score (or ".")
//! 7. strand - +, -, or .
//! 8. phase - 0, 1, 2, or . (for CDS features)
//! 9. attributes - semicolon-separated key-value pairs
//!
//! # Examples
//!
//! ```no_run
//! use genomicframe_core::formats::gff::GffReader;
//! use genomicframe_core::core::GenomicRecordIterator;
//!
//! // Streaming: O(1) memory, processes one record at a time
//! let mut reader = GffReader::from_path("annotations.gff.gz")?;
//!
//! while let Some(record) = reader.next_record()? {
//!     if record.feature_type == "gene" {
//!         println!("Gene: {} at {}:{}-{}",
//!             record.seqid, record.start, record.end,
//!             record.strand);
//!     }
//! }
//! # Ok::<(), genomicframe_core::error::Error>(())
//! ```

use crate::core::{GenomicInterval, GenomicReader, GenomicRecordIterator, Strand};
use crate::error::{Error, Result};
use crate::io::Compression;
// use anyhow::Ok;
use flate2::read::MultiGzDecoder;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

/// A single GFF/GTF record (feature annotation)
#[derive(Debug, Clone)]
pub struct GffRecord {
    /// Sequence/chromosome name
    pub seqid: String,
    /// Source of the annotation
    pub source: String,
    /// Feature type (e.g., "gene", "exon", "CDS")
    pub feature_type: String,
    /// Start position (1-based, inclusive)
    pub start: u64,
    /// End position (1-based, inclusive)
    pub end: u64,
    /// Score
    pub score: Option<f64>,
    /// Strand
    pub strand: Strand,
    /// Phase (for CDS features)
    pub phase: Option<u8>,
    /// Attributes (semicolon-separated key-value pairs, stored as raw string)
    pub attributes: String,
}

impl GffRecord {
    /// Convert to a genomic interval (0-based, half-open)
    pub fn to_interval(&self) -> Result<GenomicInterval> {
        GenomicInterval::new(self.seqid.clone(), self.start - 1, self.end)
    }

    /// Parse attributes into a HashMap (GTF format: key "value"; GFF3 format: key=value)
    ///
    /// This is lazy - only parse when needed. Most use cases just need the raw string.
    pub fn parse_attributes(&self) -> HashMap<String, String> {
        let mut attrs = HashMap::new();

        // Detect format: GTF uses quotes, GFF3 uses equals
        if self.attributes.contains('=') {
            // GFF3 format: key1=value1;key2=value2
            for pair in self.attributes.split(';') {
                let pair = pair.trim();
                if pair.is_empty() {
                    continue;
                }
                if let Some((key, value)) = pair.split_once('=') {
                    attrs.insert(key.trim().to_string(), value.trim().to_string());
                }
            }
        } else {
            // GTF format: key1 "value1"; key2 "value2";
            for pair in self.attributes.split(';') {
                let pair = pair.trim();
                if pair.is_empty() {
                    continue;
                }
                let parts: Vec<&str> = pair.splitn(2, ' ').collect();
                if parts.len() == 2 {
                    let key = parts[0].trim();
                    let value = parts[1].trim().trim_matches('"');
                    attrs.insert(key.to_string(), value.to_string());
                }
            }
        }

        attrs
    }

    /// Get a specific attribute value by key
    pub fn get_attribute(&self, key: &str) -> Option<String> {
        self.parse_attributes().get(key).cloned()
    }

    /// Get feature length
    pub fn len(&self) -> u64 {
        self.end.saturating_sub(self.start) + 1
    }

    /// Check if feature has zero length (shouldn't happen in valid GFF)
    pub fn is_empty(&self) -> bool {
        self.start > self.end
    }
}

/// GFF/GTF header metadata
///
/// GFF files may have header lines starting with ##
/// These provide metadata about the file
#[derive(Debug, Clone, Default)]
pub struct GffHeader {
    /// GFF version (e.g., "3", "2")
    pub version: Option<String>,
    /// Sequence region definitions: ##sequence-region seqid start end
    pub sequence_regions: Vec<String>,
    /// Other header directives
    pub directives: Vec<String>,
}

/// GFF/GTF file reader (streaming, memory-efficient)
///
/// **The only way to create a GffReader is `GffReader::from_path()`.**
///
/// This follows the same design as VcfReader - one obvious way to read a file.
pub struct GffReader {
    reader: Box<dyn BufRead>,
    header: GffHeader,
    line_buffer: String,
}

impl GffReader {
    /// Open a GFF/GTF file - handles .gff, .gtf, .gff.gz, .gtf.gz automatically
    ///
    /// # Memory Behavior
    ///
    /// - Opens file handle (~8KB buffer)
    /// - Parses header (~1-10KB typically)
    /// - **Does NOT load annotations into memory**
    /// - Records are parsed on-demand as you iterate
    ///
    /// # Example
    ///
    /// ```no_run
    /// use genomicframe_core::formats::gff::GffReader;
    /// use genomicframe_core::core::GenomicRecordIterator;
    ///
    /// // Works with multi-GB files using only ~10KB RAM
    /// let mut reader = GffReader::from_path("gencode.v45.gff3.gz")?;
    ///
    /// while let Some(record) = reader.next_record()? {
    ///     if record.feature_type == "exon" {
    ///         println!("{:?}", record);
    ///     }
    /// }
    /// # 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)),
        };

        Self::parse_header(reader)
    }

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

    /// Internal: Parse GFF header and return reader positioned at first record
    fn parse_header(mut reader: Box<dyn BufRead>) -> Result<Self> {
        let mut header = GffHeader::default();
        let mut line = String::new();
        let first_data_line: Option<String> = loop {
            line.clear();
            let bytes_read = reader.read_line(&mut line)?;

            // Empty file
            if bytes_read == 0 {
                break None;
            }

            let trimmed = line.trim();

            // Skip empty lines
            if trimmed.is_empty() {
                continue;
            }

            // Check if this is a header line
            if !trimmed.starts_with('#') {
                // Hit first data line - save it and done with header
                break Some(trimmed.to_string());
            }

            // Parse header directives (lines starting with ##)
            if trimmed.starts_with("##") {
                if trimmed.starts_with("##gff-version") {
                    header.version = trimmed
                        .trim_start_matches("##gff-version")
                        .trim()
                        .split_whitespace()
                        .next()
                        .map(|s| s.to_string());
                } else if trimmed.starts_with("##sequence-region") {
                    header.sequence_regions.push(trimmed.to_string());
                } else {
                    header.directives.push(trimmed.to_string());
                }
            }
            // Single # is a comment, just skip it
        };

        // Create reader with the first data line pre-loaded
        let line_buffer = first_data_line.unwrap_or_else(|| String::with_capacity(512));

        Ok(Self {
            reader,
            header,
            line_buffer,
        })
    }

    /// Parse a single GFF record line
    fn parse_record(line: &str) -> Result<GffRecord> {
        let parts: Vec<&str> = line.split('\t').collect();

        if parts.len() != 9 {
            return Err(Error::Parse(format!(
                "Invalid GFF record: expected 9 fields, got {}",
                parts.len()
            )));
        }

        // Parse start and end positions
        let start = parts[3]
            .parse::<u64>()
            .map_err(|e| Error::Parse(format!("Invalid start position '{}': {}", parts[3], e)))?;

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

        // Validate start <= end
        if start > end {
            return Err(Error::Parse(format!(
                "Invalid GFF record: start ({}) > end ({})",
                start, end
            )));
        }

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

        // Parse strand
        let strand = match parts[6] {
            "+" => Strand::Forward,
            "-" => Strand::Reverse,
            "." => Strand::Unknown,
            other => {
                return Err(Error::Parse(format!(
                    "Invalid strand '{}': must be +, -, or .",
                    other
                )))
            }
        };

        // Parse phase (optional, for CDS features)
        let phase = if parts[7] == "." {
            None
        } else {
            let p = parts[7]
                .parse::<u8>()
                .map_err(|e| Error::Parse(format!("Invalid phase '{}': {}", parts[7], e)))?;
            if p > 2 {
                return Err(Error::Parse(format!(
                    "Invalid phase '{}': must be 0, 1, 2, or .",
                    p
                )));
            }
            Some(p)
        };

        Ok(GffRecord {
            seqid: parts[0].to_string(),
            source: parts[1].to_string(),
            feature_type: parts[2].to_string(),
            start,
            end,
            score,
            strand,
            phase,
            attributes: parts[8].to_string(),
        })
    }
}

impl GenomicRecordIterator for GffReader {
    type Record = GffRecord;

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

    fn next_record(&mut self) -> Result<Option<Self::Record>> {
        loop {
            // If we have a pre-loaded line (from parse_header), use it first
            if !self.line_buffer.is_empty() {
                let line = self.line_buffer.clone();
                self.line_buffer.clear();

                let trimmed = line.trim();
                if !trimmed.is_empty() && !trimmed.starts_with('#') {
                    return Ok(Some(Self::parse_record(trimmed)?));
                }
                // If it was empty or a comment, fall through to read next line
            }

            // Read next line from file
            let bytes_read = self.reader.read_line(&mut self.line_buffer)?;

            // End of file
            if bytes_read == 0 {
                return Ok(None);
            }

            let line = self.line_buffer.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                self.line_buffer.clear();
                continue;
            }

            let result = Self::parse_record(line)?;
            self.line_buffer.clear();
            return Ok(Some(result));
        }
    }
}

impl GenomicReader for GffReader {
    type Metadata = GffHeader;

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

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

    #[test]
    fn test_gff_header_parsing() -> Result<()> {
        let gff_data = "##gff-version 3\n\
                        ##sequence-region chr1 1 248956422\n\
                        chr1\tENSEMBL\tgene\t1000\t2000\t.\t+\t.\tID=gene1;Name=BRCA1\n";

        let mut temp_file = NamedTempFile::new()?;
        temp_file.write_all(gff_data.as_bytes())?;
        temp_file.flush()?;

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

        assert_eq!(reader.header().version, Some("3".to_string()));
        assert_eq!(reader.header().sequence_regions.len(), 1);

        let record = reader.next_record()?.unwrap();
        assert_eq!(record.seqid, "chr1");
        assert_eq!(record.source, "ENSEMBL");

        Ok(())
    }

    #[test]
    fn test_gff_record_parsing() -> Result<()> {
        let line = "chr1\tENSEMBL\tgene\t1000\t2000\t100.5\t+\t.\tID=gene1;Name=BRCA1";
        let record = GffReader::parse_record(line)?;

        assert_eq!(record.seqid, "chr1");
        assert_eq!(record.source, "ENSEMBL");
        assert_eq!(record.feature_type, "gene");
        assert_eq!(record.start, 1000);
        assert_eq!(record.end, 2000);
        assert_eq!(record.score, Some(100.5));
        assert_eq!(record.strand, Strand::Forward);
        assert_eq!(record.phase, None);
        assert_eq!(record.len(), 1001);

        Ok(())
    }

    #[test]
    fn test_gff3_attributes() -> Result<()> {
        let line = "chr1\t.\tgene\t1000\t2000\t.\t+\t.\tID=gene1;Name=BRCA1;Dbxref=GeneID:672";
        let record = GffReader::parse_record(line)?;

        let attrs = record.parse_attributes();
        assert_eq!(attrs.get("ID"), Some(&"gene1".to_string()));
        assert_eq!(attrs.get("Name"), Some(&"BRCA1".to_string()));
        assert_eq!(attrs.get("Dbxref"), Some(&"GeneID:672".to_string()));

        assert_eq!(record.get_attribute("ID"), Some("gene1".to_string()));

        Ok(())
    }

    #[test]
    fn test_gtf_attributes() -> Result<()> {
        let line = "chr1\t.\texon\t1000\t2000\t.\t+\t.\tgene_id \"ENSG00000000001\"; transcript_id \"ENST00000000001\";";
        let record = GffReader::parse_record(line)?;

        let attrs = record.parse_attributes();
        assert_eq!(attrs.get("gene_id"), Some(&"ENSG00000000001".to_string()));
        assert_eq!(
            attrs.get("transcript_id"),
            Some(&"ENST00000000001".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_invalid_positions() {
        let line = "chr1\t.\tgene\t2000\t1000\t.\t+\t.\tID=gene1";
        let result = GffReader::parse_record(line);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_phase() {
        let line = "chr1\t.\tCDS\t1000\t2000\t.\t+\t3\tID=cds1";
        let result = GffReader::parse_record(line);
        assert!(result.is_err());
    }

    #[test]
    fn test_strand_parsing() -> Result<()> {
        let forward = "chr1\t.\tgene\t1000\t2000\t.\t+\t.\tID=g1";
        let reverse = "chr1\t.\tgene\t1000\t2000\t.\t-\t.\tID=g2";
        let unknown = "chr1\t.\tgene\t1000\t2000\t.\t.\t.\tID=g3";

        assert_eq!(GffReader::parse_record(forward)?.strand, Strand::Forward);
        assert_eq!(GffReader::parse_record(reverse)?.strand, Strand::Reverse);
        assert_eq!(GffReader::parse_record(unknown)?.strand, Strand::Unknown);

        Ok(())
    }
}