mathhook-core 0.2.0

Core mathematical engine for MathHook - expressions, algebra, and solving
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
//! Edge case testing for mathematical operations
//!
//! This module tests boundary conditions, error handling, and extreme cases
//! to ensure robust behavior across all mathematical operations.

use mathhook_core::prelude::*;
use num_bigint::BigInt;
use num_rational::BigRational;

// Boundary value testing
mod boundary_values {
    use super::*;

    #[test]
    fn test_zero_boundary_conditions() {
        // Test all operations with zero values
        let zero = expr!(0);
        let var = expr!(x);

        // Addition with zero
        assert_eq!(expr!(x + 0).simplify(), var);
        assert_eq!(expr!(0 + x), var);

        // Multiplication with zero
        assert_eq!(expr!(x * 0).simplify(), zero);
        assert_eq!(expr!(0 * x).simplify(), zero);

        // Power operations with zero
        assert_eq!(expr!(x ^ 0).simplify(), expr!(1));
        assert_eq!(expr!(0 ^ 1).simplify(), zero);

        // Zero with itself
        assert_eq!(expr!(0 + 0).simplify(), zero);
        assert_eq!(expr!(0 * 0).simplify(), zero);
    }

    #[test]
    fn test_unity_boundary_conditions() {
        // Test all operations with unity (1)
        let one = expr!(1);
        let var = expr!(x);

        // Multiplication with one
        assert_eq!(expr!(x * 1).simplify(), var);
        assert_eq!(expr!(1 * x).simplify(), var);

        // Power operations with one
        assert_eq!(expr!(x ^ 1).simplify(), var);
        assert_eq!(expr!(1 ^ x).simplify(), one);

        // One with itself
        assert_eq!(expr!(1 * 1).simplify(), one);
        assert_eq!(expr!(1 ^ 1).simplify().simplify(), one);
    }

    #[test]
    fn test_negative_number_handling() {
        // Test operations with negative numbers
        let pos = expr!(5);
        let neg = expr!(-5);
        let zero = expr!(0);

        // Addition with negatives
        assert_eq!(
            Expression::add(vec![pos.clone(), neg.clone()]).simplify(),
            zero
        );
        assert_eq!(
            Expression::add(vec![neg.clone(), pos.clone()]).simplify(),
            zero
        );

        // Multiplication with negatives
        assert_eq!(
            Expression::mul(vec![pos, neg.clone()]).simplify(),
            expr!(-25)
        );
        assert_eq!(
            Expression::mul(vec![neg.clone(), neg.clone()]).simplify(),
            expr!(25)
        );

        // Powers with negatives
        assert_eq!(Expression::pow(neg.clone(), expr!(2)).simplify(), expr!(25));
        assert_eq!(Expression::pow(neg, expr!(3)).simplify(), expr!(-125));
    }

    #[test]
    fn test_extreme_integer_values() {
        // Test with extreme integer values
        let max_int = Expression::integer(i64::MAX);
        let min_int = Expression::integer(i64::MIN);
        let one = expr!(1);

        // Operations near boundaries should handle gracefully
        let near_max = Expression::add(vec![max_int, one]);
        let near_min = Expression::add(vec![min_int, Expression::integer(-1)]);

        // Should not panic, may promote to BigInteger
        let max_result = near_max.simplify();
        let min_result = near_min.simplify();

        // Results should be valid expressions
        assert!(
            matches!(max_result, Expression::Number(_)),
            "Near-overflow result should be a number"
        );

        assert!(
            matches!(min_result, Expression::Number(_)),
            "Near-underflow result should be a number"
        );
    }
}

// Large number handling
mod large_numbers {
    use super::*;

    #[test]
    fn test_large_integer_arithmetic() {
        // Test arithmetic with very large integers
        let large_a = Expression::big_integer(
            BigInt::parse_bytes(b"12345678901234567890123456789012345", 10).unwrap(),
        );
        let large_b = Expression::big_integer(
            BigInt::parse_bytes(b"98765432109876543210987654321098765", 10).unwrap(),
        );

        // Should handle large number operations without overflow
        let sum = Expression::add(vec![large_a.clone(), large_b.clone()]).simplify();
        let product = Expression::mul(vec![large_a, large_b]).simplify();

        // Verify results maintain correct type
        assert!(
            matches!(
                sum,
                Expression::Number(Number::BigInteger(_) | Number::Integer(_))
            ),
            "Large number sum should be a number, got: {sum}"
        );

        assert!(
            matches!(
                product,
                Expression::Number(Number::BigInteger(_) | Number::Integer(_))
            ),
            "Large number product should be a number, got: {product}"
        );
    }

