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
use std::any::Any;
use std::fmt::Display;
use polars::prelude::*;
use super::{
create_empty_categorical_dtype,
name_dtype_tuple,
};
use crate::plsmallstr;
/// Represents the columns expected in BSX data.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum BsxColumns {
Chr,
Position,
Strand,
Context,
CountM,
CountTotal,
Density,
}
impl AsRef<str> for BsxColumns {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Display for BsxColumns {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl BsxColumns {
/// Returns the Polars Schema for the BSX columns.
pub fn schema() -> Schema {
Schema::from_iter([
name_dtype_tuple!(BsxColumns::Chr),
name_dtype_tuple!(BsxColumns::Position),
name_dtype_tuple!(BsxColumns::Strand),
name_dtype_tuple!(BsxColumns::Context),
name_dtype_tuple!(BsxColumns::CountM),
name_dtype_tuple!(BsxColumns::CountTotal),
name_dtype_tuple!(BsxColumns::Density),
])
}
/// Returns the string representation of the column name.
pub const fn as_str(&self) -> &'static str {
match self {
BsxColumns::Chr => "chr",
BsxColumns::Position => "position",
BsxColumns::Strand => "strand",
BsxColumns::Context => "context",
BsxColumns::CountM => "count_m",
BsxColumns::CountTotal => "count_total",
BsxColumns::Density => "density",
}
}
/// Returns the Polars DataType for the column.
pub const fn dtype(&self) -> DataType {
match self {
BsxColumns::Chr => create_empty_categorical_dtype(),
BsxColumns::Position => DataType::UInt32,
BsxColumns::Strand => DataType::Boolean,
BsxColumns::Context => DataType::Boolean,
BsxColumns::CountM => DataType::UInt16,
BsxColumns::CountTotal => DataType::UInt16,
BsxColumns::Density => DataType::Float32,
}
}
/// Returns an array containing all BSX column names as strings.
pub const fn colnames() -> [&'static str; 7] {
[
BsxColumns::Chr.as_str(),
BsxColumns::Position.as_str(),
BsxColumns::Strand.as_str(),
BsxColumns::Context.as_str(),
BsxColumns::CountM.as_str(),
BsxColumns::CountTotal.as_str(),
BsxColumns::Density.as_str(),
]
}
/// Checks if the given string matches any of the BSX column names.
pub fn has_name(name: &str) -> bool {
Self::colnames().contains(&name)
}
/// Creates a Polars expression (Expr) referencing this column.
#[inline(always)]
pub fn col(&self) -> Expr {
col(self.as_str())
}
/// Attempts to create a Polars AnyValue from a boxed value based on the
/// column's expected type.
///
/// # Arguments
///
/// * `value`: A boxed value that is expected to match the column's
/// DataType.
///
/// # Returns
///
/// Returns `Some(AnyValue)` if the value can be downcast to the expected
/// type, otherwise returns `None`.
pub fn create_anyvalue(
&self,
value: Box<dyn Any>,
) -> Option<AnyValue> {
match self {
BsxColumns::Chr => {
value
.downcast_ref::<String>()
.map(|v| AnyValue::StringOwned(v.into()))
},
BsxColumns::Position => {
value.downcast_ref::<u32>().map(|v| AnyValue::UInt32(*v))
},
BsxColumns::Strand => {
value.downcast_ref::<bool>().map(|v| AnyValue::Boolean(*v))
},
BsxColumns::Context => {
value
.downcast_ref::<Option<bool>>()
.map(|v| v.map(AnyValue::Boolean).unwrap_or(AnyValue::Null))
},
BsxColumns::CountM => {
value.downcast_ref::<u16>().map(|v| AnyValue::UInt16(*v))
},
BsxColumns::CountTotal => {
value.downcast_ref::<u16>().map(|v| AnyValue::UInt16(*v))
},
BsxColumns::Density => {
value.downcast_ref::<f32>().map(|v| AnyValue::Float32(*v))
},
}
}
/// Creates a Polars Series from a vector of values, attempting to cast them
/// to the column's expected type.
///
/// # Type Parameters
///
/// * `T`: The type of the elements in the input vector. Must be `Sized` and
/// have `'static` lifetime.
///
/// # Arguments
///
/// * `data`: A vector of values to be converted into a Series.
///
/// # Returns
///
/// Returns a `PolarsResult<Series>` containing the created Series or an
/// error if the conversion fails (e.g., due to incorrect type).
pub fn create_series<T>(
&self,
data: Vec<T>,
) -> PolarsResult<Series>
where
T: Sized + 'static, {
let any_vec = data
.into_iter()
.map(|value| self.create_anyvalue(Box::new(value)))
.collect::<Option<Vec<_>>>()
.ok_or(PolarsError::SchemaMismatch(
format!("Could not downcast type {}", stringify!(T)).into(),
))?;
Series::from_any_values(plsmallstr!(self.as_str()), &any_vec, true)
}
}