peacoqc-rs 0.2.4

PeacoQC quality control algorithms for flow cytometry
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
//! Export functionality for PeacoQC results
//!
//! This module provides functions to export QC results in various formats:
//! - CSV with boolean values (0/1) - recommended for general use
//! - CSV with numeric codes (2000/6000) - R-compatible format
//! - JSON metadata - structured format with QC metrics
//!
//! # Example
//!
//! ```no_run
//! use peacoqc_rs::{PeacoQCResult, PeacoQCConfig};
//! use std::path::Path;
//!
//! # let result: PeacoQCResult = todo!();
//! # let config: PeacoQCConfig = todo!();
//! // Export boolean CSV (recommended)
//! result.export_csv_boolean("qc_results.csv")?;
//!
//! // Export numeric CSV (R-compatible)
//! result.export_csv_numeric("qc_results_r.csv", 2000, 6000)?;
//!
//! // Export JSON metadata
//! result.export_json_metadata(&config, "qc_metadata.json")?;
//! # Ok::<(), peacoqc_rs::PeacoQCError>(())
//! ```

use crate::error::{PeacoQCError, Result};
use crate::qc::{PeacoQCConfig, PeacoQCResult};
use serde::Serialize;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

/// Export format options
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QCExportFormat {
    /// Boolean CSV format (0/1 values)
    BooleanCsv,
    /// Numeric CSV format (2000/6000 or custom values)
    NumericCsv,
    /// JSON metadata format
    JsonMetadata,
}

/// Export options for CSV formats
#[derive(Debug, Clone)]
pub struct QCExportOptions {
    /// Column name for CSV exports (default: "PeacoQC")
    pub column_name: String,
    /// Good event value for numeric CSV (default: 2000)
    pub good_value: u16,
    /// Bad event value for numeric CSV (default: 6000)
    pub bad_value: u16,
}

impl Default for QCExportOptions {
    fn default() -> Self {
        Self {
            column_name: "PeacoQC".to_string(),
            good_value: 2000,
            bad_value: 6000,
        }
    }
}

/// JSON structure for QC metadata export
#[derive(Debug, Serialize, serde::Deserialize)]
struct QCJsonMetadata {
    /// Total number of events analyzed
    n_events_before: usize,
    /// Number of good events
    n_events_after: usize,
    /// Number of bad events removed
    n_events_removed: usize,
    /// Percentage of events removed
    percentage_removed: f64,
    /// IT removal percentage (if used)
    it_percentage: Option<f64>,
    /// MAD removal percentage (if used)
    mad_percentage: Option<f64>,
    /// Consecutive filtering percentage
    consecutive_percentage: f64,
    /// Number of bins used
    n_bins: usize,
    /// Events per bin
    events_per_bin: usize,
    /// Channels analyzed
    channels_analyzed: Vec<String>,
    /// QC configuration used
    config: QCConfigJson,
}

/// Simplified config for JSON export
#[derive(Debug, Serialize, serde::Deserialize)]
struct QCConfigJson {
    /// QC mode used
    qc_mode: String,
    /// MAD threshold
    mad: f64,
    /// IT limit
    it_limit: f64,
    /// Consecutive bins threshold
    consecutive_bins: usize,
    /// Remove zeros flag
    remove_zeros: bool,
}

impl From<&PeacoQCConfig> for QCConfigJson {
    fn from(config: &PeacoQCConfig) -> Self {
        Self {
            qc_mode: format!("{:?}", config.determine_good_cells),
            mad: config.mad,
            it_limit: config.it_limit,
            consecutive_bins: config.consecutive_bins,
            remove_zeros: config.remove_zeros,
        }
    }
}

/// Export QC results as boolean CSV (0/1 values)
///
/// This format is recommended for general use and works well with:
/// - pandas: `df[df['PeacoQC'] == 1]`
/// - R: `df[df$PeacoQC == 1, ]`
/// - SQL: `WHERE PeacoQC = 1`
///
/// # Format
///
/// ```csv
/// PeacoQC
/// 1
/// 1
/// 0
/// 1
/// ```
///
/// Where:
/// - `1` = good event (keep)
/// - `0` = bad event (remove)
///
/// # Arguments
///
/// * `result` - PeacoQC result to export
/// * `path` - Output file path
/// * `column_name` - Optional column name (default: "PeacoQC")
///
/// # Errors
///
/// Returns an error if:
/// - The path is invalid
/// - The file cannot be written
/// - The good_cells vector is empty
pub fn export_csv_boolean(
    result: &PeacoQCResult,
    path: impl AsRef<Path>,
    column_name: Option<&str>,
) -> Result<()> {
    let path = path.as_ref();
    let column_name = column_name.unwrap_or("PeacoQC");

    if result.good_cells.is_empty() {
        return Err(PeacoQCError::ExportError(
            "Cannot export empty QC results".to_string(),
        ));
    }

    let file = File::create(path).map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to create file {}: {}", path.display(), e))
    })?;

    let mut writer = BufWriter::new(file);

    // Write header
    writeln!(writer, "{}", column_name).map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to write header: {}", e))
    })?;

    // Write data
    for &is_good in &result.good_cells {
        let value = if is_good { 1 } else { 0 };
        writeln!(writer, "{}", value).map_err(|e| {
            PeacoQCError::WriteError(format!("Failed to write data: {}", e))
        })?;
    }

    writer.flush().map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to flush file: {}", e))
    })?;

    Ok(())
}

