casadi_trilsolve.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 "trilsolve"
22 template<typename T1>
23 void casadi_trilsolve(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  // Backward substitution
38  for (c = ncol; c-- > 0; ) {
39  for (k = colind[c + 1]; k-- > colind[c]; ) {
40  x[c] += nz_a[k] * x[row[k]];
41  }
42  }
43  } else {
44  // Forward substitution
45  for (c = 0; c < ncol; ++c) {
46  for (k = colind[c]; k < colind[c+1]; ++k) {
47  x[row[k]] += nz_a[k] * x[c];
48  }
49  }
50  }
51  } else {
52  if (tr) {
53  // Backward substitution
54  for (c = ncol; c-- > 0; ) {
55  for (k = colind[c + 1]; k-- > colind[c]; ) {
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  // Forward substitution
66  for (c = 0; c < ncol; ++c) {
67  for (k = colind[c]; k < colind[c+1]; ++k) {
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 }