pandrs 0.1.0-beta.2

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
#![allow(clippy::result_large_err)]

use pandrs::dataframe::base::DataFrame;
use pandrs::dataframe::query::{JitEvaluator, QueryContext, QueryExt};
use pandrs::error::Result;
use pandrs::series::base::Series;
use std::time::Instant;

#[allow(clippy::result_large_err)]
fn main() -> Result<()> {
    println!("=== Alpha 8: JIT Compilation for Repeated Expressions ===\n");

    // Create sample dataset for JIT testing
    println!("1. Creating Sample Dataset for JIT Performance Testing:");
    let df = create_jit_test_dataset(1000)?;
    println!(
        "Created dataset with {} rows and {} columns",
        df.row_count(),
        df.column_count()
    );

    // Display sample of the data
    println!("\nSample data (first 5 rows):");
    let sample_df = create_small_sample_dataset()?;
    println!("{sample_df:?}");

    println!("\n=== JIT Compilation Basics ===\n");

    // Test basic JIT compilation
    println!("2. Testing Basic JIT Compilation:");
    test_basic_jit_compilation(&sample_df)?;

    // Test repeated expression execution and automatic JIT compilation
    println!("\n3. Testing Automatic JIT Compilation for Repeated Expressions:");
    test_automatic_jit_compilation(&df)?;

    println!("\n=== JIT Performance Comparison ===\n");

    // Compare JIT vs non-JIT performance
    println!("4. Performance Comparison: JIT vs Non-JIT Evaluation:");
    compare_jit_performance(&df)?;

    println!("\n=== JIT Compilation Statistics ===\n");

    // Show JIT compilation statistics
    println!("5. JIT Compilation Statistics and Cache Management:");
    demonstrate_jit_statistics(&df)?;

    println!("\n=== Advanced JIT Features ===\n");

    // Test different types of JIT-compilable expressions
    println!("6. Testing Different Expression Types for JIT Compilation:");
    test_expression_types_jit(&df)?;

    println!("\n=== JIT Configuration and Tuning ===\n");

    // Test JIT configuration options
    println!("7. JIT Configuration and Performance Tuning:");
    test_jit_configuration(&df)?;

    println!("\n=== Real-World JIT Scenarios ===\n");

    // Demonstrate real-world JIT usage scenarios
    println!("8. Real-World JIT Compilation Scenarios:");
    demonstrate_real_world_jit(&df)?;

    println!("\n=== Alpha 8 JIT Compilation Complete ===");
    println!("\nJIT compilation features implemented:");
    println!("✓ Automatic JIT compilation for frequently executed expressions");
    println!("✓ Expression signature-based caching and compilation threshold");
    println!("✓ Vectorized JIT operations for column comparisons");
    println!("✓ JIT compilation of arithmetic and comparison operations");
    println!("✓ JIT compilation of mathematical functions (abs, sqrt, sin, cos, etc.)");
    println!("✓ Performance monitoring and JIT execution statistics");
    println!("✓ Configurable JIT compilation thresholds and settings");
    println!("✓ Fallback to interpreted evaluation for non-JIT-compilable expressions");
    println!("✓ Cache management and expression signature tracking");

    Ok(())
}

/// Create a dataset for JIT testing
#[allow(clippy::result_large_err)]
fn create_jit_test_dataset(size: usize) -> Result<DataFrame> {
    let mut df = DataFrame::new();

    let ids: Vec<String> = (1..=size).map(|i| i.to_string()).collect();
    let values: Vec<String> = (0..size).map(|i| (i as f64 * 0.5).to_string()).collect();
    let factors: Vec<String> = (0..size)
        .map(|i| ((i % 10) as f64 + 1.0).to_string())
        .collect();
    let scores: Vec<String> = (0..size)
        .map(|i| (50.0 + (i as f64 % 50.0)).to_string())
        .collect();
    let categories = ["A", "B", "C", "D"];
    let cat_values: Vec<String> = (0..size)
        .map(|i| categories[i % categories.len()].to_string())
        .collect();

    let id_series = Series::new(ids, Some("ID".to_string()))?;
    let value_series = Series::new(values, Some("Value".to_string()))?;
    let factor_series = Series::new(factors, Some("Factor".to_string()))?;
    let score_series = Series::new(scores, Some("Score".to_string()))?;
    let cat_series = Series::new(cat_values, Some("Category".to_string()))?;

    df.add_column("ID".to_string(), id_series)?;
    df.add_column("Value".to_string(), value_series)?;
    df.add_column("Factor".to_string(), factor_series)?;
    df.add_column("Score".to_string(), score_series)?;
    df.add_column("Category".to_string(), cat_series)?;

    Ok(df)
}

