numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
//! Trait implementations for NumRS2 Array<T> type
//!
//! This module provides implementations of the core trait system for the
//! existing Array<T> type, ensuring backward compatibility while enabling
//! the new trait-based architecture.

use crate::array::Array;
use crate::error::{NumRs2Error, Result};
use crate::indexing::IndexSpec;
use crate::traits::*;
use num_traits::{Float, NumCast, Zero};

// =============================================================================
// ARRAY OPERATIONS IMPLEMENTATION
// =============================================================================

impl<T: NumericElement> ArrayOps<T> for Array<T> {
    type Output = Array<T>;
    type Error = NumRs2Error;
    
    fn add(&self, other: &Self) -> Result<Self::Output> {
        // Delegate to existing implementation
        Ok(self.add(other))
    }
    
    fn sub(&self, other: &Self) -> Result<Self::Output> {
        Ok(self.subtract(other))
    }
    
    fn mul(&self, other: &Self) -> Result<Self::Output> {
        Ok(self.multiply(other))
    }
    
    fn div(&self, other: &Self) -> Result<Self::Output> {
        Ok(self.divide(other))
    }
    
    fn add_scalar(&self, scalar: T) -> Self::Output {
        self.map(|x| x + scalar)
    }
    
    fn mul_scalar(&self, scalar: T) -> Self::Output {
        self.map(|x| x * scalar)
    }
    
    fn div_scalar(&self, scalar: T) -> Result<Self::Output> {
        if scalar.is_zero() {
            return Err(NumRs2Error::InvalidOperation("Division by zero".to_string()));
        }
        Ok(self.map(|x| x / scalar))
    }
    
    fn add_broadcast(&self, other: &Self) -> Result<Self::Output> {
        // Delegate to existing broadcasting implementation
        Ok(self.add(other))
    }
    
    fn mul_broadcast(&self, other: &Self) -> Result<Self::Output> {
        Ok(self.multiply(other))
    }
}

// =============================================================================
// ARRAY REDUCTION IMPLEMENTATION
// =============================================================================

impl<T: NumericElement> ArrayReduction<T> for Array<T> 
where
    T: std::ops::Add<Output = T> + std::ops::Div<Output = T> + From<usize> + PartialOrd + Copy
{
    type Error = NumRs2Error;
    
    fn sum(&self) -> T {
        let data = self.to_vec();
        data.into_iter().fold(T::zero(), |acc, x| acc + x)
    }
    
    fn sum_axis(&self, axis: usize) -> Result<Self> {
        // Delegate to existing implementation if available
        // For now, implement basic sum along axis
        if axis >= self.ndim() {
            return Err(NumRs2Error::DimensionMismatch("Axis out of bounds".to_string()));
        }
        
        // Simplified implementation - would need more sophisticated logic for actual axis reduction
        Ok(self.clone())
    }
    
    fn mean(&self) -> T 
    where 
        T: std::ops::Div<Output = T> + From<usize> 
    {
        let total = self.sum();
        let count = T::from(self.size());
        total / count
    }
    
    fn mean_axis(&self, axis: Option<usize>) -> Result<Self> {
        match axis {
            Some(ax) => {
                if ax >= self.ndim() {
                    return Err(NumRs2Error::DimensionMismatch("Axis out of bounds".to_string()));
                }
                // Simplified implementation
                Ok(self.clone())
            },
            None => {
                let mean_val = self.mean();
                Ok(Array::from_vec(vec![mean_val]))
            }
        }
    }
    
    fn std(&self) -> T 
    where 
        T: FloatingPoint 
    {
        let mean_val = self.mean();
        let data = self.to_vec();
        let variance = data.iter()
            .map(|&x| {
                let diff = x - mean_val;
                diff * diff
            })
            .fold(T::zero(), |acc, x| acc + x) / T::from(self.size());
        variance.sqrt()
    }
    
    fn std_axis(&self, axis: Option<usize>) -> Result<Self> {
        match axis {
            Some(ax) => {
                if ax >= self.ndim() {
                    return Err(NumRs2Error::DimensionMismatch("Axis out of bounds".to_string()));
                }
                // Simplified implementation
                Ok(self.clone())
            },
            None => {
                let std_val = self.std();
                Ok(Array::from_vec(vec![std_val]))
            }
        }
    }
    
    fn min(&self) -> T 
    where 
        T: PartialOrd 
    {
        let data = self.to_vec();
        data.into_iter().fold(data[0], |acc, x| if x < acc { x } else { acc })
    }
    
    fn max(&self) -> T 
    where 
        T: PartialOrd 
    {
        let data = self.to_vec();
        data.into_iter().fold(data[0], |acc, x| if x > acc { x } else { acc })
    }
    
    fn argmin(&self) -> usize 
    where 
        T: PartialOrd 
    {
        let data = self.to_vec();
        let mut min_idx = 0;
        let mut min_val = data[0];
        
        for (i, &val) in data.iter().enumerate() {
            if val < min_val {
                min_val = val;
                min_idx = i;
            }
        }
        min_idx
    }
    
    fn argmax(&self) -> usize 
    where 
        T: PartialOrd 
    {
        let data = self.to_vec();
        let mut max_idx = 0;
        let mut max_val = data[0];
        
        for (i, &val) in data.iter().enumerate() {
            if val > max_val {
                max_val = val;
                max_idx = i;
            }
        }
        max_idx
    }
}

