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 (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) const {
167  // Get column offsets
168  std::vector<casadi_int> col_offset;
169  col_offset.reserve(offset_.size());
170  col_offset.push_back(0);
171  for (auto&& s : output_sparsity_) {
172  col_offset.push_back(col_offset.back() + s.size2());
173  }
174 
175  res = horzsplit(arg[0], col_offset);
176  }
177 
178  void Horzsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
179  std::vector<std::vector<MX> >& fsens) const {
180  casadi_int nfwd = fsens.size();
181 
182  // Get column offsets
183  std::vector<casadi_int> col_offset;
184  col_offset.reserve(offset_.size());
185  col_offset.push_back(0);
186  for (auto&& s : output_sparsity_) {
187  col_offset.push_back(col_offset.back() + s.size2());
188  }
189 
190  // Non-differentiated output and forward sensitivities
191  for (casadi_int d=0; d<nfwd; ++d) {
192  fsens[d] = horzsplit(fseed[d][0], col_offset);
193  }
194  }
195 
196  void Horzsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
197  std::vector<std::vector<MX> >& asens) const {
198  casadi_int nadj = aseed.size();
199 
200  // Get column offsets
201  std::vector<casadi_int> col_offset;
202  col_offset.reserve(offset_.size());
203  col_offset.push_back(0);
204  for (auto&& s : output_sparsity_) {
205  col_offset.push_back(col_offset.back() + s.size2());
206  }
207 
208  for (casadi_int d=0; d<nadj; ++d) {
209  asens[d][0] += horzcat(aseed[d]);
210  }
211  }
212 
214  const std::vector<casadi_int>& offset1,
215  const std::vector<casadi_int>& offset2) : Split(x, offset1) {
216 
217  // Split up the sparsity pattern
218  output_sparsity_ = diagsplit(x.sparsity(), offset1, offset2);
219 
220  // Have offset_ refer to the nonzero offsets instead of column offsets
221  offset_.resize(1);
222  for (auto&& s : output_sparsity_) {
223  offset_.push_back(offset_.back() + s.nnz());
224  }
225 
226  casadi_assert(offset_.back()==x.nnz(),
227  "DiagSplit:: the presence of nonzeros outside the diagonal blocks in unsupported.");
228  }
229 
230  std::string Diagsplit::disp(const std::vector<std::string>& arg) const {
231  return "diagsplit(" + arg.at(0) + ")";
232  }
233 
234  void Diagsplit::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res) const {
235  // Get offsets
236  std::vector<casadi_int> offset1;
237  offset1.reserve(offset_.size());
238  offset1.push_back(0);
239  std::vector<casadi_int> offset2;
240  offset2.reserve(offset_.size());
241  offset2.push_back(0);
242  for (auto&& s : output_sparsity_) {
243  offset1.push_back(offset1.back() + s.size1());
244  offset2.push_back(offset2.back() + s.size2());
245  }
246 
247  res = diagsplit(arg[0], offset1, offset2);
248  }
249 
250  void Diagsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
251  std::vector<std::vector<MX> >& fsens) const {
252  casadi_int nfwd = fsens.size();
253  // Get offsets
254  std::vector<casadi_int> offset1;
255  offset1.reserve(offset_.size());
256  offset1.push_back(0);
257  std::vector<casadi_int> offset2;
258  offset2.reserve(offset_.size());
259  offset2.push_back(0);
260  for (auto&& s : output_sparsity_) {
261  offset1.push_back(offset1.back() + s.size1());
262  offset2.push_back(offset2.back() + s.size2());
263  }
264 
265  // Non-differentiated output and forward sensitivities
266  for (casadi_int d=0; d<nfwd; ++d) {
267  fsens[d] = diagsplit(fseed[d][0], offset1, offset2);
268  }
269  }
270 
271  void Diagsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
272  std::vector<std::vector<MX> >& asens) const {
273  casadi_int nadj = asens.size();
274 
275  // Get offsets
276  std::vector<casadi_int> offset1;
277  offset1.reserve(offset_.size());
278  offset1.push_back(0);
279  std::vector<casadi_int> offset2;
280  offset2.reserve(offset_.size());
281  offset2.push_back(0);
282  for (auto&& s : output_sparsity_) {
283  offset1.push_back(offset1.back() + s.size1());
284  offset2.push_back(offset2.back() + s.size2());
285  }
286 
287  for (casadi_int d=0; d<nadj; ++d) {
288  asens[d][0] += diagcat(aseed[d]);
289  }
290  }
291 
292  Vertsplit::Vertsplit(const MX& x, const std::vector<casadi_int>& offset) : Split(x, offset) {
293 
294  // Split up the sparsity pattern
295  output_sparsity_ = vertsplit(x.sparsity(), offset_);
296 
297  // Have offset_ refer to the nonzero offsets instead of column offsets
298  offset_.resize(1);
299  for (auto&& s : output_sparsity_) {
300  offset_.push_back(offset_.back() + s.nnz());
301  }
302  }
303 
304  std::string Vertsplit::disp(const std::vector<std::string>& arg) const {
305  return "vertsplit(" + arg.at(0) + ")";
306  }
307 
308  void Vertsplit::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res) const {
309  // Get row offsets
310  std::vector<casadi_int> row_offset;
311  row_offset.reserve(offset_.size());
312  row_offset.push_back(0);
313  for (auto&& s : output_sparsity_) {
314  row_offset.push_back(row_offset.back() + s.size1());
315  }
316 
317  res = vertsplit(arg[0], row_offset);
318  }
319 
320  void Vertsplit::ad_forward(const std::vector<std::vector<MX> >& fseed,
321  std::vector<std::vector<MX> >& fsens) const {
322  casadi_int nfwd = fsens.size();
323 
324  // Get row offsets
325  std::vector<casadi_int> row_offset;
326  row_offset.reserve(offset_.size());
327  row_offset.push_back(0);
328  for (auto&& s : output_sparsity_) {
329  row_offset.push_back(row_offset.back() + s.size1());
330  }
331 
332  for (casadi_int d=0; d<nfwd; ++d) {
333  fsens[d] = vertsplit(fseed[d][0], row_offset);
334  }
335  }
336 
337  void Vertsplit::ad_reverse(const std::vector<std::vector<MX> >& aseed,
338  std::vector<std::vector<MX> >& asens) const {
339  casadi_int nadj = aseed.size();
340 
341  // Get row offsets
342  std::vector<casadi_int> row_offset;
343  row_offset.reserve(offset_.size());
344  row_offset.push_back(0);
345  for (auto&& s : output_sparsity_) {
346  row_offset.push_back(row_offset.back() + s.size1());
347  }
348 
349  for (casadi_int d=0; d<nadj; ++d) {
350  asens[d][0] += vertcat(aseed[d]);
351  }
352  }
353 
354  MX Horzsplit::get_horzcat(const std::vector<MX>& x) const {
355  std::vector<MX> X;
356  for (auto&& e : x) {
357  if (e.nnz()!=0) X.push_back(e);
358  }
359 
360  // Check x length
361  if (X.size()!=nout()) {
362  return MXNode::get_horzcat(x);
363  }
364 
365  // Check x content
366  for (casadi_int i=0; i<X.size(); ++i) {
367  if (!(X[i]->is_output() && X[i]->which_output()==i && X[i]->dep().get()==this)) {
368  return MXNode::get_horzcat(x);
369  }
370  }
371 
372  return sparsity_cast(dep(), MXNode::get_horzcat(x).sparsity());
373  }
374 
375  MX Vertsplit::get_vertcat(const std::vector<MX>& x) const {
376  // Check x length
377  if (x.size()!=nout()) {
378  return MXNode::get_vertcat(x);
379  }
380 
381  // Check x content
382  for (casadi_int i=0; i<x.size(); ++i) {
383  if (!(x[i]->is_output() && x[i]->which_output()==i && x[i]->dep().get()==this)) {
384  return MXNode::get_vertcat(x);
385  }
386  }
387 
388  // OK if reached this point
389  return dep();
390  }
391 
392  MX Diagsplit::get_diagcat(const std::vector<MX>& x) const {
393  // Check x length
394  if (x.size()!=nout()) {
395  return MXNode::get_diagcat(x);
396  }
397 
398  // Check x content
399  for (casadi_int i=0; i<x.size(); ++i) {
400  if (!(x[i]->is_output() && x[i]->which_output()==i && x[i]->dep().get()==this)) {
401  return MXNode::get_diagcat(x);
402  }
403  }
404 
405  // OK if reached this point
406  return dep();
407  }
408 
409 } // 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:250
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: split.cpp:230
MX get_diagcat(const std::vector< MX > &x) const override
Create a diagonal concatenation node.
Definition: split.cpp:392
Diagsplit(const MX &x, const std::vector< casadi_int > &offset1, const std::vector< casadi_int > &offset2)
Constructor.
Definition: split.cpp:213
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res) const override
Evaluate symbolically (MX)
Definition: split.cpp:234
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:271
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:354
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:178
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:196
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res) 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:1118
const Sparsity & sparsity() const
Get the sparsity.
Definition: mx_node.hpp:372
casadi_int nnz(casadi_int i=0) const
Definition: mx_node.hpp:389
virtual casadi_int which_output() const
Get function output.
Definition: mx_node.cpp:334
const MX & dep(casadi_int ind=0) const
dependencies - functions that have to be evaluated before this one
Definition: mx_node.hpp:354
virtual void serialize_body(SerializingStream &s) const
Serialize an object without type information.
Definition: mx_node.cpp:523
void set_sparsity(const Sparsity &sparsity)
Set the sparsity.
Definition: mx_node.cpp:222
virtual MX get_horzcat(const std::vector< MX > &x) const
Create a horizontal concatenation node.
Definition: mx_node.cpp:1097
virtual MX get_vertcat(const std::vector< MX > &x) const
Create a vertical concatenation node (vectors only)
Definition: mx_node.cpp:1123
void set_dep(const MX &dep)
Set unary dependency.
Definition: mx_node.cpp:226
virtual bool is_output() const
Check if evaluation output.
Definition: mx_node.hpp:282
MX - Matrix expression.
Definition: mx.hpp:92
const Sparsity & sparsity() const
Get the sparsity pattern.
Definition: mx.cpp:592
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:103
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:102
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:320
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:337
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res) const override
Evaluate symbolically (MX)
Definition: split.cpp:308
Vertsplit(const MX &x, const std::vector< casadi_int > &offset)
Constructor.
Definition: split.cpp:292
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: split.cpp:304
MX get_vertcat(const std::vector< MX > &x) const override
Create a vertical concatenation node (vectors only)
Definition: split.cpp:375
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.