osqp 1.0.1

The OSQP (Operator Splitting Quadratic Program) solver.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use osqp_sys as ffi;
use std::borrow::Cow;
use std::iter;
use std::slice;

use float;
use osqp_sys::OSQPCscMatrix;

macro_rules! check {
    ($check:expr) => {
        if !{ $check } {
            return false;
        }
    };
}

/// A matrix in Compressed Sparse Column format.
#[derive(Clone, Debug, PartialEq)]
pub struct CscMatrix<'a> {
    /// The number of rows in the matrix.
    pub nrows: usize,
    /// The number of columns in the matrix.
    pub ncols: usize,
    /// The CSC column pointer array.
    ///
    /// It contains the offsets into the index and data arrays of the entries in each column.
    pub indptr: Cow<'a, [usize]>,
    /// The CSC index array.
    ///
    /// It contains the row index of each non-zero entry.
    pub indices: Cow<'a, [usize]>,
    /// The CSC data array.
    ///
    /// It contains the values of each non-zero entry.
    pub data: Cow<'a, [float]>,
}

impl<'a> CscMatrix<'a> {
    /// Creates a sparse CSC matrix with its elements filled with the components provided by an
    /// iterator in column-major order.
    ///
    /// Panics if `iter` contains fewer than `nrows * ncols` elements.
    pub fn from_column_iter<I: IntoIterator<Item = float>>(
        nrows: usize,
        ncols: usize,
        iter: I,
    ) -> CscMatrix<'static> {
        let mut iter = iter.into_iter();

        let mut indptr = Vec::with_capacity(ncols + 1);
        let mut indices = Vec::new();
        let mut data = Vec::new();

        indptr.push(0);
        for _ in 0..ncols {
            for r in 0..nrows {
                let value = iter.next().expect("not enough elements in iterator");
                if value != 0.0 {
                    indices.push(r);
                    data.push(value);
                }
            }
            indptr.push(data.len());
        }

