rustkmer 0.5.2

High-performance k-mer counting tool in Rust
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
//! Stats command implementation
//!
//! This module implements the `rustkmer stats` command for calculating
//! comprehensive statistics about RKDB databases.

use crate::cli::args::Args;
use crate::database::stats::{OutputFormat, Result, StatsConfiguration, StatsError};
use anyhow::Context;
use std::path::PathBuf;
use std::time::Instant;

/// Execute the stats command
pub fn execute_stats(args: &Args) -> anyhow::Result<()> {
    if let crate::cli::args::Commands::Stats {
        database,
        format,
        output,
        detailed,
        max_bins,
        approximate,
        progress,
        split_output,
        freq_output,
    } = &args.command
    {
        // Parse output format
        let output_format = match format.as_str() {
            "text" => OutputFormat::Text,
            "json" => OutputFormat::Json,
            "csv" => OutputFormat::Csv,
            "tsv" => OutputFormat::Tsv,
            _ => return Err(anyhow::anyhow!("Invalid output format: {}", format)),
        };

        // Create configuration
        let config = StatsConfiguration {
            output_format,
            detailed: *detailed,
            max_bins: *max_bins,
            approximate: *approximate,
            show_progress: *progress,
            output_path: output.as_ref().map(PathBuf::from),
            split_output: *split_output,
            freq_output_path: freq_output.as_ref().map(PathBuf::from),
        };

        // Execute statistics calculation
        let start_time = Instant::now();
        let stats = calculate_statistics(database.as_str(), config.clone())
            .with_context(|| format!("Failed to calculate statistics for {}", database))?;

        // Output results
        output_results(&stats, &config).with_context(|| "Failed to output statistics")?;

        let elapsed = start_time.elapsed();
        // TODO: Add quiet flag to Args if needed
        eprintln!("Statistics calculated successfully in {:?}", elapsed);

        Ok(())
    } else {
        Err(anyhow::anyhow!("Not a stats command"))
    }
}

/// Calculate statistics for a database file
fn calculate_statistics(
    database_path: &str,
    config: StatsConfiguration,
) -> Result<crate::database::stats::DatabaseStatistics> {
    use std::fs::File;
    use std::io::{BufReader, Seek, SeekFrom};
    use std::path::PathBuf;

    let start_time = std::time::Instant::now();

    // Validate database file exists
    let path = PathBuf::from(database_path);
    if !path.exists() {
        return Err(StatsError::DatabaseNotFound { path });
    }

    // Open database file
    let file = File::open(&path)?;
    let mut file = BufReader::new(file);

    // Read and validate header
    let header = crate::database::format::DatabaseHeader::read_from(&mut file).map_err(|e| {
        StatsError::InvalidFormat {
            reason: format!("Failed to read database header: {}", e),
        }
    })?;

    header.validate().map_err(|e| StatsError::InvalidFormat {
        reason: format!("Invalid database header: {}", e),
    })?;

    // Check if database is empty
    if header.total_kmers == 0 {
        return Err(StatsError::EmptyDatabase);
    }

    // Initialize statistics processor
    let mut processor = crate::database::stats::StreamingStatsProcessor::new(config.clone());

    // Fix for incorrect data_offset in header (same as in query.rs)
    let actual_data_offset = if header.data_offset < 40 || header.data_offset > 1000 {
        42 // Use correct offset when header value is out of valid range
    } else {
        header.data_offset
    };

    // Seek to data section
    file.seek(SeekFrom::Start(actual_data_offset))?;

    // Read all k-mer entries and calculate statistics
    for i in 0..header.total_kmers {
        let entry = crate::database::format::KmerEntry::read_from(&mut file)?;

        // Add count to statistics
        processor.add_count(entry.count)?;

        // Show progress if enabled
        if config.show_progress && (i + 1) % 100000 == 0 {
            eprint!("\rProcessed {} k-mers...", i + 1);
        }
    }

    if config.show_progress {
        eprintln!("\rProcessed {} k-mers... Done!", header.total_kmers);
    }

    // Finalize statistics
    let processing_time = start_time.elapsed();
    let stats = processor.finalize(
        path,
        header.kmer_size,
        header.canonical,
        header.sorted,
        processing_time,
    );

    Ok(stats)
}