/// Export QC results as numeric CSV (2000/6000 or custom values)
///
/// This format is compatible with the R PeacoQC package output.
/// Default values match R implementation: 2000 = good, 6000 = bad.
///
/// # Format
///
/// ```csv
/// PeacoQC
/// 2000
/// 2000
/// 6000
/// 2000
/// ```
///
/// Where:
/// - `2000` (or custom good_value) = good event (keep)
/// - `6000` (or custom bad_value) = bad event (remove)
///
/// # Arguments
///
/// * `result` - PeacoQC result to export
/// * `path` - Output file path
/// * `good_value` - Value for good events (default: 2000)
/// * `bad_value` - Value for bad events (default: 6000)
/// * `column_name` - Optional column name (default: "PeacoQC")
///
/// # Errors
///
/// Returns an error if:
/// - The path is invalid
/// - The file cannot be written
/// - The good_cells vector is empty
pub fn export_csv_numeric(
    result: &PeacoQCResult,
    path: impl AsRef<Path>,
    good_value: u16,
    bad_value: u16,
    column_name: Option<&str>,
) -> Result<()> {
    let path = path.as_ref();
    let column_name = column_name.unwrap_or("PeacoQC");

    if result.good_cells.is_empty() {
        return Err(PeacoQCError::ExportError(
            "Cannot export empty QC results".to_string(),
        ));
    }

    let file = File::create(path).map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to create file {}: {}", path.display(), e))
    })?;

    let mut writer = BufWriter::new(file);

    // Write header
    writeln!(writer, "{}", column_name).map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to write header: {}", e))
    })?;

    // Write data
    for &is_good in &result.good_cells {
        let value = if is_good { good_value } else { bad_value };
        writeln!(writer, "{}", value).map_err(|e| {
            PeacoQCError::WriteError(format!("Failed to write data: {}", e))
        })?;
    }

    writer.flush().map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to flush file: {}", e))
    })?;

    Ok(())
}

/// Export QC results as JSON metadata
///
/// This format includes comprehensive QC metrics and configuration,
/// making it ideal for:
/// - Programmatic access to QC results
/// - Reporting and documentation
/// - Provenance tracking
///
/// # Format
///
/// ```json
/// {
///   "n_events_before": 713904,
///   "n_events_after": 631400,
///   "n_events_removed": 82504,
///   "percentage_removed": 11.56,
///   "it_percentage": 0.0,
///   "mad_percentage": 11.56,
///   "consecutive_percentage": 0.0,
///   "n_bins": 1427,
///   "events_per_bin": 500,
///   "channels_analyzed": ["FL1-A", "FL2-A"],
///   "config": {
///     "qc_mode": "All",
///     "mad": 6.0,
///     "it_limit": 0.6,
///     "consecutive_bins": 5,
///     "remove_zeros": false
///   }
/// }
/// ```
///
/// # Arguments
///
/// * `result` - PeacoQC result to export
/// * `config` - QC configuration used
/// * `path` - Output file path
///
/// # Errors
///
/// Returns an error if:
/// - The path is invalid
/// - The file cannot be written
/// - JSON serialization fails
pub fn export_json_metadata(
    result: &PeacoQCResult,
    config: &PeacoQCConfig,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();

    let n_events_before = result.good_cells.len();
    let n_events_after = result.good_cells.iter().filter(|&&x| x).count();
    let n_events_removed = n_events_before - n_events_after;

    let metadata = QCJsonMetadata {
        n_events_before,
        n_events_after,
        n_events_removed,
        percentage_removed: result.percentage_removed,
        it_percentage: result.it_percentage,
        mad_percentage: result.mad_percentage,
        consecutive_percentage: result.consecutive_percentage,
        n_bins: result.n_bins,
        events_per_bin: result.events_per_bin,
        channels_analyzed: config.channels.clone(),
        config: QCConfigJson::from(config),
    };

    let file = File::create(path).map_err(|e| {
        PeacoQCError::WriteError(format!("Failed to create file {}: {}", path.display(), e))
    })?;

    serde_json::to_writer_pretty(file, &metadata).map_err(|e| {
        PeacoQCError::ExportError(format!("Failed to serialize JSON: {}", e))
    })?;

    Ok(())
}

