nlpsol.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 "nlpsol_impl.hpp"
27 #include "external.hpp"
28 #include "casadi/core/timing.hpp"
29 #include "nlp_builder.hpp"
30 #include "nlp_tools.hpp"
31 #include <cctype>
32 
33 namespace casadi {
34 
35  bool has_nlpsol(const std::string& name) {
36  return Nlpsol::has_plugin(name);
37  }
38 
39  void load_nlpsol(const std::string& name) {
40  Nlpsol::load_plugin(name);
41  }
42 
43  std::string doc_nlpsol(const std::string& name) {
44  return Nlpsol::getPlugin(name).doc;
45  }
46 
47  bool name_has_g(const std::string& name) {
48  size_t pos = name.find("g");
49 
50  // 'g' does not occur
51  if (pos == std::string::npos) return false;
52 
53  // Check if 'g' has a word boundary on the left
54  bool left = pos==0 || !isalnum(name[pos-1]);
55 
56  // Check if 'g' has a word boundary on the right
57  bool right = pos+1 == name.size() || !isalnum(name[pos+1]);
58 
59  return left && right;
60  }
61 
62  template<class X>
63  Function construct_nlpsol(const std::string& name, const std::string& solver,
64  const std::map<std::string, X>& nlp, const Dict& opts) {
65 
66  if (get_from_dict(opts, "detect_simple_bounds", false)) {
67  X x = get_from_dict(nlp, "x", X(0, 1));
68  X p = get_from_dict(nlp, "p", X(0, 1));
69  X f = get_from_dict(nlp, "f", X(0));
70  X g = get_from_dict(nlp, "g", X(0, 1));
71 
72  if (g.size1()>0 || g.size2()>0) {
73  // Dimension checks
74  casadi_assert(g.is_dense() && g.is_vector(),
75  "Expected a dense vector 'g', but got " + g.dim(true) + ".");
76  }
77 
78  // Read dimensions
79  casadi_int ng = g.size1();
80  casadi_int nx = x.size1();
81 
82  // Get constraint Jacobian sparsity
83  Sparsity sp = jacobian_sparsity(g, x).T();
84 
85  // Reset result vector
86  std::vector<bool> is_simple(ng, true);
87 
88  // Check nonlinearity
89  std::vector<bool> is_nonlin = which_depends(g, x, 2, true);
90 
91  const casadi_int* row = sp.colind();
92  for (casadi_int i=0;i<ng;++i) {
93  // Check if each row of jac_g_x only depends on one column
94  bool single_dependency = row[i+1]-row[i]==1;
95  is_simple[i] = single_dependency && !is_nonlin[i];
96  }
97 
98  // Full-indices of all simple constraints
99  std::vector<casadi_int> sgi = boolvec_to_index(is_simple);
100  std::vector<casadi_int> gi = boolvec_to_index(boolvec_not(is_simple));
101  X g_bounds = g(sgi);
102 
103  // Detect f2(p)x+f1(p)==0
104  Function gf = Function("gf", std::vector<X>{x, p},
105  std::vector<X>{jtimes(g_bounds, x, X::ones(nx, 1)), g_bounds});
106  casadi_assert_dev(!gf.has_free());
107 
108  std::vector<casadi_int> target_x;
109  // Loop over all constraints
110  for (casadi_int i=0;i<ng;++i) {
111  // Only treat simple ones
112  if (!is_simple[i]) continue;
113  target_x.push_back(sp.row()[row[i]]);
114  }
115 
116  Dict nlpsol_opts = opts;
117  nlpsol_opts["detect_simple_bounds_is_simple"] = is_simple;
118  nlpsol_opts["detect_simple_bounds_parts"] = gf;
119  nlpsol_opts["detect_simple_bounds_target_x"] = target_x;
120 
121  // Check for cache entries
122  Dict cache = get_from_dict(opts, "cache", Dict());
123  for (auto&& e : cache) {
124  const Function& f = e.second;
125 
126  // Check for cached Functions where g appears in in/out
127  bool needs_update = false;
128  for (casadi_int i=0;i<f.n_in();++i) {
129  // Does name contain 'g'?
130  if (name_has_g(f.name_in(i))) {
131  // Already has compated size
132  if (f.size1_in(i)==gi.size()) continue;
133  // Needs to be compacted
134  if (f.size1_in(i)==ng) needs_update = true;
135  // Structure not understood, fallback to higher-level sanity checking
136  }
137  }
138  for (casadi_int i=0;i<f.n_out();++i) {
139  if (name_has_g(f.name_out(i))) {
140  if (f.size1_out(i)==gi.size()) continue;
141  // Needs to be compacted
142  if (f.size1_out(i)==ng) needs_update = true;
143  // Structure not understood, fallback to higher-level sanity checking
144  }
145  }
146 
147  if (!needs_update) continue;
148 
149  // Arguments to create a wrapper
150  std::vector<X> args = f.sym_in<X>();
151  // Arguments to pass to the cached function
152  std::vector<X> f_args = args;
153 
154  for (casadi_int i=0;i<f.n_in();++i) {
155  if (name_has_g(f.name_in(i))) {
156  // Needs a compacted symbol
157  args[i] = X::sym(f.name_in(i), gi.size());
158 
159  // Perform projects
160  f_args[i] = X::zeros(ng);
161  f_args[i](gi) = args[i];
162  }
163  }
164 
165  // Peform call
166  std::vector<X> res;
167  f.call(f_args, res, false, false);
168 
169  for (casadi_int i=0;i<f.n_out();++i) {
170  if (name_has_g(f.name_out(i))) {
171  // Select compacted rows out of result
172  res[i] = res[i](gi, casadi::Slice());
173  }
174  }
175 
176  // Create wrapper
177  cache[e.first] = Function(f.name(), args, res, f.name_in(), f.name_out());
178  }
179  // Pass along potentially updated cache
180  nlpsol_opts["cache"] = cache;
181 
182  if (opts.find("equality")!=opts.end()) {
183  std::vector<bool> equality = opts.find("equality")->second;
184  nlpsol_opts["equality"] = vector_select(equality, is_simple, true);
185  }
186 
187  std::map<std::string, X> nlpsol_nlp = nlp;
188  nlpsol_nlp["g"] = g(gi);
189  return nlpsol(name, solver, Nlpsol::create_oracle(nlpsol_nlp, opts), nlpsol_opts);
190  } else {
191  return nlpsol(name, solver, Nlpsol::create_oracle(nlp, opts), opts);
192  }
193  }
194 
195  Function nlpsol(const std::string& name, const std::string& solver,
196  const SXDict& nlp, const Dict& opts) {
197  return construct_nlpsol(name, solver, nlp, opts);
198  }
199 
200  Function nlpsol(const std::string& name, const std::string& solver,
201  const MXDict& nlp, const Dict& opts) {
202  return construct_nlpsol(name, solver, nlp, opts);
203  }
204 
205  template<typename XType>
206  Function Nlpsol::create_oracle(const std::map<std::string, XType>& d,
207  const Dict& opts) {
208  std::vector<XType> nl_in(NL_NUM_IN), nl_out(NL_NUM_OUT);
209  for (auto&& i : d) {
210  if (i.first=="x") {
211  nl_in[NL_X]=i.second;
212  } else if (i.first=="p") {
213  nl_in[NL_P]=i.second;
214  } else if (i.first=="f") {
215  nl_out[NL_F]=i.second;
216  } else if (i.first=="g") {
217  nl_out[NL_G]=i.second;
218  } else {
219  casadi_error("No such field: " + i.first);
220  }
221  }
222  if (nl_out[NL_F].is_empty()) nl_out[NL_F] = 0;
223  if (nl_out[NL_G].is_empty()) nl_out[NL_G] = XType(0, 1);
224 
225  // Options for the oracle
226  Dict oracle_options;
227  Dict::const_iterator it = opts.find("oracle_options");
228  if (it != opts.end()) {
229  // "oracle_options" has been set
230  oracle_options = it->second;
231  } else {
232  // Propagate selected options from Nlpsol to oracle by default
233  for (const char* op : {"verbose", "regularity_check"}) {
234  it = opts.find(op);
235  if (it != opts.end()) {
236  oracle_options[op] = it->second;
237  }
238  }
239  }
240 
241  // Create oracle
242  return Function("nlp", nl_in, nl_out, NL_INPUTS, NL_OUTPUTS, oracle_options);
243  }
244 
245  Function nlpsol(const std::string& name, const std::string& solver,
246  const NlpBuilder& nl, const Dict& opts) {
247  MXDict nlp;
248  nlp["x"] = vertcat(nl.x);
249  nlp["f"] = nl.f;
250  nlp["g"] = vertcat(nl.g);
251  return nlpsol(name, solver, nlp, opts);
252  }
253 
254  Function nlpsol(const std::string& name, const std::string& solver,
255  const std::string& fname, const Dict& opts) {
256  // If fname ends with .c, JIT
257  if (fname.size()>2 && fname.compare(fname.size()-2, fname.size(), ".c")==0) {
258  Importer compiler(fname, "clang");
259  return nlpsol(name, solver, compiler, opts);
260  } else {
261  return nlpsol(name, solver, external("nlp", fname), opts);
262  }
263  }
264 
265  Function nlpsol(const std::string& name, const std::string& solver,
266  const Importer& compiler, const Dict& opts) {
267  return nlpsol(name, solver, external("nlp", compiler), opts);
268  }
269 
270  Function nlpsol(const std::string& name, const std::string& solver,
271  const Function& nlp, const Dict& opts) {
272  // Make sure that nlp is sound
273  if (nlp.has_free()) {
274  casadi_error("Cannot create '" + name + "' since " + str(nlp.get_free()) + " are free.");
275  }
276  return Function::create(Nlpsol::instantiate(name, solver, nlp), opts);
277  }
278 
279  std::vector<std::string> nlpsol_in() {
280  std::vector<std::string> ret(nlpsol_n_in());
281  for (size_t i=0; i<ret.size(); ++i) ret[i]=nlpsol_in(i);
282  return ret;
283  }
284 
285  std::vector<std::string> nlpsol_out() {
286  std::vector<std::string> ret(nlpsol_n_out());
287  for (size_t i=0; i<ret.size(); ++i) ret[i]=nlpsol_out(i);
288  return ret;
289  }
290 
291  double nlpsol_default_in(casadi_int ind) {
292  switch (ind) {
293  case NLPSOL_LBX:
294  case NLPSOL_LBG:
295  return -std::numeric_limits<double>::infinity();
296  case NLPSOL_UBX:
297  case NLPSOL_UBG:
298  return std::numeric_limits<double>::infinity();
299  default:
300  return 0;
301  }
302  }
303 
304  std::vector<double> nlpsol_default_in() {
305  std::vector<double> ret(nlpsol_n_in());
306  for (size_t i=0; i<ret.size(); ++i) ret[i]=nlpsol_default_in(i);
307  return ret;
308  }
309 
310  std::string nlpsol_in(casadi_int ind) {
311  switch (static_cast<NlpsolInput>(ind)) {
312  case NLPSOL_X0: return "x0";
313  case NLPSOL_P: return "p";
314  case NLPSOL_LBX: return "lbx";
315  case NLPSOL_UBX: return "ubx";
316  case NLPSOL_LBG: return "lbg";
317  case NLPSOL_UBG: return "ubg";
318  case NLPSOL_LAM_X0: return "lam_x0";
319  case NLPSOL_LAM_G0: return "lam_g0";
320  case NLPSOL_NUM_IN: break;
321  }
322  return std::string();
323  }
324 
325  std::string nlpsol_out(casadi_int ind) {
326  switch (static_cast<NlpsolOutput>(ind)) {
327  case NLPSOL_X: return "x";
328  case NLPSOL_F: return "f";
329  case NLPSOL_G: return "g";
330  case NLPSOL_LAM_X: return "lam_x";
331  case NLPSOL_LAM_G: return "lam_g";
332  case NLPSOL_LAM_P: return "lam_p";
333  case NLPSOL_NUM_OUT: break;
334  }
335  return std::string();
336  }
337 
338  casadi_int nlpsol_n_in() {
339  return NLPSOL_NUM_IN;
340  }
341 
342  casadi_int nlpsol_n_out() {
343  return NLPSOL_NUM_OUT;
344  }
345 
346  Nlpsol::Nlpsol(const std::string& name, const Function& oracle)
347  : OracleFunction(name, oracle) {
348 
349  // Set default options
350  callback_step_ = 1;
351  eval_errors_fatal_ = false;
352  warn_initial_bounds_ = false;
354  print_time_ = true;
355  calc_multipliers_ = false;
356  bound_consistency_ = false;
357  min_lam_ = 0;
358  calc_lam_x_ = calc_f_ = calc_g_ = false;
359  calc_lam_p_ = true;
360  no_nlp_grad_ = false;
361  error_on_fail_ = false;
362  sens_linsol_ = "qr";
363  }
364 
366  clear_mem();
367  }
368 
369  bool Nlpsol::is_a(const std::string& type, bool recursive) const {
370  return type=="Nlpsol" || (recursive && OracleFunction::is_a(type, recursive));
371  }
372 
374  switch (static_cast<NlpsolInput>(i)) {
375  case NLPSOL_X0:
376  case NLPSOL_LBX:
377  case NLPSOL_UBX:
378  case NLPSOL_LAM_X0:
379  return get_sparsity_out(NLPSOL_X);
380  case NLPSOL_LBG:
381  case NLPSOL_UBG:
382  case NLPSOL_LAM_G0:
383  return get_sparsity_out(NLPSOL_G);
384  case NLPSOL_P:
385  return oracle_.sparsity_in(NL_P);
386  case NLPSOL_NUM_IN: break;
387  }
388  return Sparsity();
389  }
390 
392  switch (static_cast<NlpsolOutput>(i)) {
393  case NLPSOL_F:
394  return oracle_.sparsity_out(NL_F);
395  case NLPSOL_X:
396  case NLPSOL_LAM_X:
397  return oracle_.sparsity_in(NL_X);
398  case NLPSOL_LAM_G:
399  case NLPSOL_G:
400  if (detect_simple_bounds_is_simple_.empty()) {
401  return oracle_.sparsity_out(NL_G);
402  } else {
404  }
405  case NLPSOL_LAM_P:
406  return get_sparsity_in(NLPSOL_P);
407  case NLPSOL_NUM_OUT: break;
408  }
409  return Sparsity();
410  }
411 
414  {{"iteration_callback",
415  {OT_FUNCTION,
416  "A function that will be called at each iteration with the solver as input. "
417  "Check documentation of Callback."}},
418  {"iteration_callback_step",
419  {OT_INT,
420  "Only call the callback function every few iterations."}},
421  {"iteration_callback_ignore_errors",
422  {OT_BOOL,
423  "If set to true, errors thrown by iteration_callback will be ignored."}},
424  {"ignore_check_vec",
425  {OT_BOOL,
426  "If set to true, the input shape of F will not be checked."}},
427  {"warn_initial_bounds",
428  {OT_BOOL,
429  "Warn if the initial guess does not satisfy LBX and UBX"}},
430  {"eval_errors_fatal",
431  {OT_BOOL,
432  "When errors occur during evaluation of f,g,...,"
433  "stop the iterations"}},
434  {"verbose_init",
435  {OT_BOOL,
436  "Print out timing information about "
437  "the different stages of initialization"}},
438  {"discrete",
439  {OT_BOOLVECTOR,
440  "Indicates which of the variables are discrete, i.e. integer-valued"}},
441  {"equality",
442  {OT_BOOLVECTOR,
443  "Indicate an upfront hint which of the constraints are equalities. "
444  "Some solvers may be able to exploit this knowledge. "
445  "When true, the corresponding lower and upper bounds are assumed equal. "
446  "When false, the corresponding bounds may be equal or different."}},
447  {"calc_multipliers",
448  {OT_BOOL,
449  "Calculate Lagrange multipliers in the Nlpsol base class"}},
450  {"calc_lam_x",
451  {OT_BOOL,
452  "Calculate 'lam_x' in the Nlpsol base class"}},
453  {"calc_lam_p",
454  {OT_BOOL,
455  "Calculate 'lam_p' in the Nlpsol base class"}},
456  {"calc_f",
457  {OT_BOOL,
458  "Calculate 'f' in the Nlpsol base class"}},
459  {"calc_g",
460  {OT_BOOL,
461  "Calculate 'g' in the Nlpsol base class"}},
462  {"no_nlp_grad",
463  {OT_BOOL,
464  "Prevent the creation of the 'nlp_grad' function"}},
465  {"bound_consistency",
466  {OT_BOOL,
467  "Ensure that primal-dual solution is consistent with the bounds"}},
468  {"min_lam",
469  {OT_DOUBLE,
470  "Minimum allowed multiplier value"}},
471  {"oracle_options",
472  {OT_DICT,
473  "Options to be passed to the oracle function"}},
474  {"sens_linsol",
475  {OT_STRING,
476  "Linear solver used for parametric sensitivities (default 'qr')."}},
477  {"sens_linsol_options",
478  {OT_DICT,
479  "Linear solver options used for parametric sensitivities."}},
480  {"detect_simple_bounds",
481  {OT_BOOL,
482  "Automatically detect simple bounds (lbx/ubx) (default false). "
483  "This is hopefully beneficial to speed and robustness but may also have adverse affects: "
484  "1) Subtleties in heuristics and stopping criteria may change the solution, "
485  "2) IPOPT may lie about multipliers of simple equality bounds unless "
486  "'fixed_variable_treatment' is set to 'relax_bounds'."}},
487  {"detect_simple_bounds_is_simple",
488  {OT_BOOLVECTOR,
489  "For internal use only."}},
490  {"detect_simple_bounds_parts",
491  {OT_FUNCTION,
492  "For internal use only."}},
493  {"detect_simple_bounds_target_x",
494  {OT_INTVECTOR,
495  "For internal use only."}}
496  }
497  };
498 
499  void Nlpsol::init(const Dict& opts) {
500  // Default options
501  bool expand = false;
502 
503  // Read options
504  for (auto&& op : opts) {
505  if (op.first=="expand") {
506  expand = op.second;
507  } else if (op.first=="detect_simple_bounds_is_simple") {
508  assign_vector(op.second.to_bool_vector(), detect_simple_bounds_is_simple_);
509  //detect_simple_bounds_is_simple_ = op.second.to_bool_vector();
510  } else if (op.first=="detect_simple_bounds_parts") {
511  detect_simple_bounds_parts_ = op.second;
512  } else if (op.first=="detect_simple_bounds_target_x") {
513  detect_simple_bounds_target_x_ = op.second;
514  }
515  }
516 
517  for (casadi_int i=0;i<detect_simple_bounds_is_simple_.size();++i) {
519  detect_simple_bounds_target_g_.push_back(i);
520  }
521  }
522 
523  // Not covered by oracle expansion
526  }
527 
528  // Call the initialization method of the base class
529  OracleFunction::init(opts);
530 
531  // Read options
532  for (auto&& op : opts) {
533  if (op.first=="iteration_callback") {
534  fcallback_ = op.second;
535  } else if (op.first=="iteration_callback_step") {
536  callback_step_ = op.second;
537  } else if (op.first=="eval_errors_fatal") {
538  eval_errors_fatal_ = op.second;
539  } else if (op.first=="warn_initial_bounds") {
540  warn_initial_bounds_ = op.second;
541  } else if (op.first=="iteration_callback_ignore_errors") {
543  } else if (op.first=="discrete") {
544  discrete_ = op.second;
545  } else if (op.first=="equality") {
546  equality_ = op.second;
547  } else if (op.first=="calc_multipliers") {
548  calc_multipliers_ = op.second;
549  } else if (op.first=="calc_lam_x") {
550  calc_lam_x_ = op.second;
551  } else if (op.first=="calc_lam_p") {
552  calc_lam_p_ = op.second;
553  } else if (op.first=="calc_f") {
554  calc_f_ = op.second;
555  } else if (op.first=="calc_g") {
556  calc_g_ = op.second;
557  } else if (op.first=="no_nlp_grad") {
558  no_nlp_grad_ = op.second;
559  } else if (op.first=="bound_consistency") {
560  bound_consistency_ = op.second;
561  } else if (op.first=="min_lam") {
562  min_lam_ = op.second;
563  } else if (op.first=="sens_linsol") {
564  sens_linsol_ = op.second.to_string();
565  } else if (op.first=="sens_linsol_options") {
566  sens_linsol_options_ = op.second;
567  }
568  }
569 
570  // Deprecated option
571  if (calc_multipliers_) {
572  calc_lam_x_ = true;
573  calc_lam_p_ = true;
574  }
575 
576  // Get dimensions
577  nx_ = nnz_out(NLPSOL_X);
578  np_ = nnz_in(NLPSOL_P);
580 
581  // No need to calculate non-existant quantities
582  if (np_==0) calc_lam_p_ = false;
583  if (ng_==0) calc_g_ = false;
584 
585  // Consistency check
586  if (no_nlp_grad_) {
587  casadi_assert(!calc_lam_p_, "Options 'no_nlp_grad' and 'calc_lam_p' inconsistent");
588  casadi_assert(!calc_lam_x_, "Options 'no_nlp_grad' and 'calc_lam_x' inconsistent");
589  casadi_assert(!calc_f_, "Options 'no_nlp_grad' and 'calc_f' inconsistent");
590  casadi_assert(!calc_g_, "Options 'no_nlp_grad' and 'calc_g' inconsistent");
591  }
592 
593  // Dimension checks
594  casadi_assert(sparsity_out_.at(NLPSOL_G).is_dense()
595  && sparsity_out_.at(NLPSOL_G).is_vector(),
596  "Expected a dense vector 'g', but got " + sparsity_out_.at(NLPSOL_G).dim(true) + ".");
597 
598  casadi_assert(sparsity_out_.at(NLPSOL_F).is_dense(),
599  "Expected a dense 'f', but got " + sparsity_out_.at(NLPSOL_F).dim(true) + ".");
600 
601  casadi_assert(sparsity_out_.at(NLPSOL_X).is_dense()
602  && sparsity_out_.at(NLPSOL_X).is_vector(),
603  "Expected a dense vector 'x', but got " + sparsity_out_.at(NLPSOL_X).dim(true) + ".");
604 
605  // Discrete marker
606  mi_ = false;
607  if (!discrete_.empty()) {
608  casadi_assert(discrete_.size()==nx_, "\"discrete\" option has wrong length");
609  if (std::find(discrete_.begin(), discrete_.end(), true)!=discrete_.end()) {
610  casadi_assert(integer_support(),
611  "Discrete variables require a solver with integer support");
612  mi_ = true;
613  }
614  }
615  if (!equality_.empty()) {
616  casadi_assert(equality_.size()==ng_, "\"equality\" option has wrong length. "
617  "Expected " + str(ng_) + " elements, but got " +
618  str(equality_.size()) + " instead.");
619  }
620 
621  set_nlpsol_prob();
622 
623  // Allocate memory
624  casadi_int sz_arg, sz_res, sz_w, sz_iw;
625  casadi_nlpsol_work(&p_nlp_, &sz_arg, &sz_res, &sz_iw, &sz_w);
626  alloc_arg(sz_arg, true);
627  alloc_res(sz_res, true);
628  alloc_iw(sz_iw, true);
629  alloc_w(sz_w, true);
630 
631  if (!fcallback_.is_null()) {
632  // Consistency checks
633  casadi_assert_dev(!fcallback_.is_null());
634  casadi_assert(fcallback_.n_out()==1 && fcallback_.numel_out()==1,
635  "Callback function must return a scalar.");
636  casadi_assert(fcallback_.n_in()==n_out_,
637  "Callback input signature must match the NLP solver output signature");
638  for (casadi_int i=0; i<n_out_; ++i) {
639  // Ignore empty arguments
640  if (fcallback_.sparsity_in(i).is_empty()) continue;
641  casadi_assert(fcallback_.size_in(i)==size_out(i),
642  "Callback function input size mismatch. For argument '" + nlpsol_out(i) + "', "
643  "callback has shape " + fcallback_.sparsity_in(i).dim() + " while NLP has " +
644  sparsity_out_.at(i).dim() + ".");
645  // TODO(@jaeandersson): Wrap fcallback_ in a function with correct sparsity
646  casadi_assert(fcallback_.sparsity_in(i)==sparsity_out_.at(i),
647  "Callback function input size mismatch. "
648  "For argument " + nlpsol_out(i) + "', callback has shape " +
649  fcallback_.sparsity_in(i).dim() + " while NLP has " +
650  sparsity_out_.at(i).dim() + ".");
651  }
652 
653  // Allocate temporary memory
654  alloc(fcallback_);
655  }
656 
657  // Function calculating f, g and the gradient of the Lagrangian w.r.t. x and p
658  if (!no_nlp_grad_) {
659  create_function("nlp_grad", {"x", "p", "lam:f", "lam:g"},
660  {"f", "g", "grad:gamma:x", "grad:gamma:p"},
661  {{"gamma", {"f", "g"}}});
662  }
663  }
664 
665  int detect_bounds_callback(const double** arg, double** res,
666  casadi_int* iw, double* w, void* callback_data) {
667  Function* f = static_cast<Function*>(callback_data);
668  return f->operator()(arg, res, iw, w);
669  }
670 
671  void Nlpsol::set_nlpsol_prob() {
672  p_nlp_.nx = nx_;
673  p_nlp_.ng = ng_;
674  p_nlp_.np = np_;
675 
679 
680  if (p_nlp_.detect_bounds.ng) {
689  }
690  }
691 
692  int Nlpsol::init_mem(void* mem) const {
693  if (OracleFunction::init_mem(mem)) return 1;
694  auto *m = static_cast<NlpsolMemory*>(mem);
695  m->add_stat("callback_fun");
696  m->success = false;
697  m->d_nlp.prob = nullptr;
698  m->unified_return_status = SOLVER_RET_UNKNOWN;
699  return 0;
700  }
701 
702  void Nlpsol::check_inputs(void* mem) const {
703  auto *m = static_cast<NlpsolMemory*>(mem);
704  auto *d_nlp = &m->d_nlp;
705 
706  // Skip check?
707  if (!inputs_check_) return;
708 
709  const double inf = std::numeric_limits<double>::infinity();
710 
711  // Number of equality constraints
712  casadi_int n_eq = 0;
713 
714  // Detect ill-posed problems (simple bounds)
715  for (casadi_int i=0; i<nx_; ++i) {
716  double lb = d_nlp->lbx ? d_nlp->lbx[i] : get_default_in(NLPSOL_LBX);
717  double ub = d_nlp->ubx ? d_nlp->ubx[i] : get_default_in(NLPSOL_UBX);
718  double x0 = d_nlp->x0 ? d_nlp->x0[i] : get_default_in(NLPSOL_X0);
719  casadi_assert(lb <= ub && lb!=inf && ub!=-inf,
720  "Ill-posed problem detected: "
721  "LBX[" + str(i) + "] <= UBX[" + str(i) + "] was violated. "
722  "Got LBX[" + str(i) + "]=" + str(lb) + " and UBX[" + str(i) + "] = " + str(ub) + ".");
723  if (warn_initial_bounds_ && (x0>ub || x0<lb)) {
724  casadi_warning("Nlpsol: The initial guess does not satisfy LBX and UBX. "
725  "Option 'warn_initial_bounds' controls this warning.");
726  break;
727  }
728  if (lb==ub) n_eq++;
729  }
730 
731  // Detect ill-posed problems (nonlinear bounds)
732  for (casadi_int i=0; i<nnz_out(NLPSOL_G); ++i) {
733  double lb = d_nlp->lbg ? d_nlp->lbg[i] : get_default_in(NLPSOL_LBG);
734  double ub = d_nlp->ubg ? d_nlp->ubg[i] : get_default_in(NLPSOL_UBG);
735  casadi_assert(lb <= ub && lb!=inf && ub!=-inf,
736  "Ill-posed problem detected: "
737  "LBG[" + str(i) + "] <= UBG[" + str(i) + "] was violated. "
738  "Got LBG[" + str(i) + "] = " + str(lb) + " and UBG[" + str(i) + "] = " + str(ub) + ".");
739  if (lb==ub) n_eq++;
740  }
741 
742  // Make sure enough degrees of freedom
743  using casadi::str; // Workaround, MingGW bug, cf. CasADi issue #890
744  if (n_eq> nx_) {
745  casadi_warning("NLP is overconstrained: There are " + str(n_eq) +
746  " equality constraints but only " + str(nx_) + " variables.");
747  }
748  }
749 
750  std::map<std::string, Nlpsol::Plugin> Nlpsol::solvers_;
751 
752 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
753  std::mutex Nlpsol::mutex_solvers_;
754 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
755 
756  const std::string Nlpsol::infix_ = "nlpsol";
757 
759  casadi_error("getReducedHessian not defined for class " + class_name());
760  return DM();
761  }
762 
763  void Nlpsol::setOptionsFromFile(const std::string & file) {
764  casadi_error("setOptionsFromFile not defined for class " + class_name());
765  }
766 
767  void Nlpsol::bound_consistency(casadi_int n, double* z, double* lam,
768  const double* lbz, const double* ubz) {
769  casadi_assert_dev(z!=nullptr);
770  casadi_assert_dev(lam!=nullptr);
771  casadi_assert_dev(lbz!=nullptr);
772  casadi_assert_dev(ubz!=nullptr);
773  // Local variables
774  casadi_int i;
775  // Loop over variables
776  for (i=0; i<n; ++i) {
777  // Make sure bounds are respected
778  z[i] = std::fmin(std::fmax(z[i], lbz[i]), ubz[i]);
779  // Adjust multipliers
780  if (std::isinf(lbz[i]) && std::isinf(ubz[i])) {
781  // Both multipliers are infinite
782  lam[i] = 0.;
783  } else if (std::isinf(lbz[i]) || z[i] - lbz[i] > ubz[i] - z[i]) {
784  // Infinite lower bound or closer to upper bound than lower bound
785  lam[i] = std::fmax(0., lam[i]);
786  } else if (std::isinf(ubz[i]) || z[i] - lbz[i] < ubz[i] - z[i]) {
787  // Infinite upper bound or closer to lower bound than upper bound
788  lam[i] = std::fmin(0., lam[i]);
789  }
790  }
791  }
792 
793  int Nlpsol::eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const {
794  auto *m = static_cast<NlpsolMemory*>(mem);
795 
796  auto *d_nlp = &m->d_nlp;
797 
798  // Reset the solver, prepare for solution
799  setup(m, arg, res, iw, w);
800  const auto *p_nlp = d_nlp->prob;
801 
802  // Set initial guess
803  casadi_copy(d_nlp->x0, nx_, d_nlp->z);
804 
805  // Read simple bounds and multiplier guesses
806  casadi_copy(d_nlp->lbx, nx_, d_nlp->lbz);
807  casadi_copy(d_nlp->ubx, nx_, d_nlp->ubz);
808  casadi_copy(d_nlp->lam_x0, nx_, d_nlp->lam);
809 
810  if (p_nlp->detect_bounds.ng==0) {
811  // Read constraint bounds and multiplier guesses
812  casadi_copy(d_nlp->lbg, ng_, d_nlp->lbz+nx_);
813  casadi_copy(d_nlp->ubg, ng_, d_nlp->ubz+nx_);
814  casadi_copy(d_nlp->lam_g0, ng_, d_nlp->lam+nx_);
815  } else {
816  if (casadi_nlpsol_detect_bounds_before(d_nlp)) return 1;
817  }
818 
819  // Set multipliers to nan
820  casadi_fill(d_nlp->lam_p, np_, nan);
821 
822  // Reset f, g
823  d_nlp->objective = nan;
824  casadi_fill(d_nlp->z + nx_, ng_, nan);
825 
826  // Check the provided inputs
827  check_inputs(m);
828 
829  // Solve the NLP
830  int flag = solve(m);
831 
832  // Join statistics (introduced for parallel oracle facilities)
833  join_results(m);
834 
835  // Calculate multiplers
836  if ((calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_) && !flag) {
837  const double lam_f = 1.;
838  m->arg[0] = d_nlp->z;
839  m->arg[1] = d_nlp->p;
840  m->arg[2] = &lam_f;
841  m->arg[3] = d_nlp->lam + nx_;
842  m->res[0] = calc_f_ ? &d_nlp->objective : nullptr;
843  m->res[1] = calc_g_ ? d_nlp->z + nx_ : nullptr;
844  m->res[2] = calc_lam_x_ ? d_nlp->lam : nullptr;
845  m->res[3] = calc_lam_p_ ? d_nlp->lam_p : nullptr;
846  if (calc_function(m, "nlp_grad")) {
847  casadi_warning("Failed to calculate multipliers");
848  }
849  if (calc_lam_x_) casadi_scal(nx_, -1., d_nlp->lam);
850  if (calc_lam_p_) casadi_scal(np_, -1., d_nlp->lam_p);
851  }
852 
853  // Make sure that an optimal solution is consistant with bounds
854  if (bound_consistency_ && !flag) {
855  bound_consistency(nx_+ng_, d_nlp->z, d_nlp->lam, d_nlp->lbz, d_nlp->ubz);
856  }
857 
858  // Get optimal solution
859  casadi_copy(d_nlp->z, nx_, d_nlp->x);
860 
861  if (p_nlp->detect_bounds.ng==0) {
862  casadi_copy(d_nlp->z + nx_, ng_, d_nlp->g);
863  casadi_copy(d_nlp->lam, nx_, d_nlp->lam_x);
864  casadi_copy(d_nlp->lam + nx_, ng_, d_nlp->lam_g);
865  } else {
866  if (casadi_nlpsol_detect_bounds_after(d_nlp)) return 1;
867  }
868 
869  casadi_copy(d_nlp->lam_p, np_, d_nlp->lam_p);
870  casadi_copy(&d_nlp->objective, 1, d_nlp->f);
871 
872  if (m->success) m->unified_return_status = SOLVER_RET_SUCCESS;
873 
874  if (error_on_fail_ && !m->success)
875  casadi_error("nlpsol process failed. "
876  "Set 'error_on_fail' option to false to ignore this error.");
877 
878  if (m->unified_return_status==SOLVER_RET_EXCEPTION) {
879  casadi_error("An exception was raised in the solver.");
880  }
881  return flag;
882  }
883 
884  void Nlpsol::set_work(void* mem, const double**& arg, double**& res,
885  casadi_int*& iw, double*& w) const {
886  auto *m = static_cast<NlpsolMemory*>(mem);
887 
888  // Problem has not been solved at this point
889  m->success = false;
890  m->unified_return_status = SOLVER_RET_UNKNOWN;
891 
892  m->d_nlp.prob = &p_nlp_;
893  m->d_nlp.oracle = &m->d_oracle;
894 
895  casadi_nlpsol_data<double>& d_nlp = m->d_nlp;
896  d_nlp.p = arg[NLPSOL_P];
897  d_nlp.lbx = arg[NLPSOL_LBX];
898  d_nlp.ubx = arg[NLPSOL_UBX];
899  d_nlp.lbg = arg[NLPSOL_LBG];
900  d_nlp.ubg = arg[NLPSOL_UBG];
901  d_nlp.x0 = arg[NLPSOL_X0];
902  d_nlp.lam_x0 = arg[NLPSOL_LAM_X0];
903  d_nlp.lam_g0 = arg[NLPSOL_LAM_G0];
904 
905  d_nlp.x = res[NLPSOL_X];
906  d_nlp.f = res[NLPSOL_F];
907  d_nlp.g = res[NLPSOL_G];
908  d_nlp.lam_x = res[NLPSOL_LAM_X];
909  d_nlp.lam_g = res[NLPSOL_LAM_G];
910  d_nlp.lam_p = res[NLPSOL_LAM_P];
911 
912 
913  arg += NLPSOL_NUM_IN;
914  res += NLPSOL_NUM_OUT;
915 
916  casadi_nlpsol_set_work(&m->d_nlp, &arg, &res, &iw, &w);
917  }
918 
919  std::vector<std::string> nlpsol_options(const std::string& name) {
920  return Nlpsol::plugin_options(name).all();
921  }
922 
923  std::string nlpsol_option_type(const std::string& name, const std::string& op) {
924  return Nlpsol::plugin_options(name).type(op);
925  }
926 
927  std::string nlpsol_option_info(const std::string& name, const std::string& op) {
928  return Nlpsol::plugin_options(name).info(op);
929  }
930 
931  void Nlpsol::disp_more(std::ostream& stream) const {
932  stream << "minimize f(x;p) subject to lbx<=x<=ubx, lbg<=g(x;p)<=ubg defined by:\n";
933  oracle_.disp(stream, true);
934  }
935 
937 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
938  // Safe access to kkt_
939  std::lock_guard<std::mutex> lock(kkt_mtx_);
940 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
941  // Quick return if cached
942  SharedObject temp;
943  if (kkt_.shared_if_alive(temp)) {
944  return shared_cast<Function>(temp);
945  }
946 
947  // Generate KKT function
948  Function ret = oracle_.factory("kkt", {"x", "p", "lam:f", "lam:g"},
949  {"jac:g:x", "hess:gamma:x:x"}, {{"gamma", {"f", "g"}}});
950 
951  // Cache and return
952  kkt_ = ret;
953  return ret;
954  }
955 
956 
958  get_forward(casadi_int nfwd, const std::string& name,
959  const std::vector<std::string>& inames,
960  const std::vector<std::string>& onames,
961  const Dict& opts) const {
962  casadi_assert(detect_simple_bounds_is_simple_.empty(),
963  "Simple bound detection not compatible with get_forward");
964 
965  // Symbolic expression for the input
966  std::vector<MX> arg = mx_in(), res = mx_out();
967 
968  // Initial guesses not used for derivative calculations
970  std::string name = arg[i].is_symbolic() ? arg[i].name() : "tmp_get_forward";
971  arg[i] = MX::sym(name, Sparsity(arg[i].size()));
972  }
973 
974  // Optimal solution
975  MX x = res[NLPSOL_X];
976  MX lam_g = res[NLPSOL_LAM_G];
977  MX lam_x = res[NLPSOL_LAM_X];
978  MX lam_p = res[NLPSOL_LAM_P];
979  MX f = res[NLPSOL_F];
980  MX g = res[NLPSOL_G];
981 
982  // Inputs used
983  MX lbx = arg[NLPSOL_LBX];
984  MX ubx = arg[NLPSOL_UBX];
985  MX lbg = arg[NLPSOL_LBG];
986  MX ubg = arg[NLPSOL_UBG];
987  MX p = arg[NLPSOL_P];
988 
989  // Get KKT function
990  Function kkt = this->kkt();
991 
992  // Hessian of the Lagrangian, Jacobian of the constraints
993  std::vector<MX> HJ_res = kkt({x, p, 1, lam_g});
994  MX JG = HJ_res.at(0);
995  MX HL = HJ_res.at(1);
996 
997  // Active set (assumed known and given by the multiplier signs)
998  MX ubIx = lam_x > min_lam_;
999  MX lbIx = lam_x < -min_lam_;
1000  MX bIx = ubIx + lbIx;
1001  MX iIx = 1-bIx;
1002  MX ubIg = lam_g > min_lam_;
1003  MX lbIg = lam_g < -min_lam_;
1004  MX bIg = ubIg + lbIg;
1005  MX iIg = 1-bIg;
1006 
1007  // KKT matrix
1008  MX H_11 = mtimes(diag(iIx), HL) + diag(bIx);
1009  MX H_12 = mtimes(diag(iIx), JG.T());
1010  MX H_21 = mtimes(diag(bIg), JG);
1011  MX H_22 = diag(-iIg);
1012  MX H = MX::blockcat({{H_11, H_12}, {H_21, H_22}});
1013 
1014  // Sensitivity inputs
1015  std::vector<MX> fseed(NLPSOL_NUM_IN);
1016  MX fwd_lbx = fseed[NLPSOL_LBX] = MX::sym("fwd_lbx", repmat(x.sparsity(), 1, nfwd));
1017  MX fwd_ubx = fseed[NLPSOL_UBX] = MX::sym("fwd_ubx", repmat(x.sparsity(), 1, nfwd));
1018  MX fwd_lbg = fseed[NLPSOL_LBG] = MX::sym("fwd_lbg", repmat(g.sparsity(), 1, nfwd));
1019  MX fwd_ubg = fseed[NLPSOL_UBG] = MX::sym("fwd_ubg", repmat(g.sparsity(), 1, nfwd));
1020  MX fwd_p = fseed[NLPSOL_P] = MX::sym("fwd_p", repmat(p.sparsity(), 1, nfwd));
1021 
1022  // Guesses are unused
1024  fseed[i] = MX(repmat(Sparsity(arg[i].size()), 1, nfwd));
1025  }
1026 
1027  // nlp_grad has the signature
1028  // (x, p, lam_f, lam_g) -> (f, g, grad_x, grad_p)
1029  // with lam_f=1 and lam_g=lam_g, grad_x = -lam_x, grad_p=-lam_p
1030  Function nlp_grad = get_function("nlp_grad");
1031 
1032  // fwd_nlp_grad has the signature
1033  // (x, p, lam_f, lam_g, f, g, grad_x, grad_p,
1034  // fwd_x, fwd_p, fwd_lam_f, fwd_lam_g)
1035  // -> (fwd_f, fwd_g, fwd_grad_x, fwd_grad_p)
1036  Function fwd_nlp_grad = nlp_grad.forward(nfwd);
1037 
1038  // Calculate sensitivities from fwd_p
1039  std::vector<MX> vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p, 0., fwd_p, 0., 0.};
1040  vv = fwd_nlp_grad(vv);
1041  MX fwd_g_p = vv.at(1);
1042  MX fwd_gL_p = vv.at(2);
1043 
1044  // Propagate forward seeds
1045  MX fwd_alpha_x = (if_else(lbIx, fwd_lbx, 0) + if_else(ubIx, fwd_ubx, 0))
1046  - if_else(iIx, fwd_gL_p, 0);
1047  MX fwd_alpha_g = (if_else(ubIg, fwd_ubg, 0) + if_else(lbIg, fwd_lbg, 0))
1048  - if_else(bIg, fwd_g_p, 0);
1049  MX v = MX::vertcat({fwd_alpha_x, fwd_alpha_g});
1050 
1051  // Solve
1053 
1054  // Extract sensitivities in x, lam_x and lam_g
1055  std::vector<MX> v_split = vertsplit(v, {0, nx_, nx_+ng_});
1056  MX fwd_x = v_split.at(0);
1057  MX fwd_lam_g = v_split.at(1);
1058 
1059  // Calculate sensitivities in lam_x, lam_g
1060  vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1061  fwd_x, fwd_p, 0, fwd_lam_g};
1062  vv = fwd_nlp_grad(vv);
1063  MX fwd_f = vv.at(0);
1064  MX fwd_g = vv.at(1);
1065  MX fwd_lam_x = -vv.at(2);
1066  MX fwd_lam_p = -vv.at(3);
1067 
1068  // Forward sensitivities
1069  std::vector<MX> fsens(NLPSOL_NUM_OUT);
1070  fsens[NLPSOL_X] = fwd_x;
1071  fsens[NLPSOL_F] = fwd_f;
1072  fsens[NLPSOL_G] = fwd_g;
1073  fsens[NLPSOL_LAM_X] = fwd_lam_x;
1074  fsens[NLPSOL_LAM_G] = fwd_lam_g;
1075  fsens[NLPSOL_LAM_P] = fwd_lam_p;
1076 
1077  // Gather return values
1078  arg.insert(arg.end(), res.begin(), res.end());
1079  arg.insert(arg.end(), fseed.begin(), fseed.end());
1080  res = fsens;
1081 
1082  Dict options = opts;
1083  options["allow_duplicate_io_names"] = true;
1084 
1085  return Function(name, arg, res, inames, onames, options);
1086  }
1087 
1089  get_reverse(casadi_int nadj, const std::string& name,
1090  const std::vector<std::string>& inames,
1091  const std::vector<std::string>& onames,
1092  const Dict& opts) const {
1093  casadi_assert(detect_simple_bounds_is_simple_.empty(),
1094  "Simple bound detection not compatible with get_reverse");
1095 
1096  // Symbolic expression for the input
1097  std::vector<MX> arg = mx_in(), res = mx_out();
1098 
1099  // Initial guesses not used for derivative calculations
1101  std::string name = arg[i].is_symbolic() ? arg[i].name() : "tmp_get_reverse";
1102  arg[i] = MX::sym(name, Sparsity(arg[i].size()));
1103  }
1104 
1105  // Optimal solution
1106  MX x = res[NLPSOL_X];
1107  MX lam_g = res[NLPSOL_LAM_G];
1108  MX lam_x = res[NLPSOL_LAM_X];
1109  MX lam_p = res[NLPSOL_LAM_P];
1110  MX f = res[NLPSOL_F];
1111  MX g = res[NLPSOL_G];
1112 
1113  // Inputs used
1114  MX lbx = arg[NLPSOL_LBX];
1115  MX ubx = arg[NLPSOL_UBX];
1116  MX lbg = arg[NLPSOL_LBG];
1117  MX ubg = arg[NLPSOL_UBG];
1118  MX p = arg[NLPSOL_P];
1119 
1120  // Get KKT function
1121  Function kkt = this->kkt();
1122 
1123  // Hessian of the Lagrangian, Jacobian of the constraints
1124  std::vector<MX> HJ_res = kkt({x, p, 1, lam_g});
1125  MX JG = HJ_res.at(0);
1126  MX HL = HJ_res.at(1);
1127 
1128  // Active set (assumed known and given by the multiplier signs)
1129  MX ubIx = lam_x > min_lam_;
1130  MX lbIx = lam_x < -min_lam_;
1131  MX bIx = ubIx + lbIx;
1132  MX iIx = 1-bIx;
1133  MX ubIg = lam_g > min_lam_;
1134  MX lbIg = lam_g < -min_lam_;
1135  MX bIg = ubIg + lbIg;
1136  MX iIg = 1-bIg;
1137 
1138  // KKT matrix
1139  MX H_11 = mtimes(diag(iIx), HL) + diag(bIx);
1140  MX H_12 = mtimes(diag(iIx), JG.T());
1141  MX H_21 = mtimes(diag(bIg), JG);
1142  MX H_22 = diag(-iIg);
1143  MX H = MX::blockcat({{H_11, H_12}, {H_21, H_22}});
1144 
1145  // Sensitivity inputs
1146  std::vector<MX> aseed(NLPSOL_NUM_OUT);
1147  MX adj_x = aseed[NLPSOL_X] = MX::sym("adj_x", repmat(x.sparsity(), 1, nadj));
1148  MX adj_lam_g = aseed[NLPSOL_LAM_G] = MX::sym("adj_lam_g", repmat(g.sparsity(), 1, nadj));
1149  MX adj_lam_x = aseed[NLPSOL_LAM_X] = MX::sym("adj_lam_x", repmat(x.sparsity(), 1, nadj));
1150  MX adj_lam_p = aseed[NLPSOL_LAM_P] = MX::sym("adj_lam_p", repmat(p.sparsity(), 1, nadj));
1151  MX adj_f = aseed[NLPSOL_F] = MX::sym("adj_f", Sparsity::dense(1, nadj));
1152  MX adj_g = aseed[NLPSOL_G] = MX::sym("adj_g", repmat(g.sparsity(), 1, nadj));
1153 
1154  // nlp_grad has the signature
1155  // (x, p, lam_f, lam_g) -> (f, g, grad_x, grad_p)
1156  // with lam_f=1 and lam_g=lam_g, grad_x = -lam_x, grad_p=-lam_p
1157  Function nlp_grad = get_function("nlp_grad");
1158 
1159  // rev_nlp_grad has the signature
1160  // (x, p, lam_f, lam_g, f, g, grad_x, grad_p,
1161  // adj_f, adj_g, adj_grad_x, adj_grad_p)
1162  // -> (adj_x, adj_p, adj_lam_f, adj_lam_g)
1163  Function rev_nlp_grad = nlp_grad.reverse(nadj);
1164 
1165  // Calculate sensitivities from f, g and lam_x
1166  std::vector<MX> vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1167  adj_f, adj_g, -adj_lam_x, -adj_lam_p};
1168  vv = rev_nlp_grad(vv);
1169  MX adj_x0 = vv.at(0);
1170  MX adj_p0 = vv.at(1);
1171  MX adj_lam_g0 = vv.at(3);
1172 
1173  // Solve to get beta_x_bar, beta_g_bar
1174  MX v = MX::vertcat({adj_x + adj_x0, adj_lam_g + adj_lam_g0});
1176  std::vector<MX> v_split = vertsplit(v, {0, nx_, nx_+ng_});
1177  MX beta_x_bar = v_split.at(0);
1178  MX beta_g_bar = v_split.at(1);
1179 
1180  // Calculate sensitivities in p
1181  vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1182  0, bIg*beta_g_bar, iIx*beta_x_bar, 0};
1183  vv = rev_nlp_grad(vv);
1184  MX adj_p = vv.at(1);
1185 
1186  // Reverse sensitivities
1187  std::vector<MX> asens(NLPSOL_NUM_IN);
1188  asens[NLPSOL_UBX] = if_else(ubIx, beta_x_bar, 0);
1189  asens[NLPSOL_LBX] = if_else(lbIx, beta_x_bar, 0);
1190  asens[NLPSOL_UBG] = if_else(ubIg, beta_g_bar, 0);
1191  asens[NLPSOL_LBG] = if_else(lbIg, beta_g_bar, 0);
1192  asens[NLPSOL_P] = adj_p0 - adj_p;
1193 
1194  // Guesses are unused
1196  asens[i] = MX(repmat(Sparsity(arg[i].size()), 1, nadj));
1197  }
1198 
1199  // Gather return values
1200  arg.insert(arg.end(), res.begin(), res.end());
1201  arg.insert(arg.end(), aseed.begin(), aseed.end());
1202  res = asens;
1203 
1204  Dict options = opts;
1205  options["allow_duplicate_io_names"] = true;
1206 
1207  return Function(name, arg, res, inames, onames, options);
1208  }
1209 
1211  // Quick return if no callback function
1212  if (fcallback_.is_null()) return 0;
1213  // Callback inputs
1214  std::fill_n(m->arg, fcallback_.n_in(), nullptr);
1215 
1216  auto *d_nlp = &m->d_nlp;
1217 
1218  m->arg[NLPSOL_X] = d_nlp->z;
1219  m->arg[NLPSOL_F] = &d_nlp->objective;
1220  m->arg[NLPSOL_G] = d_nlp->z + nx_;
1221  m->arg[NLPSOL_LAM_G] = d_nlp->lam + nx_;
1222  m->arg[NLPSOL_LAM_X] = d_nlp->lam;
1223 
1224  // Callback outputs
1225  std::fill_n(m->res, fcallback_.n_out(), nullptr);
1226  double ret = 0;
1227  m->res[0] = &ret;
1228 
1229  // Start timer
1230  m->fstats.at("callback_fun").tic();
1231  try {
1232  // Evaluate
1233  fcallback_(m->arg, m->res, m->iw, m->w, 0);
1234  } catch(KeyboardInterruptException& ex) {
1235  (void)ex; // unused
1236  throw;
1237  } catch(std::exception& ex) {
1238  print("WARNING: intermediate_callback error: %s\n", ex.what());
1240  }
1241 
1242  // User user interruption?
1243  if (static_cast<casadi_int>(ret)) return 1;
1244 
1245  // Stop timer
1246  m->fstats.at("callback_fun").toc();
1247 
1248  return 0;
1249  }
1250 
1251  Dict Nlpsol::get_stats(void* mem) const {
1252  Dict stats = OracleFunction::get_stats(mem);
1253  auto *m = static_cast<NlpsolMemory*>(mem);
1254  casadi_assert(m->d_nlp.prob,
1255  "No stats available: nlp Solver instance has not yet been called with numerical arguments.");
1256  auto *d_nlp = &m->d_nlp;
1257  stats["success"] = m->success;
1258  stats["unified_return_status"] = string_from_UnifiedReturnStatus(m->unified_return_status);
1259  if (d_nlp->prob && d_nlp->prob->detect_bounds.ng) {
1260  std::vector<bool> is_simple;
1262  stats["detect_simple_bounds_is_simple"] = is_simple;
1263  stats["detect_simple_bounds_target_x"] = detect_simple_bounds_target_x_;
1264  }
1265  return stats;
1266  }
1267 
1270  g.local("d_nlp", "struct casadi_nlpsol_data");
1271  g.local("p_nlp", "struct casadi_nlpsol_prob");
1272  codegen_setup_constants(g, "d_nlp", "p_nlp", "d_oracle");
1273  codegen_setup_per_call(g, "d_nlp");
1274  }
1275 
1276  // Per-Function-instance constants: nx/ng/np, detect_bounds descriptors, and
1277  // the prob/oracle pointer wiring that doesn't change between calls.
1278  // Plugins that own the storage (uno) call this from codegen_init_mem; the
1279  // default-name call from codegen_body_enter preserves the historical
1280  // emission order for plugins that don't opt in.
1282  const std::string& d_nlp, const std::string& p_nlp,
1283  const std::string& d_oracle) const {
1284  g << d_nlp << ".oracle = &" << d_oracle << ";\n";
1285  g << d_nlp << ".prob = &" << p_nlp << ";\n";
1286  g << p_nlp << ".nx = " << nx_ << ";\n";
1287  g << p_nlp << ".ng = " << ng_ << ";\n";
1288  g << p_nlp << ".np = " << np_ << ";\n";
1289  g << p_nlp << ".detect_bounds.ng = " << detect_simple_bounds_is_simple_.size() << ";\n";
1290  if (detect_simple_bounds_is_simple_.size()) {
1291  g << p_nlp << ".detect_bounds.sz_arg = " << detect_simple_bounds_parts_.sz_arg() << ";\n";
1292  g << p_nlp << ".detect_bounds.sz_res = " << detect_simple_bounds_parts_.sz_res() << ";\n";
1293  g << p_nlp << ".detect_bounds.sz_iw = " << detect_simple_bounds_parts_.sz_iw() << ";\n";
1294  g << p_nlp << ".detect_bounds.sz_w = " << detect_simple_bounds_parts_.sz_w() << ";\n";
1295 
1296  g << p_nlp << ".detect_bounds.nb = " << detect_simple_bounds_target_x_.size() << ";\n";
1297  g << p_nlp << ".detect_bounds.target_x = "
1299  g << p_nlp << ".detect_bounds.target_g = "
1301  g << p_nlp << ".detect_bounds.is_simple = "
1303  std::string w =
1304  g.shorthand(g.wrapper(detect_simple_bounds_parts_, "detect_simple_bounds_wrapper"));
1305  g << p_nlp << ".detect_bounds.callback = " << w << ";\n";
1306  g << p_nlp << ".detect_bounds.callback_data = 0;\n";
1307  }
1308  }
1309 
1310  // Per-call wiring: arg/res slot bindings, casadi_nlpsol_set_work's workspace
1311  // claim, and the copy_default's that populate z/lbz/ubz/lam from the
1312  // user inputs. Always runs every call.
1313  void Nlpsol::codegen_setup_per_call(CodeGenerator& g, const std::string& d_nlp) const {
1314  g << d_nlp << ".p = arg[" << NLPSOL_P << "];\n";
1315  g << d_nlp << ".lbx = arg[" << NLPSOL_LBX << "];\n";
1316  g << d_nlp << ".ubx = arg[" << NLPSOL_UBX << "];\n";
1317  g << d_nlp << ".lbg = arg[" << NLPSOL_LBG << "];\n";
1318  g << d_nlp << ".ubg = arg[" << NLPSOL_UBG << "];\n";
1319  g << d_nlp << ".x0 = arg[" << NLPSOL_X0 << "];\n";
1320  g << d_nlp << ".lam_x0 = arg[" << NLPSOL_LAM_X0 << "];\n";
1321  g << d_nlp << ".lam_g0 = arg[" << NLPSOL_LAM_G0 << "];\n";
1322  g << "arg += " << NLPSOL_NUM_IN << ";\n";
1323 
1324  g << d_nlp << ".x = res[" << NLPSOL_X << "];\n";
1325  g << d_nlp << ".f = res[" << NLPSOL_F << "];\n";
1326  g << d_nlp << ".g = res[" << NLPSOL_G << "];\n";
1327  g << d_nlp << ".lam_x = res[" << NLPSOL_LAM_X << "];\n";
1328  g << d_nlp << ".lam_g = res[" << NLPSOL_LAM_G << "];\n";
1329  g << d_nlp << ".lam_p = res[" << NLPSOL_LAM_P << "];\n";
1330  g << "res += " << NLPSOL_NUM_OUT << ";\n";
1331 
1332  g << "casadi_nlpsol_set_work(&" << d_nlp << ", &arg, &res, &iw, &w);\n";
1333 
1334  g.copy_default(d_nlp + ".x0", nx_, d_nlp + ".z", "0", false);
1335  g.copy_default(d_nlp + ".lbx", nx_, d_nlp + ".lbz", "-casadi_inf", false);
1336  g.copy_default(d_nlp + ".ubx", nx_, d_nlp + ".ubz", "casadi_inf", false);
1337  g.copy_default(d_nlp + ".lam_x0", nx_, d_nlp + ".lam", "0", false);
1338 
1339  if (detect_simple_bounds_is_simple_.empty()) {
1340  g.copy_default(d_nlp + ".lbg", ng_, d_nlp + ".lbz+" + str(nx_), "-casadi_inf", false);
1341  g.copy_default(d_nlp + ".ubg", ng_, d_nlp + ".ubz+" + str(nx_), "casadi_inf", false);
1342  g.copy_default(d_nlp + ".lam_g0", ng_, d_nlp + ".lam+" + str(nx_), "0", false);
1343  } else {
1344  g << "if (casadi_nlpsol_detect_bounds_before(&" << d_nlp << ")) return 1;\n";
1345  }
1346  }
1347 
1351  if (calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_)
1352  g.add_dependency(get_function("nlp_grad"));
1353 
1354  if (detect_simple_bounds_is_simple_.size()) {
1356  std::string w =
1357  g.shorthand(g.wrapper(detect_simple_bounds_parts_, "detect_simple_bounds_wrapper"));
1358 
1359  g << "int " << w
1360  << "(const casadi_real** arg, casadi_real** res, "
1361  << "casadi_int* iw, casadi_real* w, void* callback_data) {\n";
1362  std::string flag = g(detect_simple_bounds_parts_, "arg", "res", "iw", "w");
1363  g << "return " + flag + ";\n";
1364  g << "}\n";
1365  }
1366  }
1367 
1369  codegen_post_solve(g, "d_nlp");
1371  }
1372 
1373  void Nlpsol::codegen_post_solve(CodeGenerator& g, const std::string& d_nlp) const {
1374  if (calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_) {
1375  g.local("one", "const casadi_real");
1376  g.init_local("one", "1");
1377  g << "d->arg[0] = " << d_nlp << ".z;\n";
1378  g << "d->arg[1] = " << d_nlp << ".p;\n";
1379  g << "d->arg[2] = &one;\n";
1380  g << "d->arg[3] = " << d_nlp << ".lam+" << str(nx_) << ";\n";
1381  g << "d->res[0] = " << (calc_f_ ? "&" + d_nlp + ".objective" : "0") << ";\n";
1382  g << "d->res[1] = " << (calc_g_ ? d_nlp + ".z+" + str(nx_) : "0") << ";\n";
1383  g << "d->res[2] = " << (calc_lam_x_ ? d_nlp + ".lam+" + str(nx_) : "0") << ";\n";
1384  g << "d->res[3] = " << (calc_lam_p_ ? d_nlp + ".lam_p" : "0") << ";\n";
1385  std::string nlp_grad = g(get_function("nlp_grad"), "d->arg", "d->res", "d->iw", "d->w");
1386  g << "if (" << nlp_grad << ") return 1;\n";
1387  if (calc_lam_x_) g << g.scal(nx_, "-1.0", d_nlp + ".lam") << "\n";
1388  if (calc_lam_p_) g << g.scal(np_, "-1.0", d_nlp + ".lam_p") << "\n";
1389  }
1390  if (bound_consistency_) {
1391  g << g.bound_consistency(nx_+ng_, d_nlp + ".z", d_nlp + ".lam",
1392  d_nlp + ".lbz", d_nlp + ".ubz") << ";\n";
1393  }
1394 
1395  g << g.copy(d_nlp + ".z", nx_, d_nlp + ".x") << "\n";
1396 
1397  if (detect_simple_bounds_is_simple_.empty()) {
1398  g << g.copy(d_nlp + ".z + " + str(nx_), ng_, d_nlp + ".g") << "\n";
1399  g << g.copy(d_nlp + ".lam", nx_, d_nlp + ".lam_x") << "\n";
1400  g << g.copy(d_nlp + ".lam + " + str(nx_), ng_, d_nlp + ".lam_g") << "\n";
1401  } else {
1402  g << "if (casadi_nlpsol_detect_bounds_after(&" << d_nlp << ")) return 1;\n";
1403  }
1404 
1405  g.copy_check("&" + d_nlp + ".objective", 1, d_nlp + ".f", false, true);
1406  g.copy_check(d_nlp + ".lam_p", np_, d_nlp + ".lam_p", false, true);
1407  }
1408 
1411 
1412  s.version("Nlpsol", 5);
1413  s.pack("Nlpsol::nx", nx_);
1414  s.pack("Nlpsol::ng", ng_);
1415  s.pack("Nlpsol::np", np_);
1416  s.pack("Nlpsol::fcallback", fcallback_);
1417  s.pack("Nlpsol::callback_step", callback_step_);
1418  s.pack("Nlpsol::eval_errors_fatal", eval_errors_fatal_);
1419  s.pack("Nlpsol::warn_initial_bounds", warn_initial_bounds_);
1420  s.pack("Nlpsol::iteration_callback_ignore_errors", iteration_callback_ignore_errors_);
1421  s.pack("Nlpsol::calc_multipliers", calc_multipliers_);
1422  s.pack("Nlpsol::calc_lam_x", calc_lam_x_);
1423  s.pack("Nlpsol::calc_lam_p", calc_lam_p_);
1424  s.pack("Nlpsol::calc_f", calc_f_);
1425  s.pack("Nlpsol::calc_g", calc_g_);
1426  s.pack("Nlpsol::min_lam", min_lam_);
1427  s.pack("Nlpsol::bound_consistency", bound_consistency_);
1428  s.pack("Nlpsol::no_nlp_grad", no_nlp_grad_);
1429  s.pack("Nlpsol::discrete", discrete_);
1430  s.pack("Nlpsol::equality", equality_);
1431  s.pack("Nlpsol::mi", mi_);
1432  s.pack("Nlpsol::sens_linsol", sens_linsol_);
1433  s.pack("Nlpsol::sens_linsol_options", sens_linsol_options_);
1434  s.pack("Nlpsol::detect_simple_bounds_is_simple", detect_simple_bounds_is_simple_);
1435  s.pack("Nlpsol::detect_simple_bounds_parts", detect_simple_bounds_parts_);
1436  s.pack("Nlpsol::detect_simple_bounds_target_x", detect_simple_bounds_target_x_);
1437  }
1438 
1442  }
1443 
1446  }
1447 
1449  int version = s.version("Nlpsol", 1, 5);
1450  s.unpack("Nlpsol::nx", nx_);
1451  s.unpack("Nlpsol::ng", ng_);
1452  s.unpack("Nlpsol::np", np_);
1453  s.unpack("Nlpsol::fcallback", fcallback_);
1454  s.unpack("Nlpsol::callback_step", callback_step_);
1455  if (version<=2) {
1456  s.unpack("Nlpsol::error_on_fail", error_on_fail_);
1457  }
1458  s.unpack("Nlpsol::eval_errors_fatal", eval_errors_fatal_);
1459  s.unpack("Nlpsol::warn_initial_bounds", warn_initial_bounds_);
1460  s.unpack("Nlpsol::iteration_callback_ignore_errors", iteration_callback_ignore_errors_);
1461  s.unpack("Nlpsol::calc_multipliers", calc_multipliers_);
1462  s.unpack("Nlpsol::calc_lam_x", calc_lam_x_);
1463  s.unpack("Nlpsol::calc_lam_p", calc_lam_p_);
1464  s.unpack("Nlpsol::calc_f", calc_f_);
1465  s.unpack("Nlpsol::calc_g", calc_g_);
1466  s.unpack("Nlpsol::min_lam", min_lam_);
1467  s.unpack("Nlpsol::bound_consistency", bound_consistency_);
1468  s.unpack("Nlpsol::no_nlp_grad", no_nlp_grad_);
1469  s.unpack("Nlpsol::discrete", discrete_);
1470  if (version>=4) {
1471  s.unpack("Nlpsol::equality", equality_);
1472  }
1473  s.unpack("Nlpsol::mi", mi_);
1474  if (version>=2) {
1475  s.unpack("Nlpsol::sens_linsol", sens_linsol_);
1476  s.unpack("Nlpsol::sens_linsol_options", sens_linsol_options_);
1477  } else {
1478  sens_linsol_ = "qr";
1479  }
1480 
1481  if (version>=3) {
1482  s.unpack("Nlpsol::detect_simple_bounds_is_simple", detect_simple_bounds_is_simple_);
1483  s.unpack("Nlpsol::detect_simple_bounds_parts", detect_simple_bounds_parts_);
1484  if (version==4) {
1485  casadi_error("Saved detect_simple_bounds_parts changed signature");
1486  }
1487  s.unpack("Nlpsol::detect_simple_bounds_target_x", detect_simple_bounds_target_x_);
1488  }
1489  for (casadi_int i=0;i<detect_simple_bounds_is_simple_.size();++i) {
1491  detect_simple_bounds_target_g_.push_back(i);
1492  }
1493  }
1494  set_nlpsol_prob();
1495  }
1496 
1497 } // namespace casadi
const char * what() const override
Display error.
Definition: exception.hpp:90
Helper class for C code generation.
std::string add_dependency(const Function &f)
Add a function dependency.
std::string wrapper(const Function &base, const std::string &name)
std::string copy(const std::string &arg, std::size_t n, const std::string &res)
Create a copy operation.
std::string constant(const std::vector< casadi_int > &v)
Represent an array constant; adding it when new.
std::string scal(casadi_int n, const std::string &alpha, const std::string &x)
What does scal do??
std::string bound_consistency(casadi_int n, const std::string &x, const std::string &lam, const std::string &lbx, const std::string &ubx)
bound_consistency
void local(const std::string &name, const std::string &type, const std::string &ref="")
Declare a local variable.
void init_local(const std::string &name, const std::string &def)
Specify the default value for a local variable.
std::string shorthand(const std::string &name) const
Get a shorthand.
void copy_check(const std::string &arg, std::size_t n, const std::string &res, bool check_lhs=true, bool check_rhs=true)
void copy_default(const std::string &arg, std::size_t n, const std::string &res, const std::string &def, bool check_rhs=true)
void add_auxiliary(Auxiliary f, const std::vector< std::string > &inst={"casadi_real"})
Add a built-in auxiliary function.
Helper class for Serialization.
void unpack(Sparsity &e)
Reconstruct an object from the input stream.
void version(const std::string &name, int v)
void alloc_iw(size_t sz_iw, bool persistent=false)
Ensure required length of iw field.
void alloc_res(size_t sz_res, bool persistent=false)
Ensure required length of res field.
virtual const std::vector< MX > mx_in() const
Get function input(s) and output(s)
void alloc_arg(size_t sz_arg, bool persistent=false)
Ensure required length of arg field.
virtual bool is_a(const std::string &type, bool recursive) const
Check if the function is of a particular type.
bool inputs_check_
Errors are thrown if numerical values of inputs look bad.
size_t sz_res() const
Get required length of res field.
std::pair< casadi_int, casadi_int > size_out(casadi_int ind) const
Input/output dimensions.
casadi_int nnz_in() const
Number of input/output nonzeros.
std::vector< Sparsity > sparsity_out_
void serialize_type(SerializingStream &s) const override
Serialize type information.
size_t sz_w() const
Get required length of w field.
virtual const std::vector< MX > mx_out() const
Get function input(s) and output(s)
void alloc_w(size_t sz_w, bool persistent=false)
Ensure required length of w field.
casadi_int nnz_out() const
Number of input/output nonzeros.
size_t sz_arg() const
Get required length of arg field.
void setup(void *mem, const double **arg, double **res, casadi_int *iw, double *w) const
Set the (persistent and temporary) work vectors.
void alloc(const Function &f, bool persistent=false, int num_threads=1)
Ensure work vectors long enough to evaluate function.
size_t sz_iw() const
Get required length of iw field.
static std::string string_from_UnifiedReturnStatus(UnifiedReturnStatus status)
Function object.
Definition: function.hpp:60
Function forward(casadi_int nfwd) const
Get a function that calculates nfwd forward derivatives.
Definition: function.cpp:1324
size_t sz_res() const
Get required length of res field.
Definition: function.cpp:1237
const Sparsity & sparsity_out(casadi_int ind) const
Get sparsity of a given output.
Definition: function.cpp:1183
casadi_int size1_in(casadi_int ind) const
Get input dimension.
Definition: function.cpp:979
Function expand() const
Expand a function to SX.
Definition: function.cpp:312
const std::vector< std::string > & name_in() const
Get input scheme.
Definition: function.cpp:1113
const std::string & name() const
Name of the function.
Definition: function.cpp:1504
casadi_int numel_out() const
Get number of output elements.
Definition: function.cpp:1015
Function reverse(casadi_int nadj) const
Get a function that calculates nadj adjoint derivatives.
Definition: function.cpp:1332
const T sym_in(casadi_int iind) const
Get symbolic primitives equivalent to the input expressions.
static Function create(FunctionInternal *node)
Create from node.
Definition: function.cpp:488
const Sparsity & sparsity_in(casadi_int ind) const
Get sparsity of a given input.
Definition: function.cpp:1167
size_t sz_iw() const
Get required length of iw field.
Definition: function.cpp:1239
casadi_int n_out() const
Get the number of function outputs.
Definition: function.cpp:975
casadi_int n_in() const
Get the number of function inputs.
Definition: function.cpp:971
std::vector< std::string > get_free() const
Get free variables as a string.
Definition: function.cpp:1382
size_t sz_w() const
Get required length of w field.
Definition: function.cpp:1241
size_t sz_arg() const
Get required length of arg field.
Definition: function.cpp:1235
bool has_free() const
Does the function have free variables.
Definition: function.cpp:1894
casadi_int size1_out(casadi_int ind) const
Get output dimension.
Definition: function.cpp:987
std::pair< casadi_int, casadi_int > size_in(casadi_int ind) const
Get input dimension.
Definition: function.cpp:995
void call(const std::vector< DM > &arg, std::vector< DM > &res, bool always_inline=false, bool never_inline=false) const
Evaluate the function symbolically or numerically.
Definition: function.cpp:509
Function factory(const std::string &name, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const AuxOut &aux=AuxOut(), const Dict &opts=Dict()) const
Definition: function.cpp:2009
const std::vector< std::string > & name_out() const
Get output scheme.
Definition: function.cpp:1117
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.
bool is_null() const
Is a null pointer?
bool shared_if_alive(Shared &shared) const
Thread-safe alternative to alive()/shared()
Importer.
Definition: importer.hpp:86
MX - Matrix expression.
Definition: mx.hpp:92
const Sparsity & sparsity() const
Get the sparsity pattern.
Definition: mx.cpp:612
static MX blockcat(const std::vector< std::vector< MX > > &v)
Definition: mx.cpp:1263
MX T() const
Transpose the matrix.
Definition: mx.cpp:1095
static MX solve(const MX &a, const MX &b)
Definition: mx.cpp:2115
static MX vertcat(const std::vector< MX > &x)
Definition: mx.cpp:1165
A symbolic NLP representation.
Definition: nlp_builder.hpp:41
std::vector< MX > x
Variables.
Definition: nlp_builder.hpp:50
std::vector< MX > g
Constraints.
Definition: nlp_builder.hpp:56
MX f
Objective.
Definition: nlp_builder.hpp:53
void serialize_type(SerializingStream &s) const override
Serialize type information.
Definition: nlpsol.cpp:1439
Nlpsol(const std::string &name, const Function &oracle)
Constructor.
Definition: nlpsol.cpp:346
bool iteration_callback_ignore_errors_
Options.
Definition: nlpsol_impl.hpp:95
void codegen_post_solve(CodeGenerator &g, const std::string &d_nlp) const
Definition: nlpsol.cpp:1373
WeakRef kkt_
Cache for KKT function.
void codegen_body_exit(CodeGenerator &g) const override
Generate code for the function body.
Definition: nlpsol.cpp:1368
bool calc_lam_p_
Options.
Definition: nlpsol_impl.hpp:97
Sparsity get_sparsity_out(casadi_int i) override
Sparsities of function inputs and outputs.
Definition: nlpsol.cpp:391
virtual DM getReducedHessian()
Definition: nlpsol.cpp:758
Dict get_stats(void *mem) const override
Get all statistics.
Definition: nlpsol.cpp:1251
Function get_forward(casadi_int nfwd, const std::string &name, const std::vector< std::string > &inames, const std::vector< std::string > &onames, const Dict &opts) const override
Generate a function that calculates forward mode derivatives.
Definition: nlpsol.cpp:958
static const Options options_
Options.
void codegen_body_enter(CodeGenerator &g) const override
Generate code for the function body.
Definition: nlpsol.cpp:1268
void codegen_declarations(CodeGenerator &g) const override
Generate code for the declarations of the C function.
Definition: nlpsol.cpp:1348
void init(const Dict &opts) override
Initialize.
Definition: nlpsol.cpp:499
casadi_int ng_
Number of constraints.
Definition: nlpsol_impl.hpp:69
int eval(const double **arg, double **res, casadi_int *iw, double *w, void *mem) const final
Evaluate numerically.
Definition: nlpsol.cpp:793
Function kkt() const
Definition: nlpsol.cpp:936
virtual void check_inputs(void *mem) const
Check if the inputs correspond to a well-posed problem.
Definition: nlpsol.cpp:702
void codegen_setup_per_call(CodeGenerator &g, const std::string &d_nlp) const
Definition: nlpsol.cpp:1313
bool eval_errors_fatal_
Options.
Definition: nlpsol_impl.hpp:93
int init_mem(void *mem) const override
Initalize memory block.
Definition: nlpsol.cpp:692
void codegen_setup_constants(CodeGenerator &g, const std::string &d_nlp, const std::string &p_nlp, const std::string &d_oracle) const
Definition: nlpsol.cpp:1281
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
Definition: nlpsol.cpp:1444
Function detect_simple_bounds_parts_
Definition: nlpsol_impl.hpp:85
bool calc_multipliers_
Options.
Definition: nlpsol_impl.hpp:96
static void bound_consistency(casadi_int n, double *z, double *lam, const double *lbz, const double *ubz)
Definition: nlpsol.cpp:767
std::vector< bool > equality_
Options.
bool warn_initial_bounds_
Options.
Definition: nlpsol_impl.hpp:94
static const std::string infix_
Infix.
Dict sens_linsol_options_
Definition: nlpsol_impl.hpp:82
casadi_nlpsol_prob< double > p_nlp_
Definition: nlpsol_impl.hpp:63
void disp_more(std::ostream &stream) const override
Print description.
Definition: nlpsol.cpp:931
void serialize_body(SerializingStream &s) const override
Serialize an object without type information.
Definition: nlpsol.cpp:1409
static std::map< std::string, Plugin > solvers_
Collection of solvers.
bool calc_f_
Options.
Definition: nlpsol_impl.hpp:97
bool calc_g_
Options.
Definition: nlpsol_impl.hpp:97
Function get_reverse(casadi_int nadj, const std::string &name, const std::vector< std::string > &inames, const std::vector< std::string > &onames, const Dict &opts) const override
Generate a function that calculates reverse mode derivatives.
Definition: nlpsol.cpp:1089
std::string class_name() const override
Get type name.
std::vector< char > detect_simple_bounds_is_simple_
Definition: nlpsol_impl.hpp:84
casadi_int np_
Number of parameters.
Definition: nlpsol_impl.hpp:72
double min_lam_
Options.
Definition: nlpsol_impl.hpp:99
Sparsity get_sparsity_in(casadi_int i) override
Sparsities of function inputs and outputs.
Definition: nlpsol.cpp:373
static Function create_oracle(const std::map< std::string, XType > &d, const Dict &opts)
Convert dictionary to Problem.
Definition: nlpsol.cpp:206
bool calc_lam_x_
Options.
Definition: nlpsol_impl.hpp:97
std::vector< casadi_int > detect_simple_bounds_target_g_
Definition: nlpsol_impl.hpp:87
casadi_int callback_step_
Execute the callback function only after this amount of iterations.
Definition: nlpsol_impl.hpp:78
virtual void setOptionsFromFile(const std::string &file)
Read options from parameter xml.
Definition: nlpsol.cpp:763
std::vector< casadi_int > detect_simple_bounds_target_x_
Definition: nlpsol_impl.hpp:86
int callback(NlpsolMemory *m) const
Definition: nlpsol.cpp:1210
~Nlpsol() override=0
Destructor.
Definition: nlpsol.cpp:365
std::vector< bool > discrete_
Options.
casadi_int nx_
Number of variables.
Definition: nlpsol_impl.hpp:66
virtual bool integer_support() const
Can discrete variables be treated.
void set_work(void *mem, const double **&arg, double **&res, casadi_int *&iw, double *&w) const override
Set the (persistent) work vectors.
Definition: nlpsol.cpp:884
bool bound_consistency_
Options.
Definition: nlpsol_impl.hpp:98
bool no_nlp_grad_
Options.
std::string sens_linsol_
Linear solver and options.
Definition: nlpsol_impl.hpp:81
virtual int solve(void *mem) const =0
Function fcallback_
callback function, executed at each iteration
Definition: nlpsol_impl.hpp:75
bool is_a(const std::string &type, bool recursive) const override
Check if the function is of a particular type.
Definition: nlpsol.cpp:369
double get_default_in(casadi_int ind) const override
Get default input value.
Base class for functions that perform calculation with an oracle.
Function oracle_
Oracle: Used to generate other functions.
Function create_function(const Function &oracle, const std::string &fname, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Function::AuxOut &aux=Function::AuxOut(), const Dict &opts=Dict())
void join_results(OracleMemory *m) const
Combine results from different threads.
void init(const Dict &opts) override
int init_mem(void *mem) const override
Initalize memory block.
virtual void codegen_body_enter(CodeGenerator &g) const
Generate code for the function body.
int calc_function(OracleMemory *m, const std::string &fcn, const double *const *arg=nullptr, int thread_id=0) const
std::vector< std::string > get_function() const override
Get list of dependency functions.
static const Options options_
Options.
Dict get_stats(void *mem) const override
Get all statistics.
void serialize_body(SerializingStream &s) const override
Serialize an object without type information.
virtual void codegen_body_exit(CodeGenerator &g) const
Generate code for the function body.
static bool has_plugin(const std::string &pname, bool verbose=false)
Check if a plugin is available or can be loaded.
static Nlpsol * instantiate(const std::string &fname, const std::string &pname, Problem problem)
void serialize_type(SerializingStream &s) const
Serialize type information.
static const Options & plugin_options(const std::string &pname)
Get the plugin options.
static Plugin & getPlugin(const std::string &pname)
Load and get the creator function.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
static Plugin load_plugin(const std::string &pname, bool register_plugin=true, bool needs_lock=true)
Load a plugin dynamically.
Base class for FunctionInternal and LinsolInternal.
bool error_on_fail_
Throw an exception on failure?
void print(const char *fmt,...) const
C-style formatted printing during evaluation.
void clear_mem()
Clear all memory (called from destructor)
Helper class for Serialization.
void version(const std::string &name, int v)
void pack(const Sparsity &e)
Serializes an object to the output stream.
GenericShared implements a reference counting framework similar for efficient and.
void disp(std::ostream &stream, bool more=false) const
Print a description of the object.
Class representing a Slice.
Definition: slice.hpp:48
General sparsity class.
Definition: sparsity.hpp:106
casadi_int numel() const
The total number of elements, including structural zeros, i.e. size2()*size1()
Definition: sparsity.cpp:132
std::string dim(bool with_nz=false) const
Get the dimension as a string.
Definition: sparsity.cpp:588
static Sparsity dense(casadi_int nrow, casadi_int ncol=1)
Create a dense rectangular sparsity pattern *.
Definition: sparsity.cpp:1028
Sparsity T() const
Transpose the matrix.
Definition: sparsity.cpp:394
const casadi_int * row() const
Get a reference to row-vector,.
Definition: sparsity.cpp:164
bool is_empty(bool both=false) const
Check if the sparsity is empty.
Definition: sparsity.cpp:144
const casadi_int * colind() const
Get a reference to the colindex of all column element (see class description)
Definition: sparsity.cpp:168
std::string doc_nlpsol(const std::string &name)
Get the documentation string for a plugin.
Definition: nlpsol.cpp:43
bool has_nlpsol(const std::string &name)
Check if a particular plugin is available.
Definition: nlpsol.cpp:35
void load_nlpsol(const std::string &name)
Explicitly load a plugin dynamically.
Definition: nlpsol.cpp:39
std::string nlpsol_option_info(const std::string &name, const std::string &op)
Get documentation for a particular option.
Definition: nlpsol.cpp:927
casadi_int nlpsol_n_in()
Number of NLP solver inputs.
Definition: nlpsol.cpp:338
std::string nlpsol_option_type(const std::string &name, const std::string &op)
Get type info for a particular option.
Definition: nlpsol.cpp:923
std::vector< std::string > nlpsol_options(const std::string &name)
Get all options for a plugin.
Definition: nlpsol.cpp:919
std::vector< std::string > nlpsol_in()
Get input scheme of NLP solvers.
Definition: nlpsol.cpp:279
Function nlpsol(const std::string &name, const std::string &solver, const SXDict &nlp, const Dict &opts)
Definition: nlpsol.cpp:195
casadi_int nlpsol_n_out()
Number of NLP solver outputs.
Definition: nlpsol.cpp:342
std::vector< std::string > nlpsol_out()
Get NLP solver output scheme of NLP solvers.
Definition: nlpsol.cpp:285
double nlpsol_default_in(casadi_int ind)
Default input for an NLP solver.
Definition: nlpsol.cpp:291
The casadi namespace.
Definition: archiver.cpp:28
NlpsolInput
Input arguments of an NLP Solver.
Definition: nlpsol.hpp:194
@ NLPSOL_P
Value of fixed parameters (np x 1)
Definition: nlpsol.hpp:198
@ NLPSOL_UBX
Decision variables upper bound (nx x 1), default +inf.
Definition: nlpsol.hpp:202
@ NLPSOL_X0
Decision variables, initial guess (nx x 1)
Definition: nlpsol.hpp:196
@ NLPSOL_LAM_G0
Lagrange multipliers for bounds on G, initial guess (ng x 1)
Definition: nlpsol.hpp:210
@ NLPSOL_UBG
Constraints upper bound (ng x 1), default +inf.
Definition: nlpsol.hpp:206
@ NLPSOL_LAM_X0
Lagrange multipliers for bounds on X, initial guess (nx x 1)
Definition: nlpsol.hpp:208
@ NLPSOL_NUM_IN
Definition: nlpsol.hpp:211
@ NLPSOL_LBG
Constraints lower bound (ng x 1), default -inf.
Definition: nlpsol.hpp:204
@ NLPSOL_LBX
Decision variables lower bound (nx x 1), default -inf.
Definition: nlpsol.hpp:200
std::map< std::string, MX > MXDict
Definition: mx.hpp:1110
bool name_has_g(const std::string &name)
Definition: nlpsol.cpp:47
NlpsolOutput
Output arguments of an NLP Solver.
Definition: nlpsol.hpp:215
@ NLPSOL_G
Constraints function at the optimal solution (ng x 1)
Definition: nlpsol.hpp:221
@ NLPSOL_X
Decision variables at the optimal solution (nx x 1)
Definition: nlpsol.hpp:217
@ NLPSOL_NUM_OUT
Definition: nlpsol.hpp:228
@ NLPSOL_LAM_P
Lagrange multipliers for bounds on P at the solution (np x 1)
Definition: nlpsol.hpp:227
@ NLPSOL_F
Cost function value at the optimal solution (1 x 1)
Definition: nlpsol.hpp:219
@ NLPSOL_LAM_G
Lagrange multipliers for bounds on G at the solution (ng x 1)
Definition: nlpsol.hpp:225
@ NLPSOL_LAM_X
Lagrange multipliers for bounds on X at the solution (nx x 1)
Definition: nlpsol.hpp:223
T get_from_dict(const std::map< std::string, T > &d, const std::string &key, const T &default_value)
void assign_vector(const std::vector< S > &s, std::vector< D > &d)
@ NL_X
Decision variable.
Definition: nlpsol.hpp:170
@ NL_P
Fixed parameter.
Definition: nlpsol.hpp:172
@ NL_NUM_IN
Number of NLP inputs.
Definition: nlpsol.hpp:174
double if_else(double x, double y, double z)
Definition: calculus.hpp:296
@ NL_F
Objective function.
Definition: nlpsol.hpp:183
@ NL_G
Constraint function.
Definition: nlpsol.hpp:185
@ NL_NUM_OUT
Number of NLP outputs.
Definition: nlpsol.hpp:187
int detect_bounds_callback(const double **arg, double **res, casadi_int *iw, double *w, void *callback_data)
Definition: nlpsol.cpp:665
void casadi_copy(const T1 *x, casadi_int n, T1 *y)
COPY: y <-x.
void casadi_fill(T1 *x, casadi_int n, T1 alpha)
FILL: x <- alpha.
@ OT_BOOLVECTOR
@ OT_INTVECTOR
std::map< std::string, SX > SXDict
Definition: sx_fwd.hpp:40
std::string str(const T &v)
String representation, any type.
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
std::vector< bool > boolvec_not(const std::vector< bool > &v)
Invert all entries.
const double inf
infinity
Definition: calculus.hpp:50
const std::vector< std::string > NL_INPUTS
Shortname for onput arguments of an NLP function.
Definition: nlpsol.hpp:178
const double nan
Not a number.
Definition: calculus.hpp:53
void casadi_scal(casadi_int n, T1 alpha, T1 *x)
SCAL: x <- alpha*x.
std::vector< T > vector_select(const std::vector< T > &v, const std::vector< bool > &s, bool invert=false)
Select subset of vector.
T * get_ptr(std::vector< T > &v)
Get a pointer to the data contained in the vector.
Function construct_nlpsol(const std::string &name, const std::string &solver, const std::map< std::string, X > &nlp, const Dict &opts)
Definition: nlpsol.cpp:63
Matrix< double > DM
Definition: dm_fwd.hpp:33
Function external(const std::string &name, const Importer &li, const Dict &opts)
Load a just-in-time compiled external function.
Definition: external.cpp:42
@ SOLVER_RET_SUCCESS
@ SOLVER_RET_UNKNOWN
@ SOLVER_RET_EXCEPTION
std::vector< casadi_int > boolvec_to_index(const std::vector< bool > &v)
const std::vector< std::string > NL_OUTPUTS
Shortname for output arguments of an NLP function.
Definition: nlpsol.hpp:191
Integrator memory.
Definition: nlpsol_impl.hpp:40
casadi_nlpsol_data< double > d_nlp
Definition: nlpsol_impl.hpp:42
Options metadata for a class.
Definition: options.hpp:40
std::string type(const std::string &name) const
Definition: options.cpp:289
std::vector< std::string > all() const
Definition: options.cpp:283
std::string info(const std::string &name) const
Definition: options.cpp:295
std::map< std::string, FStats > fstats
void add_stat(const std::string &s)
const T1 * lam_g0
Definition: casadi_nlp.hpp:87
const T1 * lam_x0
Definition: casadi_nlp.hpp:87
casadi_nlpsol_detect_bounds_prob< T1 > detect_bounds
Definition: casadi_nlp.hpp:46