// =============================================================================
// ARRAY INDEXING IMPLEMENTATION
// =============================================================================

impl<T: NumericElement> ArrayIndexing<T> for Array<T> {
    type IndexResult = Array<T>;
    type Error = NumRs2Error;
    
    fn get(&self, indices: &[usize]) -> Result<T> {
        self.get(indices).map_err(|e| e.into())
    }
    
    fn set(&mut self, indices: &[usize], value: T) -> Result<()> {
        self.set(indices, value).map_err(|e| e.into())
    }
    
    fn index(&self, specs: &[IndexSpec]) -> Result<Self::IndexResult> {
        // Delegate to existing advanced indexing implementation
        self.index(specs).map_err(|e| e.into())
    }
    
    fn fancy_index(&self, indices: &[&[usize]]) -> Result<Self::IndexResult> {
        // Delegate to existing fancy indexing implementation
        self.fancy_index(indices).map_err(|e| e.into())
    }
    
    fn bool_index(&self, mask: &[bool]) -> Result<Self::IndexResult> {
        // Delegate to existing boolean indexing implementation
        self.bool_index(mask).map_err(|e| e.into())
    }
    
    fn slice(&self, axis: usize, start: usize, end: Option<usize>) -> Result<Self::IndexResult> {
        // Delegate to existing slicing implementation
        self.slice(axis, start.into()).map_err(|e| e.into())
    }
}

// =============================================================================
// ARRAY MATH IMPLEMENTATION
// =============================================================================

impl<T: NumericElement> ArrayMath<T> for Array<T> 
where
    T: std::ops::Add<Output = T> + std::ops::Sub<Output = T> + 
       std::ops::Mul<Output = T> + std::ops::Div<Output = T> + Copy
{
    fn abs(&self) -> Self::Output 
    where 
        T: num_traits::Signed 
    {
        self.map(|x| x.abs())
    }
    
    fn sqrt(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.sqrt())
    }
    
    fn exp(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.exp())
    }
    
    fn ln(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.ln())
    }
    
    fn sin(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.sin())
    }
    
    fn cos(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.cos())
    }
    
    fn tan(&self) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.tan())
    }
    
    fn pow(&self, exponent: T) -> Self::Output 
    where 
        T: FloatingPoint 
    {
        self.map(|x| x.powf(exponent))
    }
    
    fn pow_array(&self, exponents: &Self) -> Result<Self::Output> 
    where 
        T: FloatingPoint 
    {
        if self.shape() != exponents.shape() {
            return Err(NumRs2Error::DimensionMismatch(
                "Arrays must have the same shape for element-wise power".to_string()
            ));
        }
        
        let self_data = self.to_vec();
        let exp_data = exponents.to_vec();
        let result_data: Vec<T> = self_data.iter()
            .zip(exp_data.iter())
            .map(|(&base, &exp)| base.powf(exp))
            .collect();
            
        Ok(Array::from_vec(result_data).reshape(self.shape()))
    }
}