    #[test]
    fn test_large_number_gcd() {
        // Test GCD with large numbers
        let large_a = Expression::big_integer(BigInt::parse_bytes(b"123456789012345", 10).unwrap());
        let large_b = Expression::big_integer(BigInt::parse_bytes(b"987654321098765", 10).unwrap());

        // Should compute GCD without issues
        let gcd_result = large_a.gcd(&large_b);

        // Should return a valid number
        assert!(
            matches!(gcd_result, Expression::Number(_)),
            "GCD of large numbers should return a number"
        );

        // Should maintain commutative property
        assert_eq!(large_a.gcd(&large_b), large_b.gcd(&large_a));
    }

    #[test]
    fn test_factorial_like_growth() {
        // Test with numbers that grow like factorials
        let mut factorial = Expression::integer(1);

        for i in 2..=20 {
            factorial = Expression::mul(vec![factorial, Expression::integer(i)]).simplify();
        }

        // 20! should be computed correctly
        let expected_factorial_20 =
            Expression::big_integer(BigInt::parse_bytes(b"2432902008176640000", 10).unwrap());

        assert_eq!(
            factorial, expected_factorial_20,
            "20! should be computed correctly"
        );
    }
}

// Rational number edge cases
mod rational_edge_cases {
    use super::*;

    #[test]
    fn test_rational_with_large_denominators() {
        // Test rationals with very large denominators
        let large_denom = BigInt::parse_bytes(b"123456789012345", 10).unwrap();
        let rational = Expression::number(Number::rational(BigRational::new(
            BigInt::from(1),
            large_denom,
        )));

        // Should handle without precision loss
        let doubled = Expression::mul(vec![Expression::integer(2), rational]).simplify();

        assert!(
            matches!(doubled, Expression::Number(Number::Rational(_))),
            "Rational arithmetic should preserve rational type when possible"
        );
    }

    #[test]
    fn test_rational_reduction_edge_cases() {
        // Test rational reduction with edge cases
        let test_cases = vec![
            (0, 1, 0, 1),    // 0/1 = 0/1
            (1, 1, 1, 1),    // 1/1 = 1/1
            (-1, 1, -1, 1),  // -1/1 = -1/1
            (2, 4, 1, 2),    // 2/4 = 1/2
            (-6, 9, -2, 3),  // -6/9 = -2/3
            (100, 25, 4, 1), // 100/25 = 4/1
            (17, 1, 17, 1),  // 17/1 = 17/1
        ];

        for (num, den, exp_num, exp_den) in test_cases {
            let rational = Expression::number(Number::rational(BigRational::new(
                BigInt::from(num),
                BigInt::from(den),
            )));
            let expected = Expression::number(Number::rational(BigRational::new(
                BigInt::from(exp_num),
                BigInt::from(exp_den),
            )));

            assert_eq!(
                rational.simplify(),
                expected,
                "{num}/{den} should reduce to {exp_num}/{exp_den}"
            );
        }
    }

    #[test]
    fn test_rational_arithmetic_precision() {
        // Test that rational arithmetic maintains exact precision
        let test_cases = vec![
            // (a_num, a_den, b_num, b_den, expected_num, expected_den)
            (1, 3, 1, 6, 1, 2),   // 1/3 + 1/6 = 1/2
            (2, 5, 3, 10, 7, 10), // 2/5 + 3/10 = 7/10
            (1, 4, 1, 4, 1, 2),   // 1/4 + 1/4 = 1/2
        ];

        for (a_num, a_den, b_num, b_den, exp_num, exp_den) in test_cases {
            let a = Expression::number(Number::rational(BigRational::new(
                BigInt::from(a_num),
                BigInt::from(a_den),
            )));
            let b = Expression::number(Number::rational(BigRational::new(
                BigInt::from(b_num),
                BigInt::from(b_den),
            )));
            let expected = Expression::number(Number::rational(BigRational::new(
                BigInt::from(exp_num),
                BigInt::from(exp_den),
            )));

            let result = Expression::add(vec![a, b]).simplify();
            assert_eq!(
                result, expected,
                "{a_num}/{a_den} + {b_num}/{b_den} should equal {exp_num}/{exp_den}"
            );
        }
    }

