redicat 0.4.2

REDICAT - RNA Editing Cellular Assessment Toolkit: A highly parallelized utility for analyzing RNA editing events in single-cell RNA-seq data
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
//! Input validation utilities
//!
//! This module provides functions for validating input parameters, files,
//! and matrix dimensions for the REdiCAT RNA editing analysis pipeline.
//!
//! # Overview
//!
//! The validation module includes:
//! - Configuration validation for analysis parameters
//! - Input file validation to ensure required files exist and are accessible
//! - Output path validation to ensure proper file extensions and write permissions
//! - Matrix dimension validation to ensure compatibility between data structures

#![allow(dead_code)]
use crate::core::error::{RedicatError, Result};
use std::path::Path;

/// Configuration parameters for validation
///
/// This struct holds all the configuration parameters that need to be
/// validated for the RNA editing analysis pipeline.
///
/// # Fields
///
/// * `max_other_threshold` - Maximum threshold for other mismatches (0.0 to 1.0)
/// * `min_edited_threshold` - Minimum threshold for edited mismatches (0.0 to 1.0)
/// * `min_ref_threshold` - Minimum threshold for reference mismatches (0.0 to 1.0)
/// * `min_coverage` - Minimum coverage threshold
/// * `chunk_size` - Size of data chunks for processing
/// * `num_threads` - Number of threads to use for parallel processing
pub struct ValidationConfig {
    /// Maximum threshold for other mismatches (0.0 to 1.0)
    pub max_other_threshold: f64,
    /// Minimum threshold for edited mismatches (0.0 to 1.0)
    pub min_edited_threshold: f64,
    /// Minimum threshold for reference mismatches (0.0 to 1.0)
    pub min_ref_threshold: f64,
    /// Minimum coverage threshold
    pub min_coverage: u16,
    /// Size of data chunks for processing
    pub chunk_size: usize,
    /// Number of threads to use for parallel processing
    pub num_threads: usize,
}

impl ValidationConfig {
    /// Validate all configuration parameters
    ///
    /// This function validates all configuration parameters to ensure they
    /// are within acceptable ranges and meet the requirements for the
    /// RNA editing analysis pipeline.
    ///
    /// # Returns
    ///
    /// * `Result<()>` - Ok if all parameters are valid, Err otherwise
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any threshold parameter is not between 0.0 and 1.0
    /// - min_coverage is 0
    /// - chunk_size is 0
    /// - num_threads is 0
    ///
    /// # Example
    ///
    /// ```rust
    /// use redicat_lib::call::validation::ValidationConfig;
    ///
    /// let config = ValidationConfig {
    ///     max_other_threshold: 0.01,
    ///     min_edited_threshold: 0.01,
    ///     min_ref_threshold: 0.01,
    ///     min_coverage: 5,
    ///     chunk_size: 1000,
    ///     num_threads: 8,
    /// };
    /// config.validate().unwrap();
    /// ```
    pub fn validate(&self) -> Result<()> {
        self.validate_threshold("max_other_threshold", self.max_other_threshold, 0.0, 1.0)?;
        self.validate_threshold("min_edited_threshold", self.min_edited_threshold, 0.0, 1.0)?;
        self.validate_threshold("min_ref_threshold", self.min_ref_threshold, 0.0, 1.0)?;

        if self.min_coverage == 0 {
            return Err(RedicatError::InvalidInput(
                "min_coverage must be greater than 0".to_string(),
            ));
        }

        if self.chunk_size == 0 {
            return Err(RedicatError::InvalidInput(
                "chunk_size must be greater than 0".to_string(),
            ));
        }

        if self.chunk_size > 100_000 {
            log::warn!(
                "Large chunk_size ({}) may cause memory issues",
                self.chunk_size
            );
        }

        if self.num_threads == 0 {
            return Err(RedicatError::InvalidInput(
                "num_threads must be greater than 0".to_string(),
            ));
        }

        let max_threads = num_cpus::get() * 2;
        if self.num_threads > max_threads {
            log::warn!(
                "num_threads ({}) exceeds recommended maximum ({})",
                self.num_threads,
                max_threads
            );
        }

        Ok(())
    }