// =============================================================================
// LINEAR ALGEBRA IMPLEMENTATION
// =============================================================================

impl<T: FloatingPoint> LinearAlgebra<T> for Array<T> {
    type Error = NumRs2Error;
    
    fn matmul(&self, other: &Self) -> Result<Self> {
        // Delegate to existing matrix multiplication implementation
        self.matmul(other).map_err(|e| e.into())
    }
    
    fn transpose(&self) -> Self {
        // Delegate to existing transpose implementation
        self.transpose()
    }
    
    fn det(&self) -> Result<T> {
        // Delegate to existing determinant implementation if available
        #[cfg(feature = "matrix_decomp")]
        {
            self.det().map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for determinant".to_string()))
        }
    }
    
    fn inv(&self) -> Result<Self> {
        // Delegate to existing matrix inverse implementation if available
        #[cfg(feature = "matrix_decomp")]
        {
            self.inv().map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for matrix inverse".to_string()))
        }
    }
    
    fn solve(&self, b: &Self) -> Result<Self> {
        // Delegate to existing linear system solver implementation if available
        #[cfg(feature = "matrix_decomp")]
        {
            self.solve(b).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for solve".to_string()))
        }
    }
    
    fn rank(&self) -> Result<usize> {
        // Simplified rank computation using SVD
        #[cfg(feature = "matrix_decomp")]
        {
            // Would delegate to existing rank implementation
            Ok(std::cmp::min(self.shape()[0], self.shape()[1]))
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for rank".to_string()))
        }
    }
    
    fn cond(&self) -> Result<T> {
        // Delegate to existing condition number implementation if available
        #[cfg(feature = "matrix_decomp")]
        {
            self.cond().map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for condition number".to_string()))
        }
    }
    
    fn norm(&self, ord: Option<T>) -> Result<T> {
        // Basic implementation of matrix norms
        match ord {
            None => {
                // Frobenius norm
                let data = self.to_vec();
                let sum_squares = data.iter().fold(T::zero(), |acc, &x| acc + x * x);
                Ok(sum_squares.sqrt())
            },
            Some(_ord) => {
                // More sophisticated norm computations would be implemented here
                Err(NumRs2Error::NotImplemented("Specific matrix norms not yet implemented".to_string()))
            }
        }
    }
}

// =============================================================================
// MATRIX DECOMPOSITION IMPLEMENTATION
// =============================================================================