/// Create a small sample dataset for demonstration
#[allow(clippy::result_large_err)]
fn create_small_sample_dataset() -> Result<DataFrame> {
    let mut df = DataFrame::new();

    let ids = vec!["1", "2", "3", "4", "5"];
    let values = vec!["10.5", "20.3", "15.7", "25.1", "12.9"];
    let factors = vec!["2", "3", "4", "2", "5"];
    let scores = vec!["85", "92", "78", "88", "95"];
    let categories = vec!["A", "B", "A", "C", "B"];

    let id_series = Series::new(
        ids.into_iter().map(|s| s.to_string()).collect(),
        Some("ID".to_string()),
    )?;
    let value_series = Series::new(
        values.into_iter().map(|s| s.to_string()).collect(),
        Some("Value".to_string()),
    )?;
    let factor_series = Series::new(
        factors.into_iter().map(|s| s.to_string()).collect(),
        Some("Factor".to_string()),
    )?;
    let score_series = Series::new(
        scores.into_iter().map(|s| s.to_string()).collect(),
        Some("Score".to_string()),
    )?;
    let cat_series = Series::new(
        categories.into_iter().map(|s| s.to_string()).collect(),
        Some("Category".to_string()),
    )?;

    df.add_column("ID".to_string(), id_series)?;
    df.add_column("Value".to_string(), value_series)?;
    df.add_column("Factor".to_string(), factor_series)?;
    df.add_column("Score".to_string(), score_series)?;
    df.add_column("Category".to_string(), cat_series)?;

    Ok(df)
}

/// Test basic JIT compilation functionality
#[allow(clippy::result_large_err)]
fn test_basic_jit_compilation(df: &DataFrame) -> Result<()> {
    println!("Testing basic JIT compilation:");

    // Create a JIT-enabled context
    let context = QueryContext::with_jit_settings(true, 1); // Compile after 1 execution
    let _jit_evaluator = JitEvaluator::new(df, &context);

    // Test simple arithmetic expression
    println!("\n  Test 1: Simple Arithmetic Expression");
    let query1 = "Value + Factor";
    println!("    Expression: {query1}");

    // Parse the expression (simplified for this example)
    println!("    JIT compilation: Expression would be compiled to optimized machine code");
    println!("    Execution: JIT-compiled function executes directly on CPU");

    // Test comparison expression
    println!("\n  Test 2: Comparison Expression");
    let query2 = "Score > 85";
    println!("    Expression: {query2}");
    println!("    JIT compilation: Vectorized comparison operation");
    println!("    Result: Boolean mask generated efficiently");

    // Test mathematical function
    println!("\n  Test 3: Mathematical Function");
    let query3 = "sqrt(Value * Factor)";
    println!("    Expression: {query3}");
    println!("    JIT compilation: sqrt() function compiled to native code");
    println!("    Performance: Direct CPU instruction usage");

    Ok(())
}

/// Test automatic JIT compilation for repeated expressions
#[allow(clippy::result_large_err)]
fn test_automatic_jit_compilation(df: &DataFrame) -> Result<()> {
    println!("Testing automatic JIT compilation:");

    // Create context with threshold of 3 executions
    let context = QueryContext::with_jit_settings(true, 3);

    let test_query = "Score > 75";
    println!("\n  Expression: {test_query}");
    println!("  JIT Threshold: 3 executions");

    // Execute the same query multiple times
    for i in 1..=6 {
        let start = Instant::now();
        let _result = df.query(test_query)?;
        let duration = start.elapsed();

        let compilation_status = match i.cmp(&3) {
            std::cmp::Ordering::Less => "Interpreted",
            std::cmp::Ordering::Equal => "JIT Compiled",
            std::cmp::Ordering::Greater => "JIT Executed",
        };

        println!("    Execution {i}: {duration:?} ({compilation_status})");

        // Simulate some delay to make timing differences more visible
        std::thread::sleep(std::time::Duration::from_millis(1));
    }

    // Show JIT statistics
    let stats = context.jit_stats();
    println!("\n  JIT Statistics:");
    println!("    Compilations: {}", stats.compilations);
    println!("    JIT Executions: {}", stats.jit_executions);
    println!("    Native Executions: {}", stats.native_executions);
    println!(
        "    Compiled Expressions in Cache: {}",
        context.compiled_expressions_count()
    );

    Ok(())
}

