sparsemat/
vector.rs

1use std::vec::Vec;
2use crate::types::ValueType;
3
4// Common interface for vectors
5pub trait Vector<'a>
6where Self: Sized + Clone {
7    type Value: 'a + ValueType;
8    type IterVal: Iterator<Item = Self::Value>;
9
10    fn iter(&'a self) -> Self::IterVal;
11
12    // Returns an empty vector with capacity
13    fn with_capacity(cap: usize) -> Self;
14
15    // Constructs a dense vector from an actual std::vec::Vec
16    fn from_vec(vec: Vec<Self::Value>) -> Self;
17
18    // Returns a new and empty vector
19    fn new() -> Self {
20        Self::with_capacity(0)
21    }
22
23    // Return the dimension of the vector
24    fn dim(&self) -> usize;
25
26    // Returns the value at position i
27    fn get(&self, i: usize) -> Self::Value;
28
29    // Returns the value at position i mutably
30    // Appends entry if it does not exist yet
31    fn get_mut(&mut self, i: usize) -> &mut Self::Value;
32
33    fn add(&'a mut self, rhs: &Self);
34
35    fn sub(&'a mut self, rhs: &Self);
36
37    fn scale(&'a mut self, rhs: Self::Value);
38
39    // Sets value at position i to val
40    fn set(&mut self, i: usize, val: Self::Value) {
41        *self.get_mut(i) = val;
42    }
43
44    // Adds value to entry at position i
45    fn add_to(&mut self, i: usize, val: Self::Value) {
46        *self.get_mut(i) += val;
47    }
48
49    // Computes the inner product with another vector
50    fn inner_prod<V>(&'a self, rhs: &'a V) -> Self::Value
51    where V: Vector<'a, Value = Self::Value> {
52        self.iter().zip(rhs.iter()).map(|(x, y)| x * y).sum()
53    }
54
55    // Computes the squared L2 norm of the vector
56    fn norm_squared(&'a self) -> Self::Value {
57        self.iter().map(|x| x * x).sum()
58    }
59
60    // Computes the L2 norm of the vector
61    fn norm(&'a self) -> f64 {
62        f64::sqrt(self.norm_squared().into())
63    }
64}