/// Output statistics in the configured format
fn output_results(
    stats: &crate::database::stats::DatabaseStatistics,
    config: &StatsConfiguration,
) -> Result<()> {
    use crate::database::stats::OutputFormat;

    if config.split_output {
        // Validate that freq_output_path is provided when split_output is true
        let freq_path =
            config
                .freq_output_path
                .as_ref()
                .ok_or_else(|| StatsError::InvalidFormat {
                    reason: "Frequency output path is required when using split output".to_string(),
                })?;

        // Output basic statistics
        let writer: Box<dyn std::io::Write> = match &config.output_path {
            Some(path) => {
                let file = std::fs::File::create(path)?;
                Box::new(std::io::BufWriter::new(file))
            }
            None => Box::new(std::io::stdout()),
        };

        // Create a modified stats object without frequency distribution for basic stats
        let mut basic_stats = stats.clone();
        basic_stats.frequency_distribution = None;

        match config.output_format {
            OutputFormat::Text => output_text(writer, &basic_stats),
            OutputFormat::Json => output_json(writer, &basic_stats),
            OutputFormat::Csv => output_csv(writer, &basic_stats),
            OutputFormat::Tsv => output_tsv(writer, &basic_stats),
        }?;

        // Output frequency distribution separately
        let freq_writer: Box<dyn std::io::Write> = {
            let file = std::fs::File::create(freq_path)?;
            Box::new(std::io::BufWriter::new(file))
        };

        output_frequency_distribution(freq_writer, stats, config)?;
    } else {
        // Original behavior: single file output
        let writer: Box<dyn std::io::Write> = match &config.output_path {
            Some(path) => {
                let file = std::fs::File::create(path)?;
                Box::new(std::io::BufWriter::new(file))
            }
            None => Box::new(std::io::stdout()),
        };

        match config.output_format {
            OutputFormat::Text => output_text(writer, stats)?,
            OutputFormat::Json => output_json(writer, stats)?,
            OutputFormat::Csv => output_csv(writer, stats)?,
            OutputFormat::Tsv => output_tsv(writer, stats)?,
        }
    }

    Ok(())
}

/// Output statistics in human-readable text format
fn output_text<W: std::io::Write>(
    mut writer: W,
    stats: &crate::database::stats::DatabaseStatistics,
) -> Result<()> {
    writeln!(writer, "Database Statistics")?;
    writeln!(writer, "===================")?;
    writeln!(writer, "Database: {:?}", stats.database_file)?;
    writeln!(writer, "K-mer size: {}", stats.kmer_size)?;
    writeln!(writer, "Canonical: {}", stats.canonical)?;
    writeln!(writer, "Sorted: {}", stats.sorted)?;
    writeln!(writer, "Total k-mers: {}", stats.total_kmers)?;
    writeln!(writer, "Unique k-mers: {}", stats.unique_kmers)?;
    writeln!(writer, "Min count: {}", stats.min_count)?;
    writeln!(writer, "Max count: {}", stats.max_count)?;
    writeln!(writer, "Mean count: {:.2}", stats.mean_count)?;
    writeln!(writer, "Median count: {:.2}", stats.median_count)?;
    writeln!(writer, "Processing time: {:?}", stats.processing_time)?;

    if let Some(ref dist) = stats.frequency_distribution {
        writeln!(writer, "\nFrequency Distribution:")?;
        writeln!(writer, "Count\tFrequency")?;
        for (count, freq) in dist {
            writeln!(writer, "{}\t{}", count, freq)?;
        }
    }

    Ok(())
}

/// Output statistics in JSON format
fn output_json<W: std::io::Write>(
    mut writer: W,
    stats: &crate::database::stats::DatabaseStatistics,
) -> Result<()> {
    serde_json::to_writer(&mut writer, stats)?;
    Ok(())
}

/// Output statistics in CSV format
fn output_csv<W: std::io::Write>(
    mut writer: W,
    stats: &crate::database::stats::DatabaseStatistics,
) -> Result<()> {
    let mut wtr = csv::Writer::from_writer(&mut writer);

    // Write header
    wtr.write_record(&[
        "database_file",
        "kmer_size",
        "canonical",
        "sorted",
        "total_kmers",
        "unique_kmers",
        "min_count",
        "max_count",
        "mean_count",
        "median_count",
        "processing_time_ms",
        "memory_peak_bytes",
        "frequency_distribution_available",
    ])?;

    // Write data record
    wtr.write_record(&[
        stats.database_file.to_string_lossy().as_ref(),
        &stats.kmer_size.to_string(),
        &stats.canonical.to_string(),
        &stats.sorted.to_string(),
        &stats.total_kmers.to_string(),
        &stats.unique_kmers.to_string(),
        &stats.min_count.to_string(),
        &stats.max_count.to_string(),
        &stats.mean_count.to_string(),
        &stats.median_count.to_string(),
        &stats.processing_time.as_millis().to_string(),
        &stats.memory_peak_bytes.to_string(),
        if stats.frequency_distribution.is_some() {
            "true"
        } else {
            "false"
        },
    ])?;

    // Note: Frequency distribution is too large for standard CSV format
    // It's available in JSON format or through the text output

    wtr.flush()?;
    Ok(())
}