        CscMatrix {
            nrows,
            ncols,
            indptr: Cow::Owned(indptr),
            indices: Cow::Owned(indices),
            data: Cow::Owned(data),
        }
    }

    /// Creates a sprase CSC matrix with its elements filled with the components provided by an
    /// iterator in row-major order.
    ///
    /// The order of elements in the slice must follow the usual mathematic writing, i.e.,
    /// row-by-row.
    ///
    /// Panics if `iter` contains fewer than `nrows * ncols` elements.
    pub fn from_row_iter<I: IntoIterator<Item = float>>(
        nrows: usize,
        ncols: usize,
        iter: I,
    ) -> CscMatrix<'static> {
        // Create transposed CSC matrix from row iterator.
        let matrix_t = CscMatrix::from_column_iter(ncols, nrows, iter);

        // Transpose back to retain original order.
        matrix_t.transpose()
    }

    /// Creates a dense CSC matrix with its elements filled with the components provided by an
    /// iterator in column-major order.
    ///
    /// Panics if `iter` contains fewer than `nrows * ncols` elements.
    pub fn from_column_iter_dense<I: IntoIterator<Item = float>>(
        nrows: usize,
        ncols: usize,
        iter: I,
    ) -> CscMatrix<'static> {
        CscMatrix::from_column_iter_dense_inner(nrows, ncols, |size| {
            let mut data = Vec::with_capacity(size);
            data.extend(iter.into_iter().take(size));
            assert_eq!(size, data.len(), "not enough elements in iterator");
            data
        })
    }

    /// Creates a dense CSC matrix with its elements filled with the components provided by an
    /// iterator in row-major order.
    ///
    /// The order of elements in the slice must follow the usual mathematic writing, i.e.,
    /// row-by-row.
    ///
    /// Panics if `iter` contains fewer than `nrows * ncols` elements.
    pub fn from_row_iter_dense<I: IntoIterator<Item = float>>(
        nrows: usize,
        ncols: usize,
        iter: I,
    ) -> CscMatrix<'static> {
        CscMatrix::from_column_iter_dense_inner(nrows, ncols, |size| {
            let mut iter = iter.into_iter();
            let mut data = vec![0.0; size];
            for r in 0..nrows {
                for c in 0..ncols {
                    data[c * nrows + r] = iter.next().expect("not enough elements in iterator");
                }
            }
            data
        })
    }

    fn from_column_iter_dense_inner<F: FnOnce(usize) -> Vec<float>>(
        nrows: usize,
        ncols: usize,
        f: F,
    ) -> CscMatrix<'static> {
        let size = nrows
            .checked_mul(ncols)
            .expect("overflow calculating matrix size");

        let data = f(size);

        CscMatrix {
            nrows,
            ncols,
            indptr: Cow::Owned((0..ncols + 1).map(|i| i * nrows).collect()),
            indices: Cow::Owned(iter::repeat(0..nrows).take(ncols).flat_map(|i| i).collect()),
            data: Cow::Owned(data),
        }
    }

    /// Returns `true` if the matrix is structurally upper triangular.
    ///
    /// A matrix is structurally upper triangular if, for each column, all elements below the
    /// diagonal, i.e. with their row number greater than their column number, are empty.
    ///
    /// Note that an element with an explicit value of zero is not empty. To be empty an element
    /// must not be present in the sparse encoding of the matrix.
    pub fn is_structurally_upper_tri(&self) -> bool {
        for col in 0..self.indptr.len().saturating_sub(1) {
            let col_data_start_idx = self.indptr[col];
            let col_data_end_idx = self.indptr[col + 1];

            for &row in &self.indices[col_data_start_idx..col_data_end_idx] {
                if row > col {
                    return false;
                }
            }
        }

        true
    }

    /// Extracts the upper triangular elements of the matrix.
    ///
    /// This operation performs no allocations if the matrix is already structurally upper
    /// triangular or if it contains only owned data.
    ///
    /// The returned matrix is guaranteed to be structurally upper triangular.
    pub fn into_upper_tri(self) -> CscMatrix<'a> {
        if self.is_structurally_upper_tri() {
            return self;
        }

        let mut indptr = self.indptr.into_owned();
        let mut indices = self.indices.into_owned();
        let mut data = self.data.into_owned();

        let mut next_data_idx = 0;

        for col in 0..indptr.len().saturating_sub(1) {
            let col_start_idx = indptr[col];
            let next_col_start_idx = indptr[col + 1];

            indptr[col] = next_data_idx;

            for data_idx in col_start_idx..next_col_start_idx {
                let row = indices[data_idx];

                if row <= col {
                    data[next_data_idx] = data[data_idx];
                    indices[next_data_idx] = row;
                    next_data_idx += 1;
                }
            }
        }

        if let Some(data_len) = indptr.last_mut() {
            *data_len = next_data_idx
        }
        indices.truncate(next_data_idx);
        data.truncate(next_data_idx);

        CscMatrix {
            indptr: Cow::Owned(indptr),
            indices: Cow::Owned(indices),
            data: Cow::Owned(data),
            ..self
        }
    }

    fn transpose(&self) -> CscMatrix<'static> {
        let mut indptr_t = vec![0; self.nrows + 1];
        let mut indices_t = vec![0; self.indices.len()];
        let mut data_t = vec![0.0; self.data.len()];

        // Find the number of non-zero elements in each row.
        for i in 0..self.data.len() {
            indptr_t[self.indices[i] + 1] += 1;
        }

        // Cumulative sum to convert to row indices array.
        let mut sum = 0;
        for v in indptr_t.iter_mut() {
            sum += *v;
            *v = sum;
        }

        // Traverse each column and place elements in the correct row.
        // Row indices array will be offset by the number of non-zero elements in each row.
        for c in 0..self.ncols {
            for i in self.indptr[c]..self.indptr[c + 1] {
                let r = self.indices[i];
                let j = indptr_t[r];

                indices_t[j] = c;
                data_t[j] = self.data[i];

                indptr_t[r] += 1;
            }
        }

        // Un-offset the row indices array.
        indptr_t.rotate_right(1);
        indptr_t[0] = 0;

        CscMatrix {
            nrows: self.ncols,
            ncols: self.nrows,
            indptr: Cow::Owned(indptr_t),
            indices: Cow::Owned(indices_t),
            data: Cow::Owned(data_t),
        }
    }

    // TODO: Remove *mut in return type here
    pub(crate) unsafe fn to_ffi(&self) -> *mut OSQPCscMatrix {
        // Casting is safe as at this point no indices exceed isize::MAX and osqp_int is a signed
        // integer of the same size as usize/isize.
        ffi::OSQPCscMatrix_new(
            self.nrows as ffi::osqp_int,
            self.ncols as ffi::osqp_int,
            self.data.len() as ffi::osqp_int,
            self.data.as_ptr() as *mut float,
            self.indices.as_ptr() as *mut usize as *mut ffi::osqp_int,
            self.indptr.as_ptr() as *mut usize as *mut ffi::osqp_int,
        )
    }

    #[allow(dead_code)]
    pub(crate) unsafe fn from_ffi<'b>(csc: *const ffi::OSQPCscMatrix) -> CscMatrix<'b> {
        let nrows = (*csc).m as usize;
        let ncols = (*csc).n as usize;
        let indptr = Cow::Borrowed(slice::from_raw_parts((*csc).p as *const usize, ncols + 1));
        // OSQP sets `nzmax = max(nnz, 1)`, presumably so as not to have zero length allocations.
        let nnz = if indptr[ncols] == 0 {
            0
        } else {
            (*csc).nzmax as usize
        };

        CscMatrix {
            nrows,
            ncols,
            indptr,
            indices: Cow::Borrowed(slice::from_raw_parts((*csc).i as *const usize, nnz)),
            data: Cow::Borrowed(slice::from_raw_parts((*csc).x as *const float, nnz)),
        }
    }

    pub(crate) fn assert_same_sparsity_structure(&self, other: &CscMatrix) {
        assert_eq!(self.nrows, other.nrows);
        assert_eq!(self.ncols, other.ncols);
        assert_eq!(&*self.indptr, &*other.indptr);
        assert_eq!(&*self.indices, &*other.indices);
        assert_eq!(self.data.len(), other.data.len());
    }

    pub(crate) fn is_valid(&self) -> bool {
        let max_idx = isize::max_value() as usize;
        check!(self.nrows <= max_idx);
        check!(self.ncols <= max_idx);
        check!(self.indptr.len() <= max_idx);
        check!(self.indices.len() <= max_idx);
        check!(self.data.len() <= max_idx);

        // Check row pointers
        check!(self.indptr.len() == self.ncols + 1);
        check!(self.indptr[self.ncols] == self.data.len());
        let mut prev_row_idx = 0;
        for &row_idx in self.indptr.iter() {
            // Row pointers must be monotonically nondecreasing
            check!(row_idx >= prev_row_idx);
            prev_row_idx = row_idx;
        }

        // Check index values
        check!(self.data.len() == self.indices.len());
        check!(self.indices.iter().all(|r| *r < self.nrows));
        for i in 0..self.ncols {
            let row_indices = &self.indices[self.indptr[i] as usize..self.indptr[i + 1] as usize];
            let mut row_indices = row_indices.iter();
            if let Some(&first_row) = row_indices.next() {
                let mut prev_row = first_row;
                for &row in row_indices {
                    // Row indices within each column must be monotonically increasing
                    check!(row > prev_row);
                    prev_row = row;
                }
                check!(prev_row < self.nrows);
            }
        }

        true
    }
}

