tensor-operations 0.1.0

Week 13: Matrix and Tensor Operations in Rust - Manual vs Optimized
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
# Week 13: Matrix and Tensor Operations in Rust

## ๐Ÿ“š Complete Learning Guide

This project teaches linear algebra and matrix operations using Rust, with two complementary implementations:
- **Manual**: Pure Rust for learning algorithms
- **Optimized**: Using nalgebra for production code

---

## ๐ŸŽฏ Project Goals

1. Understand matrix operations and linear algebra
2. Learn Rust fundamentals through practical implementation
3. Compare manual vs. optimized approaches
4. Understand performance implications of different implementations
5. Create production-ready numerical computing code

---

## ๐Ÿ“ Project Structure

```
tensor-operations/
โ”œโ”€โ”€ Cargo.toml                              # Project configuration
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs                             # Library root
โ”‚   โ”œโ”€โ”€ manual.rs                          # Manual matrix implementation
โ”‚   โ””โ”€โ”€ optimized.rs                       # nalgebra-based implementation
โ”œโ”€โ”€ benches/
โ”‚   โ””โ”€โ”€ matrix_benchmarks.rs               # Criterion benchmarks
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ basic_operations.rs                # Basic usage examples
โ”‚   โ”œโ”€โ”€ performance_comparison.rs          # Performance benchmarks
โ”‚   โ””โ”€โ”€ advanced_operations.rs             # Advanced operations
โ””โ”€โ”€ README.md                              # Project documentation
```

---

## ๐Ÿš€ Quick Start

### Prerequisites

