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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Expression Tree System for JIT Optimization
//!
//! This module provides an expression tree representation for complex operations
//! that enables advanced optimizations like common subexpression elimination,
//! algebraic simplification, and vectorization.

use crate::core::error::{Error, Result};
use crate::optimized::jit::types::{JitNumeric, NumericValue, TypedVector};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

/// Expression tree node representing a computation
#[derive(Debug, Clone, PartialEq)]
pub enum ExpressionNode {
    /// Constant value
    Constant(NumericValue),
    /// Variable (input parameter)
    Variable {
        name: String,
        var_type: String,
        index: usize,
    },
    /// Array access
    ArrayAccess {
        array: Box<ExpressionNode>,
        index: Box<ExpressionNode>,
    },
    /// Binary operation
    BinaryOp {
        left: Box<ExpressionNode>,
        right: Box<ExpressionNode>,
        operator: BinaryOperator,
    },
    /// Unary operation
    UnaryOp {
        operand: Box<ExpressionNode>,
        operator: UnaryOperator,
    },
    /// Function call
    FunctionCall {
        function: String,
        arguments: Vec<ExpressionNode>,
    },
    /// Reduction operation (sum, mean, etc.)
    Reduction {
        array: Box<ExpressionNode>,
        operation: ReductionOperation,
        axis: Option<usize>,
    },
    /// Conditional expression
    Conditional {
        condition: Box<ExpressionNode>,
        true_expr: Box<ExpressionNode>,
        false_expr: Box<ExpressionNode>,
    },
}

/// Binary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinaryOperator {
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Power,
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    LogicalAnd,
    LogicalOr,
    BitwiseAnd,
    BitwiseOr,
    BitwiseXor,
}

/// Unary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnaryOperator {
    Negate,
    LogicalNot,
    BitwiseNot,
    Abs,
    Sqrt,
    Sin,
    Cos,
    Tan,
    Log,
    Exp,
    Floor,
    Ceil,
    Round,
}

/// Reduction operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReductionOperation {
    Sum,
    Product,
    Mean,
    Min,
    Max,
    Count,
    Any,
    All,
    Variance,
    StandardDeviation,
}

impl fmt::Display for BinaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BinaryOperator::Add => write!(f, "+"),
            BinaryOperator::Subtract => write!(f, "-"),
            BinaryOperator::Multiply => write!(f, "*"),
            BinaryOperator::Divide => write!(f, "/"),
            BinaryOperator::Modulo => write!(f, "%"),
            BinaryOperator::Power => write!(f, "**"),
            BinaryOperator::Equal => write!(f, "=="),
            BinaryOperator::NotEqual => write!(f, "!="),
            BinaryOperator::LessThan => write!(f, "<"),
            BinaryOperator::LessThanOrEqual => write!(f, "<="),
            BinaryOperator::GreaterThan => write!(f, ">"),
            BinaryOperator::GreaterThanOrEqual => write!(f, ">="),
            BinaryOperator::LogicalAnd => write!(f, "&&"),
            BinaryOperator::LogicalOr => write!(f, "||"),
            BinaryOperator::BitwiseAnd => write!(f, "&"),
            BinaryOperator::BitwiseOr => write!(f, "|"),
            BinaryOperator::BitwiseXor => write!(f, "^"),
        }
    }
}

impl fmt::Display for UnaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UnaryOperator::Negate => write!(f, "-"),
            UnaryOperator::LogicalNot => write!(f, "!"),
            UnaryOperator::BitwiseNot => write!(f, "~"),
            UnaryOperator::Abs => write!(f, "abs"),
            UnaryOperator::Sqrt => write!(f, "sqrt"),
            UnaryOperator::Sin => write!(f, "sin"),
            UnaryOperator::Cos => write!(f, "cos"),
            UnaryOperator::Tan => write!(f, "tan"),
            UnaryOperator::Log => write!(f, "log"),
            UnaryOperator::Exp => write!(f, "exp"),
            UnaryOperator::Floor => write!(f, "floor"),
            UnaryOperator::Ceil => write!(f, "ceil"),
            UnaryOperator::Round => write!(f, "round"),
        }
    }
}