/// Output statistics in TSV format
fn output_tsv<W: std::io::Write>(
    mut writer: W,
    stats: &crate::database::stats::DatabaseStatistics,
) -> Result<()> {
    let mut wtr = csv::WriterBuilder::new()
        .delimiter(b'\t')
        .from_writer(&mut writer);

    // Write header
    wtr.write_record(&[
        "database_file",
        "kmer_size",
        "canonical",
        "sorted",
        "total_kmers",
        "unique_kmers",
        "min_count",
        "max_count",
        "mean_count",
        "median_count",
        "processing_time_ms",
        "memory_peak_bytes",
        "frequency_distribution_available",
    ])?;

    // Write data record
    wtr.write_record(&[
        stats.database_file.to_string_lossy().as_ref(),
        &stats.kmer_size.to_string(),
        &stats.canonical.to_string(),
        &stats.sorted.to_string(),
        &stats.total_kmers.to_string(),
        &stats.unique_kmers.to_string(),
        &stats.min_count.to_string(),
        &stats.max_count.to_string(),
        &stats.mean_count.to_string(),
        &stats.median_count.to_string(),
        &stats.processing_time.as_millis().to_string(),
        &stats.memory_peak_bytes.to_string(),
        if stats.frequency_distribution.is_some() {
            "true"
        } else {
            "false"
        },
    ])?;

    // Note: Frequency distribution is too large for standard TSV format
    // It's available in JSON format or through the text output
    if stats.frequency_distribution.is_some() {
        wtr.write_record(&[
            "frequency_distribution_available",
            "true",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
        ])?;
    }

    wtr.flush()?;
    Ok(())
}
/// Output frequency distribution to a separate file
fn output_frequency_distribution<W: std::io::Write>(
    mut writer: W,
    stats: &crate::database::stats::DatabaseStatistics,
    config: &StatsConfiguration,
) -> Result<()> {
    use crate::database::stats::OutputFormat;

    if let Some(ref dist) = stats.frequency_distribution {
        match config.output_format {
            OutputFormat::Text => {
                writeln!(writer, "Frequency Distribution")?;
                writeln!(writer, "====================")?;
                writeln!(writer, "Database: {:?}", stats.database_file)?;
                writeln!(writer, "K-mer size: {}", stats.kmer_size)?;
                writeln!(writer, "Total k-mers: {}", stats.total_kmers)?;
                writeln!(writer, "Unique k-mers: {}", stats.unique_kmers)?;
                writeln!(writer, "")?;
                writeln!(writer, "Count	Frequency")?;
                for (count, freq) in dist {
                    writeln!(writer, "{}	{}", count, freq)?;
                }
            }
            OutputFormat::Json => {
                // Create a JSON object with just the frequency distribution
                let freq_json = serde_json::json!({
                    "database_file": stats.database_file,
                    "kmer_size": stats.kmer_size,
                    "frequency_distribution": dist
                });
                serde_json::to_writer(&mut writer, &freq_json)?;
            }
            OutputFormat::Csv => {
                let mut wtr = csv::Writer::from_writer(&mut writer);

                // Write header
                wtr.write_record(&["Count", "Frequency"])?;

                // Write data
                for (count, freq) in dist {
                    wtr.write_record(&[&count.to_string(), &freq.to_string()])?;
                }

                wtr.flush()?;
            }
            OutputFormat::Tsv => {
                let mut wtr = csv::WriterBuilder::new()
                    .delimiter(b'\t')
                    .from_writer(&mut writer);

                // Write header
                wtr.write_record(&["Count", "Frequency"])?;

                // Write data
                for (count, freq) in dist {
                    wtr.write_record(&[&count.to_string(), &freq.to_string()])?;
                }

                wtr.flush()?;
            }
        }
    } else {
        return Err(StatsError::InvalidFormat {
            reason: "No frequency distribution data available".to_string(),
        });
    }

    Ok(())
}