deepbiop_utils/io.rs
1mod json;
2#[cfg(feature = "cache")]
3mod parquet;
4
5use std::path::Path;
6
7use anyhow::Result;
8pub use json::*;
9#[cfg(feature = "cache")]
10pub use parquet::*;
11use std::fs::File;
12
13use flate2::read::GzDecoder;
14use noodles::bgzf;
15#[cfg(feature = "python")]
16use pyo3::prelude::*;
17#[cfg(feature = "python")]
18use pyo3_stub_gen::derive::*;
19use std::io;
20use std::io::Read;
21use std::path::PathBuf;
22
23/// Represents different types of file compression formats
24///
25/// This enum is used to identify and handle various compression formats commonly used for files.
26/// It can be used in Python through the deepbiop.utils module.
27///
28/// # Variants
29///
30/// * `Uncompress` - Uncompressed/raw file format
31/// * `Gzip` - Standard gzip compression (.gz files)
32/// * `Bgzip` - Blocked gzip format, commonly used in bioinformatics
33/// * `Zip` - ZIP archive format
34/// * `Bzip2` - bzip2 compression format
35/// * `Xz` - XZ compression format (LZMA2)
36/// * `Zstd` - Zstandard compression format
37/// * `Unknown` - Unknown or unrecognized compression format
38#[cfg_attr(feature = "python", gen_stub_pyclass_enum)]
39#[cfg_attr(
40 feature = "python",
41 pyclass(eq, eq_int, module = "deepbiop.utils", skip_from_py_object)
42)]
43#[derive(Debug, PartialEq, Clone, Eq, Hash)]
44pub enum CompressedType {
45 Uncompress,
46 Gzip,
47 Bgzip,
48 Zip,
49 Bzip2,
50 Xz,
51 Zstd,
52 Unknown,
53}
54
55/// Determines the compression type of a file by examining its header/signature
56///
57/// This function reads the first few bytes of a file and checks for known magic numbers
58/// or file signatures to identify the compression format used.
59///
60/// # Arguments
61///
62/// * `file_path` - Path to the file to check, can be any type that converts to a Path
63///
64/// # Returns
65///
66/// * `Result<CompressedType>` - The detected compression type wrapped in a Result
67///
68/// # Errors
69///
70/// Returns an error if:
71/// * The file cannot be opened
72/// * There are issues reading the file header
73///
74/// # Examples
75///
76/// ```no_run
77/// use deepbiop_utils::io::check_compressed_type;
78/// use std::path::Path;
79///
80/// let file_path = Path::new("test.gz");
81/// let compression = check_compressed_type(file_path).unwrap();
82/// ```
83pub fn check_compressed_type<P: AsRef<Path>>(file_path: P) -> Result<CompressedType> {
84 let mut file = File::open(file_path)?;
85 let mut buffer = [0u8; 18]; // Large enough for BGZF detection
86
87 // Read the first few bytes
88 let bytes_read = file.read(&mut buffer)?;
89 if bytes_read < 2 {
90 return Ok(CompressedType::Uncompress);
91 }
92
93 // Check magic numbers/file signatures
94 match &buffer[..] {
95 // Check for BGZF first (starts with gzip magic number + specific extra fields)
96 [0x1f, 0x8b, 0x08, 0x04, ..] if bytes_read >= 18 => {
97 // Check for BGZF extra field
98 let xlen = u16::from_le_bytes([buffer[10], buffer[11]]) as usize;
99 if xlen >= 6 && buffer[12] == 0x42 // B
100 && buffer[13] == 0x43 // C
101 && buffer[14] == 0x02 // Length of subfield (2)
102 && buffer[15] == 0x00
103 // Length of subfield (2)
104 {
105 Ok(CompressedType::Bgzip)
106 } else {
107 Ok(CompressedType::Gzip)
108 }
109 }
110
111 // Regular Gzip: starts with 0x1F 0x8B
112 [0x1f, 0x8b, ..] => Ok(CompressedType::Gzip),
113
114 // Zip: starts with "PK\x03\x04" or "PK\x05\x06" (empty archive) or "PK\x07\x08" (spanned archive)
115 [0x50, 0x4b, 0x03, 0x04, ..]
116 | [0x50, 0x4b, 0x05, 0x06, ..]
117 | [0x50, 0x4b, 0x07, 0x08, ..] => Ok(CompressedType::Zip),
118
119 // Bzip2: starts with "BZh"
120 [0x42, 0x5a, 0x68, ..] => Ok(CompressedType::Bzip2),
121
122 // XZ: starts with 0xFD "7zXZ"
123 [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, ..] => Ok(CompressedType::Xz),
124
125 // Zstandard: starts with magic number 0xFD2FB528
126 [0x28, 0xb5, 0x2f, 0xfd, ..] => Ok(CompressedType::Zstd),
127
128 // If no compression signature is found, assume it's a normal file
129 _ => {
130 // Additional check for text/binary content could be added here
131 Ok(CompressedType::Uncompress)
132 }
133 }
134}
135
136/// Checks if a file is compressed by examining its file signature/magic numbers
137///
138/// # Arguments
139/// * `file_path` - Path to the file to check
140///
141/// # Returns
142/// * `Ok(true)` if the file is compressed (gzip, bgzip, zip, bzip2, xz, zstd)
143/// * `Ok(false)` if the file is uncompressed or compression type is unknown
144/// * `Err` if there was an error reading the file
145///
146/// # Example
147/// ```no_run
148/// use deepbiop_utils::io;
149///
150/// let is_compressed = io::is_compressed("file.gz").unwrap();
151/// assert!(is_compressed);
152/// ```
153pub fn is_compressed<P: AsRef<Path>>(file_path: P) -> Result<bool> {
154 match check_compressed_type(file_path)? {
155 CompressedType::Uncompress => Ok(false),
156 CompressedType::Unknown => Ok(false),
157 _ => Ok(true),
158 }
159}
160
161/// Creates a reader for a file that may be compressed
162///
163/// This function detects the compression type of the file and returns an appropriate reader.
164/// Currently supports uncompressed files, gzip, and bgzip formats.
165///
166/// # Arguments
167/// * `file_path` - Path to the file to read, can be compressed or uncompressed
168///
169/// # Returns
170/// * `Ok(Box<dyn io::Read>)` - A boxed reader appropriate for the file's compression
171/// * `Err` - If the file cannot be opened or has an unsupported compression type
172pub fn create_reader_for_compressed_file<P: AsRef<Path>>(
173 file_path: P,
174) -> Result<Box<dyn io::Read + Send + Sync>> {
175 let compressed_type = check_compressed_type(file_path.as_ref())?;
176 let file = File::open(file_path)?;
177
178 Ok(match compressed_type {
179 CompressedType::Uncompress => Box::new(file),
180 CompressedType::Gzip => Box::new(GzDecoder::new(file)),
181 CompressedType::Bgzip => Box::new(bgzf::io::Reader::new(file)),
182 _ => return Err(anyhow::anyhow!("unsupported compression type")),
183 })
184}
185
186/// Creates a multithreaded BGZip reader for compressed files
187///
188/// This function creates a reader optimized for reading BGZip-compressed files
189/// using multiple threads for decompression. The thread count is automatically
190/// capped at the system's available parallelism.
191///
192/// # Arguments
193///
194/// * `file_path` - Path to the BGZip-compressed file
195/// * `threads` - Optional number of threads to use (defaults to 2 if None)
196///
197/// # Returns
198///
199/// * `Ok(bgzf::io::Reader<File>)` - A multithreaded BGZip reader
200/// * `Err` - If the file cannot be opened
201///
202/// # Examples
203///
204/// ```no_run
205/// use deepbiop_utils::io::create_multithreaded_reader;
206/// use std::path::Path;
207///
208/// let reader = create_multithreaded_reader(Path::new("data.fq.gz"), Some(4)).unwrap();
209/// // Use reader with noodles parsers
210/// ```
211pub fn create_multithreaded_reader<P: AsRef<Path>>(
212 file_path: P,
213 threads: Option<usize>,
214) -> Result<bgzf::io::Reader<File>> {
215 use crate::parallel::calculate_worker_count;
216
217 let worker_count = calculate_worker_count(threads);
218 let file = File::open(file_path)?;
219
220 // Note: noodles bgzf::io::Reader doesn't currently expose worker count
221 // configuration in the same way as Writer. This creates a standard reader
222 // that will use internal threading. For now, we return a standard reader.
223 // The worker_count calculation is kept for API consistency and future use.
224 let _ = worker_count; // Acknowledge unused variable for now
225
226 Ok(bgzf::io::Reader::new(file))
227}
228
229/// Creates a multithreaded BGZip writer for compressed files
230///
231/// This function creates a writer optimized for writing BGZip-compressed files
232/// using multiple threads for compression. The thread count is automatically
233/// capped at the system's available parallelism.
234///
235/// # Arguments
236///
237/// * `file_path` - Path where the BGZip-compressed file will be written
238/// * `threads` - Optional number of threads to use (defaults to 2 if None)
239///
240/// # Returns
241///
242/// * `Ok(bgzf::io::MultithreadedWriter<File>)` - A multithreaded BGZip writer
243/// * `Err` - If the file cannot be created
244///
245/// # Examples
246///
247/// ```no_run
248/// use deepbiop_utils::io::create_multithreaded_writer;
249/// use std::path::Path;
250///
251/// let writer = create_multithreaded_writer(Path::new("output.fq.gz"), Some(4)).unwrap();
252/// // Use writer with noodles writers
253/// ```
254pub fn create_multithreaded_writer<P: AsRef<Path>>(
255 file_path: P,
256 threads: Option<usize>,
257) -> Result<bgzf::io::MultithreadedWriter<File>> {
258 use crate::parallel::calculate_worker_count;
259
260 let worker_count = calculate_worker_count(threads.or(Some(2)));
261 let file = File::create(file_path)?;
262
263 Ok(bgzf::io::MultithreadedWriter::with_worker_count(
264 worker_count,
265 file,
266 ))
267}
268
269/// Streams and merges records from multiple files into a single output file
270///
271/// This is a generic function that processes multiple input files sequentially,
272/// reading records one at a time and writing them to a single output file without
273/// loading all data into memory. This is memory-efficient for large biological datasets.
274///
275/// # Type Parameters
276///
277/// * `P` - Path type that can be converted to `AsRef<Path>`
278/// * `R` - Reader type that implements `Iterator<Item = Result<T, E>>`
279/// * `W` - Writer type that can write records
280/// * `T` - Record type being processed
281/// * `E` - Error type from the reader
282/// * `CreateReader` - Function that creates a reader from a path
283/// * `CreateWriter` - Function that creates a writer from a path and thread count
284/// * `WriteRecord` - Function that writes a single record
285///
286/// # Arguments
287///
288/// * `paths` - Slice of input file paths to merge
289/// * `result_path` - Path where the merged output will be written
290/// * `threads` - Optional number of threads for the writer (if supported)
291/// * `create_reader` - Closure that creates a reader for a given path
292/// * `create_writer` - Closure that creates a writer for the output path
293/// * `write_record` - Closure that writes a single record to the writer
294///
295/// # Returns
296///
297/// * `Ok(())` - If all files were successfully merged
298/// * `Err` - If any file operation fails
299///
300/// # Examples
301///
302/// Basic usage pattern (implementation details omitted for brevity):
303///
304/// ```rust,ignore
305/// use deepbiop_utils::io::stream_merge_records;
306/// use std::path::PathBuf;
307/// use anyhow::Result;
308///
309/// // This function demonstrates the pattern for merging FASTQ files
310/// // The actual implementation would need to handle reader/writer lifetimes appropriately
311/// fn merge_fastq_files(paths: &[PathBuf], output: PathBuf) -> Result<()> {
312/// stream_merge_records(
313/// paths,
314/// output.as_path(),
315/// Some(2),
316/// create_fastq_reader, // Function that creates a reader iterator
317/// create_fastq_writer, // Function that creates a writer
318/// write_fastq_record, // Function that writes a single record
319/// )
320/// }
321/// ```
322pub fn stream_merge_records<P, R, W, T, E, CreateReader, CreateWriter, WriteRecord>(
323 paths: &[PathBuf],
324 result_path: P,
325 threads: Option<usize>,
326 create_reader: CreateReader,
327 create_writer: CreateWriter,
328 write_record: WriteRecord,
329) -> Result<()>
330where
331 P: AsRef<Path>,
332 R: Iterator<Item = std::result::Result<T, E>>,
333 E: Into<anyhow::Error>,
334 CreateReader: Fn(&Path) -> Result<R>,
335 CreateWriter: Fn(&Path, Option<usize>) -> Result<W>,
336 WriteRecord: Fn(&mut W, &T) -> Result<()>,
337{
338 log::info!(
339 "Merging {} files to {:?}",
340 paths.len(),
341 result_path.as_ref()
342 );
343
344 let mut writer = create_writer(result_path.as_ref(), threads)?;
345
346 // Process each file sequentially in a streaming fashion
347 for path in paths {
348 log::info!("Processing file: {:?}", path);
349 let reader = create_reader(path)?;
350
351 // Stream records one at a time without loading all into memory
352 for result in reader {
353 let record = result.map_err(|e| e.into())?;
354 write_record(&mut writer, &record)?;
355 }
356 }
357
358 log::info!("Successfully merged {} files", paths.len());
359 Ok(())
360}
361
362/// Represents different types of sequence file formats
363#[cfg_attr(feature = "python", gen_stub_pyclass_enum)]
364#[cfg_attr(
365 feature = "python",
366 pyclass(eq, eq_int, module = "deepbiop.utils", skip_from_py_object)
367)]
368#[derive(Debug, PartialEq, Eq, Clone, Hash)]
369pub enum SequenceFileType {
370 Fasta,
371 Fastq,
372 Unknown,
373}
374
375/// Determines if a file is FASTA or FASTQ format by checking its first character
376///
377/// # Arguments
378/// * `file_path` - Path to the sequence file (can be compressed or uncompressed)
379///
380/// # Returns
381/// * `Ok(SequenceFileType)` - The detected sequence file type
382/// * `Err` - If there was an error reading the file
383///
384/// # Example
385/// ```no_run
386/// use deepbiop_utils::io;
387///
388/// let file_type = io::check_sequence_file_type("sample.fq").unwrap();
389/// ```
390pub fn check_sequence_file_type<P: AsRef<Path>>(file_path: P) -> Result<SequenceFileType> {
391 let mut reader = create_reader_for_compressed_file(file_path)?;
392 let mut buffer = [0u8; 1];
393
394 // Read the first byte
395 match reader.read_exact(&mut buffer) {
396 Ok(_) => match buffer[0] as char {
397 '>' => Ok(SequenceFileType::Fasta),
398 '@' => Ok(SequenceFileType::Fastq),
399 _ => Ok(SequenceFileType::Unknown),
400 },
401 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(SequenceFileType::Unknown),
402 Err(e) => Err(e.into()),
403 }
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409 use std::io::Write;
410 use tempfile::NamedTempFile;
411
412 #[test]
413 fn test_check_file_type() -> Result<()> {
414 // Test gzip file
415 let mut gzip_file = NamedTempFile::new()?;
416 gzip_file.write_all(&[0x1f, 0x8b])?;
417 assert_eq!(
418 check_compressed_type(gzip_file.path())?,
419 CompressedType::Gzip
420 );
421
422 // Test bgzip file
423 let mut bgzip_file = NamedTempFile::new()?;
424 let bgzip_header = [
425 0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x42, 0x43,
426 0x02, 0x00, 0x00, 0x00,
427 ];
428 bgzip_file.write_all(&bgzip_header)?;
429 assert_eq!(
430 check_compressed_type(bgzip_file.path())?,
431 CompressedType::Bgzip
432 );
433
434 // Test zip file
435 let mut zip_file = NamedTempFile::new()?;
436 zip_file.write_all(&[0x50, 0x4b, 0x03, 0x04])?;
437 assert_eq!(check_compressed_type(zip_file.path())?, CompressedType::Zip);
438
439 // Test bzip2 file
440 let mut bzip2_file = NamedTempFile::new()?;
441 bzip2_file.write_all(&[0x42, 0x5a, 0x68])?;
442 assert_eq!(
443 check_compressed_type(bzip2_file.path())?,
444 CompressedType::Bzip2
445 );
446
447 // Test xz file
448 let mut xz_file = NamedTempFile::new()?;
449 xz_file.write_all(&[0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00])?;
450 assert_eq!(check_compressed_type(xz_file.path())?, CompressedType::Xz);
451
452 // Test zstd file
453 let mut zstd_file = NamedTempFile::new()?;
454 zstd_file.write_all(&[0x28, 0xb5, 0x2f, 0xfd])?;
455 assert_eq!(
456 check_compressed_type(zstd_file.path())?,
457 CompressedType::Zstd
458 );
459
460 // Test normal file
461 let mut normal_file = NamedTempFile::new()?;
462 normal_file.write_all(b"Hello world")?;
463 assert_eq!(
464 check_compressed_type(normal_file.path())?,
465 CompressedType::Uncompress
466 );
467
468 Ok(())
469 }
470
471 #[test]
472 fn test_is_compressed() -> Result<()> {
473 // Test compressed file
474 let mut gzip_file = NamedTempFile::new()?;
475 gzip_file.write_all(&[0x1f, 0x8b])?;
476 assert!(is_compressed(gzip_file.path())?);
477
478 // Test uncompressed file
479 let mut normal_file = NamedTempFile::new()?;
480 normal_file.write_all(b"Hello world")?;
481 assert!(!is_compressed(normal_file.path())?);
482
483 Ok(())
484 }
485
486 #[test]
487 fn test_real_example() -> Result<()> {
488 let test1 = "./tests/data/test.fastq.gz";
489 let test2 = "./tests/data/test.fastqbgz.gz";
490 let test3 = "./tests/data/test.fastq";
491
492 assert_eq!(check_compressed_type(test1)?, CompressedType::Gzip);
493 assert_eq!(check_compressed_type(test2)?, CompressedType::Bgzip);
494 assert_eq!(check_compressed_type(test3)?, CompressedType::Uncompress);
495 Ok(())
496 }
497
498 #[test]
499 fn test_sequence_file_type() -> Result<()> {
500 let test_fq = "./tests/data/test.fastq";
501 assert_eq!(check_sequence_file_type(test_fq)?, SequenceFileType::Fastq);
502
503 let test_fa = "./tests/data/test.fa.gz";
504 assert_eq!(check_sequence_file_type(test_fa)?, SequenceFileType::Fasta);
505
506 let test_compresed_fq = "./tests/data/test.fastq.gz";
507 assert_eq!(
508 check_sequence_file_type(test_compresed_fq)?,
509 SequenceFileType::Fastq
510 );
511 Ok(())
512 }
513}