impl Hash for ExpressionNode {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            ExpressionNode::Constant(value) => {
                value.type_name().hash(state);
                // Hash the numeric value as bits
                value.to_f64().to_bits().hash(state);
            }
            ExpressionNode::Variable {
                name,
                var_type,
                index,
            } => {
                name.hash(state);
                var_type.hash(state);
                index.hash(state);
            }
            ExpressionNode::ArrayAccess { array, index } => {
                array.hash(state);
                index.hash(state);
            }
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                left.hash(state);
                right.hash(state);
                operator.hash(state);
            }
            ExpressionNode::UnaryOp { operand, operator } => {
                operand.hash(state);
                operator.hash(state);
            }
            ExpressionNode::FunctionCall {
                function,
                arguments,
            } => {
                function.hash(state);
                for arg in arguments {
                    arg.hash(state);
                }
            }
            ExpressionNode::Reduction {
                array,
                operation,
                axis,
            } => {
                array.hash(state);
                operation.hash(state);
                axis.hash(state);
            }
            ExpressionNode::Conditional {
                condition,
                true_expr,
                false_expr,
            } => {
                condition.hash(state);
                true_expr.hash(state);
                false_expr.hash(state);
            }
        }
    }
}

/// Expression tree for representing complex computations
#[derive(Debug, Clone)]
pub struct ExpressionTree {
    /// Root node of the expression tree
    pub root: ExpressionNode,
    /// Variable definitions
    pub variables: HashMap<String, VariableInfo>,
    /// Expression metadata
    pub metadata: ExpressionMetadata,
}

/// Information about a variable in the expression
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VariableInfo {
    /// Variable name
    pub name: String,
    /// Data type
    pub data_type: String,
    /// Shape (for arrays)
    pub shape: Option<Vec<usize>>,
    /// Whether this variable is mutable
    pub is_mutable: bool,
}

/// Metadata about an expression tree
#[derive(Debug, Clone)]
pub struct ExpressionMetadata {
    /// Estimated computational complexity
    pub complexity: u64,
    /// Whether the expression is vectorizable
    pub is_vectorizable: bool,
    /// Whether the expression is parallelizable
    pub is_parallelizable: bool,
    /// Memory usage estimate in bytes
    pub estimated_memory_usage: usize,
    /// Optimization opportunities
    pub optimizations: Vec<OptimizationOpportunity>,
}

/// Optimization opportunity identified in the expression
#[derive(Debug, Clone)]
pub struct OptimizationOpportunity {
    /// Type of optimization
    pub optimization_type: OptimizationType,
    /// Description of the optimization
    pub description: String,
    /// Estimated performance improvement (0.0 to 1.0)
    pub estimated_improvement: f64,
    /// Node path where optimization can be applied
    pub node_path: Vec<usize>,
}

/// Types of optimizations that can be applied
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptimizationType {
    CommonSubexpressionElimination,
    ConstantFolding,
    AlgebraicSimplification,
    LoopFusion,
    Vectorization,
    MemoryLayoutOptimization,
    BranchElimination,
    StrengthReduction,
}

impl ExpressionTree {
    /// Create a new expression tree
    pub fn new(root: ExpressionNode) -> Self {
        let mut tree = Self {
            root,
            variables: HashMap::new(),
            metadata: ExpressionMetadata {
                complexity: 0,
                is_vectorizable: false,
                is_parallelizable: false,
                estimated_memory_usage: 0,
                optimizations: Vec::new(),
            },
        };

        tree.analyze();
        tree
    }

    /// Add a variable definition
    pub fn add_variable(
        &mut self,
        name: String,
        data_type: String,
        shape: Option<Vec<usize>>,
        is_mutable: bool,
    ) {
        let var_info = VariableInfo {
            name: name.clone(),
            data_type,
            shape,
            is_mutable,
        };
        self.variables.insert(name, var_info);
    }

    /// Analyze the expression tree for optimization opportunities
    pub fn analyze(&mut self) {
        self.calculate_complexity();
        self.analyze_vectorization();
        self.analyze_parallelization();
        self.estimate_memory_usage();
        self.find_optimizations();
    }

    /// Calculate computational complexity
    fn calculate_complexity(&mut self) {
        self.metadata.complexity = self.calculate_node_complexity(&self.root);
    }

