proven 0.9.0

Safe, formally verified library for math, crypto, parsing, validation, and ML - Rust bindings
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: 2025 Hyperpolymath
//! Safe tensor and matrix operations with bounds checking.
//!
//! This module provides safe operations for vectors and matrices commonly used
//! in machine learning and numerical computing. All operations include bounds
//! checking and prevent common errors like shape mismatches.
//!
//! # Design Philosophy
//!
//! Matrix operations in ML are prone to runtime panics from:
//! - Index out of bounds
//! - Shape mismatches in operations
//! - Empty tensor operations
//!
//! This module makes all these errors explicit through Rust's Result type.
//!
//! # Example
//!
//! ```rust
//! use proven::SafeTensor;
//!
//! // Safe dot product with shape checking
//! let a = vec![1.0, 2.0, 3.0];
//! let b = vec![4.0, 5.0, 6.0];
//! assert_eq!(SafeTensor::dot(&a, &b).unwrap(), 32.0);
//!
//! // Shape mismatch returns Error
//! let c = vec![1.0, 2.0];
//! assert!(SafeTensor::dot(&a, &c).is_err());
//! ```

use crate::core::{Error, Result};
use crate::safe_float::SafeFloat;

/// Safe tensor operations that never panic on bounds errors.
pub struct SafeTensor;