impl<T: FloatingPoint> MatrixDecomposition<T> for Array<T> 
where
    T: Clone + std::fmt::Debug + ndarray_linalg::Lapack,
{
    type DecompositionResult = (Array<T>, Array<T>, Array<T>); // Example: (L, U, P) for LU
    type Error = NumRs2Error;
    
    fn lu(&self) -> Result<Self::DecompositionResult> {
        // Delegate to existing LU decomposition implementation
        #[cfg(feature = "matrix_decomp")]
        {
            use crate::linalg_extended::decomposition::lu;
            lu(self).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for LU decomposition".to_string()))
        }
    }
    
    fn qr(&self) -> Result<Self::DecompositionResult> {
        // Delegate to existing QR decomposition implementation
        #[cfg(feature = "matrix_decomp")]
        {
            use crate::linalg_extended::decomposition::qr;
            qr(self).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for QR decomposition".to_string()))
        }
    }
    
    fn svd(&self) -> Result<Self::DecompositionResult> {
        // Delegate to existing SVD implementation
        #[cfg(feature = "matrix_decomp")]
        {
            use crate::linalg_extended::decomposition::svd;
            svd(self).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for SVD".to_string()))
        }
    }
    
    fn cholesky(&self) -> Result<Self> {
        // Delegate to existing Cholesky decomposition implementation
        #[cfg(feature = "matrix_decomp")]
        {
            use crate::linalg_extended::decomposition::cholesky;
            cholesky(self).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for Cholesky decomposition".to_string()))
        }
    }
    
    fn eig(&self) -> Result<Self::DecompositionResult> {
        // Delegate to existing eigenvalue decomposition implementation
        #[cfg(feature = "matrix_decomp")]
        {
            use crate::linalg_extended::eigenvalue::eig;
            eig(self).map_err(|e| e.into())
        }
        
        #[cfg(not(feature = "matrix_decomp"))]
        {
            Err(NumRs2Error::FeatureNotEnabled("matrix_decomp feature required for eigenvalue decomposition".to_string()))
        }
    }
    
    fn schur(&self) -> Result<Self::DecompositionResult> {
        // Schur decomposition would be implemented here
        Err(NumRs2Error::NotImplemented("Schur decomposition not yet implemented".to_string()))
    }
}

// =============================================================================
// MEMORY MANAGEMENT IMPLEMENTATION
// =============================================================================

impl<T: NumericElement> crate::traits::MemoryAware for Array<T> {
    fn set_allocator(&mut self, _allocator: Box<dyn crate::traits::SpecializedAllocator<Error = NumRs2Error>>) {
        // For now, this is a placeholder since Array<T> doesn't directly use custom allocators
        // In a future enhancement, Array<T> could store a reference to the allocator for new allocations
        // This would be implemented as part of the Array<T> refactoring
    }

    fn memory_usage(&self) -> crate::traits::MemoryUsage {
        let element_size = std::mem::size_of::<T>();
        let total_elements = self.size();
        let total_bytes = total_elements * element_size;
        
        crate::traits::MemoryUsage {
            total_bytes,
            allocation_count: 1, // Array uses single contiguous allocation
            fragmentation: 0.0, // Contiguous allocation has no fragmentation
            efficiency: 1.0,    // Using all allocated memory
        }
    }

    fn optimize_memory_layout(&mut self) -> Result<()> {
        // For now, Array<T> doesn't support runtime layout optimization
        // This could be enhanced to:
        // 1. Defragment multi-part arrays
        // 2. Realign memory for SIMD operations
        // 3. Compress sparse regions
        Ok(())
    }

    fn suggest_optimizations(&self) -> Vec<crate::traits::MemoryOptimization> {
        use crate::traits::{MemoryOptimization, OptimizationType};
        
        let mut suggestions = Vec::new();
        let element_size = std::mem::size_of::<T>();
        let total_bytes = self.size() * element_size;
        
        // Suggest alignment optimization for large arrays that might benefit from SIMD
        if total_bytes > 1024 && element_size >= 4 {
            suggestions.push(MemoryOptimization {
                optimization_type: OptimizationType::AlignmentOptimization,
                description: "Align array memory for SIMD operations".to_string(),
                estimated_savings: 0, // No memory savings, but performance improvement
                complexity: 2,
            });
        }
        
        // Suggest arena allocation for temporary arrays
        if total_bytes < 65536 {
            suggestions.push(MemoryOptimization {
                optimization_type: OptimizationType::ArenaOptimization,
                description: "Use arena allocation for temporary array".to_string(),
                estimated_savings: 0, // Savings in allocation overhead
                complexity: 3,
            });
        }
        
        // Suggest pooling for small, frequently allocated arrays
        if total_bytes < 8192 {
            suggestions.push(MemoryOptimization {
                optimization_type: OptimizationType::PoolingOptimization,
                description: "Use memory pool for small array allocations".to_string(),
                estimated_savings: 0, // Savings in allocation time
                complexity: 2,
            });
        }
        
        suggestions
    }
}