    /// Calculate complexity of a node and its children
    fn calculate_node_complexity(&self, node: &ExpressionNode) -> u64 {
        match node {
            ExpressionNode::Constant(_) => 1,
            ExpressionNode::Variable { .. } => 1,
            ExpressionNode::ArrayAccess { array, index } => {
                self.calculate_node_complexity(array) + self.calculate_node_complexity(index) + 2
            }
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                let left_complexity = self.calculate_node_complexity(left);
                let right_complexity = self.calculate_node_complexity(right);
                let op_complexity = match operator {
                    BinaryOperator::Add | BinaryOperator::Subtract => 1,
                    BinaryOperator::Multiply => 2,
                    BinaryOperator::Divide => 5,
                    BinaryOperator::Power => 10,
                    _ => 1,
                };
                left_complexity + right_complexity + op_complexity
            }
            ExpressionNode::UnaryOp { operand, operator } => {
                let operand_complexity = self.calculate_node_complexity(operand);
                let op_complexity = match operator {
                    UnaryOperator::Negate | UnaryOperator::LogicalNot => 1,
                    UnaryOperator::Abs => 2,
                    UnaryOperator::Sqrt => 5,
                    UnaryOperator::Sin | UnaryOperator::Cos | UnaryOperator::Tan => 10,
                    UnaryOperator::Log | UnaryOperator::Exp => 8,
                    _ => 3,
                };
                operand_complexity + op_complexity
            }
            ExpressionNode::FunctionCall { arguments, .. } => {
                let args_complexity: u64 = arguments
                    .iter()
                    .map(|arg| self.calculate_node_complexity(arg))
                    .sum();
                args_complexity + 10 // Function call overhead
            }
            ExpressionNode::Reduction {
                array, operation, ..
            } => {
                let array_complexity = self.calculate_node_complexity(array);
                let reduction_complexity = match operation {
                    ReductionOperation::Sum | ReductionOperation::Count => 1,
                    ReductionOperation::Mean => 2,
                    ReductionOperation::Min | ReductionOperation::Max => 1,
                    ReductionOperation::Variance | ReductionOperation::StandardDeviation => 10,
                    _ => 5,
                };
                array_complexity * reduction_complexity
            }
            ExpressionNode::Conditional {
                condition,
                true_expr,
                false_expr,
            } => {
                let condition_complexity = self.calculate_node_complexity(condition);
                let true_complexity = self.calculate_node_complexity(true_expr);
                let false_complexity = self.calculate_node_complexity(false_expr);
                condition_complexity + true_complexity.max(false_complexity) + 2
            }
        }
    }

    /// Analyze whether the expression can be vectorized
    fn analyze_vectorization(&mut self) {
        self.metadata.is_vectorizable = self.is_node_vectorizable(&self.root);
    }

    /// Check if a node can be vectorized
    fn is_node_vectorizable(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::Constant(_) => true,
            ExpressionNode::Variable { .. } => true,
            ExpressionNode::ArrayAccess { .. } => true,
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                let vectorizable_ops = [
                    BinaryOperator::Add,
                    BinaryOperator::Subtract,
                    BinaryOperator::Multiply,
                    BinaryOperator::Divide,
                ];
                vectorizable_ops.contains(operator)
                    && self.is_node_vectorizable(left)
                    && self.is_node_vectorizable(right)
            }
            ExpressionNode::UnaryOp { operand, operator } => {
                let vectorizable_ops = [
                    UnaryOperator::Negate,
                    UnaryOperator::Abs,
                    UnaryOperator::Sqrt,
                ];
                vectorizable_ops.contains(operator) && self.is_node_vectorizable(operand)
            }
            ExpressionNode::Reduction { .. } => true, // Reductions are naturally vectorizable
            _ => false, // Function calls and conditionals may not be vectorizable
        }
    }

    /// Analyze whether the expression can be parallelized
    fn analyze_parallelization(&mut self) {
        self.metadata.is_parallelizable = self.is_node_parallelizable(&self.root);
    }

    /// Check if a node can be parallelized
    fn is_node_parallelizable(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::Constant(_) => true,
            ExpressionNode::Variable { .. } => true,
            ExpressionNode::ArrayAccess { .. } => true,
            ExpressionNode::BinaryOp { left, right, .. } => {
                self.is_node_parallelizable(left) && self.is_node_parallelizable(right)
            }
            ExpressionNode::UnaryOp { operand, .. } => self.is_node_parallelizable(operand),
            ExpressionNode::Reduction { .. } => true, // Reductions can be parallelized
            ExpressionNode::FunctionCall { arguments, .. } => {
                // Function calls can be parallelized if all arguments are parallelizable
                // and the function is pure (side-effect free)
                arguments.iter().all(|arg| self.is_node_parallelizable(arg))
            }
            ExpressionNode::Conditional { .. } => false, // Conditionals typically can't be parallelized
        }
    }

    /// Estimate memory usage of the expression
    fn estimate_memory_usage(&mut self) {
        self.metadata.estimated_memory_usage = self.estimate_node_memory(&self.root);
    }

    /// Estimate memory usage of a node
    fn estimate_node_memory(&self, node: &ExpressionNode) -> usize {
        match node {
            ExpressionNode::Constant(_) => 8, // Assume 8 bytes per constant
            ExpressionNode::Variable { var_type, .. } => {
                // Estimate based on type and shape
                let base_size = match var_type.as_str() {
                    "f64" => 8,
                    "f32" => 4,
                    "i64" => 8,
                    "i32" => 4,
                    _ => 8,
                };

                if let Some(var_info) = self.variables.get(&format!("{}", var_type)) {
                    if let Some(shape) = &var_info.shape {
                        let total_elements: usize = shape.iter().product();
                        base_size * total_elements
                    } else {
                        base_size
                    }
                } else {
                    base_size
                }
            }
            ExpressionNode::ArrayAccess { array, index } => {
                self.estimate_node_memory(array) + self.estimate_node_memory(index)
            }
            ExpressionNode::BinaryOp { left, right, .. } => {
                self.estimate_node_memory(left) + self.estimate_node_memory(right) + 8
            }
            ExpressionNode::UnaryOp { operand, .. } => self.estimate_node_memory(operand) + 8,
            ExpressionNode::FunctionCall { arguments, .. } => {
                arguments
                    .iter()
                    .map(|arg| self.estimate_node_memory(arg))
                    .sum::<usize>()
                    + 64
            }
            ExpressionNode::Reduction { array, .. } => {
                self.estimate_node_memory(array) + 64 // Extra space for reduction state
            }
            ExpressionNode::Conditional {
                condition,
                true_expr,
                false_expr,
            } => {
                self.estimate_node_memory(condition)
                    + self
                        .estimate_node_memory(true_expr)
                        .max(self.estimate_node_memory(false_expr))
            }
        }
    }

    /// Find optimization opportunities in the expression tree
    fn find_optimizations(&mut self) {
        self.metadata.optimizations.clear();
        let root_clone = self.root.clone();
        self.find_node_optimizations(&root_clone, &mut Vec::new());
    }

    /// Find optimizations for a specific node
    fn find_node_optimizations(&mut self, node: &ExpressionNode, path: &mut Vec<usize>) {
        // Look for constant folding opportunities
        if self.can_constant_fold(node) {
            self.metadata.optimizations.push(OptimizationOpportunity {
                optimization_type: OptimizationType::ConstantFolding,
                description: "Constant expression can be pre-computed".to_string(),
                estimated_improvement: 0.2,
                node_path: path.clone(),
            });
        }

        // Look for algebraic simplifications
        if self.can_algebraic_simplify(node) {
            self.metadata.optimizations.push(OptimizationOpportunity {
                optimization_type: OptimizationType::AlgebraicSimplification,
                description: "Expression can be algebraically simplified".to_string(),
                estimated_improvement: 0.15,
                node_path: path.clone(),
            });
        }

        // Look for vectorization opportunities
        if self.metadata.is_vectorizable && self.can_vectorize(node) {
            self.metadata.optimizations.push(OptimizationOpportunity {
                optimization_type: OptimizationType::Vectorization,
                description: "Operation can be vectorized with SIMD instructions".to_string(),
                estimated_improvement: 0.4,
                node_path: path.clone(),
            });
        }

        // Recursively analyze child nodes
        match node {
            ExpressionNode::ArrayAccess { array, index } => {
                path.push(0);
                self.find_node_optimizations(array, path);
                path.pop();
                path.push(1);
                self.find_node_optimizations(index, path);
                path.pop();
            }
            ExpressionNode::BinaryOp { left, right, .. } => {
                path.push(0);
                self.find_node_optimizations(left, path);
                path.pop();
                path.push(1);
                self.find_node_optimizations(right, path);
                path.pop();
            }
            ExpressionNode::UnaryOp { operand, .. } => {
                path.push(0);
                self.find_node_optimizations(operand, path);
                path.pop();
            }
            ExpressionNode::FunctionCall { arguments, .. } => {
                for (i, arg) in arguments.iter().enumerate() {
                    path.push(i);
                    self.find_node_optimizations(arg, path);
                    path.pop();
                }
            }
            ExpressionNode::Reduction { array, .. } => {
                path.push(0);
                self.find_node_optimizations(array, path);
                path.pop();
            }
            ExpressionNode::Conditional {
                condition,
                true_expr,
                false_expr,
            } => {
                path.push(0);
                self.find_node_optimizations(condition, path);
                path.pop();
                path.push(1);
                self.find_node_optimizations(true_expr, path);
                path.pop();
                path.push(2);
                self.find_node_optimizations(false_expr, path);
                path.pop();
            }
            _ => {} // Constants and variables don't have children
        }
    }

    /// Check if a node can be constant folded
    fn can_constant_fold(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::BinaryOp { left, right, .. } => {
                matches!(**left, ExpressionNode::Constant(_))
                    && matches!(**right, ExpressionNode::Constant(_))
            }
            ExpressionNode::UnaryOp { operand, .. } => {
                matches!(**operand, ExpressionNode::Constant(_))
            }
            _ => false,
        }
    }

    /// Check if a node can be algebraically simplified
    fn can_algebraic_simplify(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                // Look for patterns like x + 0, x * 1, x * 0, etc.
                match operator {
                    BinaryOperator::Add => {
                        self.is_zero_constant(left) || self.is_zero_constant(right)
                    }
                    BinaryOperator::Multiply => {
                        self.is_zero_constant(left)
                            || self.is_zero_constant(right)
                            || self.is_one_constant(left)
                            || self.is_one_constant(right)
                    }
                    BinaryOperator::Power => {
                        self.is_zero_constant(right) || self.is_one_constant(right)
                    }
                    _ => false,
                }
            }
            _ => false,
        }
    }

    /// Check if a node can be vectorized
    fn can_vectorize(&self, node: &ExpressionNode) -> bool {
        // For now, simple heuristic: vectorize arithmetic operations on arrays
        match node {
            ExpressionNode::BinaryOp { operator, .. } => {
                matches!(
                    operator,
                    BinaryOperator::Add
                        | BinaryOperator::Subtract
                        | BinaryOperator::Multiply
                        | BinaryOperator::Divide
                )
            }
            ExpressionNode::UnaryOp { operator, .. } => {
                matches!(
                    operator,
                    UnaryOperator::Negate | UnaryOperator::Abs | UnaryOperator::Sqrt
                )
            }
            _ => false,
        }
    }

    /// Check if a node is a zero constant
    fn is_zero_constant(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::Constant(value) => value.to_f64() == 0.0,
            _ => false,
        }
    }

    /// Check if a node is a one constant
    fn is_one_constant(&self, node: &ExpressionNode) -> bool {
        match node {
            ExpressionNode::Constant(value) => value.to_f64() == 1.0,
            _ => false,
        }
    }

    /// Generate optimized expression tree
    pub fn optimize(&self) -> Result<ExpressionTree> {
        let mut optimized_root = self.root.clone();

        // Apply optimizations in order of importance
        optimized_root = self.apply_constant_folding(optimized_root)?;
        optimized_root = self.apply_algebraic_simplification(optimized_root)?;
        optimized_root = self.apply_common_subexpression_elimination(optimized_root)?;

        let mut optimized_tree = ExpressionTree::new(optimized_root);
        optimized_tree.variables = self.variables.clone();

        Ok(optimized_tree)
    }

    /// Apply constant folding optimization
    fn apply_constant_folding(&self, node: ExpressionNode) -> Result<ExpressionNode> {
        match node {
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                let left = self.apply_constant_folding(*left)?;
                let right = self.apply_constant_folding(*right)?;

                if let (ExpressionNode::Constant(l_val), ExpressionNode::Constant(r_val)) =
                    (&left, &right)
                {
                    // Evaluate the constant expression
                    let result = self.evaluate_binary_constant_op(l_val, r_val, operator)?;
                    Ok(ExpressionNode::Constant(result))
                } else {
                    Ok(ExpressionNode::BinaryOp {
                        left: Box::new(left),
                        right: Box::new(right),
                        operator,
                    })
                }
            }
            ExpressionNode::UnaryOp { operand, operator } => {
                let operand = self.apply_constant_folding(*operand)?;

                if let ExpressionNode::Constant(val) = &operand {
                    let result = self.evaluate_unary_constant_op(val, operator)?;
                    Ok(ExpressionNode::Constant(result))
                } else {
                    Ok(ExpressionNode::UnaryOp {
                        operand: Box::new(operand),
                        operator,
                    })
                }
            }
            _ => Ok(node), // Other node types don't need constant folding
        }
    }

    /// Apply algebraic simplification
    fn apply_algebraic_simplification(&self, node: ExpressionNode) -> Result<ExpressionNode> {
        match node {
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                let left = self.apply_algebraic_simplification(*left)?;
                let right = self.apply_algebraic_simplification(*right)?;

                // Apply simplification rules
                match operator {
                    BinaryOperator::Add => {
                        if self.is_zero_constant(&left) {
                            return Ok(right);
                        }
                        if self.is_zero_constant(&right) {
                            return Ok(left);
                        }
                    }
                    BinaryOperator::Multiply => {
                        if self.is_zero_constant(&left) || self.is_zero_constant(&right) {
                            return Ok(ExpressionNode::Constant(NumericValue::F64(0.0)));
                        }
                        if self.is_one_constant(&left) {
                            return Ok(right);
                        }
                        if self.is_one_constant(&right) {
                            return Ok(left);
                        }
                    }
                    BinaryOperator::Power => {
                        if self.is_zero_constant(&right) {
                            return Ok(ExpressionNode::Constant(NumericValue::F64(1.0)));
                        }
                        if self.is_one_constant(&right) {
                            return Ok(left);
                        }
                    }
                    _ => {}
                }

                Ok(ExpressionNode::BinaryOp {
                    left: Box::new(left),
                    right: Box::new(right),
                    operator,
                })
            }
            _ => Ok(node),
        }
    }

    /// Apply common subexpression elimination
    fn apply_common_subexpression_elimination(
        &self,
        node: ExpressionNode,
    ) -> Result<ExpressionNode> {
        // This is a simplified implementation - a full CSE would require
        // building a hash table of all subexpressions and their frequencies
        Ok(node)
    }

    /// Evaluate a binary operation on constants
    fn evaluate_binary_constant_op(
        &self,
        left: &NumericValue,
        right: &NumericValue,
        operator: BinaryOperator,
    ) -> Result<NumericValue> {
        let l_val = left.to_f64();
        let r_val = right.to_f64();

        let result = match operator {
            BinaryOperator::Add => l_val + r_val,
            BinaryOperator::Subtract => l_val - r_val,
            BinaryOperator::Multiply => l_val * r_val,
            BinaryOperator::Divide => {
                if r_val == 0.0 {
                    return Err(Error::InvalidOperation("Division by zero".to_string()));
                }
                l_val / r_val
            }
            BinaryOperator::Power => l_val.powf(r_val),
            _ => {
                return Err(Error::NotImplemented(format!(
                    "Constant evaluation for {:?}",
                    operator
                )))
            }
        };

        Ok(NumericValue::F64(result))
    }

    /// Evaluate a unary operation on a constant
    fn evaluate_unary_constant_op(
        &self,
        operand: &NumericValue,
        operator: UnaryOperator,
    ) -> Result<NumericValue> {
        let val = operand.to_f64();

        let result = match operator {
            UnaryOperator::Negate => -val,
            UnaryOperator::Abs => val.abs(),
            UnaryOperator::Sqrt => {
                if val < 0.0 {
                    return Err(Error::InvalidOperation(
                        "Square root of negative number".to_string(),
                    ));
                }
                val.sqrt()
            }
            UnaryOperator::Sin => val.sin(),
            UnaryOperator::Cos => val.cos(),
            UnaryOperator::Tan => val.tan(),
            UnaryOperator::Log => {
                if val <= 0.0 {
                    return Err(Error::InvalidOperation(
                        "Logarithm of non-positive number".to_string(),
                    ));
                }
                val.ln()
            }
            UnaryOperator::Exp => val.exp(),
            UnaryOperator::Floor => val.floor(),
            UnaryOperator::Ceil => val.ceil(),
            UnaryOperator::Round => val.round(),
            _ => {
                return Err(Error::NotImplemented(format!(
                    "Constant evaluation for {:?}",
                    operator
                )))
            }
        };

        Ok(NumericValue::F64(result))
    }

    /// Convert the expression tree to a human-readable string
    pub fn to_string(&self) -> String {
        self.node_to_string(&self.root)
    }

    /// Convert a node to a string representation
    fn node_to_string(&self, node: &ExpressionNode) -> String {
        match node {
            ExpressionNode::Constant(value) => format!("{}", value.to_f64()),
            ExpressionNode::Variable { name, .. } => name.clone(),
            ExpressionNode::ArrayAccess { array, index } => {
                format!(
                    "{}[{}]",
                    self.node_to_string(array),
                    self.node_to_string(index)
                )
            }
            ExpressionNode::BinaryOp {
                left,
                right,
                operator,
            } => {
                format!(
                    "({} {} {})",
                    self.node_to_string(left),
                    operator,
                    self.node_to_string(right)
                )
            }
            ExpressionNode::UnaryOp { operand, operator } => {
                format!("{}({})", operator, self.node_to_string(operand))
            }
            ExpressionNode::FunctionCall {
                function,
                arguments,
            } => {
                let args: Vec<String> = arguments
                    .iter()
                    .map(|arg| self.node_to_string(arg))
                    .collect();
                format!("{}({})", function, args.join(", "))
            }
            ExpressionNode::Reduction {
                array,
                operation,
                axis,
            } => {
                let axis_str = if let Some(axis) = axis {
                    format!(", axis={})", axis)
                } else {
                    ")".to_string()
                };
                format!("{:?}({}{}", operation, self.node_to_string(array), axis_str)
            }
            ExpressionNode::Conditional {
                condition,
                true_expr,
                false_expr,
            } => {
                format!(
                    "if {} then {} else {}",
                    self.node_to_string(condition),
                    self.node_to_string(true_expr),
                    self.node_to_string(false_expr)
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_expression_creation() {
        let x = ExpressionNode::Variable {
            name: "x".to_string(),
            var_type: "f64".to_string(),
            index: 0,
        };

        let constant = ExpressionNode::Constant(NumericValue::F64(2.0));

        let expr = ExpressionNode::BinaryOp {
            left: Box::new(x),
            right: Box::new(constant),
            operator: BinaryOperator::Multiply,
        };

        let tree = ExpressionTree::new(expr);
        assert!(tree.metadata.complexity > 0);
    }

    #[test]
    fn test_constant_folding() {
        let left = ExpressionNode::Constant(NumericValue::F64(2.0));
        let right = ExpressionNode::Constant(NumericValue::F64(3.0));

        let expr = ExpressionNode::BinaryOp {
            left: Box::new(left),
            right: Box::new(right),
            operator: BinaryOperator::Add,
        };

        let tree = ExpressionTree::new(expr);
        let optimized = tree.optimize().expect("operation should succeed");

        // Should have folded to a constant 5.0
        if let ExpressionNode::Constant(value) = optimized.root {
            assert_eq!(value.to_f64(), 5.0);
        } else {
            panic!("Expected constant folded result");
        }
    }

    #[test]
    fn test_algebraic_simplification() {
        let x = ExpressionNode::Variable {
            name: "x".to_string(),
            var_type: "f64".to_string(),
            index: 0,
        };

        let zero = ExpressionNode::Constant(NumericValue::F64(0.0));

        let expr = ExpressionNode::BinaryOp {
            left: Box::new(x.clone()),
            right: Box::new(zero),
            operator: BinaryOperator::Add,
        };

        let tree = ExpressionTree::new(expr);
        let optimized = tree.optimize().expect("operation should succeed");

        // Should have simplified to just x
        if let ExpressionNode::Variable { name, .. } = optimized.root {
            assert_eq!(name, "x");
        } else {
            panic!("Expected simplified result to be just variable x");
        }
    }

    #[test]
    fn test_expression_string_representation() {
        let x = ExpressionNode::Variable {
            name: "x".to_string(),
            var_type: "f64".to_string(),
            index: 0,
        };

        let constant = ExpressionNode::Constant(NumericValue::F64(2.0));

        let expr = ExpressionNode::BinaryOp {
            left: Box::new(x),
            right: Box::new(constant),
            operator: BinaryOperator::Multiply,
        };

        let tree = ExpressionTree::new(expr);
        let string_repr = tree.to_string();

        assert_eq!(string_repr, "(x * 2)");
    }
}