casadi_interpn_grad.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 // SYMBOL "interpn_grad"
21 template<typename T1>
22 void casadi_interpn_grad(T1* grad, casadi_int ndim, const T1* grid, const casadi_int* offset, const T1* values, const T1* x, const casadi_int* lookup_mode, casadi_int m, casadi_int* iw, T1* w) { // NOLINT(whitespace/line_length)
23  T1 *alpha, *coeff, *v;
24  casadi_int *index, *corner;
25  casadi_int i;
26  // Quick return
27  if (!grad) return;
28  // Work vectors
29  alpha = w; w += ndim;
30  coeff = w; w += ndim;
31  v = w; w+= m;
32  index = iw; iw += ndim;
33  corner = iw; iw += ndim;
34 
35  // Left index and fraction of interval
36  casadi_interpn_weights(ndim, grid, offset, x, alpha, index, lookup_mode);
37  // Loop over all corners, add contribution to output
38  casadi_clear_casadi_int(corner, ndim);
39  casadi_clear(grad, ndim*m);
40  do {
41  casadi_int i, j;
42  // Get coefficients
43  casadi_clear(v, m);
44  casadi_interpn_interpolate(v, ndim, offset, values,
45  alpha, index, corner, coeff, m);
46  // Propagate to alpha
47  for (i=ndim-1; i>=0; --i) {
48  if (corner[i]) {
49  for (j=0; j<m; ++j) {
50  grad[i*m+j] += v[j]*coeff[i];
51  v[j] *= alpha[i];
52  }
53  } else {
54  for (j=0; j<m; ++j) {
55  grad[i*m+j] -= v[j]*coeff[i];
56  v[j] *= 1-alpha[i];
57  }
58  }
59  }
60  } while (casadi_flip(corner, ndim));
61  // Propagate to x
62  for (i=0; i<ndim; ++i) {
63  casadi_int k, j;
64  const T1* g;
65  T1 delta;
66  g = grid + offset[i];
67  j = index[i];
68  delta = g[j+1]-g[j];
69  for (k=0;k<m;++k) grad[k] /= delta;
70  grad += m;
71  }
72 }