    #[test]
    fn test_mixed_number_types() {
        // Test operations mixing integers, rationals, and floats
        let integer = Expression::integer(3);
        let rational = Expression::number(Number::rational(BigRational::new(
            BigInt::from(1),
            BigInt::from(2),
        )));
        let float_val = Expression::number(Number::float(2.5));

        // Mixed operations should handle gracefully
        let mixed_expr = Expression::add(vec![integer, rational, float_val]);
        let result = mixed_expr.simplify();

        // Should produce valid result without panic
        assert!(
            matches!(result, Expression::Number(_)),
            "Mixed number arithmetic should produce a number"
        );
    }
}

// Expression structure edge cases
mod expression_structure {
    use super::*;

    #[test]
    fn test_deeply_nested_expressions() {
        // Test very deeply nested expression structures
        let mut expr = Expression::integer(1);

        // Create deeply nested structure: 1 + (1 + (1 + ... ))
        expr = (0..49).fold(expr, |acc, _| {
            Expression::add(vec![Expression::integer(1), acc])
        });

        // Should handle without stack overflow
        let result = expr.simplify();
        assert_eq!(result, Expression::integer(50));
    }

    #[test]
    fn test_wide_expressions() {
        // Test expressions with many sibling terms
        let many_terms: Vec<Expression> = (1..=1000).map(Expression::integer).collect();
        let wide_expr = Expression::add(many_terms);

        // Should handle efficiently
        let result = wide_expr.simplify();
        assert_eq!(result, Expression::integer(500500)); // Sum of 1 to 1000
    }

    #[test]
    fn test_empty_expression_lists() {
        // Test behavior with empty operation lists
        let empty_add = Expression::add(vec![]);
        let empty_mul = Expression::mul(vec![]);

        // Should handle gracefully
        let _add_result = empty_add.simplify();
        let _mul_result = empty_mul.simplify();

        // Test passes if no panic occurs (simplify() handles empty expressions gracefully)
    }

    #[test]
    fn test_single_element_expressions() {
        // Test expressions with single elements
        let x = symbol!(x);
        let single_add = Expression::add(vec![Expression::symbol(x.clone())]);
        let single_mul = Expression::mul(vec![Expression::symbol(x.clone())]);

        // Should simplify to the single element
        assert_eq!(single_add.simplify(), Expression::symbol(x.clone()));
        assert_eq!(single_mul.simplify(), Expression::symbol(x));
    }

    #[test]
    fn test_alternating_operations() {
        // Test expressions with alternating positive and negative terms
        let alternating_sum = Expression::add(vec![
            Expression::integer(10),
            Expression::integer(-5),
            Expression::integer(8),
            Expression::integer(-3),
            Expression::integer(7),
            Expression::integer(-2),
        ]);

        let result = alternating_sum.simplify();
        assert_eq!(
            result,
            Expression::integer(15),
            "Alternating sum should be computed correctly"
        );
    }
}

// Symbol and variable edge cases
mod symbol_edge_cases {
    use super::*;

    #[test]
    fn test_symbol_name_edge_cases() {
        // Test symbols with various name patterns
        let edge_case_names = vec![
            "x",                                                    // Single letter
            "var123",                                               // Alphanumeric
            "x_prime",                                              // Underscore
            "X",                                                    // Capital letter
            "very_long_variable_name_that_exceeds_typical_lengths", // Long name
        ];

        for name in edge_case_names {
            let symbol = Symbol::new(name);
            let expr = Expression::symbol(symbol.clone());

            // Should handle all valid symbol names
            assert_eq!(expr.simplify(), Expression::symbol(symbol));

            // Should work in arithmetic operations
            let arithmetic = Expression::add(vec![expr.clone(), Expression::integer(1)]).simplify();

            // Should not panic and produce valid result
            assert!(
                matches!(
                    arithmetic,
                    Expression::Add(_) | Expression::Symbol(_) | Expression::Number(_)
                ),
                "Arithmetic with symbols should produce valid expression"
            );
        }
    }