    /// Validate a threshold parameter
    ///
    /// This function validates a threshold parameter to ensure it is
    /// a finite number within the specified range.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the parameter for error reporting
    /// * `value` - Value of the parameter to validate
    /// * `min` - Minimum allowed value
    /// * `max` - Maximum allowed value
    ///
    /// # Returns
    ///
    /// * `Result<()>` - Ok if parameter is valid, Err otherwise
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Value is not finite
    /// - Value is outside the specified range
    fn validate_threshold(&self, name: &str, value: f64, min: f64, max: f64) -> Result<()> {
        if !value.is_finite() {
            return Err(RedicatError::InvalidInput(format!(
                "{} must be a finite number",
                name
            )));
        }

        if value < min || value > max {
            return Err(RedicatError::ThresholdValidation {
                field: name.to_string(),
                min,
                max,
                value,
            });
        }

        Ok(())
    }
}

/// Validate input files for the analysis pipeline
///
/// This function validates that all required input files exist and have
/// the correct formats for the RNA editing analysis pipeline.
///
/// # Arguments
///
/// * `input` - Path to the input AnnData (.h5ad) file
/// * `fa` - Path to the reference genome FASTA file
/// * `rediportal` - Path to the REDIPortal editing sites file
///
/// # Returns
///
/// * `Result<()>` - Ok if all files are valid, Err otherwise
///
/// # Errors
///
/// Returns an error if:
/// - Input file doesn't exist
/// - Input file doesn't have .h5ad extension
/// - Reference genome file doesn't exist
/// - FASTA index file doesn't exist
/// - REDIPortal file doesn't exist
///
/// # Example
///
/// ```rust
/// use redicat_lib::call::validation::validate_input_files;
///
/// // validate_input_files("input.h5ad", "reference.fa", "editing_sites.tsv.gz").unwrap();
/// ```
pub fn validate_input_files(input: &str, fa: &str, rediportal: &str) -> Result<()> {
    if !Path::new(input).exists() {
        return Err(RedicatError::FileNotFound(format!(
            "Input file not found: {}",
            input
        )));
    }

    if !input.ends_with(".h5ad") {
        return Err(RedicatError::InvalidInput(
            "Input file must have .h5ad extension".to_string(),
        ));
    }

    if !Path::new(fa).exists() {
        return Err(RedicatError::FileNotFound(format!(
            "Reference genome file not found: {}",
            fa
        )));
    }

    let fai_path = format!("{}.fai", fa);
    if !Path::new(&fai_path).exists() {
        return Err(RedicatError::FileNotFound(format!(
            "FASTA index file not found: {}. Please create it using: samtools faidx {}",
            fai_path, fa
        )));
    }

    if !Path::new(rediportal).exists() {
        return Err(RedicatError::FileNotFound(format!(
            "REDIPortal file not found: {}",
            rediportal
        )));
    }

    Ok(())
}

/// Validate output path for the analysis pipeline
///
/// This function validates that the output path is valid and writable,
/// and that it has the correct file extension.
///
/// # Arguments
///
/// * `output` - Path to the output file
///
/// # Returns
///
/// * `Result<()>` - Ok if output path is valid, Err otherwise
///
/// # Errors
///
/// Returns an error if:
/// - Output directory doesn't exist
/// - Output directory is read-only
/// - Output file doesn't have .h5ad extension
///
/// # Example
///
/// ```rust
/// use redicat_lib::call::validation::validate_output_path;
///
/// // validate_output_path("output.h5ad").unwrap();
/// ```
pub fn validate_output_path(output: &str) -> Result<()> {
    let path = Path::new(output);

    // Check if output file exists, if so, remove it
    if path.exists() {
        std::fs::remove_file(path).map_err(|e| {
            RedicatError::InvalidInput(format!(
                "Failed to remove existing output file '{}': {}",
                output, e
            ))
        })?;
    }

    if !output.ends_with(".h5ad") {
        return Err(RedicatError::InvalidInput(
            "Output file must have .h5ad extension".to_string(),
        ));
    }

    Ok(())
}

