gtars-genomicdist 0.8.0

Rust port of GenomicDistributions: tools for computing statistics for genomic interval sets
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
//! BED file format classifier
//!
//! This module provides functionality to classify BED files according to their format
//! and compliance with UCSC and ENCODE specifications.

#[cfg(feature = "bedclassifier")]
use crate::errors::BedClassifierError;
#[cfg(feature = "bedclassifier")]
use gtars_core::models::RegionSet;
#[cfg(feature = "bedclassifier")]
use regex::Regex;
use std::fmt::{self, Display};

#[cfg(feature = "bedclassifier")]
use polars::prelude::*;

///
/// Data format enumeration for BED file classification
///
#[derive(Clone, Debug, PartialEq)]
pub enum DataFormat {
    Unknown,
    UcscBed,
    UcscBedRs,
    BedLike,
    BedLikeRs,
    EncodeNarrowPeak,
    EncodeNarrowPeakRs,
    EncodeBroadPeak,
    EncodeBroadPeakRs,
    EncodeGappedPeak,
    EncodeGappedPeakRs,
    EncodeRnaElements,
    EncodeRnaElementsRs,
}

impl Display for DataFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            DataFormat::Unknown => "unknown_data_format",
            DataFormat::UcscBed => "ucsc_bed",
            DataFormat::UcscBedRs => "ucsc_bed_rs",
            DataFormat::BedLike => "bed_like",
            DataFormat::BedLikeRs => "bed_like_rs",
            DataFormat::EncodeNarrowPeak => "encode_narrowpeak",
            DataFormat::EncodeNarrowPeakRs => "encode_narrowpeak_rs",
            DataFormat::EncodeBroadPeak => "encode_broadpeak",
            DataFormat::EncodeBroadPeakRs => "encode_broadpeak_rs",
            DataFormat::EncodeGappedPeak => "encode_gappedpeak",
            DataFormat::EncodeGappedPeakRs => "encode_gappedpeak_rs",
            DataFormat::EncodeRnaElements => "encode_rna_elements",
            DataFormat::EncodeRnaElementsRs => "encode_rna_elements_rs",
        };
        write!(f, "{}", s)
    }
}

///
/// BED file classification output
///
#[derive(Clone, Debug)]
pub struct BedClassificationOutput {
    pub bed_compliance: String,
    pub data_format: DataFormat,
    pub compliant_columns: usize,
    pub non_compliant_columns: usize,
}

impl Display for BedClassificationOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "BedClassificationOutput {{ bed_compliance: {}, data_format: {}, compliant_columns: {}, non_compliant_columns: {} }}",
            self.bed_compliance, self.data_format, self.compliant_columns, self.non_compliant_columns
        )
    }
}

