casadi_triusolve.hpp
1 //
2 // MIT No Attribution
3 //
4 // Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl, KU Leuven.
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining a copy of this
7 // software and associated documentation files (the "Software"), to deal in the Software
8 // without restriction, including without limitation the rights to use, copy, modify,
9 // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so.
11 //
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13 // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14 // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
15 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
16 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
17 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 //
19 
20 
21 // SYMBOL "triusolve"
22 template<typename T1>
23 void casadi_triusolve(const casadi_int* sp_a, const T1* nz_a, T1* x, int tr, int unity,
24  casadi_int nrhs) {
25  // Local variables
26  casadi_int nrow, ncol, r, c, k, rhs;
27  const casadi_int *colind, *row;
28  // Extract sparsity
29  nrow = sp_a[0];
30  ncol = sp_a[1];
31  colind = sp_a + 2;
32  row = colind + ncol + 1;
33  // For all right hand sides
34  for (rhs = 0; rhs < nrhs; ++rhs) {
35  if (unity) {
36  if (tr) {
37  // Forward substitution
38  for (c = 0; c < ncol; ++c) {
39  for (k = colind[c]; k < colind[c+1]; ++k) {
40  x[c] += nz_a[k] * x[row[k]];
41  }
42  }
43  } else {
44  // Backward substitution
45  for (c = ncol; c-- > 0; ) {
46  for (k = colind[c + 1]; k-- > colind[c]; ) {
47  x[row[k]] += nz_a[k] * x[c];
48  }
49  }
50  }
51  } else {
52  if (tr) {
53  // Forward substitution
54  for (c = 0; c < ncol; ++c) {
55  for (k = colind[c]; k < colind[c+1]; ++k) {
56  r = row[k];
57  if (r == c) {
58  x[c] /= nz_a[k];
59  } else {
60  x[c] -= nz_a[k] * x[r];
61  }
62  }
63  }
64  } else {
65  // Backward substitution
66  for (c = ncol; c-- > 0; ) {
67  for (k = colind[c + 1]; k-- > colind[c]; ) {
68  r = row[k];
69  if (r == c) {
70  x[r] /= nz_a[k];
71  } else {
72  x[r] -= nz_a[k] * x[c];
73  }
74  }
75  }
76  }
77  }
78  // Next right-hand-side
79  x += nrow;
80  }
81 }