pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! # SIMD-Enhanced Column Operations
//!
//! This module provides SIMD-accelerated operations for column types,
//! extending the basic column functionality with high-performance
//! vectorized operations for numeric data.

use crate::column::{ColumnTrait, Float64Column, Int64Column};
use crate::core::error::{Error, Result};
use crate::optimized::jit::simd_column_ops::{
    simd_abs_f64, simd_abs_i64, simd_add_f64, simd_add_i64, simd_add_scalar_f64,
    simd_add_scalar_i64, simd_compare_f64, simd_compare_i64, simd_divide_f64, simd_multiply_f64,
    simd_multiply_i64, simd_multiply_scalar_f64, simd_sqrt_f64, simd_subtract_f64,
    simd_subtract_i64, ComparisonOp,
};

/// Trait for SIMD-enhanced column operations on Float64 columns
pub trait SIMDFloat64Ops {
    /// Element-wise addition with another Float64Column using SIMD
    fn simd_add(&self, other: &Float64Column) -> Result<Float64Column>;

    /// Element-wise subtraction with another Float64Column using SIMD
    fn simd_subtract(&self, other: &Float64Column) -> Result<Float64Column>;

    /// Element-wise multiplication with another Float64Column using SIMD
    fn simd_multiply(&self, other: &Float64Column) -> Result<Float64Column>;

    /// Element-wise division with another Float64Column using SIMD
    fn simd_divide(&self, other: &Float64Column) -> Result<Float64Column>;

    /// Scalar addition using SIMD
    fn simd_add_scalar(&self, scalar: f64) -> Result<Float64Column>;

    /// Scalar multiplication using SIMD
    fn simd_multiply_scalar(&self, scalar: f64) -> Result<Float64Column>;

    /// Absolute value using SIMD
    fn simd_abs(&self) -> Result<Float64Column>;

    /// Square root using SIMD
    fn simd_sqrt(&self) -> Result<Float64Column>;

    /// Element-wise comparison using SIMD
    fn simd_compare(&self, other: &Float64Column, op: ComparisonOp) -> Result<Vec<bool>>;

    /// Scalar comparison using SIMD
    fn simd_compare_scalar(&self, scalar: f64, op: ComparisonOp) -> Result<Vec<bool>>;
}

/// Trait for SIMD-enhanced column operations on Int64 columns
pub trait SIMDInt64Ops {
    /// Element-wise addition with another Int64Column using SIMD
    fn simd_add(&self, other: &Int64Column) -> Result<Int64Column>;

    /// Element-wise subtraction with another Int64Column using SIMD
    fn simd_subtract(&self, other: &Int64Column) -> Result<Int64Column>;

    /// Element-wise multiplication with another Int64Column using SIMD
    fn simd_multiply(&self, other: &Int64Column) -> Result<Int64Column>;

    /// Scalar addition using SIMD
    fn simd_add_scalar(&self, scalar: i64) -> Result<Int64Column>;

    /// Absolute value using SIMD
    fn simd_abs(&self) -> Result<Int64Column>;

    /// Element-wise comparison using SIMD
    fn simd_compare(&self, other: &Int64Column, op: ComparisonOp) -> Result<Vec<bool>>;

    /// Scalar comparison using SIMD
    fn simd_compare_scalar(&self, scalar: i64, op: ComparisonOp) -> Result<Vec<bool>>;

    /// Convert to Float64Column for mixed operations
    fn to_float64_simd(&self) -> Result<Float64Column>;
}

