Skip to main content

tensor_operations/
optimized.rs

1/// Optimized matrix operations using nalgebra library
2/// nalgebra provides high-performance linear algebra operations
3
4use nalgebra::DMatrix;
5use rand::random;
6use std::fmt;
7
8/// A wrapper around nalgebra's DMatrix for consistency with our API
9pub struct OptimizedMatrix {
10    data: DMatrix<f64>,
11}
12
13impl OptimizedMatrix {
14    /// Create a new optimized matrix from a nested vector
15    pub fn new(data: Vec<Vec<f64>>) -> Result<Self, String> {
16        if data.is_empty() || data[0].is_empty() {
17            return Err("Matrix cannot be empty".to_string());
18        }
19
20        let rows = data.len();
21        let cols = data[0].len();
22
23        // Validate all rows have the same length
24        for row in &data {
25            if row.len() != cols {
26                return Err("All rows must have the same length".to_string());
27            }
28        }
29
30        // Convert to nalgebra matrix
31        let mut flat_data = Vec::new();
32        for row in data {
33            flat_data.extend(row);
34        }
35
36        let matrix = DMatrix::from_row_slice(rows, cols, &flat_data);
37        Ok(OptimizedMatrix { data: matrix })
38    }
39
40    /// Get the number of rows
41    pub fn rows(&self) -> usize {
42        self.data.nrows()
43    }
44
45    /// Get the number of columns
46    pub fn cols(&self) -> usize {
47        self.data.ncols()
48    }
49
50    /// Get the shape as (rows, cols)
51    pub fn shape(&self) -> (usize, usize) {
52        (self.rows(), self.cols())
53    }
54
55    /// Get a reference to the underlying nalgebra matrix
56    pub fn data(&self) -> &DMatrix<f64> {
57        &self.data
58    }
59
60    /// Get the element at position (i, j)
61    pub fn get(&self, i: usize, j: usize) -> Option<f64> {
62        self.data.get((i, j)).copied()
63    }
64
65    /// Convert to nested vector format
66    pub fn to_vec(&self) -> Vec<Vec<f64>> {
67        let mut result = Vec::new();
68        for i in 0..self.rows() {
69            let mut row = Vec::new();
70            for j in 0..self.cols() {
71                row.push(self.data[(i, j)]);
72            }
73            result.push(row);
74        }
75        result
76    }
77
78    /// Matrix addition
79    pub fn add(&self, other: &OptimizedMatrix) -> Result<OptimizedMatrix, String> {
80        if self.rows() != other.rows() || self.cols() != other.cols() {
81            return Err(format!(
82                "Cannot add matrices with different dimensions: ({},{}) + ({},{})",
83                self.rows(),
84                self.cols(),
85                other.rows(),
86                other.cols()
87            ));
88        }
89
90        let result = &self.data + &other.data;
91        Ok(OptimizedMatrix { data: result })
92    }
93
94    /// Matrix subtraction
95    pub fn sub(&self, other: &OptimizedMatrix) -> Result<OptimizedMatrix, String> {
96        if self.rows() != other.rows() || self.cols() != other.cols() {
97            return Err(format!(
98                "Cannot subtract matrices with different dimensions: ({},{}) - ({},{})",
99                self.rows(),
100                self.cols(),
101                other.rows(),
102                other.cols()
103            ));
104        }
105
106        let result = &self.data - &other.data;
107        Ok(OptimizedMatrix { data: result })
108    }
109
110    /// Scalar multiplication
111    pub fn scalar_mul(&self, scalar: f64) -> Result<OptimizedMatrix, String> {
112        let result = &self.data * scalar;
113        Ok(OptimizedMatrix { data: result })
114    }
115
116    /// Matrix multiplication
117    pub fn mul(&self, other: &OptimizedMatrix) -> Result<OptimizedMatrix, String> {
118        if self.cols() != other.rows() {
119            return Err(format!(
120                "Cannot multiply matrices: ({},{}) × ({},{})",
121                self.rows(),
122                self.cols(),
123                other.rows(),
124                other.cols()
125            ));
126        }
127
128        let result = &self.data * &other.data;
129        Ok(OptimizedMatrix { data: result })
130    }
131
132    /// Calculate determinant
133    pub fn determinant(&self) -> Result<f64, String> {
134        if !self.is_square() {
135            return Err("Determinant only defined for square matrices".to_string());
136        }
137
138        Ok(self.data.determinant())
139    }
140
141    /// Check if matrix is square
142    pub fn is_square(&self) -> bool {
143        self.rows() == self.cols()
144    }
145
146    /// Check if matrix is invertible
147    pub fn is_invertible(&self) -> Result<bool, String> {
148        if !self.is_square() {
149            return Ok(false);
150        }
151
152        let det = self.determinant()?;
153        Ok(det.abs() > 1e-10)
154    }
155
156    /// Calculate matrix inverse
157    pub fn inverse(&self) -> Result<OptimizedMatrix, String> {
158        if !self.is_invertible()? {
159            return Err("Matrix is not invertible (determinant is zero)".to_string());
160        }
161
162        match self.data.clone().try_inverse() {
163            Some(inv) => Ok(OptimizedMatrix { data: inv }),
164            None => Err("Failed to compute matrix inverse".to_string()),
165        }
166    }
167
168    /// Transpose the matrix
169    pub fn transpose(&self) -> Result<OptimizedMatrix, String> {
170        let result = self.data.transpose();
171        Ok(OptimizedMatrix { data: result })
172    }
173
174    /// Calculate the Frobenius norm
175    pub fn frobenius_norm(&self) -> f64 {
176        self.data.norm()
177    }
178
179    /// Calculate the trace (sum of diagonal elements)
180    pub fn trace(&self) -> Result<f64, String> {
181        if !self.is_square() {
182            return Err("Trace only defined for square matrices".to_string());
183        }
184
185        Ok(self.data.trace())
186    }
187
188    /// Calculate eigenvalues (for symmetric matrices)
189    pub fn eigenvalues(&self) -> Result<Vec<f64>, String> {
190        if !self.is_square() {
191            return Err("Eigenvalues only defined for square matrices".to_string());
192        }
193
194        // For symmetric matrices
195        let eigen = self.data.clone().symmetric_eigen();
196        Ok(eigen.eigenvalues.data.as_vec().to_vec())
197    }
198
199    /// Get matrix rank
200    pub fn rank(&self) -> Result<usize, String> {
201        let eps = 1e-10;
202        Ok(self.data.rank(eps))
203    }
204
205    /// QR Decomposition
206    pub fn qr_decomposition(
207        &self,
208    ) -> Result<(OptimizedMatrix, OptimizedMatrix), String> {
209        let qr = self.data.clone().qr();
210        let q = qr.q();
211        let r = qr.r();
212
213        Ok((
214            OptimizedMatrix { data: q },
215            OptimizedMatrix { data: r },
216        ))
217    }
218
219    /// Singular Value Decomposition
220    pub fn svd(&self) -> Result<(OptimizedMatrix, Vec<f64>, OptimizedMatrix), String> {
221        let svd_result = self.data.clone().svd(true, true);
222        let u = svd_result.u.expect("U matrix should exist");
223        let vt = svd_result.v_t.expect("V^T matrix should exist");
224        let singular_values = svd_result.singular_values.data.as_vec().to_vec();
225
226        Ok((
227            OptimizedMatrix { data: u },
228            singular_values,
229            OptimizedMatrix { data: vt },
230        ))
231    }
232
233    /// Solve linear system Ax = b
234    pub fn solve(&self, b: &OptimizedMatrix) -> Result<OptimizedMatrix, String> {
235        if !self.is_square() {
236            return Err("Linear system solver requires square matrix".to_string());
237        }
238
239        match self.data.clone().lu().solve(&b.data) {
240            Some(result) => Ok(OptimizedMatrix { data: result }),
241            None => Err("Failed to solve linear system".to_string()),
242        }
243    }
244
245    /// Create an identity matrix of size n×n
246    pub fn identity(n: usize) -> Result<OptimizedMatrix, String> {
247        if n == 0 {
248            return Err("Matrix dimensions must be positive".to_string());
249        }
250        let data = DMatrix::identity(n, n);
251        Ok(OptimizedMatrix { data })
252    }
253
254    /// Create a zero matrix of size rows×cols
255    pub fn zeros(rows: usize, cols: usize) -> Result<OptimizedMatrix, String> {
256        if rows == 0 || cols == 0 {
257            return Err("Matrix dimensions must be positive".to_string());
258        }
259        let data = DMatrix::zeros(rows, cols);
260        Ok(OptimizedMatrix { data })
261    }
262
263    /// Create a matrix of ones
264    pub fn ones(rows: usize, cols: usize) -> Result<OptimizedMatrix, String> {
265        if rows == 0 || cols == 0 {
266            return Err("Matrix dimensions must be positive".to_string());
267        }
268        let data = DMatrix::from_element(rows, cols, 1.0);
269        Ok(OptimizedMatrix { data })
270    }
271
272    /// Create a random matrix
273    pub fn random(rows: usize, cols: usize) -> Result<OptimizedMatrix, String> {
274        if rows == 0 || cols == 0 {
275            return Err("Matrix dimensions must be positive".to_string());
276        }
277        // Create matrix with random values using from_fn
278        let data = DMatrix::from_fn(rows, cols, |_, _| {
279            (random::<f64>() - 0.5) * 2.0
280        });
281        Ok(OptimizedMatrix { data })
282    }
283}
284
285impl fmt::Display for OptimizedMatrix {
286    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287        writeln!(f, "OptimizedMatrix ({} × {})", self.rows(), self.cols())?;
288        for i in 0..self.rows() {
289            write!(f, "[")?;
290            for j in 0..self.cols() {
291                if j > 0 {
292                    write!(f, ", ")?;
293                }
294                write!(f, "{:8.2}", self.data[(i, j)])?;
295            }
296            writeln!(f, "]")?;
297        }
298        Ok(())
299    }
300}
301
302impl fmt::Debug for OptimizedMatrix {
303    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
304        write!(f, "{}", self)
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn test_matrix_creation() {
314        let m = OptimizedMatrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
315        assert_eq!(m.rows(), 2);
316        assert_eq!(m.cols(), 2);
317    }
318
319    #[test]
320    fn test_matrix_addition() {
321        let a = OptimizedMatrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
322        let b = OptimizedMatrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]).unwrap();
323        let c = a.add(&b).unwrap();
324        assert_eq!(c.get(0, 0).unwrap(), 6.0);
325        assert_eq!(c.get(1, 1).unwrap(), 12.0);
326    }
327
328    #[test]
329    fn test_determinant() {
330        let m = OptimizedMatrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
331        let det = m.determinant().unwrap();
332        assert!((det - (-2.0)).abs() < 1e-10);
333    }
334
335    #[test]
336    fn test_transpose() {
337        let m = OptimizedMatrix::new(vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]]).unwrap();
338        let t = m.transpose().unwrap();
339        assert_eq!(t.rows(), 3);
340        assert_eq!(t.cols(), 2);
341    }
342
343    #[test]
344    fn test_trace() {
345        let m = OptimizedMatrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
346        let trace = m.trace().unwrap();
347        assert_eq!(trace, 5.0);
348    }
349}