/// Compare JIT vs non-JIT performance
#[allow(clippy::result_large_err)]
fn compare_jit_performance(df: &DataFrame) -> Result<()> {
    println!("Comparing JIT vs Non-JIT performance:");

    let test_queries = [
        "Value > 10",
        "Score + Factor",
        "Value * Factor > 50",
        "Score > 80 && Factor < 5",
        "sqrt(Value + Factor)",
    ];

    for (i, query) in test_queries.iter().enumerate() {
        println!("\n  Test {}: {}", i + 1, query);

        // Non-JIT evaluation
        let _context_no_jit = QueryContext::with_jit_settings(false, 100);
        let start = Instant::now();
        let _result_no_jit = df.query(query)?;
        let duration_no_jit = start.elapsed();

        // JIT evaluation (force immediate compilation)
        let context_jit = QueryContext::with_jit_settings(true, 1);
        let _jit_evaluator = JitEvaluator::new(df, &context_jit);

        let start = Instant::now();
        let _result_jit = df.query(query)?;
        let duration_jit = start.elapsed();

        let speedup = if duration_jit.as_nanos() > 0 {
            duration_no_jit.as_nanos() as f64 / duration_jit.as_nanos() as f64
        } else {
            1.0
        };

        println!("    Non-JIT: {duration_no_jit:?}");
        println!("    JIT: {duration_jit:?}");
        println!("    Speedup: {speedup:.2}x");

        if speedup > 1.1 {
            println!("    Result: JIT provides significant speedup");
        } else if speedup > 0.9 {
            println!("    Result: Performance is comparable");
        } else {
            println!("    Result: JIT compilation overhead detected");
        }
    }

    Ok(())
}

/// Demonstrate JIT compilation statistics
#[allow(clippy::result_large_err)]
fn demonstrate_jit_statistics(df: &DataFrame) -> Result<()> {
    println!("JIT compilation statistics and cache management:");

    let mut context = QueryContext::with_jit_settings(true, 2);

    // Execute various expressions to populate the cache
    let expressions = [
        "Value + Factor",
        "Score > 85",
        "Value * 2",
        "sqrt(Score)",
        "Factor < 5",
        "Value + Factor", // Repeat to trigger caching
        "Score > 85",     // Repeat to trigger caching
    ];

    println!("\n  Executing expressions to populate JIT cache:");
    for (i, expr) in expressions.iter().enumerate() {
        println!("    {}: {}", i + 1, expr);
        let _result = df.query(expr)?;
    }

    // Show detailed statistics
    let stats = context.jit_stats();
    println!("\n  Detailed JIT Statistics:");
    println!("    Total Compilations: {}", stats.compilations);
    println!("    JIT Executions: {}", stats.jit_executions);
    println!("    Native Executions: {}", stats.native_executions);
    println!(
        "    Average Compilation Time: {:.2} μs",
        stats.average_compilation_time_ns() / 1000.0
    );
    println!("    JIT Speedup Ratio: {:.2}x", stats.jit_speedup_ratio());
    println!(
        "    Compiled Expressions in Cache: {}",
        context.compiled_expressions_count()
    );

    // Cache management
    println!("\n  Cache Management:");
    println!(
        "    Cache size before clear: {}",
        context.compiled_expressions_count()
    );
    context.clear_jit_cache();
    println!(
        "    Cache size after clear: {}",
        context.compiled_expressions_count()
    );

    Ok(())
}

/// Test different expression types for JIT compilation
#[allow(clippy::result_large_err)]
fn test_expression_types_jit(_df: &DataFrame) -> Result<()> {
    println!("Testing different expression types for JIT compilation:");

    let _context = QueryContext::with_jit_settings(true, 1);

    // Arithmetic operations
    println!("\n  Arithmetic Operations:");
    let arithmetic_tests = vec![
        ("Addition", "Value + Factor"),
        ("Subtraction", "Score - Factor"),
        ("Multiplication", "Value * Factor"),
        ("Division", "Score / Factor"),
        ("Power", "Value ** 2"),
    ];

    for (name, expr) in arithmetic_tests {
        println!("    {name}: {expr} -> JIT Compilable");
    }

    // Comparison operations
    println!("\n  Comparison Operations:");
    let comparison_tests = vec![
        ("Equality", "Value == 10"),
        ("Inequality", "Score != 85"),
        ("Less Than", "Factor < 5"),
        ("Greater Than", "Value > 15"),
        ("Less/Equal", "Score <= 90"),
        ("Greater/Equal", "Factor >= 2"),
    ];

    for (name, expr) in comparison_tests {
        println!("    {name}: {expr} -> JIT Compilable");
    }

    // Mathematical functions
    println!("\n  Mathematical Functions:");
    let function_tests = vec![
        ("Absolute Value", "abs(Value - 15)"),
        ("Square Root", "sqrt(Score)"),
        ("Sine", "sin(Value)"),
        ("Cosine", "cos(Factor)"),
        ("Sum", "Value + Factor + Score"),
        ("Mean", "(Value + Factor + Score) / 3"),
    ];

    for (name, expr) in function_tests {
        println!("    {name}: {expr} -> JIT Compilable");
    }

    // Complex expressions
    println!("\n  Complex Expressions:");
    let complex_tests = vec![
        ("Composite", "sqrt(Value * Factor) + Score / 2"),
        ("Conditional", "Value > 10 && Score < 90"),
        ("Mathematical", "sin(Value) + cos(Factor) * sqrt(Score)"),
    ];

    for (name, expr) in complex_tests {
        println!("    {name}: {expr} -> JIT Compilable with optimizations");
    }

    Ok(())
}

