split.cpp
1 /*
2  * This file is part of CasADi.
3  *
4  * CasADi -- A symbolic framework for dynamic optimization.
5  * Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl,
6  * KU Leuven. All rights reserved.
7  * Copyright (C) 2011-2014 Greg Horn
8  *
9  * CasADi is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 3 of the License, or (at your option) any later version.
13  *
14  * CasADi is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with CasADi; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24 
25 
26 #include "split.hpp"
27 #include "casadi_misc.hpp"
28 #include "global_options.hpp"
29 #include "serializing_stream.hpp"
30 
31 namespace casadi {
32 
34  s.unpack("Split::offset", offset_);
35  s.unpack("Split::output_sparsity", output_sparsity_);
36  }
37 
40  s.pack("Split::offset", offset_);
41  s.pack("Split::output_sparsity", output_sparsity_);
42  }
43 
44  Split::Split(const MX& x, const std::vector<casadi_int>& offset) : offset_(offset) {
45  set_dep(x);
47  }
48 
50  }
51 
52  int Split::eval(const double** arg, double** res, casadi_int* iw, double* w) const {
53  return eval_gen<double>(arg, res, iw, w);
54  }
55 
56  int Split::eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w) const {
57  return eval_gen<SXElem>(arg, res, iw, w);
58  }
59 
60  template<typename T>
61  int Split::eval_gen(const T** arg, T** res, casadi_int* iw, T* w) const {
62  // Number of derivatives
63  casadi_int nx = offset_.size()-1;
64 
65  for (casadi_int i=0; i<nx; ++i) {
66  casadi_int nz_first = offset_[i];
67  casadi_int nz_last = offset_[i+1];
68  if (res[i]!=nullptr) {
69  std::copy(arg[0]+nz_first, arg[0]+nz_last, res[i]);
70  }
71  }
72  return 0;
73  }
74 
75  int Split::sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const {
76  casadi_int nx = offset_.size()-1;
77  for (casadi_int i=0; i<nx; ++i) {
78  if (res[i]!=nullptr) {
79  const bvec_t *arg_ptr = arg[0] + offset_[i];
80  casadi_int n_i = sparsity(i).nnz();
81  bvec_t *res_i_ptr = res[i];
82  for (casadi_int k=0; k<n_i; ++k) {
83  *res_i_ptr++ = *arg_ptr++;
84  }
85  }
86  }
87  return 0;
88  }
89 
90  int Split::sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const {
91  casadi_int nx = offset_.size()-1;
92  for (casadi_int i=0; i<nx; ++i) {
93  if (res[i]!=nullptr) {
94  bvec_t *arg_ptr = arg[0] + offset_[i];
95  casadi_int n_i = sparsity(i).nnz();
96  bvec_t *res_i_ptr = res[i];
97  for (casadi_int k=0; k<n_i; ++k) {
98  *arg_ptr++ |= *res_i_ptr;
99  *res_i_ptr++ = 0;
100  }
101  }
102  }
103  return 0;
104  }
105 
107  const std::vector<casadi_int>& arg,
108  const std::vector<casadi_int>& res,
109  const std::vector<bool>& arg_is_ref,
110  std::vector<bool>& res_is_ref) const {
111  casadi_int nx = nout();
112  for (casadi_int i=0; i<nx; ++i) {
113  casadi_int nz_first = offset_[i];
114  casadi_int nz_last = offset_[i+1];
115  casadi_int nz = nz_last-nz_first;
116  if (res[i]>=0 && nz>0) { // if anything to assign
117  if (nz==1) { // assign scalar
118  g << g.workel(res[i]) << " = ";
119  if (dep(0).nnz()==1) {
120  // rhs is also scalar
121  casadi_assert_dev(nz_first==0);
122  g << g.workel(arg[0]) << ";\n";
123  } else {
124  // rhs is an element in a vector
125  g << g.work(arg[0], dep(0).nnz(), arg_is_ref[0]) << "[" << nz_first << "];\n";
126  }
127  } else {
128  // assign vector
129  std::string r = g.work(arg[0], dep(0).nnz(), arg_is_ref[0]);
130  if (nz_first!=0) r = r + "+" + str(nz_first);
131  if (arg_is_ref[0]) {
132  g << g.work(res[i], nnz(i), true) << " = " << r << ";\n";
133  res_is_ref[i] = true;
134  } else {
135  g << g.copy(r, nz, g.work(res[i], nnz(i), false)) << "\n";
136  }
137  }
138  }
139  }
140  }
141 
142  Dict Split::info() const {
143  std::vector<MX> arg;
144  for (const auto& sp : output_sparsity_)
145  arg.push_back(MX::sym("x", sp));
146  Function output("output", std::vector<MX>{}, arg, {{"allow_free", true}});
147  return {{"offset", offset_}, {"output", output}};
148  }
149 
150  Horzsplit::Horzsplit(const MX& x, const std::vector<casadi_int>& offset) : Split(x, offset) {
151 
152  // Split up the sparsity pattern
153  output_sparsity_ = horzsplit(x.sparsity(), offset_);
154 
155  // Have offset_ refer to the nonzero offsets instead of column offsets
156  offset_.resize(1);
157  for (auto&& s : output_sparsity_) {
158  offset_.push_back(offset_.back() + s.nnz());
159  }
160  }
161 
162  std::string Horzsplit::disp(const std::vector<std::string>& arg) const {
163  return "horzsplit(" + arg.at(0) + ")";
164  }
165 
166  void Horzsplit::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res,
167  const std::vector<bool>& unique) const {
168  // Get column offsets
169  std::vector<casadi_int> col_offset;
170  col_offset.reserve(offset_.size());
171  col_offset.push_back(0);
172  for (auto&& s : output_sparsity_) {
173  col_offset.push_back(col_offset.back() + s.size2());
174  }
175 
176  res = horzsplit(arg[0], col_offset);
177  }
178 
179  void Horzsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
180  std::vector<std::vector<MX> >& fsens) const {
181  casadi_int nfwd = fsens.size();
182 
183  // Get column offsets
184  std::vector<casadi_int> col_offset;
185  col_offset.reserve(offset_.size());
186  col_offset.push_back(0);
187  for (auto&& s : output_sparsity_) {
188  col_offset.push_back(col_offset.back() + s.size2());
189  }
190 
191  // Non-differentiated output and forward sensitivities
192  for (casadi_int d=0; d<nfwd; ++d) {
193  fsens[d] = horzsplit(fseed[d][0], col_offset);
194  }
195  }
196 
197  void Horzsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
198  std::vector<std::vector<MX> >& asens) const {
199  casadi_int nadj = aseed.size();
200 
201  // Get column offsets
202  std::vector<casadi_int> col_offset;
203  col_offset.reserve(offset_.size());
204  col_offset.push_back(0);
205  for (auto&& s : output_sparsity_) {
206  col_offset.push_back(col_offset.back() + s.size2());
207  }
208 
209  for (casadi_int d=0; d<nadj; ++d) {
210  asens[d][0] += horzcat(aseed[d]);
211  }
212  }
213 
215  const std::vector<casadi_int>& offset1,
216  const std::vector<casadi_int>& offset2) : Split(x, offset1) {
217 
218  // Split up the sparsity pattern
219  output_sparsity_ = diagsplit(x.sparsity(), offset1, offset2);
220 
221  // Have offset_ refer to the nonzero offsets instead of column offsets
222  offset_.resize(1);
223  for (auto&& s : output_sparsity_) {
224  offset_.push_back(offset_.back() + s.nnz());
225  }
226 
227  casadi_assert(offset_.back()==x.nnz(),
228  "DiagSplit:: the presence of nonzeros outside the diagonal blocks in unsupported.");
229  }
230 
231  std::string Diagsplit::disp(const std::vector<std::string>& arg) const {
232  return "diagsplit(" + arg.at(0) + ")";
233  }
234 
235  void Diagsplit::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res,
236  const std::vector<bool>& unique) const {
237  // Get offsets
238  std::vector<casadi_int> offset1;
239  offset1.reserve(offset_.size());
240  offset1.push_back(0);
241  std::vector<casadi_int> offset2;
242  offset2.reserve(offset_.size());
243  offset2.push_back(0);
244  for (auto&& s : output_sparsity_) {
245  offset1.push_back(offset1.back() + s.size1());
246  offset2.push_back(offset2.back() + s.size2());
247  }
248 
249  res = diagsplit(arg[0], offset1, offset2);
250  }
251 
252  void Diagsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
253  std::vector<std::vector<MX> >& fsens) const {
254  casadi_int nfwd = fsens.size();
255  // Get offsets
256  std::vector<casadi_int> offset1;
257  offset1.reserve(offset_.size());
258  offset1.push_back(0);
259  std::vector<casadi_int> offset2;
260  offset2.reserve(offset_.size());
261  offset2.push_back(0);
262  for (auto&& s : output_sparsity_) {
263  offset1.push_back(offset1.back() + s.size1());
264  offset2.push_back(offset2.back() + s.size2());
265  }
266 
267  // Non-differentiated output and forward sensitivities
268  for (casadi_int d=0; d<nfwd; ++d) {
269  fsens[d] = diagsplit(fseed[d][0], offset1, offset2);
270  }
271  }
272 
273  void Diagsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
274  std::vector<std::vector<MX> >& asens) const {
275  casadi_int nadj = asens.size();
276 
277  // Get offsets
278  std::vector<casadi_int> offset1;
279  offset1.reserve(offset_.size());
280  offset1.push_back(0);
281  std::vector<casadi_int> offset2;
282  offset2.reserve(offset_.size());
283  offset2.push_back(0);
284  for (auto&& s : output_sparsity_) {
285  offset1.push_back(offset1.back() + s.size1());
286  offset2.push_back(offset2.back() + s.size2());
287  }
288 
289  for (casadi_int d=0; d<nadj; ++d) {
290  asens[d][0] += diagcat(aseed[d]);
291  }
292  }
293 
294  Vertsplit::Vertsplit(const MX& x, const std::vector<casadi_int>& offset) : Split(x, offset) {
295 
296  // Split up the sparsity pattern
297  output_sparsity_ = vertsplit(x.sparsity(), offset_);
298 
299  // Have offset_ refer to the nonzero offsets instead of column offsets
300  offset_.resize(1);
301  for (auto&& s : output_sparsity_) {
302  offset_.push_back(offset_.back() + s.nnz());
303  }
304  }
305 
306  std::string Vertsplit::disp(const std::vector<std::string>& arg) const {
307  return "vertsplit(" + arg.at(0) + ")";
308  }
309 
310  void Vertsplit::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res,
311  const std::vector<bool>& unique) const {
312  // Get row offsets
313  std::vector<casadi_int> row_offset;
314  row_offset.reserve(offset_.size());
315  row_offset.push_back(0);
316  for (auto&& s : output_sparsity_) {
317  row_offset.push_back(row_offset.back() + s.size1());
318  }
319 
320  res = vertsplit(arg[0], row_offset);
321  }
322 
323  void Vertsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
324  std::vector<std::vector<MX> >& fsens) const {
325  casadi_int nfwd = fsens.size();
326 
327  // Get row offsets
328  std::vector<casadi_int> row_offset;
329  row_offset.reserve(offset_.size());
330  row_offset.push_back(0);
331  for (auto&& s : output_sparsity_) {
332  row_offset.push_back(row_offset.back() + s.size1());
333  }
334 
335  for (casadi_int d=0; d<nfwd; ++d) {
336  fsens[d] = vertsplit(fseed[d][0], row_offset);
337  }
338  }
339 
340  void Vertsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
341  std::vector<std::vector<MX> >& asens) const {
342  casadi_int nadj = aseed.size();
343 
344  // Get row offsets
345  std::vector<casadi_int> row_offset;
346  row_offset.reserve(offset_.size());
347  row_offset.push_back(0);
348  for (auto&& s : output_sparsity_) {
349  row_offset.push_back(row_offset.back() + s.size1());
350  }
351 
352  for (casadi_int d=0; d<nadj; ++d) {
353  asens[d][0] += vertcat(aseed[d]);
354  }
355  }
356 
357  MX Horzsplit::get_horzcat(const std::vector<MX>& x) const {
358  std::vector<MX> X;
359  for (auto&& e : x) {
360  if (e.nnz()!=0) X.push_back(e);
361  }
362 
363  // Check x length
364  if (X.size()!=nout()) {
365  return MXNode::get_horzcat(x);
366  }
367 
368  // Check x content
369  for (casadi_int i=0; i<X.size(); ++i) {
370  if (!(X[i]->is_output() && X[i]->which_output()==i && X[i]->dep().get()==this)) {
371  return MXNode::get_horzcat(x);
372  }
373  }
374 
375  return sparsity_cast(dep(), MXNode::get_horzcat(x).sparsity());
376  }
377 
378  MX Vertsplit::get_vertcat(const std::vector<MX>& x) const {
379  // Check x length
380  if (x.size()!=nout()) {
381  return MXNode::get_vertcat(x);
382  }
383 
384  // Check x content
385  for (casadi_int i=0; i<x.size(); ++i) {
386  if (!(x[i]->is_output() && x[i]->which_output()==i && x[i]->dep().get()==this)) {
387  return MXNode::get_vertcat(x);
388  }
389  }
390 
391  // OK if reached this point
392  return dep();
393  }
394 
395  MX Diagsplit::get_diagcat(const std::vector<MX>& x) const {
396  // Check x length
397  if (x.size()!=nout()) {
398  return MXNode::get_diagcat(x);
399  }
400 
401  // Check x content
402  for (casadi_int i=0; i<x.size(); ++i) {
403  if (!(x[i]->is_output() && x[i]->which_output()==i && x[i]->dep().get()==this)) {
404  return MXNode::get_diagcat(x);
405  }
406  }
407 
408  // OK if reached this point
409  return dep();
410  }
411 
412 } // namespace casadi
Helper class for C code generation.
std::string work(casadi_int n, casadi_int sz, bool is_ref) const
std::string copy(const std::string &arg, std::size_t n, const std::string &res)
Create a copy operation.
std::string workel(casadi_int n) const
Helper class for Serialization.
void unpack(Sparsity &e)
Reconstruct an object from the input stream.
void ad_forward(const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens) const override
Calculate forward mode directional derivatives.
Definition: split.cpp:252
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res, const std::vector< bool > &unique={}) const override
Evaluate symbolically (MX)
Definition: split.cpp:235
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: split.cpp:231
MX get_diagcat(const std::vector< MX > &x) const override
Create a diagonal concatenation node.
Definition: split.cpp:395
Diagsplit(const MX &x, const std::vector< casadi_int > &offset1, const std::vector< casadi_int > &offset2)
Constructor.
Definition: split.cpp:214
void ad_reverse(const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens) const override
Calculate reverse mode directional derivatives.
Definition: split.cpp:273
Function object.
Definition: function.hpp:60
casadi_int nnz() const
Get the number of (structural) non-zero elements.
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: split.cpp:162
Horzsplit(const MX &x, const std::vector< casadi_int > &offset)
Constructor.
Definition: split.cpp:150
MX get_horzcat(const std::vector< MX > &x) const override
Create a horizontal concatenation node.
Definition: split.cpp:357
void ad_forward(const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens) const override
Calculate forward mode directional derivatives.
Definition: split.cpp:179
void ad_reverse(const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens) const override
Calculate reverse mode directional derivatives.
Definition: split.cpp:197
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res, const std::vector< bool > &unique={}) const override
Evaluate symbolically (MX)
Definition: split.cpp:166
virtual MX get_diagcat(const std::vector< MX > &x) const
Create a diagonal concatenation node.
Definition: mx_node.cpp:1165
const Sparsity & sparsity() const
Get the sparsity.
Definition: mx_node.hpp:410
casadi_int nnz(casadi_int i=0) const
Definition: mx_node.hpp:427
virtual casadi_int which_output() const
Get function output.
Definition: mx_node.cpp:336
const MX & dep(casadi_int ind=0) const
dependencies - functions that have to be evaluated before this one
Definition: mx_node.hpp:392
virtual void serialize_body(SerializingStream &s) const
Serialize an object without type information.
Definition: mx_node.cpp:530
void set_sparsity(const Sparsity &sparsity)
Set the sparsity.
Definition: mx_node.cpp:224
virtual MX get_horzcat(const std::vector< MX > &x) const
Create a horizontal concatenation node.
Definition: mx_node.cpp:1144
virtual MX get_vertcat(const std::vector< MX > &x) const
Create a vertical concatenation node (vectors only)
Definition: mx_node.cpp:1170
void set_dep(const MX &dep)
Set unary dependency.
Definition: mx_node.cpp:228
virtual bool is_output() const
Check if evaluation output.
Definition: mx_node.hpp:320
MX - Matrix expression.
Definition: mx.hpp:92
const Sparsity & sparsity() const
Get the sparsity pattern.
Definition: mx.cpp:612
The basic scalar symbolic class of CasADi.
Definition: sx_elem.hpp:75
Helper class for Serialization.
void pack(const Sparsity &e)
Serializes an object to the output stream.
casadi_int nnz() const
Get the number of (structural) non-zeros.
Definition: sparsity.cpp:148
static Sparsity scalar(bool dense_scalar=true)
Create a scalar sparsity pattern *.
Definition: sparsity.hpp:153
Split: Split into multiple expressions splitting the nonzeros.
Definition: split.hpp:43
Split(const MX &x, const std::vector< casadi_int > &offset)
Constructor.
Definition: split.cpp:44
Dict info() const override
Definition: split.cpp:142
void generate(CodeGenerator &g, const std::vector< casadi_int > &arg, const std::vector< casadi_int > &res, const std::vector< bool > &arg_is_ref, std::vector< bool > &res_is_ref) const override
Generate code for the operation.
Definition: split.cpp:106
void serialize_body(SerializingStream &s) const override
Serialize an object without type information.
Definition: split.cpp:38
std::vector< Sparsity > output_sparsity_
Definition: split.hpp:110
int eval_gen(const T **arg, T **res, casadi_int *iw, T *w) const
Evaluate the function (template)
Definition: split.cpp:61
std::vector< casadi_int > offset_
Definition: split.hpp:109
int eval(const double **arg, double **res, casadi_int *iw, double *w) const override
Evaluate the function numerically.
Definition: split.cpp:52
int eval_sx(const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w) const override
Evaluate the function symbolically (SX)
Definition: split.cpp:56
casadi_int nout() const override
Number of outputs.
Definition: split.hpp:54
int sp_reverse(bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const override
Propagate sparsity backwards.
Definition: split.cpp:90
~Split() override=0
Destructor.
Definition: split.cpp:49
int sp_forward(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const override
Propagate sparsity forward.
Definition: split.cpp:75
void ad_forward(const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens) const override
Calculate forward mode directional derivatives.
Definition: split.cpp:323
void ad_reverse(const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens) const override
Calculate reverse mode directional derivatives.
Definition: split.cpp:340
Vertsplit(const MX &x, const std::vector< casadi_int > &offset)
Constructor.
Definition: split.cpp:294
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: split.cpp:306
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res, const std::vector< bool > &unique={}) const override
Evaluate symbolically (MX)
Definition: split.cpp:310
MX get_vertcat(const std::vector< MX > &x) const override
Create a vertical concatenation node (vectors only)
Definition: split.cpp:378
The casadi namespace.
Definition: archiver.cpp:28
unsigned long long bvec_t
std::string str(const T &v)
String representation, any type.
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.