    #[test]
    fn test_identical_symbols() {
        // Test operations with identical symbols
        let x1 = symbol!(x);
        let x2 = symbol!(x);

        let expr1 = Expression::symbol(x1);
        let expr2 = Expression::symbol(x2);

        // Symbols with same name should be equal
        assert_eq!(expr1, expr2);

        // Operations should work correctly
        let sum = Expression::add(vec![expr1.clone(), expr2.clone()]);
        let product = Expression::mul(vec![expr1, expr2]);

        // Should handle without issues
        let sum_result = sum.simplify();
        let product_result = product.simplify();

        // Results should be valid expressions
        assert!(
            matches!(
                sum_result,
                Expression::Add(_)
                    | Expression::Mul(_)
                    | Expression::Symbol(_)
                    | Expression::Number(_)
            ),
            "Sum of identical symbols should produce valid expression"
        );

        assert!(
            matches!(
                product_result,
                Expression::Add(_)
                    | Expression::Mul(_)
                    | Expression::Pow(_, _)
                    | Expression::Symbol(_)
                    | Expression::Number(_)
            ),
            "Product of identical symbols should produce valid expression"
        );
    }

    #[test]
    fn test_symbols_in_complex_expressions() {
        // Test symbols in deeply nested and complex expressions
        let x = symbol!(x);
        let y = symbol!(y);

        let complex_expr = Expression::add(vec![
            Expression::mul(vec![
                Expression::integer(2),
                Expression::pow(Expression::symbol(x), Expression::integer(2)),
            ]),
            Expression::mul(vec![Expression::integer(3), Expression::symbol(y)]),
            Expression::integer(5),
        ]);

        let result = complex_expr.simplify();

        // Should handle complex symbolic expressions
        assert!(
            matches!(
                result,
                Expression::Add(_)
                    | Expression::Mul(_)
                    | Expression::Pow(_, _)
                    | Expression::Symbol(_)
                    | Expression::Number(_)
            ),
            "Complex symbolic expression should produce valid result"
        );
    }
}

// Performance and memory edge cases
mod performance_edge_cases {
    use super::*;
    use std::time::{Duration, Instant};

    #[test]
    fn test_memory_efficiency_large_expressions() {
        // Test that large expressions don't cause memory issues
        let start = Instant::now();

        // Create and simplify many large expressions
        for _ in 0..100 {
            let terms: Vec<Expression> = (1..=100).map(Expression::integer).collect();
            let expr = Expression::add(terms);
            let _ = expr.simplify();
        }

        let duration = start.elapsed();

        // Should complete in reasonable time
        assert!(
            duration < Duration::from_secs(5),
            "Large expression handling too slow: {duration:?}"
        );
    }

    #[test]
    fn test_recursive_expression_limits() {
        // Test limits of recursive expression processing
        let mut expr = Expression::integer(0);

        // Build moderately deep recursion
        for i in 1..=20 {
            expr = Expression::add(vec![Expression::integer(i), expr]);
        }

        // Should handle without stack overflow
        let result = expr.simplify();
        assert_eq!(result, Expression::integer(210)); // Sum of 1 to 20
    }
}

// Float and precision edge cases
mod float_edge_cases {
    use super::*;

    #[test]
    fn test_float_arithmetic_precision() {
        // Test floating point arithmetic behavior
        let float_a = Expression::number(Number::float(0.1));
        let float_b = Expression::number(Number::float(0.2));

        let sum = Expression::add(vec![float_a, float_b]).simplify();

        // Due to floating point precision, this might not equal exactly 0.3
        // But should be close and handle gracefully
        assert!(
            matches!(sum, Expression::Number(Number::Float(_))),
            "Float arithmetic should produce float result"
        );
    }

    #[test]
    fn test_float_special_values() {
        // Test handling of special float values
        let infinity = Expression::number(Number::float(f64::INFINITY));
        let neg_infinity = Expression::number(Number::float(f64::NEG_INFINITY));
        let nan = Expression::number(Number::float(f64::NAN));

        // Should handle special values without panicking
        let _ = infinity.simplify();
        let _ = neg_infinity.simplify();
        let _ = nan.simplify();

        // Operations with special values should be handled
        let expr_with_inf = Expression::add(vec![Expression::integer(5), infinity]);

        let _ = expr_with_inf.simplify();
    }

    #[test]
    fn test_float_integer_mixed_arithmetic() {
        // Test arithmetic mixing floats and integers
        let float_val = Expression::number(Number::float(2.5));
        let integer_val = Expression::integer(3);

        let mixed_sum = Expression::add(vec![float_val.clone(), integer_val.clone()]).simplify();
        let mixed_product = Expression::mul(vec![float_val, integer_val]).simplify();

        // Should handle mixed arithmetic
        assert!(
            matches!(mixed_sum, Expression::Number(_)),
            "Mixed float-integer arithmetic should produce number"
        );

        assert!(
            matches!(mixed_product, Expression::Number(_)),
            "Mixed float-integer arithmetic should produce number"
        );
    }
}