///
/// Classify BED file format
///
/// This function analyzes the BED file structure and returns classification details.
/// It uses polars DataFrame to perform column validation similar to bedboss bedclassifier.
///
/// # Arguments
/// - region_set: Reference to a RegionSet to classify
///
/// # Returns
/// BedClassificationOutput with format classification details
///
/// # Example
/// ```no_run
/// use gtars_genomicdist::bed_classifier::classify_bed;
/// use gtars_core::models::RegionSet;
///
/// let region_set = RegionSet::try_from("file.bed").unwrap();
/// let classification = classify_bed(&region_set).unwrap();
/// println!("Format: {}", classification.data_format);
/// ```
///
#[cfg(feature = "bedclassifier")]
pub fn classify_bed(region_set: &RegionSet) -> Result<BedClassificationOutput, BedClassifierError> {
    // Get polars DataFrame
    let df = match region_set.to_polars() {
        Ok(df) => df,
        Err(_) => {
            return Ok(BedClassificationOutput {
                bed_compliance: "unknown_bed_compliance".to_string(),
                data_format: DataFormat::Unknown,
                compliant_columns: 0,
                non_compliant_columns: 0,
            });
        }
    };

    let num_cols = df.width();
    let mut compliant_columns = 0;
    let mut relaxed = false;

    // Helper function to check if a column matches a regex pattern
    let check_string_column = |df: &DataFrame, col_idx: usize, pattern: &str| -> bool {
        if let Ok(col) = df.column(&format!("column_{}", col_idx + 1)) {
            if let Ok(series) = col.cast(&DataType::String) {
                let regex = Regex::new(pattern).unwrap();
                if let Ok(ca) = series.str() {
                    return ca
                        .into_iter()
                        .all(|opt| opt.map(|s| regex.is_match(s)).unwrap_or(false));
                }
            }
        }
        false
    };

    // Helper function to check if a column is integer and meets conditions
    let check_int_column =
        |df: &DataFrame, col_idx: usize, min_val: Option<i64>, max_val: Option<i64>| -> bool {
            if let Ok(col) = df.column(&format!("column_{}", col_idx + 1)) {
                if let Ok(ca) = col.i64() {
                    return ca.into_iter().all(|opt| {
                        opt.map(|val| {
                            let mut valid = true;
                            if let Some(min) = min_val {
                                valid = valid && val >= min;
                            }
                            if let Some(max) = max_val {
                                valid = valid && val <= max;
                            }
                            valid
                        })
                        .unwrap_or(false)
                    });
                }
            }
            false
        };

    // Helper function to check if column is float or contains -1
    let check_float_or_minus_one = |df: &DataFrame, col_idx: usize| -> bool {
        if let Ok(col) = df.column(&format!("column_{}", col_idx + 1)) {
            // Try as float first
            if col.dtype().is_float() {
                return true;
            }
            // Try as int and check if all values are -1
            if let Ok(ca) = col.i64() {
                return ca
                    .into_iter()
                    .all(|opt| opt.map(|v| v == -1).unwrap_or(false));
            }
        }
        false
    };

    // RGB color pattern
    let regex_colors =
        r"^(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?:,(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){0,2}$";

    // Validate columns
    for col_idx in 0..num_cols {
        let is_valid = match col_idx {
            0 => check_string_column(&df, col_idx, r"[A-Za-z0-9_]{1,255}"),
            1 => check_int_column(&df, col_idx, Some(0), None),
            2 => check_int_column(&df, col_idx, Some(0), None),
            3 => check_string_column(&df, col_idx, r"[\x20-\x7e]{1,255}"),
            4 => {
                // Standard check: integer 0-1000
                if check_int_column(&df, col_idx, Some(0), Some(1000)) {
                    true
                } else {
                    // Relaxed check: any non-negative integer
                    if check_int_column(&df, col_idx, Some(0), None) {
                        relaxed = true;
                        true
                    } else {
                        false
                    }
                }
            }
            5 => {
                // Check for strand: +, -, or .
                if let Ok(col) = df.column(&format!("column_{}", col_idx + 1)) {
                    if let Ok(series) = col.cast(&DataType::String) {
                        if let Ok(ca) = series.str() {
                            ca.into_iter().all(|opt| {
                                opt.map(|s| s == "+" || s == "-" || s == ".")
                                    .unwrap_or(false)
                            })
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            6 => check_int_column(&df, col_idx, Some(0), None),
            7 => check_int_column(&df, col_idx, Some(0), None),
            8 => check_string_column(&df, col_idx, regex_colors),
            9 => check_int_column(&df, col_idx, None, None),
            10 => check_string_column(&df, col_idx, r"^(0(,\d+)*|\d+(,\d+)*)?,?$"),
            11 => check_string_column(&df, col_idx, r"^(0(,\d+)*|\d+(,\d+)*)?,?$"),
            12 => check_float_or_minus_one(&df, col_idx),
            13 => {
                if let Ok(col) = df.column(&format!("column_{}", col_idx + 1)) {
                    if let Ok(ca) = col.i64() {
                        if let Some(first) = ca.get(0) {
                            first != -1
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            _ => false,
        };

        if is_valid && col_idx < 12 {
            compliant_columns += 1;
        } else {
            let nccols = num_cols - compliant_columns;

            // Check for special ENCODE formats
            if col_idx >= 6 {
                // NarrowPeak: 10 columns
                if num_cols == 10
                    && col_idx == 6
                    && check_float_or_minus_one(&df, 6)
                    && check_float_or_minus_one(&df, 7)
                    && check_float_or_minus_one(&df, 8)
                    && check_int_column(&df, 9, None, None)
                {
                    return Ok(BedClassificationOutput {
                        bed_compliance: format!("bed{}+{}", compliant_columns, nccols),
                        data_format: if relaxed {
                            DataFormat::EncodeNarrowPeakRs
                        } else {
                            DataFormat::EncodeNarrowPeak
                        },
                        compliant_columns,
                        non_compliant_columns: nccols,
                    });
                }

                // BroadPeak or RNA elements: 9 columns
                if num_cols == 9 && col_idx == 6 {
                    if check_float_or_minus_one(&df, 6)
                        && check_float_or_minus_one(&df, 7)
                        && check_float_or_minus_one(&df, 8)
                    {
                        return Ok(BedClassificationOutput {
                            bed_compliance: format!("bed{}+{}", compliant_columns, nccols),
                            data_format: if relaxed {
                                DataFormat::EncodeBroadPeakRs
                            } else {
                                DataFormat::EncodeBroadPeak
                            },
                            compliant_columns,
                            non_compliant_columns: nccols,
                        });
                    } else if check_float_or_minus_one(&df, 6) && check_float_or_minus_one(&df, 7) {
                        // Check if column 8 first value is not -1 (RNA elements)
                        if let Ok(col) = df.column(&format!("column_{}", 9)) {
                            if let Ok(ca) = col.i64() {
                                if let Some(first) = ca.get(0) {
                                    if first != -1 {
                                        return Ok(BedClassificationOutput {
                                            bed_compliance: format!(
                                                "bed{}+{}",
                                                compliant_columns, nccols
                                            ),
                                            data_format: if relaxed {
                                                DataFormat::EncodeRnaElementsRs
                                            } else {
                                                DataFormat::EncodeRnaElements
                                            },
                                            compliant_columns,
                                            non_compliant_columns: nccols,
                                        });
                                    }
                                }
                            }
                        }
                    }
                }

                // GappedPeak: 15 columns
                if num_cols == 15
                    && col_idx == 12
                    && check_float_or_minus_one(&df, 12)
                    && check_float_or_minus_one(&df, 13)
                    && check_float_or_minus_one(&df, 14)
                {
                    return Ok(BedClassificationOutput {
                        bed_compliance: format!("bed{}+{}", compliant_columns, nccols),
                        data_format: if relaxed {
                            DataFormat::EncodeGappedPeakRs
                        } else {
                            DataFormat::EncodeGappedPeak
                        },
                        compliant_columns,
                        non_compliant_columns: nccols,
                    });
                }
            }

            // Default to BED_LIKE if validation fails
            return Ok(BedClassificationOutput {
                bed_compliance: format!("bed{}+{}", compliant_columns, nccols),
                data_format: if relaxed {
                    if nccols == 0 {
                        DataFormat::UcscBedRs
                    } else {
                        DataFormat::BedLikeRs
                    }
                } else {
                    DataFormat::BedLike
                },
                compliant_columns,
                non_compliant_columns: nccols,
            });
        }
    }

    // All columns validated successfully
    Ok(BedClassificationOutput {
        bed_compliance: format!("bed{}+0", compliant_columns),
        data_format: if relaxed {
            DataFormat::UcscBedRs
        } else {
            DataFormat::UcscBed
        },
        compliant_columns,
        non_compliant_columns: 0,
    })
}

#[cfg(test)]
#[cfg(feature = "bedclassifier")]
mod tests {
    use super::*;

    fn get_test_path(file_name: &str) -> std::path::PathBuf {
        std::env::current_dir()
            .unwrap()
            .join("../tests/data/regionset")
            .join(file_name)
    }

    #[cfg(feature = "bedclassifier")]
    #[test]
    fn test_classify_bed_narrowpeak() {
        let file_path = get_test_path("dummy.narrowPeak");
        let region_set = RegionSet::try_from(file_path.to_str().unwrap()).unwrap();

        let classification = classify_bed(&region_set).unwrap();
        println!("Classification: {}", classification);
        println!("Bed compliance: {}", classification.bed_compliance);
        println!("Data format: {}", classification.data_format);
        println!("Compliant columns: {}", classification.compliant_columns);
        println!(
            "Non-compliant columns: {}",
            classification.non_compliant_columns
        );

        // NarrowPeak files should have 10 columns (bed6+4)
        assert!(classification.bed_compliance.starts_with("bed"));
        assert_eq!(classification.data_format, DataFormat::EncodeNarrowPeak);
    }

    #[cfg(feature = "bedclassifier")]
    #[test]
    fn test_classify_bed_basic() {
        let file_path = get_test_path("dummy_headers.bed");
        let region_set = RegionSet::try_from(file_path.to_str().unwrap()).unwrap();

        let classification = classify_bed(&region_set).unwrap();
        println!("Classification: {}", classification);
        println!("Bed compliance: {}", classification.bed_compliance);
        println!("Data format: {}", classification.data_format);

        // Basic BED files should be classified
        assert!(classification.bed_compliance.starts_with("bed"));
        assert!(classification.compliant_columns >= 3); // At least chr, start, end
        assert_eq!(classification.data_format, DataFormat::UcscBed);
    }
}