// Any &CscMatrix can be converted into a CscMatrix without allocation due to the use of Cow.
impl<'a, 'b: 'a> From<&'a CscMatrix<'b>> for CscMatrix<'a> {
    fn from(mat: &'a CscMatrix<'b>) -> CscMatrix<'a> {
        CscMatrix {
            nrows: mat.nrows,
            ncols: mat.ncols,
            indptr: (*mat.indptr).into(),
            indices: (*mat.indices).into(),
            data: (*mat.data).into(),
        }
    }
}

// Enable creating a csc matrix from a slice of arrays for testing and small problems.
//
// let A: CscMatrix = (&[[1.0, 2.0],
//                       [3.0, 0.0],
//                       [0.0, 4.0]]).into;
//
impl<'a, I: 'a, J: 'a> From<I> for CscMatrix<'static>
where
    I: IntoIterator<Item = J>,
    J: IntoIterator<Item = &'a float>,
{
    fn from(rows: I) -> CscMatrix<'static> {
        let rows: Vec<Vec<float>> = rows
            .into_iter()
            .map(|r| r.into_iter().map(|&v| v).collect())
            .collect();

        let nrows = rows.len();
        let ncols = rows.iter().map(|r| r.len()).next().unwrap_or(0);
        assert!(rows.iter().all(|r| r.len() == ncols));
        let nnz = rows.iter().flat_map(|r| r).filter(|&&v| v != 0.0).count();

        let mut indptr = Vec::with_capacity(ncols + 1);
        let mut indices = Vec::with_capacity(nnz);
        let mut data = Vec::with_capacity(nnz);

        indptr.push(0);
        for c in 0..ncols {
            for r in 0..nrows {
                let value = rows[r][c];
                if value != 0.0 {
                    indices.push(r);
                    data.push(value);
                }
            }
            indptr.push(data.len());
        }

        CscMatrix {
            nrows,
            ncols,
            indptr: indptr.into(),
            indices: indices.into(),
            data: data.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;

    #[test]
    fn csc_from_array() {
        let mat = &[[1.0, 2.0], [3.0, 0.0], [0.0, 4.0]];
        let csc: CscMatrix = mat.into();

        assert_eq!(3, csc.nrows);
        assert_eq!(2, csc.ncols);
        assert_eq!(&[0, 2, 4], &*csc.indptr);
        assert_eq!(&[0, 1, 0, 2], &*csc.indices);
        assert_eq!(&[1.0, 3.0, 2.0, 4.0], &*csc.data);
    }

    #[test]
    fn csc_from_ref() {
        let mat = &[[1.0, 2.0], [3.0, 0.0], [0.0, 4.0]];
        let csc: CscMatrix = mat.into();
        let csc_ref: CscMatrix = (&csc).into();

        // csc_ref must be created without allocation
        if let Cow::Owned(_) = csc_ref.indptr {
            panic!();
        }
        if let Cow::Owned(_) = csc_ref.indices {
            panic!();
        }
        if let Cow::Owned(_) = csc_ref.data {
            panic!();
        }

        assert_eq!(csc.nrows, csc_ref.nrows);
        assert_eq!(csc.ncols, csc_ref.ncols);
        assert_eq!(csc.indptr, csc_ref.indptr);
        assert_eq!(csc.indices, csc_ref.indices);
        assert_eq!(csc.data, csc_ref.data);
    }

    #[test]
    fn csc_from_iter_sparse() {
        let from_column = CscMatrix::from_column_iter(
            4,
            3,
            [1.0, 0.0, 2.0, 3.0, 0.0, 4.0, 0.0, 5.0, 6.0, 7.0, 0.0, 8.0]
                .iter()
                .copied(),
        );

        let from_row = CscMatrix::from_row_iter(
            4,
            3,
            [1.0, 0.0, 6.0, 0.0, 4.0, 7.0, 2.0, 0.0, 0.0, 3.0, 5.0, 8.0]
                .iter()
                .copied(),
        );

        let expected = CscMatrix {
            nrows: 4,
            ncols: 3,
            indptr: Cow::Borrowed(&[0, 3, 5, 8]),
            indices: Cow::Borrowed(&[0, 2, 3, 1, 3, 0, 1, 3]),
            data: Cow::Borrowed(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]),
        };

        assert_eq!(from_column, expected);
        assert_eq!(from_row, expected);
    }

    #[test]
    fn csc_from_iter_dense() {
        let from_column = CscMatrix::from_column_iter_dense(
            4,
            3,
            [
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
            ]
            .iter()
            .copied(),
        );

        let from_row = CscMatrix::from_row_iter_dense(
            4,
            3,
            [
                1.0, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0,
            ]
            .iter()
            .copied(),
        );

        let expected: CscMatrix = (&[
            [1.0, 5.0, 9.0],
            [2.0, 6.0, 10.0],
            [3.0, 7.0, 11.0],
            [4.0, 8.0, 12.0],
        ])
            .into();

        assert_eq!(from_column, expected);
        assert_eq!(from_row, expected);
    }

    #[test]
    fn same_sparsity_structure_ok() {
        let mat1: CscMatrix = (&[[1.0, 2.0, 0.0], [3.0, 0.0, 0.0], [0.0, 5.0, 0.0]]).into();
        let mat2: CscMatrix = (&[[7.0, 8.0, 0.0], [9.0, 0.0, 0.0], [0.0, 10.0, 0.0]]).into();
        mat1.assert_same_sparsity_structure(&mat2);
    }

    #[test]
    #[should_panic]
    fn different_sparsity_structure_panics() {
        let mat1: CscMatrix = (&[[1.0, 2.0, 0.0], [3.0, 0.0, 0.0], [0.0, 5.0, 6.0]]).into();
        let mat2: CscMatrix = (&[[7.0, 8.0, 0.0], [9.0, 0.0, 0.0], [0.0, 10.0, 0.0]]).into();
        mat1.assert_same_sparsity_structure(&mat2);
    }

    #[test]
    fn is_structurally_upper_tri() {
        let structurally_upper_tri: CscMatrix =
            (&[[1.0, 0.0, 5.0], [0.0, 3.0, 4.0], [0.0, 0.0, 2.0]]).into();
        let numerically_upper_tri: CscMatrix = CscMatrix::from_row_iter_dense(
            3,
            3,
            [1.0, 0.0, 5.0, 0.0, 3.0, 4.0, 0.0, 0.0, 2.0]
                .iter()
                .cloned(),
        );
        let not_upper_tri: CscMatrix =
            (&[[7.0, 2.0, 0.0], [9.0, 0.0, 5.0], [7.0, 10.0, 0.0]]).into();
        assert!(structurally_upper_tri.is_structurally_upper_tri());
        assert!(!numerically_upper_tri.is_structurally_upper_tri());
        assert!(!not_upper_tri.is_structurally_upper_tri());
    }

    #[test]
    fn into_upper_tri() {
        let mat: CscMatrix = (&[[1.0, 0.0, 5.0], [7.0, 3.0, 4.0], [6.0, 0.0, 2.0]]).into();
        let mat_upper_tri: CscMatrix =
            (&[[1.0, 0.0, 5.0], [0.0, 3.0, 4.0], [0.0, 0.0, 2.0]]).into();
        assert_eq!(mat.into_upper_tri(), mat_upper_tri);
    }
}