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
//! Parallel processing functionality for OptimizedDataFrame
use rayon::prelude::*;
use std::collections::HashMap;
use super::core::OptimizedDataFrame;
use crate::column::{BooleanColumn, Column, ColumnTrait, Float64Column, Int64Column, StringColumn};
use crate::error::{Error, Result};
impl OptimizedDataFrame {
/// Parallel row filtering
///
/// Extracts only rows where the value in the condition column (Boolean type) is true,
/// applying parallel processing for large datasets.
///
/// # Arguments
/// * `condition_column` - Name of Boolean column to use as filter condition
///
/// # Returns
/// * `Result<Self>` - A new DataFrame with filtered rows
pub fn par_filter(&self, condition_column: &str) -> Result<Self> {
// Threshold for optimal parallelization (smaller datasets benefit from serial processing)
const PARALLEL_THRESHOLD: usize = 100_000;
// Get condition column
let column_idx = self
.column_indices
.get(condition_column)
.ok_or_else(|| Error::ColumnNotFound(condition_column.to_string()))?;
let condition = &self.columns[*column_idx];
// Verify the condition column is boolean type
if let Column::Boolean(bool_col) = condition {
let row_count = bool_col.len();
// Choose serial/parallel processing based on data size
let indices: Vec<usize> = if row_count < PARALLEL_THRESHOLD {
// Serial processing (small data)
(0..row_count)
.filter_map(|i| {
if let Ok(Some(true)) = bool_col.get(i) {
Some(i)
} else {
None
}
})
.collect()
} else {
// Parallel processing (large data)
// Optimize chunk size to reduce parallelization overhead
let chunk_size = (row_count / rayon::current_num_threads()).max(1000);
// First convert range to array, then process chunks
(0..row_count)
.collect::<Vec<_>>()
.par_chunks(chunk_size)
.flat_map(|chunk| {
chunk
.iter()
.filter_map(|&i| {
if let Ok(Some(true)) = bool_col.get(i) {
Some(i)
} else {
None
}
})
.collect::<Vec<_>>()
})
.collect()
};
if indices.is_empty() {
// Return empty DataFrame
let mut result = Self::new();
for name in &self.column_names {
let col_idx = self.column_indices[name];
let empty_col = match &self.columns[col_idx] {
Column::Int64(_) => Column::Int64(Int64Column::new(Vec::new())),
Column::Float64(_) => Column::Float64(Float64Column::new(Vec::new())),
Column::String(_) => Column::String(StringColumn::new(Vec::new())),
Column::Boolean(_) => Column::Boolean(BooleanColumn::new(Vec::new())),
};
result.add_column(name.clone(), empty_col)?;
}
return Ok(result);
}
// Create new DataFrame
let mut result = Self::new();
// Pre-allocate vector for result columns
let mut result_columns = Vec::with_capacity(self.column_names.len());
// Choose column processing method based on data size
if indices.len() < PARALLEL_THRESHOLD || self.column_names.len() < 4 {
// Serial processing (small data or few columns)
for name in &self.column_names {
let i = self.column_indices[name];
let column = &self.columns[i];
let filtered_column = match column {
Column::Int64(col) => {
let filtered_data: Vec<i64> = indices
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
0 // Default value
}
})
.collect();
Column::Int64(Int64Column::new(filtered_data))
}
Column::Float64(col) => {
let filtered_data: Vec<f64> = indices
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
0.0 // Default value
}
})
.collect();
Column::Float64(Float64Column::new(filtered_data))
}
Column::String(col) => {
let filtered_data: Vec<String> = indices
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val.to_string()
} else {
String::new() // Default value
}
})
.collect();
Column::String(StringColumn::new(filtered_data))
}
Column::Boolean(col) => {
let filtered_data: Vec<bool> = indices
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
false // Default value
}
})
.collect();
Column::Boolean(BooleanColumn::new(filtered_data))
}
};
result_columns.push((name.clone(), filtered_column));
}
} else {
// Parallel processing for large data
// Process each column in parallel (coarse-grained parallelism at column level)
result_columns = self
.column_names
.par_iter()
.map(|name| {
let i = self.column_indices[name];
let column = &self.columns[i];
let indices_len = indices.len();
let filtered_column = match column {
Column::Int64(col) => {
// Split large index list for processing
let chunk_size = (indices_len / 8).max(1000);
let mut filtered_data = Vec::with_capacity(indices_len);
// Use chunks to ensure all elements are processed
for chunk in indices.chunks(chunk_size) {
let chunk_data: Vec<i64> = chunk
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
0 // Default value
}
})
.collect();
filtered_data.extend(chunk_data);
}
Column::Int64(Int64Column::new(filtered_data))
}
Column::Float64(col) => {
// Split large index list for processing
let chunk_size = (indices_len / 8).max(1000);
let mut filtered_data = Vec::with_capacity(indices_len);
// Use chunks to ensure all elements are processed
for chunk in indices.chunks(chunk_size) {
let chunk_data: Vec<f64> = chunk
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
0.0 // Default value
}
})
.collect();
filtered_data.extend(chunk_data);
}
Column::Float64(Float64Column::new(filtered_data))
}
Column::String(col) => {
// String processing is especially heavy, use finer chunks
let chunk_size = (indices_len / 16).max(500);
let mut filtered_data = Vec::with_capacity(indices_len);
// Use chunks to ensure all elements are processed
for chunk in indices.chunks(chunk_size) {
let chunk_data: Vec<String> = chunk
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val.to_string()
} else {
String::new() // Default value
}
})
.collect();
filtered_data.extend(chunk_data);
}
Column::String(StringColumn::new(filtered_data))
}
Column::Boolean(col) => {
let filtered_data: Vec<bool> = indices
.iter()
.map(|&idx| {
if let Ok(Some(val)) = col.get(idx) {
val
} else {
false // Default value
}
})
.collect();
Column::Boolean(BooleanColumn::new(filtered_data))
}
};
(name.clone(), filtered_column)
})
.collect();
}
// Add results to DataFrame
for (name, column) in result_columns {
result.add_column(name, column)?;
}
// Copy index
if let Some(ref idx) = self.index {
result.index = Some(idx.clone());
}
Ok(result)
} else {
Err(Error::OperationFailed(format!(
"Column '{}' is not of boolean type",
condition_column
)))
}
}
}