impl SIMDFloat64Ops for Float64Column {
    fn simd_add(&self, other: &Float64Column) -> Result<Float64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0.0; self.len()];
        simd_add_f64(&self.data, &other.data, &mut result_data)?;

        // Combine null masks if they exist
        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_subtract(&self, other: &Float64Column) -> Result<Float64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0.0; self.len()];
        simd_subtract_f64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_multiply(&self, other: &Float64Column) -> Result<Float64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0.0; self.len()];
        simd_multiply_f64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_divide(&self, other: &Float64Column) -> Result<Float64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0.0; self.len()];
        simd_divide_f64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_add_scalar(&self, scalar: f64) -> Result<Float64Column> {
        let mut result_data = vec![0.0; self.len()];
        simd_add_scalar_f64(&self.data, scalar, &mut result_data)?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_multiply_scalar(&self, scalar: f64) -> Result<Float64Column> {
        let mut result_data = vec![0.0; self.len()];
        simd_multiply_scalar_f64(&self.data, scalar, &mut result_data)?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_abs(&self) -> Result<Float64Column> {
        let mut result_data = vec![0.0; self.len()];
        simd_abs_f64(&self.data, &mut result_data)?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_sqrt(&self) -> Result<Float64Column> {
        let mut result_data = vec![0.0; self.len()];
        simd_sqrt_f64(&self.data, &mut result_data)?;

        Ok(Float64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_compare(&self, other: &Float64Column, op: ComparisonOp) -> Result<Vec<bool>> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result = vec![false; self.len()];
        simd_compare_f64(&self.data, &other.data, op, &mut result)?;

        // Handle null values - comparisons with nulls should be false
        apply_null_mask_to_comparison(&mut result, &self.null_mask, &other.null_mask);

        Ok(result)
    }

    fn simd_compare_scalar(&self, scalar: f64, op: ComparisonOp) -> Result<Vec<bool>> {
        let scalar_vec = vec![scalar; self.len()];
        let mut result = vec![false; self.len()];
        simd_compare_f64(&self.data, &scalar_vec, op, &mut result)?;

        // Handle null values
        apply_null_mask_to_comparison(&mut result, &self.null_mask, &None);

        Ok(result)
    }
}

impl SIMDInt64Ops for Int64Column {
    fn simd_add(&self, other: &Int64Column) -> Result<Int64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0i64; self.len()];
        simd_add_i64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Int64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_subtract(&self, other: &Int64Column) -> Result<Int64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0i64; self.len()];
        simd_subtract_i64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Int64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_multiply(&self, other: &Int64Column) -> Result<Int64Column> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result_data = vec![0i64; self.len()];
        simd_multiply_i64(&self.data, &other.data, &mut result_data)?;

        let null_mask = combine_null_masks(&self.null_mask, &other.null_mask, self.len())?;

        Ok(Int64Column {
            data: result_data.into(),
            null_mask,
            name: None,
        })
    }

    fn simd_add_scalar(&self, scalar: i64) -> Result<Int64Column> {
        let mut result_data = vec![0i64; self.len()];
        simd_add_scalar_i64(&self.data, scalar, &mut result_data)?;

        Ok(Int64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_abs(&self) -> Result<Int64Column> {
        let mut result_data = vec![0i64; self.len()];
        simd_abs_i64(&self.data, &mut result_data)?;

        Ok(Int64Column {
            data: result_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }

    fn simd_compare(&self, other: &Int64Column, op: ComparisonOp) -> Result<Vec<bool>> {
        if self.len() != other.len() {
            return Err(Error::InconsistentRowCount {
                expected: self.len(),
                found: other.len(),
            });
        }

        let mut result = vec![false; self.len()];
        simd_compare_i64(&self.data, &other.data, op, &mut result)?;

        apply_null_mask_to_comparison(&mut result, &self.null_mask, &other.null_mask);

        Ok(result)
    }

    fn simd_compare_scalar(&self, scalar: i64, op: ComparisonOp) -> Result<Vec<bool>> {
        let scalar_vec = vec![scalar; self.len()];
        let mut result = vec![false; self.len()];
        simd_compare_i64(&self.data, &scalar_vec, op, &mut result)?;

        apply_null_mask_to_comparison(&mut result, &self.null_mask, &None);

        Ok(result)
    }

    fn to_float64_simd(&self) -> Result<Float64Column> {
        let float_data: Vec<f64> = self.data.iter().map(|&x| x as f64).collect();

        Ok(Float64Column {
            data: float_data.into(),
            null_mask: self.null_mask.clone(),
            name: None,
        })
    }
}

/// Combine null masks from two columns using logical OR
fn combine_null_masks(
    mask1: &Option<std::sync::Arc<[u8]>>,
    mask2: &Option<std::sync::Arc<[u8]>>,
    len: usize,
) -> Result<Option<std::sync::Arc<[u8]>>> {
    match (mask1, mask2) {
        (Some(m1), Some(m2)) => {
            let bytes_needed = (len + 7) / 8;
            let mut combined = vec![0u8; bytes_needed];

            for i in 0..bytes_needed.min(m1.len()).min(m2.len()) {
                combined[i] = m1[i] | m2[i];
            }

            Ok(Some(combined.into()))
        }
        (Some(m), None) | (None, Some(m)) => Ok(Some(m.clone())),
        (None, None) => Ok(None),
    }
}

/// Apply null masks to comparison results (nulls should produce false)
fn apply_null_mask_to_comparison(
    result: &mut [bool],
    mask1: &Option<std::sync::Arc<[u8]>>,
    mask2: &Option<std::sync::Arc<[u8]>>,
) {
    // If either value is null, the comparison result should be false
    for i in 0..result.len() {
        let is_null = is_null_at_index(mask1, i) || is_null_at_index(mask2, i);
        if is_null {
            result[i] = false;
        }
    }
}

/// Check if a value is null at the given index
fn is_null_at_index(mask: &Option<std::sync::Arc<[u8]>>, index: usize) -> bool {
    if let Some(m) = mask {
        let byte_idx = index / 8;
        let bit_idx = index % 8;
        if byte_idx < m.len() {
            (m[byte_idx] & (1 << bit_idx)) != 0
        } else {
            false
        }
    } else {
        false
    }
}

/// High-level SIMD operations for mixed column arithmetic
pub struct SIMDColumnArithmetic;

impl SIMDColumnArithmetic {
    /// Add two numeric columns with automatic type promotion
    pub fn add_columns(
        left: &crate::column::Column,
        right: &crate::column::Column,
    ) -> Result<crate::column::Column> {
        use crate::column::Column;

        match (left, right) {
            (Column::Float64(l), Column::Float64(r)) => Ok(Column::Float64(l.simd_add(r)?)),
            (Column::Int64(l), Column::Int64(r)) => Ok(Column::Int64(l.simd_add(r)?)),
            (Column::Float64(l), Column::Int64(r)) => {
                let r_float = r.to_float64_simd()?;
                Ok(Column::Float64(l.simd_add(&r_float)?))
            }
            (Column::Int64(l), Column::Float64(r)) => {
                let l_float = l.to_float64_simd()?;
                Ok(Column::Float64(l_float.simd_add(r)?))
            }
            _ => Err(Error::InvalidOperation(
                "SIMD addition not supported for these column types".to_string(),
            )),
        }
    }

    /// Multiply two numeric columns with automatic type promotion
    pub fn multiply_columns(
        left: &crate::column::Column,
        right: &crate::column::Column,
    ) -> Result<crate::column::Column> {
        use crate::column::Column;

        match (left, right) {
            (Column::Float64(l), Column::Float64(r)) => Ok(Column::Float64(l.simd_multiply(r)?)),
            (Column::Int64(l), Column::Int64(r)) => Ok(Column::Int64(l.simd_multiply(r)?)),
            (Column::Float64(l), Column::Int64(r)) => {
                let r_float = r.to_float64_simd()?;
                Ok(Column::Float64(l.simd_multiply(&r_float)?))
            }
            (Column::Int64(l), Column::Float64(r)) => {
                let l_float = l.to_float64_simd()?;
                Ok(Column::Float64(l_float.simd_multiply(r)?))
            }
            _ => Err(Error::InvalidOperation(
                "SIMD multiplication not supported for these column types".to_string(),
            )),
        }
    }

    /// Apply scalar operation to a column
    pub fn multiply_scalar(
        column: &crate::column::Column,
        scalar: f64,
    ) -> Result<crate::column::Column> {
        use crate::column::Column;

        match column {
            Column::Float64(col) => Ok(Column::Float64(col.simd_multiply_scalar(scalar)?)),
            Column::Int64(col) => {
                let float_col = col.to_float64_simd()?;
                Ok(Column::Float64(float_col.simd_multiply_scalar(scalar)?))
            }
            _ => Err(Error::InvalidOperation(
                "SIMD scalar multiplication not supported for this column type".to_string(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::column::{Float64Column, Int64Column};

    #[test]
    fn test_simd_float64_add() {
        let col1 = Float64Column::new(vec![1.0, 2.0, 3.0, 4.0]);
        let col2 = Float64Column::new(vec![1.0, 1.0, 1.0, 1.0]);

        let result = col1.simd_add(&col2).expect("operation should succeed");

        assert_eq!(result.data(), vec![2.0, 3.0, 4.0, 5.0]);
    }

    #[test]
    fn test_simd_float64_scalar_multiply() {
        let col = Float64Column::new(vec![1.0, 2.0, 3.0, 4.0]);

        let result = col
            .simd_multiply_scalar(2.0)
            .expect("operation should succeed");

        assert_eq!(result.data(), vec![2.0, 4.0, 6.0, 8.0]);
    }

    #[test]
    fn test_simd_float64_abs() {
        let col = Float64Column::new(vec![-1.0, 2.0, -3.0, 4.0]);

        let result = col.simd_abs().expect("operation should succeed");

        assert_eq!(result.data(), vec![1.0, 2.0, 3.0, 4.0]);
    }

    #[test]
    fn test_simd_float64_compare() {
        let col1 = Float64Column::new(vec![1.0, 2.0, 3.0, 4.0]);
        let col2 = Float64Column::new(vec![1.0, 1.0, 4.0, 4.0]);

        let result = col1
            .simd_compare(&col2, ComparisonOp::GreaterThan)
            .expect("operation should succeed");

        assert_eq!(result, vec![false, true, false, false]);
    }

    #[test]
    fn test_simd_int64_add() {
        let col1 = Int64Column::new(vec![1, 2, 3, 4]);
        let col2 = Int64Column::new(vec![1, 1, 1, 1]);

        let result = col1.simd_add(&col2).expect("operation should succeed");

        assert_eq!(result.data(), vec![2, 3, 4, 5]);
    }

    #[test]
    fn test_simd_int64_to_float64() {
        let col = Int64Column::new(vec![1, 2, 3, 4]);

        let result = col.to_float64_simd().expect("operation should succeed");

        assert_eq!(result.data(), vec![1.0, 2.0, 3.0, 4.0]);
    }

    #[test]
    fn test_mixed_column_arithmetic() {
        use crate::column::Column;

        let col1 = Column::Float64(Float64Column::new(vec![1.0, 2.0, 3.0]));
        let col2 = Column::Int64(Int64Column::new(vec![1, 2, 3]));

        let result =
            SIMDColumnArithmetic::add_columns(&col1, &col2).expect("operation should succeed");

        if let Column::Float64(float_result) = result {
            assert_eq!(float_result.data(), vec![2.0, 4.0, 6.0]);
        } else {
            panic!("Expected Float64 column result");
        }
    }

    #[test]
    fn test_length_mismatch_error() {
        let col1 = Float64Column::new(vec![1.0, 2.0]);
        let col2 = Float64Column::new(vec![1.0]);

        let result = col1.simd_add(&col2);
        assert!(result.is_err());
    }
}