- Rust 1.56+ installed ([install.rust-lang.org]https://www.rust-lang.org/install.html)

### Running Examples

```bash
# Basic operations
cargo run --example basic_operations

# Performance comparison
cargo run --example performance_comparison --release

# Advanced operations
cargo run --example advanced_operations
```

### Running Tests

```bash
# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Run specific test
cargo test test_matrix_creation
```

### Running Benchmarks

```bash
# Run criterion benchmarks
cargo bench
```

---

## ๐Ÿง  Core Concepts

### 1. Manual Matrix Implementation (`manual.rs`)

**Purpose**: Educational - understand how matrix operations work

**Key Struct**: `Matrix`
```rust
pub struct Matrix {
    data: Vec<Vec<f64>>,
    rows: usize,
    cols: usize,
}
```

**Available Operations**:
- Creation: `Matrix::new(data)`
- Addition: `a.add(&b)`
- Subtraction: `a.sub(&b)`
- Multiplication: `a.mul(&b)`
- Scalar multiply: `a.scalar_mul(2.0)`
- Transpose: `a.transpose()`
- Determinant: `a.determinant()` (via cofactor expansion)
- Inverse: `a.inverse()`
- Frobenius norm: `a.frobenius_norm()`
- Trace: `a.trace()`

**Characteristics**:
- Pure Rust, no external dependencies for core operations
- Row-major storage
- Good for learning
- Relatively slow for large matrices

### 2. Optimized Implementation (`optimized.rs`)

**Purpose**: Production-ready code with high performance

**Key Struct**: `OptimizedMatrix` (wraps `nalgebra::DMatrix<f64>`)

**Available Operations**:
- All operations from Manual Matrix
- QR Decomposition: `m.qr_decomposition()`
- SVD: `m.svd()`
- Eigenvalues: `m.eigenvalues()`
- Matrix Rank: `m.rank()`
- Linear system solving: `m.solve(&b)`

**Characteristics**:
- Uses nalgebra library
- BLAS-optimized
- 10-1000x faster than manual
- Production-ready

---

## ๐Ÿ“Š Algorithm Explanations

### Matrix Multiplication

**Time Complexity**: O(nยณ) for nร—n matrices

**Algorithm**:
```
result[i][j] = sum(matrix_a[i][k] * matrix_b[k][j]) for all k
```

**Manual Implementation** (naive):
- Three nested loops
- Direct computation
- Easy to understand

**Optimized Implementation**:
- Uses BLAS (Basic Linear Algebra Subroutines)
- Blocked algorithms
- Cache-conscious implementation

### Determinant Calculation

**Manual Implementation** (Cofactor Expansion):
- Base case: 1ร—1 and 2ร—2 matrices
- Recursive expansion along first row
- Time Complexity: O(n!)

**Optimized Implementation** (LU Decomposition):
- Uses numerical algorithms
- Time Complexity: O(nยณ)
- Much faster for larger matrices

### Matrix Inverse

**Manual Implementation** (Adjugate Method):
1. Calculate cofactor matrix
2. Transpose to get adjugate
3. Divide by determinant

**Optimized Implementation**:
- Uses LU decomposition
- More numerically stable
- Better for practical use

---

## ๐Ÿ’ป Code Examples

### Creating a Matrix

```rust
use tensor_operations::manual::Matrix;

// From vector of vectors
let m = Matrix::new(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
])?;

// Identity matrix
let i = Matrix::identity(3)?;

// Zero matrix
let z = Matrix::zeros(2, 3)?;

// Ones matrix
let o = Matrix::ones(2, 2)?;
```

### Matrix Operations

```rust
// Addition
let sum = a.add(&b)?;

// Multiplication
let product = a.mul(&b)?;

// Transpose
let transposed = a.transpose()?;

// Determinant
let det = a.determinant()?;

// Inverse
let inv = a.inverse()?;

// Frobenius norm
let norm = a.frobenius_norm();

// Trace
let tr = a.trace()?;
```

### Advanced Operations (Optimized Only)

```rust
use tensor_operations::optimized::OptimizedMatrix;

let m = OptimizedMatrix::new(data)?;

// QR Decomposition
let (q, r) = m.qr_decomposition()?;

// SVD
let (u, singular_values, vt) = m.svd()?;

// Eigenvalues
let evals = m.eigenvalues()?;

// Rank
let rank = m.rank()?;

// Solve Ax = b
let x = a.solve(&b)?;
```

---

## ๐Ÿ”ฌ Error Handling

All operations return `Result<T, String>`:

```rust
match matrix.determinant() {
    Ok(det) => println!("Determinant: {}", det),
    Err(e) => println!("Error: {}", e),
}

// Or using ? operator in functions that return Result
let det = matrix.determinant()?;
```

**Common Errors**:
- Dimension mismatch for operations
- Non-square matrix for determinant/trace
- Non-invertible matrix for inverse
- Division by zero

---

## ๐Ÿ“ˆ Performance Characteristics

### Typical Benchmarks (on modern hardware)

**Addition (10ร—10 matrix)**:
- Manual: ~5 ยตs
- Optimized: ~0.7 ยตs
- Speedup: **7x**

**Multiplication (20ร—20 matrix)**:
- Manual: ~16 ms
- Optimized: ~150 ยตs
- Speedup: **100x**

**Determinant (5ร—5 matrix)**:
- Manual: ~50 ยตs (cofactor expansion)
- Optimized: ~5 ยตs (LU decomposition)
- Speedup: **10x**

### Why Optimized is Faster

1. **BLAS Library**: Uses tuned algorithms
2. **Cache Locality**: Blocked algorithms
3. **SIMD Instructions**: Vectorized operations
4. **Memory Layout**: Optimized storage

---

## ๐Ÿงช Testing

Tests are included for both implementations:

```bash
# Run all tests
cargo test

# Run specific module tests
cargo test manual::
cargo test optimized::

# Run with output
cargo test -- --nocapture

# Run single test
cargo test test_matrix_multiplication
```

Each operation has tests validating:
- Correctness
- Edge cases
- Error handling

---

## ๐ŸŽ“ Learning Path

### Week 13 Study Plan

**Day 1-2: Foundations**
- [ ] Read Rust fundamentals (ownership, borrowing, Result type)
- [ ] Understand matrix math basics
- [ ] Review linear algebra concepts

**Day 3-4: Manual Implementation**
- [ ] Study `src/manual.rs`
- [ ] Run `basic_operations` example
- [ ] Implement tests for manual operations
- [ ] Understand algorithm complexity

**Day 5-6: Optimized Implementation**
- [ ] Study `src/optimized.rs`
- [ ] Learn nalgebra library
- [ ] Run `advanced_operations` example
- [ ] Compare API design

**Day 7: Performance & Analysis**
- [ ] Run benchmarks: `cargo bench`
- [ ] Run performance example: `cargo run --example performance_comparison --release`
- [ ] Analyze results
- [ ] Document findings

### Projects to Practice

1. **Matrix Solver**: Solve systems of linear equations
2. **Image Processing**: Use matrices for image transformations
3. **Data Analysis**: Compute statistics on datasets
4. **Machine Learning**: Implement basic ML algorithms

---

## ๐Ÿ”— Dependencies

### Direct Dependencies

- **nalgebra** 0.32: High-performance linear algebra library
- **ndarray** 0.15: N-dimensional array operations
- **serde** 1.0: Serialization framework

### Dev Dependencies

- **criterion** 0.5: Benchmarking framework
- **rand** 0.8: Random number generation

### Why These?

- **nalgebra**: Most popular Rust linear algebra library
- **criterion**: Industry-standard benchmarking
- **serde**: For future serialization features

---

## ๐Ÿ“š Further Learning

### Rust Concepts Covered

- Ownership and borrowing
- Error handling with Result
- Trait implementation (Display, Add, Sub, Mul, Index)
- Generic types
- Module system
- Testing

### Linear Algebra Topics

- Matrix operations (add, mul, transpose)
- Determinant and inverse
- QR decomposition
- Singular Value Decomposition (SVD)
- Eigenvalues and eigenvectors
- Linear system solving

### Resources

- [Rust Book]https://doc.rust-lang.org/book/
- [nalgebra documentation]https://nalgebra.org/
- [3Blue1Brown - Essence of Linear Algebra]https://www.youtube.com/c/3Blue1Brown
- [Linear Algebra - MIT OpenCourseWare]https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/

---

## ๐Ÿš€ Publishing This Project

### Steps to Publish on crates.io

1. **Create crates.io account**: https://crates.io/me/

2. **Update Cargo.toml with metadata**:
   ```toml
   [package]
   name = "tensor-operations"
   version = "0.1.0"
   authors = ["Your Name <email@example.com>"]
   description = "Matrix and linear algebra operations in Rust"
   license = "MIT"
   repository = "https://github.com/yourname/tensor-operations"
   ```

3. **Get authentication token**:
   ```bash
   cargo login
   ```

4. **Run final checks**:
   ```bash
   cargo test
   cargo bench
   cargo doc --no-deps --open
   ```

5. **Publish**:
   ```bash
   cargo publish
   ```

---

## ๐Ÿ“ License

MIT License - See LICENSE file

---

**Status**: Ready for publication! โœจ