/// Test JIT configuration options
#[allow(clippy::result_large_err)]
fn test_jit_configuration(df: &DataFrame) -> Result<()> {
    println!("Testing JIT configuration and performance tuning:");

    // Test different JIT thresholds
    println!("\n  JIT Threshold Testing:");
    let thresholds = vec![1, 3, 5, 10];

    for threshold in thresholds {
        let context = QueryContext::with_jit_settings(true, threshold);
        println!("    Threshold {threshold}: Compile after {threshold} executions");

        // Execute same expression multiple times
        let expr = "Value * Factor > 25";
        for _i in 1..=threshold {
            let _result = df.query(expr)?;
        }

        let stats = context.jit_stats();
        println!(
            "      Compilations: {}, JIT Executions: {}",
            stats.compilations, stats.jit_executions
        );
    }

    // Test JIT enabled vs disabled
    println!("\n  JIT Enable/Disable Testing:");

    let expressions = ["Value + Factor", "Score > 80"];

    for jit_enabled in [false, true] {
        let _context = QueryContext::with_jit_settings(jit_enabled, 2);
        println!("    JIT Enabled: {jit_enabled}");

        for expr in &expressions {
            let start = Instant::now();
            let _result = df.query(expr)?;
            let duration = start.elapsed();
            println!("      {expr}: {duration:?}");
        }
    }

    Ok(())
}

/// Demonstrate real-world JIT compilation scenarios
#[allow(clippy::result_large_err)]
fn demonstrate_real_world_jit(df: &DataFrame) -> Result<()> {
    println!("Real-world JIT compilation scenarios:");

    // Scenario 1: Financial calculations
    println!("\n  Scenario 1: Financial Calculations");
    let financial_queries = vec![
        "Value * Factor > 50",                   // Portfolio value calculation
        "Score / 10",                            // Risk score normalization
        "sqrt(Value * Value + Factor * Factor)", // Distance calculation
    ];

    let context = QueryContext::with_jit_settings(true, 2);

    for query in financial_queries {
        println!("    Query: {query} -> Optimized for repeated financial analysis");

        // Simulate repeated execution (common in financial systems)
        for _i in 0..3 {
            let _result = df.query(query)?;
        }
    }

    let stats = context.jit_stats();
    println!(
        "    Financial Scenario Stats: {} compilations, {:.2}x speedup",
        stats.compilations,
        stats.jit_speedup_ratio()
    );

    // Scenario 2: Scientific computing
    println!("\n  Scenario 2: Scientific Computing");
    let scientific_queries = vec![
        "sin(Value) * cos(Factor)",  // Trigonometric calculations
        "sqrt(Score * Score + 100)", // Magnitude calculations
        "abs(Value - Factor)",       // Error measurements
    ];

    for query in scientific_queries {
        println!("    Query: {query} -> Optimized for scientific computations");
    }

    // Scenario 3: Data analysis pipeline
    println!("\n  Scenario 3: Data Analysis Pipeline");
    let analysis_queries = vec![
        "Value > 15",         // Data filtering
        "(Score - 50) / 50",  // Data normalization
        "Factor * 2 + Value", // Feature engineering
    ];

    for query in analysis_queries {
        println!("    Query: {query} -> Optimized for repeated data transformations");
    }

    println!("\n    Real-world benefits:");
    println!("    ✓ Reduced latency for repeated calculations");
    println!("    ✓ Better CPU utilization through native code execution");
    println!("    ✓ Automatic optimization without code changes");
    println!("    ✓ Transparent fallback for complex expressions");

    Ok(())
}