/// Validate matrix dimensions for compatibility
///
/// This function validates that two matrices have compatible dimensions
/// for element-wise operations.
///
/// # Arguments
///
/// * `_matrix_name` - Name of the matrix for error reporting (currently unused)
/// * `actual_shape` - Actual dimensions of the matrix (rows, cols)
/// * `expected_shape` - Expected dimensions of the matrix (rows, cols)
///
/// # Returns
///
/// * `Result<()>` - Ok if dimensions are compatible, Err otherwise
///
/// # Errors
///
/// Returns an error if:
/// - Actual and expected dimensions don't match
///
/// # Example
///
/// ```rust
/// use redicat_lib::call::validation::validate_matrix_dimensions;
///
/// validate_matrix_dimensions("test_matrix", (100, 50), (100, 50)).unwrap();
/// ```
pub fn validate_matrix_dimensions(
    _matrix_name: &str,
    actual_shape: (usize, usize),
    expected_shape: (usize, usize),
) -> Result<()> {
    if actual_shape != expected_shape {
        return Err(RedicatError::DimensionMismatch {
            expected: format!("{} × {}", expected_shape.0, expected_shape.1),
            actual: format!("{} × {}", actual_shape.0, actual_shape.1),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn valid_config() -> ValidationConfig {
        ValidationConfig {
            max_other_threshold: 0.01,
            min_edited_threshold: 0.05,
            min_ref_threshold: 0.1,
            min_coverage: 5,
            chunk_size: 1000,
            num_threads: 2,
        }
    }

    #[test]
    fn validation_config_accepts_valid_values() {
        valid_config().validate().unwrap();
    }

    #[test]
    fn validation_config_rejects_invalid_thresholds_and_sizes() {
        let mut cfg = valid_config();
        cfg.max_other_threshold = 1.5;
        let err = cfg.validate().unwrap_err();
        assert!(format!("{}", err).contains("max_other_threshold"));

        let mut cfg = valid_config();
        cfg.min_ref_threshold = f64::NAN;
        let err = cfg.validate().unwrap_err();
        assert!(format!("{}", err).contains("finite number"));

        let mut cfg = valid_config();
        cfg.min_coverage = 0;
        let err = cfg.validate().unwrap_err();
        assert!(format!("{}", err).contains("min_coverage must be greater than 0"));

        let mut cfg = valid_config();
        cfg.chunk_size = 0;
        let err = cfg.validate().unwrap_err();
        assert!(format!("{}", err).contains("chunk_size must be greater than 0"));

        let mut cfg = valid_config();
        cfg.num_threads = 0;
        let err = cfg.validate().unwrap_err();
        assert!(format!("{}", err).contains("num_threads must be greater than 0"));
    }

    #[test]
    fn validate_input_files_checks_presence_and_extensions() {
        let dir = tempdir().unwrap();
        let input = dir.path().join("input.h5ad");
        let fasta = dir.path().join("ref.fa");
        let fai = dir.path().join("ref.fa.fai");
        let redi = dir.path().join("redi.tsv.gz");

        fs::write(&input, b"dummy").unwrap();
        fs::write(&fasta, b">chr1\nA\n").unwrap();
        fs::write(&fai, b"chr1\t1\t6\t1\t2\n").unwrap();
        fs::write(&redi, b"dummy").unwrap();

        validate_input_files(
            input.to_str().unwrap(),
            fasta.to_str().unwrap(),
            redi.to_str().unwrap(),
        )
        .unwrap();

        let bad_input = dir.path().join("input.txt");
        fs::write(&bad_input, b"dummy").unwrap();
        let err = validate_input_files(
            bad_input.to_str().unwrap(),
            fasta.to_str().unwrap(),
            redi.to_str().unwrap(),
        )
        .unwrap_err();
        assert!(format!("{}", err).contains(".h5ad"));

        let err = validate_input_files(
            input.to_str().unwrap(),
            dir.path().join("missing.fa").to_str().unwrap(),
            redi.to_str().unwrap(),
        )
        .unwrap_err();
        assert!(format!("{}", err).contains("Reference genome file not found"));

        fs::remove_file(&fai).unwrap();
        let err = validate_input_files(
            input.to_str().unwrap(),
            fasta.to_str().unwrap(),
            redi.to_str().unwrap(),
        )
        .unwrap_err();
        assert!(format!("{}", err).contains("FASTA index file not found"));
    }

    #[test]
    fn validate_output_path_enforces_extension_and_overwrite() {
        let dir = tempdir().unwrap();
        let out = dir.path().join("out.h5ad");
        fs::write(&out, b"old").unwrap();

        validate_output_path(out.to_str().unwrap()).unwrap();
        assert!(!out.exists());

        let bad_out = dir.path().join("out.txt");
        let err = validate_output_path(bad_out.to_str().unwrap()).unwrap_err();
        assert!(format!("{}", err).contains("Output file must have .h5ad extension"));
    }

    #[test]
    fn validate_matrix_dimensions_detects_mismatch() {
        validate_matrix_dimensions("m", (10, 5), (10, 5)).unwrap();

        let err = validate_matrix_dimensions("m", (10, 4), (10, 5)).unwrap_err();
        assert!(format!("{}", err).contains("10 × 5"));
    }
}