/// Export QC results as a new FCS file with QC parameter column
///
/// This creates a NEW FCS file (doesn't modify the original) with:
/// - All original parameters
/// - New "PeacoQC" parameter with 0/1 values
/// - Only good events (if filter=true) or all events with QC column (if filter=false)
///
/// **Note**: Requires FCS writing support in flow-fcs crate
///
/// # Arguments
///
/// * `fcs` - Original FCS file
/// * `result` - PeacoQC result
/// * `output_path` - Path for new FCS file
/// * `filter` - If true, only export good events; if false, export all with QC column
///
/// # Errors
///
/// Returns an error if FCS writing is not yet implemented
#[cfg(feature = "flow-fcs")]
pub fn export_fcs_with_column(
    _fcs: &flow_fcs::Fcs,
    _result: &PeacoQCResult,
    _output_path: impl AsRef<Path>,
    _filter: bool,
) -> Result<()> {
    Err(PeacoQCError::ExportError(
        "FCS writing not yet implemented in flow-fcs crate".to_string(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::qc::{PeacoQCConfig, PeacoQCResult, QCMode};
    use std::collections::HashMap;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_result() -> PeacoQCResult {
        PeacoQCResult {
            good_cells: vec![true, true, false, true, false],
            percentage_removed: 40.0,
            it_percentage: Some(20.0),
            mad_percentage: Some(20.0),
            consecutive_percentage: 0.0,
            peaks: HashMap::new(),
            n_bins: 10,
            events_per_bin: 50,
        }
    }

    fn create_test_config() -> PeacoQCConfig {
        PeacoQCConfig {
            channels: vec!["FL1-A".to_string(), "FL2-A".to_string()],
            determine_good_cells: QCMode::All,
            mad: 6.0,
            it_limit: 0.6,
            consecutive_bins: 5,
            remove_zeros: false,
            ..Default::default()
        }
    }

    #[test]
    fn test_export_csv_boolean() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_boolean.csv");
        let result = create_test_result();

        export_csv_boolean(&result, &path, None).unwrap();

        let content = fs::read_to_string(&path).unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines[0], "PeacoQC");
        assert_eq!(lines[1], "1");
        assert_eq!(lines[2], "1");
        assert_eq!(lines[3], "0");
        assert_eq!(lines[4], "1");
        assert_eq!(lines[5], "0");
    }

    #[test]
    fn test_export_csv_numeric() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_numeric.csv");
        let result = create_test_result();

        export_csv_numeric(&result, &path, 2000, 6000, None).unwrap();

        let content = fs::read_to_string(&path).unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines[0], "PeacoQC");
        assert_eq!(lines[1], "2000");
        assert_eq!(lines[2], "2000");
        assert_eq!(lines[3], "6000");
        assert_eq!(lines[4], "2000");
        assert_eq!(lines[5], "6000");
    }

    #[test]
    fn test_export_json_metadata() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_metadata.json");
        let result = create_test_result();
        let config = create_test_config();

        export_json_metadata(&result, &config, &path).unwrap();

        let content = fs::read_to_string(&path).unwrap();
        let metadata: QCJsonMetadata = serde_json::from_str(&content).unwrap();

        assert_eq!(metadata.n_events_before, 5);
        assert_eq!(metadata.n_events_after, 3);
        assert_eq!(metadata.n_events_removed, 2);
        assert_eq!(metadata.percentage_removed, 40.0);
        assert_eq!(metadata.channels_analyzed, vec!["FL1-A", "FL2-A"]);
    }

    #[test]
    fn test_export_empty_result() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_empty.csv");
        let result = PeacoQCResult {
            good_cells: vec![],
            percentage_removed: 0.0,
            it_percentage: None,
            mad_percentage: None,
            consecutive_percentage: 0.0,
            peaks: HashMap::new(),
            n_bins: 0,
            events_per_bin: 0,
        };

        assert!(export_csv_boolean(&result, &path, None).is_err());
    }

    #[test]
    fn test_custom_column_name() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_custom.csv");
        let result = create_test_result();

        export_csv_boolean(&result, &path, Some("QC_Result")).unwrap();

        let content = fs::read_to_string(&path).unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines[0], "QC_Result");
    }
}