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
use crate::smat::{DataPosition, DataRange, MatrixMask};
use log::{debug, trace};
use shine_stdext::stdext::SliceOrdExt;

/// Compressed Sparse (Square) Row matrix.
/// Its a variant of the CSR data structure where a dense vector is
///  used to store the offset for the occupied rows.
pub struct CSMatrixMask {
    // Offsets of the start in the indices(data) vector for each row
    offsets: Vec<usize>,

    // Column indices for each non-zero items
    indices: Vec<usize>,
}

impl CSMatrixMask {
    /// Creates a new CSMatrixMask with the given capacity
    pub fn new_with_capacity(row_capacity: usize, nnz_capacity: usize) -> CSMatrixMask {
        CSMatrixMask {
            offsets: vec![0usize; row_capacity + 1],
            indices: Vec::with_capacity(nnz_capacity),
        }
    }

    /// Creates an empty CSMatrixMask
    pub fn new() -> CSMatrixMask {
        Self::new_with_capacity(0, 0)
    }

    /// Return the row capacity.
    pub fn nnz(&self) -> usize {
        *self.offsets.last().unwrap()
    }

    /// Return the row capacity.
    pub fn capacity(&self) -> usize {
        self.offsets.len() - 1
    }

    /// Increase the row capacity to the given value.
    /// If matrix has a bigger capacity, it is not shrunk.
    pub fn increase_capacity_to(&mut self, capacity: usize) {
        if capacity <= self.capacity() {
            return;
        }

        debug!("resized to: {}", capacity);
        let nnz = self.nnz();
        self.offsets.resize(capacity + 1, nnz);
    }
}

impl Default for CSMatrixMask {
    fn default() -> Self {
        Self::new()
    }
}

impl MatrixMask for CSMatrixMask {
    fn clear(&mut self) {
        self.indices.clear();
        self.offsets.clear();
        self.offsets.push(0);
    }

    fn add(&mut self, row: usize, column: usize) -> (DataPosition, bool) {
        let capacity = if row > column { row + 1 } else { column + 1 };
        if capacity > self.capacity() {
            self.increase_capacity_to(capacity);
        }

        let idx0 = self.offsets[row];
        let idx1 = self.offsets[row + 1];
        let pos = {
            if idx0 == idx1 {
                trace!("new row opened: {}", row);
                idx0
            } else {
                self.indices[idx0..idx1].lower_bound(&column) + idx0
            }
        };

        if pos < idx1 && self.indices[pos] == column {
            trace!("item replaced at: {}", pos);
            (DataPosition(pos), true)
        } else {
            trace!("item added at: {}", pos);
            self.indices.insert(pos, column);
            for offset in self.offsets[row + 1..].iter_mut() {
                *offset += 1;
            }
            (DataPosition(pos), false)
        }
    }

    fn remove(&mut self, row: usize, column: usize) -> Option<(DataPosition, DataRange)> {
        if row >= self.capacity() || column >= self.capacity() {
            return None;
        }

        let idx0 = self.offsets[row];
        let idx1 = self.offsets[row + 1];
        let pos = self.indices[idx0..idx1].lower_bound(&column) + idx0;

        if pos < idx1 && self.indices[pos] == column {
            trace!("item removed at: {}", pos);
            self.indices.remove(pos);
            for offset in self.offsets[row + 1..].iter_mut() {
                *offset -= 1;
            }
            Some((DataPosition(pos), DataRange(self.offsets[row], self.offsets[row + 1])))
        } else {
            None
        }
    }

    fn get_data_range(&self, row: usize) -> DataRange {
        let cap = self.capacity();
        if row >= cap {
            // return an empty range
            DataRange(usize::max_value(), usize::max_value())
        } else {
            let idx0 = self.offsets[row];
            let idx1 = self.offsets[row + 1];
            DataRange(idx0, idx1)
        }
    }

    fn lower_bound_column_position(&self, column: usize, range: DataRange) -> Option<(usize, DataPosition)> {
        let DataRange(range_start, range_end) = range;
        if range_start >= range_end {
            return None;
        }
        let pos = self.indices[range_start..range_end].lower_bound(&column) + range_start;
        if pos < range_end {
            Some((self.indices[pos], pos.into()))
        } else {
            None
        }
    }

    fn get_column_index(&self, pos: DataPosition) -> usize {
        self.indices[usize::from(pos)]
    }
}