1use crate::error::{Error, Result, ensure, ensure_finite};
4
5#[derive(Clone, Debug, PartialEq)]
11pub struct Bounds {
12 pub lower: Vec<f64>,
14 pub upper: Vec<f64>,
16}
17
18impl Bounds {
19 pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
21 Self { lower, upper }
22 }
23
24 pub fn free(n: usize) -> Self {
26 Self::new(vec![f64::NEG_INFINITY; n], vec![f64::INFINITY; n])
27 }
28
29 pub fn non_negative(n: usize) -> Self {
31 Self::new(vec![0.0; n], vec![f64::INFINITY; n])
32 }
33
34 pub fn fixed(values: Vec<f64>) -> Self {
36 Self::new(values.clone(), values)
37 }
38
39 pub fn len(&self) -> usize {
41 self.lower.len()
42 }
43
44 pub fn is_empty(&self) -> bool {
46 self.lower.is_empty()
47 }
48
49 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 pub fn violation(&self, values: &[f64]) -> f64 {
82 self.checked_violation(values)
83 .expect("invalid bounds/point or nonfinite violation")
84 }
85
86 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#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct CsrPattern {
115 pub rows: usize,
117 pub cols: usize,
119 pub indptr: Vec<usize>,
121 pub indices: Vec<usize>,
123}
124
125impl CsrPattern {
126 pub fn nnz(&self) -> usize {
128 self.indices.len()
129 }
130
131 pub fn row(&self, r: usize) -> &[usize] {
136 &self.indices[self.indptr[r]..self.indptr[r + 1]]
137 }
138
139 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#[derive(Clone, Debug, PartialEq)]
188pub struct CsrMatrix {
189 pub pattern: CsrPattern,
191 pub values: Vec<f64>,
193}
194
195impl CsrMatrix {
196 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 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 pub fn rows(&self) -> usize {
243 self.pattern.rows
244 }
245
246 pub fn cols(&self) -> usize {
248 self.pattern.cols
249 }
250
251 pub fn nnz(&self) -> usize {
253 self.pattern.nnz()
254 }
255
256 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 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 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}