Skip to main content

lp_ip_craft/
sparse.rs

1//! Bounds and sparse matrices in zero-based CSR form.
2
3use crate::error::{Error, Result, ensure, ensure_finite};
4
5/// Elementwise bounds `lower[i] <= v[i] <= upper[i]`.
6///
7/// Equal finite bounds express an equality. `-inf` lower or `+inf` upper
8/// bounds express one-sided or free entries. NaN, `lower = +inf`,
9/// `upper = -inf` and `lower > upper` are invalid.
10#[derive(Clone, Debug, PartialEq)]
11pub struct Bounds {
12    /// Lower bounds; `f64::NEG_INFINITY` for none.
13    pub lower: Vec<f64>,
14    /// Upper bounds; `f64::INFINITY` for none.
15    pub upper: Vec<f64>,
16}
17
18impl Bounds {
19    /// Bounds from two vectors. Validation happens where the bounds are used.
20    pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
21        Self { lower, upper }
22    }
23
24    /// `n` free entries.
25    pub fn free(n: usize) -> Self {
26        Self::new(vec![f64::NEG_INFINITY; n], vec![f64::INFINITY; n])
27    }
28
29    /// `n` entries `0 <= v[i] < +inf`.
30    pub fn non_negative(n: usize) -> Self {
31        Self::new(vec![0.0; n], vec![f64::INFINITY; n])
32    }
33
34    /// Equalities `v[i] = values[i]`.
35    pub fn fixed(values: Vec<f64>) -> Self {
36        Self::new(values.clone(), values)
37    }
38
39    /// Number of entries (length of `lower`).
40    pub fn len(&self) -> usize {
41        self.lower.len()
42    }
43
44    /// Whether there are no entries.
45    pub fn is_empty(&self) -> bool {
46        self.lower.is_empty()
47    }
48
49    /// Checks lengths against `n` and every pair for consistency. `what` names
50    /// the bounds in the error message.
51    pub fn validate(&self, n: usize, what: &str) -> Result<()> {
52        ensure(self.lower.len() == n && self.upper.len() == n, || {
53            format!(
54                "{what}: expected {n} entries, got lower={} and upper={}",
55                self.lower.len(),
56                self.upper.len()
57            )
58        })?;
59        for (i, (&l, &u)) in self.lower.iter().zip(&self.upper).enumerate() {
60            let ok = !l.is_nan()
61                && !u.is_nan()
62                && l != f64::INFINITY
63                && u != f64::NEG_INFINITY
64                && l <= u;
65            ensure(ok, || {
66                format!(
67                    "{what}: entry {i} has lower={l}, upper={u}; need lower <= upper, \
68                     no NaN, lower < +inf and upper > -inf"
69                )
70            })?;
71        }
72        Ok(())
73    }
74
75    /// Largest amount by which `values` exceed the bounds, or `0.0` when all
76    /// entries are within them. Absolute and in the units of `values`.
77    ///
78    /// # Panics
79    /// If bounds/point are invalid or a finite-bound distance overflows. Use
80    /// [`Self::checked_violation`] for a fallible call.
81    pub fn violation(&self, values: &[f64]) -> f64 {
82        self.checked_violation(values)
83            .expect("invalid bounds/point or nonfinite violation")
84    }
85
86    /// Checked bound violation, rejecting malformed inputs and arithmetic overflow.
87    pub fn checked_violation(&self, values: &[f64]) -> Result<f64> {
88        self.validate(values.len(), "bounds")?;
89        let mut result = 0.0_f64;
90        for (i, &v) in values.iter().enumerate() {
91            ensure(v.is_finite(), || format!("point entry {i} must be finite"))?;
92            if self.lower[i].is_finite() {
93                result = result.max(crate::error::finite(
94                    self.lower[i] - v,
95                    "lower-bound distance",
96                )?);
97            }
98            if self.upper[i].is_finite() {
99                result = result.max(crate::error::finite(
100                    v - self.upper[i],
101                    "upper-bound distance",
102                )?);
103            }
104        }
105        Ok(result)
106    }
107}
108
109/// Structure of a sparse matrix in zero-based compressed sparse row (CSR) form.
110///
111/// Row `r` holds the column indices `indices[indptr[r]..indptr[r + 1]]`, which
112/// must be strictly increasing (sorted, no duplicates) and smaller than `cols`.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct CsrPattern {
115    /// Number of rows.
116    pub rows: usize,
117    /// Number of columns.
118    pub cols: usize,
119    /// Row pointers, `rows + 1` entries, starting at 0 and ending at `indices.len()`.
120    pub indptr: Vec<usize>,
121    /// Column index of every stored entry.
122    pub indices: Vec<usize>,
123}
124
125impl CsrPattern {
126    /// Number of stored entries.
127    pub fn nnz(&self) -> usize {
128        self.indices.len()
129    }
130
131    /// Column indices of row `r`.
132    ///
133    /// # Panics
134    /// If `r >= self.rows` or the pattern is invalid.
135    pub fn row(&self, r: usize) -> &[usize] {
136        &self.indices[self.indptr[r]..self.indptr[r + 1]]
137    }
138
139    /// Checks the CSR invariants. `what` names the matrix in the error message.
140    pub fn validate(&self, what: &str) -> Result<()> {
141        ensure(self.rows.checked_add(1) == Some(self.indptr.len()), || {
142            format!(
143                "{what}: indptr has {} entries, expected rows + 1 with rows = {}",
144                self.indptr.len(),
145                self.rows
146            )
147        })?;
148        ensure(
149            self.indptr[0] == 0 && self.indptr[self.rows] == self.indices.len(),
150            || {
151                format!(
152                    "{what}: indptr must start at 0 and end at the number of indices ({}), \
153                     got {} and {}",
154                    self.indices.len(),
155                    self.indptr[0],
156                    self.indptr[self.rows]
157                )
158            },
159        )?;
160        for r in 0..self.rows {
161            let (start, end) = (self.indptr[r], self.indptr[r + 1]);
162            ensure(start <= end && end <= self.indices.len(), || {
163                format!("{what}: indptr decreases at row {r} ({start} > {end})")
164            })?;
165            let row = &self.indices[start..end];
166            if let Some(&j) = row.iter().find(|&&j| j >= self.cols) {
167                return Err(Error::InvalidInput(format!(
168                    "{what}: row {r} has column index {j}, but there are only {} columns",
169                    self.cols
170                )));
171            }
172            ensure(row.windows(2).all(|p| p[0] < p[1]), || {
173                format!(
174                    "{what}: row {r} column indices must be strictly increasing \
175                     (sorted, no duplicates), got {row:?}"
176                )
177            })?;
178        }
179        Ok(())
180    }
181}
182
183/// A sparse matrix: a [`CsrPattern`] plus one value per stored entry.
184///
185/// Duplicate entries are rejected, not summed: combine and sort them before
186/// building the matrix. Explicitly stored zeros are allowed.
187#[derive(Clone, Debug, PartialEq)]
188pub struct CsrMatrix {
189    /// Structure.
190    pub pattern: CsrPattern,
191    /// Values in the order of `pattern.indices`.
192    pub values: Vec<f64>,
193}
194
195impl CsrMatrix {
196    /// A matrix from its CSR arrays. Validation happens where it is used.
197    pub fn new(
198        rows: usize,
199        cols: usize,
200        indptr: Vec<usize>,
201        indices: Vec<usize>,
202        values: Vec<f64>,
203    ) -> Self {
204        Self {
205            pattern: CsrPattern {
206                rows,
207                cols,
208                indptr,
209                indices,
210            },
211            values,
212        }
213    }
214
215    /// The nonzero entries of a dense `rows x cols` matrix given row by row.
216    /// Exact zeros are not stored.
217    pub fn from_dense(rows: usize, cols: usize, row_major: &[f64]) -> Result<Self> {
218        ensure(rows.checked_mul(cols) == Some(row_major.len()), || {
219            format!(
220                "dense matrix: {} values for a {rows} x {cols} matrix",
221                row_major.len()
222            )
223        })?;
224        ensure_finite(row_major, "dense matrix")?;
225        let mut indptr = Vec::with_capacity(rows + 1);
226        let mut indices = Vec::new();
227        let mut values = Vec::new();
228        indptr.push(0);
229        for r in 0..rows {
230            for (j, &a) in row_major[r * cols..(r + 1) * cols].iter().enumerate() {
231                if a != 0.0 {
232                    indices.push(j);
233                    values.push(a);
234                }
235            }
236            indptr.push(indices.len());
237        }
238        Ok(Self::new(rows, cols, indptr, indices, values))
239    }
240
241    /// Number of rows.
242    pub fn rows(&self) -> usize {
243        self.pattern.rows
244    }
245
246    /// Number of columns.
247    pub fn cols(&self) -> usize {
248        self.pattern.cols
249    }
250
251    /// Number of stored entries.
252    pub fn nnz(&self) -> usize {
253        self.pattern.nnz()
254    }
255
256    /// Checks the pattern, the number of values and their finiteness.
257    pub fn validate(&self, what: &str) -> Result<()> {
258        self.pattern.validate(what)?;
259        ensure(self.values.len() == self.pattern.nnz(), || {
260            format!(
261                "{what}: {} values for {} stored entries",
262                self.values.len(),
263                self.pattern.nnz()
264            )
265        })?;
266        ensure_finite(&self.values, &format!("{what} values"))
267    }
268
269    /// `y = A x`.
270    ///
271    /// # Panics
272    /// On length mismatches.
273    pub fn multiply(&self, x: &[f64], y: &mut [f64]) {
274        let p = &self.pattern;
275        assert_eq!(self.values.len(), p.nnz(), "values length");
276        assert_eq!(x.len(), p.cols, "x length");
277        assert_eq!(y.len(), p.rows, "y length");
278        for (r, out) in y.iter_mut().enumerate() {
279            let range = p.indptr[r]..p.indptr[r + 1];
280            *out = p.indices[range.clone()]
281                .iter()
282                .zip(&self.values[range])
283                .map(|(&j, &a)| a * x[j])
284                .sum();
285        }
286    }
287
288    /// `y = A^T x`.
289    ///
290    /// # Panics
291    /// On length mismatches.
292    pub fn multiply_transpose(&self, x: &[f64], y: &mut [f64]) {
293        let p = &self.pattern;
294        assert_eq!(self.values.len(), p.nnz(), "values length");
295        assert_eq!(x.len(), p.rows, "x length");
296        assert_eq!(y.len(), p.cols, "y length");
297        y.fill(0.0);
298        for (r, &xr) in x.iter().enumerate() {
299            let range = p.indptr[r]..p.indptr[r + 1];
300            for (&j, &a) in p.indices[range.clone()].iter().zip(&self.values[range]) {
301                y[j] += a * xr;
302            }
303        }
304    }
305}