impl SafeTensor {
    /// Safe dot product with length check.
    ///
    /// Returns Error if vectors have different lengths.
    ///
    /// # Example
    /// ```rust
    /// use proven::SafeTensor;
    ///
    /// let a = vec![1.0, 2.0, 3.0];
    /// let b = vec![4.0, 5.0, 6.0];
    /// assert_eq!(SafeTensor::dot(&a, &b).unwrap(), 32.0); // 1*4 + 2*5 + 3*6 = 32
    /// ```
    pub fn dot(a: &[f64], b: &[f64]) -> Result<f64> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Dot product shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x * y).sum())
    }

    /// Safe f32 dot product.
    pub fn dot_f32(a: &[f32], b: &[f32]) -> Result<f32> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Dot product shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x * y).sum())
    }

    /// Safe element-wise addition.
    ///
    /// Returns Error if vectors have different lengths.
    pub fn add(a: &[f64], b: &[f64]) -> Result<Vec<f64>> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Add shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x + y).collect())
    }

    /// Safe f32 element-wise addition.
    pub fn add_f32(a: &[f32], b: &[f32]) -> Result<Vec<f32>> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Add shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x + y).collect())
    }

    /// Safe element-wise subtraction.
    pub fn sub(a: &[f64], b: &[f64]) -> Result<Vec<f64>> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Sub shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x - y).collect())
    }

    /// Safe element-wise multiplication (Hadamard product).
    pub fn hadamard(a: &[f64], b: &[f64]) -> Result<Vec<f64>> {
        if a.len() != b.len() {
            return Err(Error::ValidationError(format!(
                "Hadamard product shape mismatch: {} vs {}",
                a.len(),
                b.len()
            )));
        }
        Ok(a.iter().zip(b.iter()).map(|(x, y)| x * y).collect())
    }

    /// Safe scalar multiplication.
    pub fn scale(v: &[f64], scalar: f64) -> Vec<f64> {
        v.iter().map(|x| x * scalar).collect()
    }

    /// Safe f32 scalar multiplication.
    pub fn scale_f32(v: &[f32], scalar: f32) -> Vec<f32> {
        v.iter().map(|x| x * scalar).collect()
    }

    /// Safe matrix-vector multiplication.
    ///
    /// Matrix is represented as rows × cols, where each inner vec is a row.
    /// Returns Error if dimensions don't match.
    ///
    /// # Example
    /// ```rust
    /// use proven::SafeTensor;
    ///
    /// let matrix = vec![
    ///     vec![1.0, 2.0],
    ///     vec![3.0, 4.0],
    /// ];
    /// let vector = vec![1.0, 2.0];
    /// let result = SafeTensor::mat_vec(&matrix, &vector).unwrap();
    /// assert_eq!(result, vec![5.0, 11.0]); // [1*1+2*2, 3*1+4*2]
    /// ```
    pub fn mat_vec(matrix: &[Vec<f64>], vector: &[f64]) -> Result<Vec<f64>> {
        if matrix.is_empty() {
            return Ok(Vec::new());
        }

        let cols = matrix[0].len();
        if vector.len() != cols {
            return Err(Error::ValidationError(format!(
                "Matrix-vector dimension mismatch: matrix cols {} vs vector len {}",
                cols,
                vector.len()
            )));
        }

        // Verify all rows have same length
        for (i, row) in matrix.iter().enumerate() {
            if row.len() != cols {
                return Err(Error::ValidationError(format!(
                    "Matrix row {} has {} cols, expected {}",
                    i,
                    row.len(),
                    cols
                )));
            }
        }

        let mut result = Vec::with_capacity(matrix.len());
        for row in matrix {
            let dot = Self::dot(row, vector)?;
            result.push(dot);
        }
        Ok(result)
    }

    /// Safe f32 matrix-vector multiplication.
    pub fn mat_vec_f32(matrix: &[Vec<f32>], vector: &[f32]) -> Result<Vec<f32>> {
        if matrix.is_empty() {
            return Ok(Vec::new());
        }

        let cols = matrix[0].len();
        if vector.len() != cols {
            return Err(Error::ValidationError(format!(
                "Matrix-vector dimension mismatch: matrix cols {} vs vector len {}",
                cols,
                vector.len()
            )));
        }

        for (i, row) in matrix.iter().enumerate() {
            if row.len() != cols {
                return Err(Error::ValidationError(format!(
                    "Matrix row {} has {} cols, expected {}",
                    i,
                    row.len(),
                    cols
                )));
            }
        }

        let mut result = Vec::with_capacity(matrix.len());
        for row in matrix {
            let dot = Self::dot_f32(row, vector)?;
            result.push(dot);
        }
        Ok(result)
    }

    /// Safe index access with bounds checking.
    ///
    /// Returns Error instead of panicking on out-of-bounds.
    pub fn get<T: Clone>(v: &[T], index: usize) -> Result<T> {
        v.get(index).cloned().ok_or_else(|| {
            Error::OutOfBounds {
                value: index as i64,
                min: 0,
                max: v.len() as i64 - 1,
            }
        })
    }

    /// Safe index access for 2D arrays.
    pub fn get_2d<T: Clone>(matrix: &[Vec<T>], row: usize, col: usize) -> Result<T> {
        let r = matrix.get(row).ok_or_else(|| Error::OutOfBounds {
            value: row as i64,
            min: 0,
            max: matrix.len() as i64 - 1,
        })?;
        r.get(col).cloned().ok_or_else(|| Error::OutOfBounds {
            value: col as i64,
            min: 0,
            max: r.len() as i64 - 1,
        })
    }

    /// Safe argmax - returns index of maximum value.
    ///
    /// Returns Error for empty vectors.
    pub fn argmax(v: &[f64]) -> Result<usize> {
        if v.is_empty() {
            return Err(Error::EmptyInput);
        }
        let (idx, _) = v
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .unwrap();
        Ok(idx)
    }

    /// Safe f32 argmax.
    pub fn argmax_f32(v: &[f32]) -> Result<usize> {
        if v.is_empty() {
            return Err(Error::EmptyInput);
        }
        let (idx, _) = v
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .unwrap();
        Ok(idx)
    }

    /// Safe argmin - returns index of minimum value.
    pub fn argmin(v: &[f64]) -> Result<usize> {
        if v.is_empty() {
            return Err(Error::EmptyInput);
        }
        let (idx, _) = v
            .iter()
            .enumerate()
            .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .unwrap();
        Ok(idx)
    }

    /// Safe sum with overflow check for large vectors.
    pub fn sum(v: &[f64]) -> Result<f64> {
        let result: f64 = v.iter().sum();
        if !result.is_finite() {
            return Err(Error::Overflow("Vector sum overflowed to infinity".to_string()));
        }
        Ok(result)
    }

    /// Safe f32 sum.
    pub fn sum_f32(v: &[f32]) -> Result<f32> {
        let result: f32 = v.iter().sum();
        if !result.is_finite() {
            return Err(Error::Overflow("Vector sum overflowed to infinity".to_string()));
        }
        Ok(result)
    }

    /// Safe outer product.
    ///
    /// Returns a matrix where result[i][j] = a[i] * b[j]
    pub fn outer(a: &[f64], b: &[f64]) -> Vec<Vec<f64>> {
        a.iter()
            .map(|&ai| b.iter().map(|&bj| ai * bj).collect())
            .collect()
    }

    /// Safe transpose of a matrix.
    ///
    /// Returns Error if matrix is jagged (inconsistent row lengths).
    pub fn transpose(matrix: &[Vec<f64>]) -> Result<Vec<Vec<f64>>> {
        if matrix.is_empty() {
            return Ok(Vec::new());
        }

        let rows = matrix.len();
        let cols = matrix[0].len();

        // Check all rows have same length
        for (i, row) in matrix.iter().enumerate() {
            if row.len() != cols {
                return Err(Error::ValidationError(format!(
                    "Jagged matrix: row {} has {} cols, expected {}",
                    i,
                    row.len(),
                    cols
                )));
            }
        }

        let mut result = vec![vec![0.0; rows]; cols];
        for (i, row) in matrix.iter().enumerate() {
            for (j, &val) in row.iter().enumerate() {
                result[j][i] = val;
            }
        }
        Ok(result)
    }

    /// Check if two vectors have the same shape.
    pub fn same_shape<T>(a: &[T], b: &[T]) -> bool {
        a.len() == b.len()
    }

    /// Validate matrix is rectangular (all rows same length).
    pub fn is_rectangular<T>(matrix: &[Vec<T>]) -> bool {
        if matrix.is_empty() {
            return true;
        }
        let cols = matrix[0].len();
        matrix.iter().all(|row| row.len() == cols)
    }

    /// Get matrix shape (rows, cols).
    ///
    /// Returns Error for jagged matrices.
    pub fn shape<T>(matrix: &[Vec<T>]) -> Result<(usize, usize)> {
        if matrix.is_empty() {
            return Ok((0, 0));
        }
        let rows = matrix.len();
        let cols = matrix[0].len();

        if !Self::is_rectangular(matrix) {
            return Err(Error::ValidationError("Jagged matrix has no consistent shape".to_string()));
        }
        Ok((rows, cols))
    }
}

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

    #[test]
    fn test_dot_product() {
        let a = vec![1.0, 2.0, 3.0];
        let b = vec![4.0, 5.0, 6.0];
        assert_eq!(SafeTensor::dot(&a, &b).unwrap(), 32.0);
    }

    #[test]
    fn test_dot_product_mismatch() {
        let a = vec![1.0, 2.0, 3.0];
        let b = vec![4.0, 5.0];
        assert!(SafeTensor::dot(&a, &b).is_err());
    }

    #[test]
    fn test_add() {
        let a = vec![1.0, 2.0, 3.0];
        let b = vec![4.0, 5.0, 6.0];
        assert_eq!(SafeTensor::add(&a, &b).unwrap(), vec![5.0, 7.0, 9.0]);
    }

    #[test]
    fn test_add_mismatch() {
        let a = vec![1.0, 2.0];
        let b = vec![1.0];
        assert!(SafeTensor::add(&a, &b).is_err());
    }

    #[test]
    fn test_mat_vec() {
        let matrix = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        let vector = vec![1.0, 2.0];
        let result = SafeTensor::mat_vec(&matrix, &vector).unwrap();
        assert_eq!(result, vec![5.0, 11.0]);
    }

    #[test]
    fn test_mat_vec_mismatch() {
        let matrix = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
        let vector = vec![1.0, 2.0]; // Wrong size
        assert!(SafeTensor::mat_vec(&matrix, &vector).is_err());
    }

    #[test]
    fn test_get_bounds() {
        let v = vec![1, 2, 3];
        assert_eq!(SafeTensor::get(&v, 0).unwrap(), 1);
        assert_eq!(SafeTensor::get(&v, 2).unwrap(), 3);
        assert!(SafeTensor::get(&v, 3).is_err());
    }

    #[test]
    fn test_argmax() {
        let v = vec![1.0, 5.0, 3.0, 2.0];
        assert_eq!(SafeTensor::argmax(&v).unwrap(), 1);
    }

    #[test]
    fn test_argmax_empty() {
        let v: Vec<f64> = vec![];
        assert!(SafeTensor::argmax(&v).is_err());
    }

    #[test]
    fn test_transpose() {
        let matrix = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
        let transposed = SafeTensor::transpose(&matrix).unwrap();
        assert_eq!(transposed.len(), 3);
        assert_eq!(transposed[0], vec![1.0, 4.0]);
        assert_eq!(transposed[1], vec![2.0, 5.0]);
        assert_eq!(transposed[2], vec![3.0, 6.0]);
    }

    #[test]
    fn test_transpose_jagged() {
        let matrix = vec![vec![1.0, 2.0], vec![3.0, 4.0, 5.0]];
        assert!(SafeTensor::transpose(&matrix).is_err());
    }

    #[test]
    fn test_shape() {
        let matrix = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
        assert_eq!(SafeTensor::shape(&matrix).unwrap(), (2, 3));
    }

    #[test]
    fn test_outer_product() {
        let a = vec![1.0, 2.0];
        let b = vec![3.0, 4.0, 5.0];
        let result = SafeTensor::outer(&a, &b);
        assert_eq!(result, vec![vec![3.0, 4.0, 5.0], vec![6.0, 8.0, 10.0]]);
    }
}