code_generator.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 
27 #include "code_generator.hpp"
28 #include "function_internal.hpp"
29 #include "convexify.hpp"
30 #include "blas_impl.hpp"
31 #include <casadi_runtime_str.h>
32 #include "global_options.hpp"
33 #include "filesystem_impl.hpp"
34 #include <iomanip>
35 
36 namespace casadi {
37 
38  CodeGenerator::CodeGenerator(const std::string& name, const Dict& opts) {
39  // Default options
40  this->verbose = true;
41  this->verbose_runtime = false;
42  this->mex = false;
43  this->with_sfunction = false;
44  this->unroll_args = false;
45  this->static_aux = false;
46  this->inline_aux = false;
47  this->cpp = false;
48  this->main = false;
49  this->casadi_real_type = "double";
50  this->casadi_int_type = CASADI_INT_TYPE_STR;
51  this->codegen_scalars = false;
52  this->with_header = false;
53  this->with_mem = false;
54  this->with_export = true;
55  this->with_import = false;
56  this->include_math = true;
57  this->infinity = "INFINITY";
58  this->nan = "NAN";
59  this->real_min = "";
60  bool prefix_set = false;
61  this->prefix = "";
62  this->dump_dir_prefix = "";
63  this->dump_dir_suffix = "";
64  this->max_declarations_per_line = 12;
66  this->force_canonical = false;
67  this->l1_blas = false;
68 
69  avoid_stack_ = false;
70  indent_ = 2;
71  sz_zeros_ = 0;
72  sz_ones_ = 0;
73  thread_safe_ = false;
74 
75  // Read options
76  for (auto&& e : opts) {
77  if (e.first=="verbose") {
78  this->verbose = e.second;
79  } else if (e.first=="verbose_runtime") {
80  this->verbose_runtime = e.second;
81  } else if (e.first=="mex") {
82  this->mex = e.second;
83  } else if (e.first=="with_sfunction") {
84  this->with_sfunction = e.second;
85  } else if (e.first=="unroll_args") {
86  this->unroll_args = e.second;
87  } else if (e.first=="static_aux") {
88  this->static_aux = e.second;
89  } else if (e.first=="inline_aux") {
90  this->inline_aux = e.second;
91  } else if (e.first=="cpp") {
92  this->cpp = e.second;
93  } else if (e.first=="main") {
94  this->main = e.second;
95  } else if (e.first=="casadi_real") {
96  this->casadi_real_type = e.second.to_string();
97  } else if (e.first=="casadi_int") {
98  this->casadi_int_type = e.second.to_string();
99  } else if (e.first=="codegen_scalars") {
100  this->codegen_scalars = e.second;
101  } else if (e.first=="with_header") {
102  this->with_header = e.second;
103  } else if (e.first=="with_mem") {
104  this->with_mem = e.second;
105  } else if (e.first=="with_export") {
106  this->with_export = e.second;
107  } else if (e.first=="with_import") {
108  this->with_import = e.second;
109  } else if (e.first=="include_math") {
110  this->include_math = e.second;
111  } else if (e.first=="infinity") {
112  this->infinity = e.second.to_string();
113  } else if (e.first=="nan") {
114  this->nan = e.second.to_string();
115  } else if (e.first=="real_min") {
116  this->real_min = e.second.to_string();
117  } else if (e.first=="indent") {
118  indent_ = e.second;
119  casadi_assert_dev(indent_>=0);
120  } else if (e.first=="avoid_stack") {
121  avoid_stack_ = e.second;
122  } else if (e.first=="prefix") {
123  this->prefix = e.second.to_string();
124  prefix_set = true;
125  } else if (e.first=="dump_dir_prefix") {
126  this->dump_dir_prefix = e.second.to_string();
127  } else if (e.first=="dump_dir_suffix") {
128  this->dump_dir_suffix = e.second.to_string();
129  } else if (e.first=="max_declarations_per_line") {
130  this->max_declarations_per_line = e.second;
131  casadi_assert(this->max_declarations_per_line>=0,
132  "Option max_declarations_per_line must be >=0");
133  } else if (e.first=="max_initializer_elements_per_line") {
134  this->max_initializer_elements_per_line = e.second;
135  casadi_assert(this->max_initializer_elements_per_line>=0,
136  "Option max_initializer_elements_per_line must be >=0");
137  } else if (e.first=="force_canonical") {
138  this->force_canonical = e.second;
139  } else if (e.first=="l1_blas") {
140  this->l1_blas = e.second;
141  } else if (e.first=="thread_safe") {
142  thread_safe_ = e.second;
143  } else {
144  casadi_error("Unrecognized option: " + str(e.first));
145  }
146  }
147 
148  if (with_mem && !force_canonical) {
149  casadi_error("Codegen options 'with_mem' and 'force_canonical=false' (the default) "
150  "are incompatible. If you rely on with_mem, please explicitly set force_canonical=true.");
151  }
152 
153  // If real_min is not specified, make an educated guess
154  if (this->real_min.empty()) {
155  std::stringstream ss;
156  ss << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1);
157  if (casadi_real_type=="float") {
158  ss << std::numeric_limits<float>::min();
159  this->real_min = ss.str();
160  } else if (casadi_real_type=="double") {
161  ss << std::numeric_limits<double>::min();
162  this->real_min = ss.str();
163  } else {
164  this->real_min = "<NOT SPECIFIED>";
165  }
166  }
167 
169 
170  // Start at new line with no indentation
171  newline_ = true;
172  current_indent_ = 0;
173 
174  // Start off without the need for thread-local memory
175  needs_mem_ = false;
176 
177  // Divide name into base and suffix (if any)
178  std::string::size_type dotpos = name.rfind('.');
179  if (dotpos==std::string::npos) {
180  this->name = name;
181  this->suffix = this->cpp ? ".cpp" : ".c";
182  } else {
183  this->name = name.substr(0, dotpos);
184  this->suffix = name.substr(dotpos);
185  }
186 
187  // Symbol prefix
188  if (this->with_export) dll_export = "CASADI_SYMBOL_EXPORT ";
189  if (this->with_import) dll_import = "CASADI_SYMBOL_IMPORT ";
190 
191  // Make sure that the base name is sane
192  casadi_assert_dev(Function::check_name(this->name));
193 
194  // Includes needed
195  if (this->include_math) add_include("math.h");
196  if (this->main) add_include("stdio.h");
198 
199  // Mex and main need string.h
200  if (this->mex || this->main) {
201  add_include("string.h");
202  }
203 
204  // Mex
205  if (this->mex) {
206  add_include("mex.h", false, "MATLAB_MEX_FILE");
207  }
208 
209  // s-Function
210  if (this->with_sfunction) {
211  this->casadi_real_type = "real_T";
212  this->casadi_int_type = "int_T";
213  this->with_header = true;
214  add_include("simstruc.h");
215  }
216 
217  // Memory struct entry point
218  if (this->with_mem) {
219  this->header << "#include <casadi/mem.h>\n";
220  }
221 
222  // Use name as default prefix
223  if (!prefix_set) {
224  this->prefix = this->name;
225  }
226 
227  }
228 
230  local_variables_.clear();
231  local_default_.clear();
232  local_cleanup_.clear();
233  local_void_ = true;
234  }
235 
236  void CodeGenerator::scope_return(const std::string& value) {
237  local_void_ = false;
238  if (local_cleanup_.empty()) {
239  *this << "return " << value << ";\n";
240  return;
241  }
242  local("ret", "int");
243  *this << "ret = " << value << ";\n";
244  *this << "goto done" << local_cleanup_.size() << ";\n";
245  }
246 
248  if (local_cleanup_.empty()) {
249  *this << "return;\n";
250  return;
251  }
252  *this << "goto done" << local_cleanup_.size() << ";\n";
253  }
254 
255 
256  void CodeGenerator::scope_add_cleanup(const std::string& code) {
257  local_cleanup_.push_back(code);
258  }
259 
261  // Order local variables
262  std::map<std::string, std::set<std::pair<std::string, std::string>>> local_variables_by_type;
263  for (auto&& e : local_variables_) {
264  local_variables_by_type[e.second.first].insert(std::make_pair(e.first, e.second.second));
265  }
266 
267  // Codegen local variables
268  for (auto&& e : local_variables_by_type) {
269  casadi_int cnt = 0;
270  for (auto it=e.second.begin(); it!=e.second.end(); ++it) {
271  bool split_declaration = it==e.second.begin() ||
273  if (split_declaration) {
274  if (it!=e.second.begin()) body << ";\n";
275  body << " " << e.first << " ";
276  } else {
277  body << ", ";
278  }
279  body << it->second << it->first;
280  // Insert definition, if any
281  auto k=local_default_.find(it->first);
282  if (k!=local_default_.end()) body << "=" << k->second;
283  cnt++;
284  }
285  body << ";\n";
286  }
287 
288  // Loop over local_cleanup_ in reverse order
289  if (!local_cleanup_.empty()) {
290  *this << "done" << local_cleanup_.size() << ":\n";
291  for (casadi_int i=local_cleanup_.size()-1; i>=0; --i) {
292  *this << local_cleanup_[i];
293  }
294  if (local_void_) {
295  *this << "return;\n";
296  } else {
297  *this << "return ret;\n";
298  }
299  }
300  }
301 
302  std::string CodeGenerator::wrapper(const Function& base, const std::string& name) {
303  FunctionInternal* f = base.get();
304  std::map<FunctionInternal*, casadi_int>& funs = added_wrappers_[name];
305  auto it = funs.find(f);
306  if (it==funs.end()) {
307  casadi_int n = funs.size();
308  funs[f] = n;
309  return name + str(n);
310  } else {
311  return name + str(it->second);
312  }
313  }
314 
315  std::string CodeGenerator::add_dependency(const Function& f) {
316  // Quick return if it already exists
317  for (auto&& e : added_functions_) if (e.f==f) return e.codegen_name;
318 
319  // Give it a name
320  std::string fname = shorthand("f" + str(added_functions_.size()));
321 
322  // Add to list of functions
323  added_functions_.push_back({f, fname});
324 
325  // Generate declarations
326  f->codegen_declarations(*this);
327 
328  // Print to file
329  f->codegen(*this, fname);
330 
331  bool fun_needs_mem = f->codegen_needs_mem();
332  needs_mem_ |= fun_needs_mem;
333 
334  if (fun_needs_mem) {
335 
336  if (!f->codegen_mem_is_opaque()) {
337  // Alloc memory
338  *this << "int " << fname << "_alloc_mem(void) {\n";
339  flush(this->body);
340  scope_enter();
341  f->codegen_alloc_mem(*this);
342  scope_exit();
343  *this << "}\n\n";
344 
345  // Initialize memory
346  *this << "int " << fname << "_init_mem(int mem) {\n";
347  flush(this->body);
348  scope_enter();
349  f->codegen_init_mem(*this);
350  scope_exit();
351  *this << "}\n\n";
352 
353  // Clear memory
354  *this << "void " << fname << "_free_mem(int mem) {\n";
355  flush(this->body);
356  scope_enter();
357  f->codegen_free_mem(*this);
358  scope_exit();
359  *this << "}\n\n";
360  }
361 
362  // Checkout
363  *this << "int " << fname << "_checkout(void) {\n";
364  flush(this->body);
365  scope_enter();
366  f->codegen_checkout(*this);
367  scope_exit();
368  *this << "}\n\n";
369 
370  // Clear memory
371  *this << "void " << fname << "_release(int mem) {\n";
372  flush(this->body);
373  scope_enter();
374  f->codegen_release(*this);
375  scope_exit();
376  *this << "}\n\n";
377 
378  }
379 
380  // Codegen reference count functions, if needed
381  if (f->has_refcount_in_deps_) {
382  // Increase reference counter
383  *this << "void " << fname << "_incref(void) {\n";
384  f->codegen_incref(*this);
385  *this << "}\n\n";
386 
387  // Decrease reference counter
388  *this << "void " << fname << "_decref(void) {\n";
389  f->codegen_decref(*this);
390  *this << "}\n\n";
391  }
392 
393  // Flush to body
394  flush(this->body);
395 
396  return fname;
397  }
398 
399  void CodeGenerator::add(const Function& f, bool with_jac_sparsity) {
400  // Add if not already added
401  std::string codegen_name = add_dependency(f);
402  casadi_assert(!external_names_.count(f.name()),
403  "Cannot code generate '" + f.name() + "': name conflicts with an external dependency.");
404 
405  // Define function
406  *this << declare(f->signature(f.name())) << "{\n"
407  << "return " << codegen_name << "(arg, res, iw, w, mem);\n"
408  << "}\n\n";
409 
410  if (this->unroll_args) {
411  // Define function
412  *this << declare(f->signature_unrolled(f.name())) << "{\n";
413  for (casadi_int i=0; i<f.n_in(); ++i) {
414  *this << "arg[" << i << "] = " << f.name_in(i) << ";\n";
415  }
416  for (casadi_int i=0; i<f.n_out(); ++i) {
417  *this << "res[" << i << "] = " << f.name_out(i) << ";\n";
418  }
419  *this << "return " << codegen_name << "(arg, res, iw, w, mem);\n";
420  *this << "}\n\n";
421  // Flush buffers
422  flush(this->body);
423  }
424 
425  // Generate meta information
426  f->codegen_meta(*this);
427 
428  // Generate Jacobian sparsity information
429  if (with_jac_sparsity) {
430  // Generate/get Jacobian sparsity
431  std::vector<Sparsity> jac = f.jac_sparsity();
432  // Code generate the sparsity pattern
433  add_io_sparsities("jac_" + f.name(), f->sparsity_in_, jac);
434 
435  // Flush buffers
436  flush(this->body);
437  }
438 
439  // Generate function specific code for Simulink sfunction
440  if (this->with_sfunction) this->added_sfunctions.push_back( this->codegen_sfunction(f) );
441 
442  // Add to list of exposed symbols
443  this->exposed_fname.push_back(f.name());
444  }
445 
446  std::string CodeGenerator::dump() {
447  std::stringstream s;
448  dump(s);
449  return s.str();
450  }
451 
453  std::stringstream ss;
454  ss << CASADI_MAJOR_VERSION << "." << CASADI_MINOR_VERSION << "." << CASADI_PATCH_VERSION;
455  if (!CASADI_IS_RELEASE) ss << "+";
456  return ss.str();
457  }
458 
459  void CodeGenerator::stream_open(std::ostream& f, bool cpp) {
460 
461  // Print header
462  f << "/* This file was automatically generated by CasADi " << casadi_version() << ".\n"
463  << " * It consists of: \n"
464  << " * 1) content generated by CasADi runtime: not copyrighted\n"
465  << " * 2) template code copied from CasADi source: permissively licensed (MIT-0)\n"
466  << " * 3) user code: owned by the user\n"
467  << " *\n"
468  << " */\n";
469 
470  // C linkage
471  if (!cpp) {
472  f << "#ifdef __cplusplus\n"
473  << "extern \"C\" {\n"
474  << "#endif\n\n";
475  }
476  }
477 
478  void CodeGenerator::stream_close(std::ostream& f, bool cpp) {
479  // C linkage
480  if (!cpp) {
481  f << "#ifdef __cplusplus\n"
482  << "} /* extern \"C\" */\n"
483  << "#endif\n";
484  }
485  }
486 
487  void CodeGenerator::generate_casadi_real(std::ostream &s) const {
488  s << "#ifndef casadi_real\n"
489  << "#define casadi_real " << this->casadi_real_type << std::endl
490  << "#endif\n\n";
491  }
492 
493  void CodeGenerator::generate_export_symbol(std::ostream &s) const {
494  s << "/* Symbol visibility in DLLs */\n"
495  << "#ifndef CASADI_SYMBOL_EXPORT\n"
496  << " #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n"
497  << " #if defined(STATIC_LINKED)\n"
498  << " #define CASADI_SYMBOL_EXPORT\n"
499  << " #else\n"
500  << " #define CASADI_SYMBOL_EXPORT __declspec(dllexport)\n"
501  << " #endif\n"
502  << " #elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n"
503  << " #define CASADI_SYMBOL_EXPORT __attribute__ ((visibility (\"default\")))\n"
504  << " #else" << std::endl
505  << " #define CASADI_SYMBOL_EXPORT\n"
506  << " #endif\n"
507  << "#endif\n\n";
508  }
509 
510  void CodeGenerator::generate_import_symbol(std::ostream &s) const {
511  s << "/* Symbol visibility in DLLs */\n"
512  << "#ifndef CASADI_SYMBOL_IMPORT\n"
513  << " #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n"
514  << " #if defined(STATIC_LINKED)\n"
515  << " #define CASADI_SYMBOL_IMPORT\n"
516  << " #else\n"
517  << " #define CASADI_SYMBOL_IMPORT __declspec(dllimport)\n"
518  << " #endif\n"
519  << " #elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n"
520  << " #define CASADI_SYMBOL_IMPORT __attribute__ ((visibility (\"default\")))\n"
521  << " #else" << std::endl
522  << " #define CASADI_SYMBOL_IMPORT\n"
523  << " #endif\n"
524  << "#endif\n\n";
525  }
526 
527  void CodeGenerator::generate_casadi_int(std::ostream &s) const {
528  s << "#ifndef casadi_int\n"
529  << "#define casadi_int " << this->casadi_int_type << std::endl
530  << "#endif\n\n";
531  }
532 
533  std::string CodeGenerator::generate(const std::string& prefix) {
534  // Throw an error if the prefix contains the filename, since since syntax
535  // has changed
536  casadi_assert(prefix.find(this->name + this->suffix)==std::string::npos,
537  "The signature of CodeGenerator::generate has changed. "
538  "Instead of providing the filename, only provide the prefix.");
539 
540  // Create c file
541  std::string fullname = prefix + this->name + this->suffix;
542 
543  auto s_ptr = Filesystem::ofstream_ptr(fullname);
544  std::ostream& s = *s_ptr;
545  stream_open(s, this->cpp);
546 
547  // Dump code to file
548  dump(s);
549 
550  if (!pool_double_defaults_.empty()) {
551  s << "CASADI_SYMBOL_EXPORT casadi_real* CASADI_PREFIX(get_pool_double)(const char* name) {\n";
552  for (const auto& e : pool_double_) {
553  casadi_int i = e.second;
554  s << " if (strcmp(name, \"" + e.first + "\")==0) "
555  << "return casadi_pd" + str(i) + ";\n";
556  }
557  s << " return 0;\n";
558  s << "}\n";
559  }
560 
561  // Mex entry point
562  if (this->mex) generate_mex(s);
563 
564  // Main entry point
565  if (this->main) generate_main(s);
566 
567  // Finalize file
568  stream_close(s, this->cpp);
569  s_ptr.reset();
570 
571  // Generate s-function
572  if (this->with_sfunction) {
573  for (unsigned ii=0; ii<this->added_sfunctions.size(); ii++) {
574  std::string sfunction_code = this->added_sfunctions.at(ii);
575  std::string sfunction_name = this->exposed_fname.at(ii);
576  generate_sfunction(sfunction_name, sfunction_code);
577  }
578  }
579 
580  // Generate header
581  if (this->with_header) {
582  auto s_ptr = Filesystem::ofstream_ptr(prefix + this->name + ".h");
583  std::ostream& s = *s_ptr;
584  // Create a header file
585  stream_open(s, this->cpp);
586 
587  // Define the casadi_real type (typically double)
588  generate_casadi_real(s);
589 
590  // Define the casadi_int type
591  generate_casadi_int(s);
592 
593  // Generate export symbol macros
594  if (this->with_import) generate_import_symbol(s);
595 
596  // Add declarations
597  s << this->header.str();
598 
599  // Finalize file
600  stream_close(s, this->cpp);
601  s_ptr.reset();
602  }
603  return fullname;
604  }
605 
606  void CodeGenerator::generate_mex(std::ostream &s) const {
607  // Begin conditional compilation
608  s << "#ifdef MATLAB_MEX_FILE\n";
609 
610  // Function prototype
611  if (this->cpp) s << "extern \"C\"\n"; // C linkage
612  s << "void mexFunction(int resc, mxArray *resv[], int argc, const mxArray *argv[]) {"
613  << std::endl;
614 
615  // Create a buffer
616  size_t buf_len = 0;
617  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
618  buf_len = std::max(buf_len, exposed_fname[i].size());
619  }
620  s << " char buf[" << (buf_len+1) << "];\n";
621 
622  // Read std::string argument
623  s << " int buf_ok = argc > 0 && !mxGetString(*argv, buf, sizeof(buf));\n";
624 
625  // Create switch
626  s << " if (!buf_ok) {\n";
627  // Allow stringless call when unambiguous
628  if (exposed_fname.size()==1) {
629  s << " mex_" << exposed_fname[0] << "(resc, resv, argc, argv);\n"
630  << " return;\n";
631  } else {
632  s << " /* name error */\n";
633  }
634  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
635  s << " } else if (strcmp(buf, \"" << exposed_fname[i] << "\")==0) {\n"
636  << " mex_" << exposed_fname[i] << "(resc, resv, argc-1, argv+1);\n"
637  << " return;\n";
638  }
639  s << " }\n";
640 
641  // Error
642  s << " mexErrMsgTxt(\"First input should be a command string. Possible values:";
643  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
644  s << " '" << exposed_fname[i] << "'";
645  }
646  s << "\");\n";
647 
648  // End conditional compilation and function
649  s << "}\n"
650  << "#endif\n";
651  }
652 
653  void CodeGenerator::generate_sfunction(const std::string& name,
654  const std::string& sfunction) const {
655  // Create c file
656  auto f_ptr = Filesystem::ofstream_ptr("sfun_"+ name + ".c");
657  std::ostream& f = *f_ptr;
658 
659  // Print header
660  f << "// Must specify the S_FUNCTION_NAME as the name of the S-function\n"
661  << "#define S_FUNCTION_NAME sfun_" << name << "\n"
662  << "#define S_FUNCTION_LEVEL 2\n\n"
663  << "// Need to include simstruc.h for the definition of the SimStruct and its\n"
664  << "// associated macro definitions\n"
665  << "#ifndef __SIMSTRUC__\n"
666  << "#include \"simstruc.h\"\n"
667  << "#endif\n\n"
668  << "// Specific header file(s) required by the legacy code function\n"
669  << "#include \"" << this->name << ".h\"\n\n\n";
670 
671  // Codegenerate s-function
672  f << sfunction;
673 
674  }
675 
676  std::string CodeGenerator::codegen_sfunction(const Function& f) const {
677  std::stringstream g;
678  // TODO(@jaeandersson): These helper functions really should be moved
679  // to the runtime directory
680 
681  // Initialize function
682  g << "/* Function: mdlInitializeSizes ===========================================\n"
683  << "* Abstract:\n"
684  << "* The sizes information is used by Simulink to determine the S-function\n"
685  << "* blocks characteristics (number of inputs, outputs, states, etc.).\n"
686  << "*/\n"
687  << "static void mdlInitializeSizes(SimStruct *S)\n"
688  << "{\n\n"
689  << " /* Declare auxilary variables */\n"
690  << " int_T ii;\n"
691  << " const int_T* sp;\n\n"
692  << " /* Set number of simulink s-function block parameters "
693  "(the ones which appear by double click on simulink block) */\n"
694  << " ssSetNumSFcnParams(S, 0);\n\n"
695  << " /* Report if parameter mismatch occurs */\n"
696  << " if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) return;\n\n"
697  << " /* Specify the number of states for which a block detects "
698  "zero crossings that occur between sample points */\n"
699  << " ssSetNumNonsampledZCs(S, 0);\n\n"
700  << " /* Set number of simulink input ports */\n"
701  << " if (!ssSetNumInputPorts(S, " << f->n_in_ << ")) return;\n\n"
702  << " /* Configure simulink input ports (inputs are assumed to be dense "
703  "vectors or matrices) */\n"
704  << " for (ii=0; ii<" << f->n_in_ << "; ++ii) {\n"
705  << " sp = " << f.name() << "_sparsity_in(ii);\n"
706  << " if (sp[1]==1) {\n"
707  << " ssSetInputPortWidth(S, ii, sp[0]);\n"
708  << " }\n"
709  << " else {\n"
710  << " ssSetInputPortMatrixDimensions(S, ii, sp[0], sp[1]);\n"
711  << " }\n"
712  << " ssSetInputPortDirectFeedThrough(S, ii, 1);\n"
713  << " }\n\n"
714  << " /* Set number of simulink output ports */\n"
715  << " if (!ssSetNumOutputPorts(S, " << f->n_out_ << ")) return;\n\n"
716  << " /* Configure simulink output ports (dense or sparse vectors or matrices allowed) */\n"
717  << " for (ii=0; ii<" << f->n_out_ << "; ++ii) {\n"
718  << " sp = " << f.name() << "_sparsity_out(ii);\n"
719  << " if (sp[1]==1) {\n"
720  << " ssSetOutputPortWidth(S, ii, sp[0]);\n"
721  << " }\n"
722  << " else {\n"
723  << " ssSetOutputPortMatrixDimensions(S, ii, sp[0], sp[1]);\n"
724  << " }\n"
725  << " }\n"
726  << " ssSetOutputPortOutputExprInRTW(S, 0, 0);\n\n"
727  << " /* This S-function can be used in referenced model simulating in normal mode */\n"
728  << " ssSetModelReferenceNormalModeSupport(S, MDL_START_AND_MDL_PROCESS_PARAMS_OK);\n\n"
729  << " /* Set the number of sample time */\n"
730  << " ssSetNumSampleTimes(S, 1);\n\n"
731  << " /* Set the compliance with the SimState feature */\n"
732  << " ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);\n\n"
733  << " /**\n"
734  << " * All options have the form SS_OPTION_<name> and are documented in\n"
735  << " * matlabroot/simulink/include/simstruc.h. The options should be\n"
736  << " * bitwise ord together as in\n"
737  << " * ssSetOptions(S, (SS_OPTION_name1 | SS_OPTION_name2))\n"
738  << " */\n"
739  << "}\n\n\n";
740 
741  // Initialize sample times function
742  g << "/* Function: mdlInitializeSampleTimes =====================================\n"
743  << " * Abstract:\n"
744  << " * This function is used to specify the sample time(s) for your\n"
745  << " * S-function. You must register the same number of sample times as\n"
746  << " * specified in ssSetNumSampleTimes.\n"
747  << " */\n"
748  << "static void mdlInitializeSampleTimes(SimStruct *S)\n"
749  << "{\n"
750  << " ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);\n"
751  << " ssSetOffsetTime(S, 0, FIXED_IN_MINOR_STEP_OFFSET);\n"
752  << " #if defined(ssSetModelReferenceSampleTimeDefaultInheritance)\n"
753  << " ssSetModelReferenceSampleTimeDefaultInheritance(S);\n"
754  << " #endif\n"
755  << "}\n\n\n";
756 
757  // Model output function
758  g << "/* Function: mdlOutputs ===================================================\n"
759  << " * Abstract:\n"
760  << " * In this function, you compute the outputs of your S-function\n"
761  << " * block. Generally outputs are placed in the output vector(s),\n"
762  << " * ssGetOutputPortSignal.\n"
763  << " */\n"
764  << "static void mdlOutputs(SimStruct *S, int_T tid)\n"
765  << "{\n\n"
766  << " /* Declare auxilary variables */\n"
767  << " int_T ii, jj, row, col, nnz_col, ind_start_row_index, offset = 0, jj_total = 0;\n"
768  << " const int_T* sp;\n\n"
769  << " /* Allocate buffers for casadi input and output and simulink output */\n"
770  << " " + array("real_T", "w", f->sz_w()+f->nnz_out())
771  << " " + array("int_T", "iw", f->sz_iw())
772  << " const real_T* arg[" << f->sz_arg() <<"] = {0};\n"
773  << " real_T* res[" << f->sz_res() << "] = {0};\n"
774  << " real_T* y[" << f->n_out_ << "] = {0};\n\n"
775  << " /* Point inputs directly to casadi input buffer */\n"
776  << " for (ii=0; ii<" << f->n_in_ << ";++ii) {\n"
777  << " arg[ii] = *ssGetInputPortRealSignalPtrs( S, ii );\n"
778  << " }\n\n"
779  << " /* Point outputs to buffer */\n"
780  << " for (ii=0; ii<" << f->n_out_ << ";++ii) {\n"
781  << " y[ii] = ssGetOutputPortRealSignal( S, ii );\n"
782  << " }\n\n"
783  << " /* Point allocated working array to casadi output buffer */\n";
784  for (casadi_int ii=0; ii<f->n_out_; ++ii) {
785  g << " res[" << ii << "] = w + offset;\n"
786  << " offset += " << f.nnz_out(ii) << ";\n";
787  }
788  g << " \n"
789  << " /* Call CasADi function */\n"
790  << " " << f.name() << "( arg, res, iw, w+offset, 0 );\n\n"
791  << " /* Assign results to Simulink output array */\n"
792  << " for (ii=0; ii<" << f->n_out_ << "; ++ii){\n\n"
793  << " /* Get sparsity information of casadi function output "
794  "(sp[0] - n_rows, sp[1] - n_cols, sp[2] - dense/sparse) */\n"
795  << " sp = " << f.name() << "_sparsity_out(ii);\n\n"
796  << " /* Check if output is dense (sp[2]=1) or sparse (sp[2]=0) */\n"
797  << " if (sp[2]==0) {\n"
798  << " jj_total = 0;\n"
799  << " ind_start_row_index = 2 + sp[1] + 1;\n\n"
800  << " /* Distribute nonzero elements column by column */\n"
801  << " for (col=0; col<sp[1]; col++) {\n\n"
802  << " /* The cumulative sum of nonzero elements after each column starts at index 2, "
803  "after last entry of CCS array col_ptr; number of nonzero elements in current column is "
804  "obtained by the difference of two consecutive values */\n"
805  << " nnz_col = sp[2+col+1] - sp[2+col];\n\n"
806  << " /* Distribute nonzero elements of current column to correct row position */\n"
807  << " for (jj=0; jj<nnz_col; jj++) {\n"
808  << " row = sp[ind_start_row_index+jj_total];\n"
809  << " y[ii][row + sp[0]*col] = res[ii][jj_total];\n"
810  << " jj_total++;\n"
811  << " }\n"
812  << " }\n"
813  << " }\n"
814  << " else {\n"
815  << " y[ii] = res[ii];\n"
816  << " }\n"
817  << " }\n"
818  << "}\n\n\n";
819 
820  // Model terminate function
821  g << "/* Function: mdlTerminate =================================================\n"
822  << " * Abstract:\n"
823  << " * In this function, you should perform any actions that are necessary\n"
824  << " * at the termination of a simulation.\n"
825  << " */\n"
826  << "static void mdlTerminate(SimStruct *S)\n"
827  << "{\n"
828  << "}\n\n\n"
829  << "/* Required S-function trailer */\n"
830  << "#ifdef MATLAB_MEX_FILE\n"
831  << "# include \"simulink.c\"\n"
832  << "#else\n"
833  << "# include \"cg_sfun.h\"\n"
834  << "#endif";
835 
836  return g.str();
837  }
838 
839  void CodeGenerator::generate_main(std::ostream &s) const {
840  s << this->dll_export << "int main(int argc, char* argv[]) {\n";
841 
842  // Create switch
843  s << " if (argc<2) {\n"
844  << " /* name error */\n";
845  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
846  s << " } else if (strcmp(argv[1], \"" << exposed_fname[i] << "\")==0) {\n"
847  << " return main_" << exposed_fname[i] << "(argc-2, argv+2);\n";
848  }
849  s << " }\n";
850 
851  // Error
852  s << " fprintf(stderr, \"First input should be a command string. Possible values:";
853  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
854  s << " '" << exposed_fname[i] << "'";
855  }
856  s << "\\n";
857  s << "Note: you may use function.generate_input to create a command string.";
858  s << "\\n\");\n";
859 
860  // End main
861  s << " return 1;\n"
862  << "}\n";
863  }
864 
865  void CodeGenerator::define_rom_double(const void* id, casadi_int size) {
866  auto it = file_scope_double_.find(id);
867  casadi_assert(it==file_scope_double_.end(), "Already defined.");
868  shorthand("rd" + str(file_scope_double_.size()));
869  file_scope_double_[id] = size;
870  }
871 
872  std::string CodeGenerator::rom_double(const void* id) const {
873  auto it = file_scope_double_.find(id);
874  casadi_assert(it!=file_scope_double_.end(), "Not defined.");
875  casadi_int size = std::distance(file_scope_double_.begin(), it);
876  return "casadi_rd" + str(size);
877  }
878 
879  void CodeGenerator::define_rom_integer(const void* id, casadi_int size) {
880  auto it = file_scope_double_.find(id);
881  casadi_assert(it==file_scope_double_.end(), "Already defined.");
882  shorthand("ri" + str(file_scope_double_.size()));
883  file_scope_double_[id] = size;
884  }
885 
886  std::string CodeGenerator::rom_integer(const void* id) const {
887  auto it = file_scope_double_.find(id);
888  casadi_assert(it!=file_scope_double_.end(), "Not defined.");
889  casadi_int size = std::distance(file_scope_double_.begin(), it);
890  return "casadi_ri" + str(size);
891  }
892 
893  void CodeGenerator::define_pool_double(const std::string& name, const std::vector<double>& def) {
894  auto it = pool_double_.find(name);
895  if (it==pool_double_.end()) {
896  casadi_int index = pool_double_defaults_.size();
897  pool_double_defaults_.push_back(def);
898  shorthand("pd" + str(index));
899  pool_double_[name] = index;
900  } else {
901  casadi_assert_dev(def==pool_double_defaults_[it->second]);
902  }
903  }
904 
905  std::string CodeGenerator::pool_double(const std::string& name) const {
906  auto it = pool_double_.find(name);
907  casadi_assert(it!=pool_double_.end(), "Not defined.");
908  return "casadi_pd" + str(it->second);
909  }
910 
912  const std::string& name) {
913  if (!thread_safe()) return;
914  if (!local_mutexes_[f.get()].insert(name).second) return; // already defined
915  std::string sh = shorthand(name);
916  auxiliaries << "#if CASADI_MUTEX_USE_STATIC_INIT == 0\n";
917  auxiliaries << "static CASADI_MUTEX_TYPE " << sh << ";\n";
918  auxiliaries << "#else\n";
919  auxiliaries << "static CASADI_MUTEX_TYPE " << sh
920  << " = CASADI_MUTEX_STATIC_INIT;\n";
921  auxiliaries << "#endif\n";
922  }
923 
924  std::string CodeGenerator::local_mutex(const Function& f,
925  const std::string& name) const {
926  auto it = local_mutexes_.find(f.get());
927  casadi_assert(it != local_mutexes_.end() && it->second.count(name),
928  "Mutex not defined: " + name);
929  return shorthand(name);
930  }
931 
932  static const std::set<std::string> empty_mutex_set_;
933 
934  const std::set<std::string>& CodeGenerator::local_mutexes(
935  const Function& f) const {
936  auto it = local_mutexes_.find(f.get());
937  if (it == local_mutexes_.end()) return empty_mutex_set_;
938  return it->second;
939  }
940 
941  void CodeGenerator::dump(std::ostream& s) {
942  // Consistency check
943  casadi_assert_dev(current_indent_ == 0);
944 
945  // Prefix internal symbols to avoid symbol collisions
946  s << "/* How to prefix internal symbols */\n"
947  << "#ifdef CASADI_CODEGEN_PREFIX\n"
948  << " #define CASADI_NAMESPACE_CONCAT(NS, ID) _CASADI_NAMESPACE_CONCAT(NS, ID)\n"
949  << " #define _CASADI_NAMESPACE_CONCAT(NS, ID) NS ## ID\n"
950  << " #define CASADI_PREFIX(ID) CASADI_NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)\n"
951  << "#else\n"
952  << " #define CASADI_PREFIX(ID) " << this->prefix << "_ ## ID\n"
953  << "#endif\n\n";
954 
955  s << this->includes.str();
956  s << std::endl;
957 
958  // Numeric types after includes: may depend on them. e.g. mex type
959  // Real type (usually double)
960  generate_casadi_real(s);
961 
962  // Integer type (usually long long)
963  generate_casadi_int(s);
964 
965  if (needs_mem_) {
966  s << "#ifndef CASADI_MAX_NUM_THREADS\n";
967  s << "#define CASADI_MAX_NUM_THREADS 1\n";
968  s << "#endif\n\n";
969  }
970 
971  // casadi/mem after numeric types to define derived types
972  // Memory struct entry point
973  if (this->with_mem) {
974  s << "#include <casadi/mem.h>\n" << std::endl;
975  }
976 
977  // Macros
978  if (!added_shorthands_.empty()) {
979  s << "/* Add prefix to internal symbols */\n";
980  for (auto&& i : added_shorthands_) {
981  s << "#define " << "casadi_" << i << " CASADI_PREFIX(" << i << ")\n";
982  }
983  s << std::endl;
984  }
985 
986  if (this->with_export) generate_export_symbol(s);
987 
988  // Check if inf/nan is needed
989  for (const auto& d : double_constants_) {
990  for (double e : d) {
991  if (isinf(e)) add_auxiliary(AUX_INF);
992  if (isnan(e)) add_auxiliary(AUX_NAN);
993  }
994  }
995 
996  // Codegen auxiliary functions
997  s << this->auxiliaries.str();
998 
999  // Print integer constants
1000  if (!integer_constants_.empty()) {
1001  for (casadi_int i=0; i<integer_constants_.size(); ++i) {
1002  print_vector(s, "casadi_s" + str(i), integer_constants_[i]);
1003  }
1004  s << std::endl;
1005  }
1006 
1007  // Print double constants
1008  if (!double_constants_.empty()) {
1009  for (casadi_int i=0; i<double_constants_.size(); ++i) {
1010  print_vector(s, "casadi_c" + str(i), double_constants_[i]);
1011  }
1012  s << std::endl;
1013  }
1014 
1015  // Print char constants
1016  if (!char_constants_.empty()) {
1017  for (casadi_int i=0; i<char_constants_.size(); ++i) {
1018  print_vector(s, "casadi_b" + str(i), char_constants_[i]);
1019  }
1020  s << std::endl;
1021  }
1022 
1023  // Print string constants
1024  if (!string_constants_.empty()) {
1025  for (casadi_int i=0; i<string_constants_.size(); ++i) {
1026  print_vector(s, "casadi_a" + str(i), string_constants_[i]);
1027  }
1028  s << std::endl;
1029  }
1030 
1031  if (sz_zeros_) {
1032  std::vector<double> sz_zeros(sz_zeros_, 0);
1033  print_vector(s, "casadi_zeros", std::vector<double>(sz_zeros));
1034  s << std::endl;
1035  }
1036 
1037  if (sz_ones_) {
1038  std::vector<double> sz_ones(sz_ones_, 0);
1039  print_vector(s, "casadi_ones", std::vector<double>(sz_ones));
1040  s << std::endl;
1041  }
1042 
1043  // Print file scope double work
1044  if (!file_scope_double_.empty()) {
1045  casadi_int i=0;
1046  for (const auto& it : file_scope_double_) {
1047  s << "static casadi_real casadi_rd" + str(i++) + "[" + str(it.second) + "];\n";
1048  }
1049  s << std::endl;
1050  }
1051 
1052  // Print file scope integer work
1053  if (!file_scope_integer_.empty()) {
1054  casadi_int i=0;
1055  for (const auto& it : file_scope_integer_) {
1056  s << "static casadi_real casadi_ri" + str(i++) + "[" + str(it.second) + "];\n";
1057  }
1058  s << std::endl;
1059  }
1060 
1061  // Print file scope double pool
1062  if (!pool_double_.empty()) {
1063  casadi_int i=0;
1064  for (const auto& v : pool_double_defaults_) {
1065  s << "casadi_real casadi_pd" + str(i) +
1066  "[" + str(v.size()) + "] = " + initializer(v) + ";\n";
1067  i++;
1068  }
1069  s << std::endl;
1070  }
1071 
1072  // External function declarations
1073  if (!added_externals_.empty()) {
1074  s << "/* External functions */\n";
1075  for (auto&& i : added_externals_) {
1076  s << i << std::endl;
1077  }
1078  s << std::endl << std::endl;
1079  }
1080 
1081  // Codegen body
1082  s << this->body.str();
1083 
1084  // End with new line
1085  s << std::endl;
1086  }
1087 
1088  std::string CodeGenerator::work(casadi_int n, casadi_int sz, bool is_ref) const {
1089  if (is_ref) {
1090  return "wr" + format_padded(n);
1091  }
1092  if (n<0 || sz==0) {
1093  return "0";
1094  } else if (sz==1 && !this->codegen_scalars) {
1095  return "(&w" + format_padded(n) + ")";
1096  } else {
1097  return "w" + format_padded(n);
1098  }
1099  }
1100 
1101  std::string CodeGenerator::workel(casadi_int n) const {
1102  if (n<0) return "0";
1103  std::stringstream s;
1104  if (this->codegen_scalars) s << "*";
1105  s << "w" << format_padded(n);
1106  return s.str();
1107  }
1108 
1109  void CodeGenerator::reserve_work(casadi_int n) {
1110  if (n == 0) {
1111  padding_length_ = 1;
1112  } else {
1113  // Zero based counting. The 10th entry is to be rendered as '9'
1114  padding_length_ = str(n-1).length();
1115  }
1116  }
1117 
1119  codegen_sz_w_[f] = sz_w;
1120  }
1121 
1122  bool CodeGenerator::get_codegen_sz_w(const FunctionInternal* f, size_t& sz_w) const {
1123  auto it = codegen_sz_w_.find(f);
1124  if (it==codegen_sz_w_.end()) return false;
1125  sz_w = it->second;
1126  return true;
1127  }
1128 
1129  std::string CodeGenerator::format_padded(casadi_int i) const {
1130  std::stringstream ss;
1131  ss.str("");
1132  ss << std::setw(padding_length_) << std::setfill('0') << i;
1133  return ss.str();
1134  }
1135 
1136  std::string CodeGenerator::array(const std::string& type, const std::string& name, casadi_int len,
1137  const std::string& def) {
1138  std::stringstream s;
1139  s << type << " ";
1140  if (len==0) {
1141  s << "*" << name << " = 0";
1142  } else {
1143  s << name << "[" << len << "]";
1144  if (!def.empty()) s << " = " << def;
1145  }
1146  s << ";\n";
1147  return s.str();
1148  }
1149 
1150  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1151  const std::vector<casadi_int>& v) {
1152  s << array("static const casadi_int", name, v.size(), initializer(v));
1153  }
1154 
1155  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1156  const std::vector<char>& v) {
1157  s << array("static const char", name, v.size(), initializer(v));
1158  }
1159 
1160  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1161  const std::vector<double>& v) {
1162  s << array("static const casadi_real", name, v.size(), initializer(v));
1163  }
1164 
1165  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1166  const std::vector<std::string>& v) {
1167  s << array("static const char*", name, v.size(), initializer(v));
1168  }
1169 
1170  std::string CodeGenerator::print_canonical(const Sparsity& sp, const std::string& arg) {
1172  std::stringstream s;
1173  s << "casadi_print_canonical(" << sparsity(sp) << ", " << arg << ");";
1174  return s.str();
1175  }
1176 
1177  std::string CodeGenerator::print_vector(casadi_int sz, const std::string& arg) {
1179  std::stringstream s;
1180  s << "casadi_print_vector(" << sz << ", " << arg << ");";
1181  return s.str();
1182  }
1183 
1184  std::string CodeGenerator::print_scalar(const std::string& arg) {
1186  std::stringstream s;
1187  s << "casadi_print_scalar(" << arg << ");";
1188  return s.str();
1189  }
1190 
1191  std::string CodeGenerator::fprintf_scalar(const std::string& f, const std::string& arg) {
1193  std::stringstream s;
1194  s << "casadi_fprintf_scalar(" << f << ", " << arg << ");";
1195  return s.str();
1196  }
1197 
1198  std::string CodeGenerator::fprintf_vector(const std::string& f, casadi_int sz,
1199  const std::string& arg, const std::string& sep) {
1201  std::stringstream s;
1202  s << "casadi_fprintf_vector(" << f << ", " << sz << ", " << arg << ", \"" << sep << "\");";
1203  return s.str();
1204  }
1205 
1206  std::string CodeGenerator::print_op(casadi_int op, const std::string& a0) {
1207  switch (op) {
1208  case OP_FABS:
1210  return "casadi_fabs("+a0+")";
1211  case OP_SQ:
1213  return "casadi_sq("+a0+")";
1214  case OP_SIGN:
1216  return "casadi_sign("+a0+")";
1217  case OP_LOG1P:
1219  return "casadi_log1p("+a0+")";
1220  case OP_EXPM1:
1222  return "casadi_expm1("+a0+")";
1223  default:
1224  return casadi_math<double>::print(op, a0);
1225  }
1226  }
1227  std::string CodeGenerator::print_op(casadi_int op, const std::string& a0, const std::string& a1) {
1228  switch (op) {
1229  case OP_FMIN:
1231  return "casadi_fmin("+a0+","+a1+")";
1232  case OP_FMAX:
1234  return "casadi_fmax("+a0+","+a1+")";
1235  case OP_HYPOT:
1237  return "casadi_hypot("+a0+","+a1+")";
1238  case OP_PRINTME:
1240  return "casadi_printme("+a0+","+a1+")";
1241  default:
1242  return casadi_math<double>::print(op, a0, a1);
1243  }
1244  }
1245 
1246  void CodeGenerator::add_include(const std::string& new_include, bool relative_path,
1247  const std::string& use_ifdef) {
1248  // Register the new element
1249  bool added = added_includes_.insert(new_include).second;
1250 
1251  // Quick return if it already exists
1252  if (!added) return;
1253 
1254  // Ifdef opening
1255  if (!use_ifdef.empty()) this->includes << "#ifdef " << use_ifdef << std::endl;
1256 
1257  // Print to the header section
1258  if (relative_path) {
1259  this->includes << "#include \"" << new_include << "\"\n";
1260  } else {
1261  this->includes << "#include <" << new_include << ">\n";
1262  }
1263 
1264  // Ifdef closing
1265  if (!use_ifdef.empty()) this->includes << "#endif\n";
1266  }
1267 
1268  void CodeGenerator::setup_callback(const std::string& s, const Function& f) {
1269  std::string name = add_dependency(f);
1270  bool needs_mem = f->codegen_needs_mem();
1271  if (needs_mem) {
1272  *this << s << ".checkout = " << name << "_checkout;\n";
1273  } else {
1274  *this << s << ".checkout = 0;\n";
1275  }
1276 
1277  *this << s << ".eval = " << name << ";\n";
1278  if (needs_mem) {
1279  *this << s << ".release = " << name << "_release;\n";
1280  } else {
1281  *this << s << ".release = 0;\n";
1282  }
1283  }
1284 
1285  std::string CodeGenerator::
1286  operator()(const Function& f, const std::string& arg,
1287  const std::string& res, const std::string& iw,
1288  const std::string& w, const std::string& failure_ret) {
1289  std::string name = add_dependency(f);
1290 
1291  std::string cg_name = f->codegen_name(*this, false);
1292  bool needs_mem = f->codegen_needs_mem();
1293  if (needs_mem) {
1294  std::string mem = "mid";
1295  local("flag", "int");
1296  local(mem, "int");
1297  std::string checkout = shorthand(cg_name + "_checkout");
1298  *this << mem << " = " << checkout << "();\n";
1299  if (failure_ret.empty()) {
1300  *this << "if (" << mem << "<0) {\n";
1301  *this << "flag = 1;\n";
1302  *this << "} else {\n";
1303  } else {
1304  *this << "if (" << mem << "<0) return " << failure_ret << ";\n";
1305  }
1306 
1307  *this << "flag = " + name + "(" + arg + ", " + res + ", "
1308  + iw + ", " + w + ", " << mem << ");\n";
1309 
1310  if (failure_ret.empty()) {
1311  *this << "}\n";
1312  }
1313 
1314  std::string release = shorthand(cg_name + "_release");
1315  *this << release << "(" << mem << ");\n";
1316  return "flag";
1317  } else {
1318  return name + "(" + arg + ", " + res + ", "
1319  + iw + ", " + w + ", 0)";
1320  }
1321  }
1322 
1323  void CodeGenerator::add_external(const std::string& new_external, const std::string& name) {
1324  if (!name.empty()) {
1325  casadi_assert(std::find(exposed_fname.begin(), exposed_fname.end(), name)
1326  ==exposed_fname.end(),
1327  "Cannot code generate '" + name + "': name conflicts with an external dependency.");
1328  external_names_.insert(name);
1329  }
1330  added_externals_.insert(new_external);
1331  }
1332 
1333  std::string CodeGenerator::shorthand(const std::string& name) const {
1334  casadi_assert(added_shorthands_.count(name), "No such macro: " + name);
1335  return "casadi_" + name;
1336  }
1337 
1338  std::string CodeGenerator::shorthand(const std::string& name, bool allow_adding) {
1339  bool added = added_shorthands_.insert(name).second;
1340  if (!allow_adding) {
1341  casadi_assert(added, "Duplicate macro: " + name);
1342  }
1343  return "casadi_" + name;
1344  }
1345 
1346  casadi_int CodeGenerator::add_sparsity(const Sparsity& sp, bool canonical) {
1347  return get_constant(sp.compress(canonical), true);
1348  }
1349 
1350  std::string CodeGenerator::sparsity(const Sparsity& sp, bool canonical) {
1351  return shorthand("s" + str(add_sparsity(sp, canonical)));
1352  }
1353 
1354  casadi_int CodeGenerator::get_sparsity(const Sparsity& sp) const {
1355  return const_cast<CodeGenerator&>(*this).get_constant(sp, false);
1356  }
1357 
1358  size_t CodeGenerator::hash(const std::vector<double>& v) {
1359  // Calculate a hash value for the vector
1360  std::size_t seed=0;
1361  if (!v.empty()) {
1362  casadi_assert_dev(sizeof(double) % sizeof(size_t)==0);
1363  const casadi_int int_len = v.size()*(sizeof(double)/sizeof(size_t));
1364  const size_t* int_v = reinterpret_cast<const size_t*>(&v.front());
1365  for (size_t i=0; i<int_len; ++i) {
1366  hash_combine(seed, int_v[i]);
1367  }
1368  }
1369  return seed;
1370  }
1371 
1372  size_t CodeGenerator::hash(const std::vector<casadi_int>& v) {
1373  size_t seed=0;
1374  hash_combine(seed, v);
1375  return seed;
1376  }
1377 
1378  size_t CodeGenerator::hash(const std::vector<char>& v) {
1379  size_t seed=0;
1380  hash_combine(seed, v);
1381  return seed;
1382  }
1383 
1384  size_t CodeGenerator::hash(const std::vector<std::string>& v) {
1385  size_t seed=0;
1386  hash_combine(seed, v);
1387  return seed;
1388  }
1389 
1390  casadi_int CodeGenerator::get_constant(const std::vector<double>& v, bool allow_adding) {
1391  // Hash the vector
1392  size_t h = hash(v);
1393 
1394  // Try to locate it in already added constants
1395  auto eq = added_double_constants_.equal_range(h);
1396  for (auto i=eq.first; i!=eq.second; ++i) {
1397  if (equal(v, double_constants_[i->second])) return i->second;
1398  }
1399 
1400  if (allow_adding) {
1401  // Add to constants
1402  casadi_int ind = double_constants_.size();
1403  double_constants_.push_back(v);
1404  added_double_constants_.insert(std::make_pair(h, ind));
1405  return ind;
1406  } else {
1407  casadi_error("Constant not found");
1408  return -1;
1409  }
1410  }
1411 
1412  casadi_int CodeGenerator::get_constant(const std::vector<casadi_int>& v, bool allow_adding) {
1413  // Hash the vector
1414  size_t h = hash(v);
1415 
1416  // Try to locate it in already added constants
1417  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1418  added_integer_constants_.equal_range(h);
1419  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1420  if (equal(v, integer_constants_[i->second])) return i->second;
1421  }
1422 
1423  if (allow_adding) {
1424  // Add to constants
1425  casadi_int ind = integer_constants_.size();
1426  integer_constants_.push_back(v);
1427  added_integer_constants_.insert(std::pair<size_t, size_t>(h, ind));
1428  return ind;
1429  } else {
1430  casadi_error("Constant not found");
1431  return -1;
1432  }
1433  }
1434 
1435  casadi_int CodeGenerator::get_constant(const std::vector<char>& v, bool allow_adding) {
1436  // Hash the vector
1437  size_t h = hash(v);
1438 
1439  // Try to locate it in already added constants
1440  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1441  added_char_constants_.equal_range(h);
1442  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1443  if (equal(v, char_constants_[i->second])) return i->second;
1444  }
1445 
1446  if (allow_adding) {
1447  // Add to constants
1448  casadi_int ind = char_constants_.size();
1449  char_constants_.push_back(v);
1450  added_char_constants_.insert(std::pair<size_t, size_t>(h, ind));
1451  return ind;
1452  } else {
1453  casadi_error("Constant not found");
1454  return -1;
1455  }
1456  }
1457 
1458  casadi_int CodeGenerator::get_constant(const std::vector<std::string>& v, bool allow_adding) {
1459  // Hash the vector
1460  size_t h = hash(v);
1461 
1462  // Try to locate it in already added constants
1463  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1464  added_string_constants_.equal_range(h);
1465  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1466  if (equal(v, string_constants_[i->second])) return i->second;
1467  }
1468 
1469  if (allow_adding) {
1470  // Add to constants
1471  casadi_int ind = string_constants_.size();
1472  string_constants_.push_back(v);
1473  added_string_constants_.insert(std::pair<size_t, size_t>(h, ind));
1474  return ind;
1475  } else {
1476  casadi_error("Constant not found");
1477  return -1;
1478  }
1479  }
1480 
1481  std::string CodeGenerator::constant(const std::vector<casadi_int>& v) {
1482  return shorthand("s" + str(get_constant(v, true)));
1483  }
1484 
1485  std::string CodeGenerator::constant(const std::vector<char>& v) {
1486  return shorthand("b" + str(get_constant(v, true)));
1487  }
1488 
1489  std::string CodeGenerator::constant(const std::vector<std::string>& v) {
1490  return shorthand("a" + str(get_constant(v, true)));
1491  }
1492 
1493  std::string CodeGenerator::zeros(casadi_int sz) {
1494  sz_zeros_ = std::max(sz_zeros_, sz);
1495  return shorthand("zeros");
1496  }
1497 
1498  std::string CodeGenerator::ones(casadi_int sz) {
1499  sz_ones_ = std::max(sz_ones_, sz);
1500  return shorthand("ones");
1501  }
1502 
1504  const std::string& name, const std::vector<casadi_int>& v, const std::string& type) {
1505  std::string ref = constant(v);
1506  if (!v.empty()) {
1507  local(name+"[" + str(v.size()) + "]", type);
1508  } else {
1509  local(name, type, "*");
1510  }
1511  if (!v.empty()) {
1512  local("i", type);
1513  (*this) << "for (i=0;i<" << v.size() << ";++i) " + name + "[i] = " + ref + "[i];\n";
1514  } else {
1515  init_local(name, "0");
1516  }
1517  }
1518 
1519  std::string CodeGenerator::constant(const std::vector<double>& v) {
1520  return shorthand("c" + str(get_constant(v, true)));
1521  }
1522 
1523  void CodeGenerator::add_auxiliary(Auxiliary f, const std::vector<std::string>& inst) {
1524  // Look for existing instantiations
1525  auto f_match = added_auxiliaries_.equal_range(f);
1526  // Look for duplicates
1527  for (auto it=f_match.first; it!=f_match.second; ++it) {
1528  if (it->second==inst) return;
1529  }
1530  added_auxiliaries_.insert(std::make_pair(f, inst));
1531 
1532  // Add the appropriate function
1533  switch (f) {
1534  case AUX_COPY:
1535  if (this->l1_blas) {
1536  Blas::codegen_copy_aux(*this, inst);
1537  } else {
1538  this->auxiliaries << sanitize_source(casadi_copy_str, inst);
1539  }
1540  break;
1541  case AUX_SCALED_COPY:
1542  this->auxiliaries << sanitize_source(casadi_scaled_copy_str, inst);
1543  break;
1544  case AUX_SWAP:
1545  this->auxiliaries << sanitize_source(casadi_swap_str, inst);
1546  break;
1547  case AUX_SCAL:
1548  if (!(this->l1_blas && Blas::codegen_scal_aux(*this, inst)))
1549  this->auxiliaries << sanitize_source(casadi_scal_str, inst);
1550  break;
1551  case AUX_AXPY:
1552  if (!(this->l1_blas && Blas::codegen_axpy_aux(*this, inst)))
1553  this->auxiliaries << sanitize_source(casadi_axpy_str, inst);
1554  break;
1555  case AUX_DOT:
1556  if (!(this->l1_blas && Blas::codegen_dot_aux(*this, inst)))
1557  this->auxiliaries << sanitize_source(casadi_dot_str, inst);
1558  break;
1559  case AUX_BILIN:
1560  this->auxiliaries << sanitize_source(casadi_bilin_str, inst);
1561  break;
1562  case AUX_KRON:
1563  this->auxiliaries << sanitize_source(casadi_kron_str, inst);
1564  break;
1565  case AUX_KRON_DENSE:
1566  this->auxiliaries << sanitize_source(casadi_kron_dense_str, inst);
1567  break;
1568  case AUX_KRON_DENSE_SPARSE:
1569  this->auxiliaries << sanitize_source(casadi_kron_dense_sparse_str, inst);
1570  break;
1571  case AUX_KRON_SPARSE_DENSE:
1572  this->auxiliaries << sanitize_source(casadi_kron_sparse_dense_str, inst);
1573  break;
1575  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_str, inst);
1576  break;
1578  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_dense_str, inst);
1579  break;
1581  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_dense_sparse_str, inst);
1582  break;
1584  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_sparse_dense_str, inst);
1585  break;
1587  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_str, inst);
1588  break;
1590  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_dense_str, inst);
1591  break;
1593  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_dense_sparse_str, inst);
1594  break;
1596  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_sparse_dense_str, inst);
1597  break;
1598  case AUX_RANK1:
1599  this->auxiliaries << sanitize_source(casadi_rank1_str, inst);
1600  break;
1601  case AUX_IAMAX:
1603  this->auxiliaries << sanitize_source(casadi_iamax_str, inst);
1604  break;
1605  case AUX_INTERPN:
1608  add_auxiliary(AUX_FLIP, {});
1610  add_auxiliary(AUX_CLEAR, {"casadi_int"});
1611  this->auxiliaries << sanitize_source(casadi_interpn_str, inst);
1612  break;
1613  case AUX_INTERPN_GRAD:
1615  this->auxiliaries << sanitize_source(casadi_interpn_grad_str, inst);
1616  break;
1617  case AUX_DE_BOOR:
1618  this->auxiliaries << sanitize_source(casadi_de_boor_str, inst);
1619  break;
1620  case AUX_TENSOR_TTV:
1621  this->auxiliaries << sanitize_source(casadi_tensor_ttv_str, inst);
1622  break;
1623  case AUX_ND_BOOR_EVAL:
1629  this->auxiliaries << sanitize_source(casadi_nd_boor_eval_str, inst);
1630  break;
1631  case AUX_FLIP:
1632  this->auxiliaries << sanitize_source(casadi_flip_str, inst);
1633  break;
1634  case AUX_LOW:
1635  this->auxiliaries << sanitize_source(casadi_low_str, inst);
1636  break;
1637  case AUX_INTERPN_WEIGHTS:
1639  this->auxiliaries << sanitize_source(casadi_interpn_weights_str, inst);
1640  break;
1642  this->auxiliaries << sanitize_source(casadi_interpn_interpolate_str, inst);
1643  break;
1644  case AUX_NORM_1:
1645  if (!(this->l1_blas && Blas::codegen_norm_1_aux(*this, inst))) {
1647  this->auxiliaries << sanitize_source(casadi_norm_1_str, inst);
1648  }
1649  break;
1650  case AUX_NORM_2:
1651  if (!(this->l1_blas && Blas::codegen_norm_2_aux(*this, inst))) {
1653  this->auxiliaries << sanitize_source(casadi_norm_2_str, inst);
1654  }
1655  break;
1656  case AUX_NORM_INF:
1659  this->auxiliaries << sanitize_source(casadi_norm_inf_str, inst);
1660  break;
1661  case AUX_VECTOR_FMAX:
1663  this->auxiliaries << sanitize_source(casadi_vector_fmax_str, inst);
1664  break;
1665  case AUX_VECTOR_FMIN:
1667  this->auxiliaries << sanitize_source(casadi_vector_fmin_str, inst);
1668  break;
1669  case AUX_MASKED_NORM_INF:
1672  this->auxiliaries << sanitize_source(casadi_masked_norm_inf_str, inst);
1673  break;
1674  case AUX_CLIP_MIN:
1675  // add_auxiliary(AUX_CLIP_MIN);
1676  this->auxiliaries << sanitize_source(casadi_clip_min_str, inst);
1677  break;
1678  case AUX_CLIP_MAX:
1679  // add_auxiliary(AUX_CLIP_MAX);
1680  this->auxiliaries << sanitize_source(casadi_clip_max_str, inst);
1681  break;
1682  case AUX_CLEAR:
1683  this->auxiliaries << sanitize_source(casadi_clear_str, inst);
1684  break;
1685  case AUX_FILL:
1686  this->auxiliaries << sanitize_source(casadi_fill_str, inst);
1687  break;
1688  case AUX_MV:
1689  this->auxiliaries << sanitize_source(casadi_mv_str, inst);
1690  break;
1691  case AUX_MV_DENSE:
1692  this->auxiliaries << sanitize_source(casadi_mv_dense_str, inst);
1693  break;
1694  case AUX_MTIMES:
1695  this->auxiliaries << sanitize_source(casadi_mtimes_str, inst);
1696  break;
1697  case AUX_MTIMES_DENSE:
1698  this->auxiliaries << sanitize_source(casadi_mtimes_dense_str, inst);
1699  break;
1701  this->auxiliaries << sanitize_source(casadi_mtimes_dense_sparse_str, inst);
1702  break;
1703  case AUX_TRILSOLVE:
1704  this->auxiliaries << sanitize_source(casadi_trilsolve_str, inst);
1705  break;
1706  case AUX_TRIUSOLVE:
1707  this->auxiliaries << sanitize_source(casadi_triusolve_str, inst);
1708  break;
1709  case AUX_PROJECT:
1710  this->auxiliaries << sanitize_source(casadi_project_str, inst);
1711  break;
1712  case AUX_TRI_PROJECT:
1713  this->auxiliaries << sanitize_source(casadi_tri_project_str, inst);
1714  break;
1715  case AUX_DENSIFY:
1718  {
1719  std::vector<std::string> inst2 = inst;
1720  if (inst.size()==1) inst2.push_back(inst[0]);
1721  this->auxiliaries << sanitize_source(casadi_densify_str, inst2);
1722  }
1723  break;
1724  case AUX_SPARSIFY:
1726  {
1727  std::vector<std::string> inst2 = inst;
1728  if (inst.size()==1) inst2.push_back(inst[0]);
1729  this->auxiliaries << sanitize_source(casadi_sparsify_str, inst2);
1730  }
1731  break;
1732  case AUX_TRANS:
1733  this->auxiliaries << sanitize_source(casadi_trans_str, inst);
1734  break;
1735  case AUX_TO_MEX:
1737  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1738  << sanitize_source(casadi_to_mex_str, inst)
1739  << "#endif\n\n";
1740  break;
1741  case AUX_FROM_MEX:
1743  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1744  << sanitize_source(casadi_from_mex_str, inst)
1745  << "#endif\n\n";
1746  break;
1747  case AUX_FINITE_DIFF:
1752  this->auxiliaries << sanitize_source(casadi_finite_diff_str, inst);
1753  break;
1754  case AUX_QR:
1759  this->auxiliaries << sanitize_source(casadi_qr_str, inst);
1760  break;
1761  case AUX_DET:
1762  this->auxiliaries << sanitize_source(casadi_det_str, inst);
1763  break;
1764  case AUX_LSQR:
1771  this->auxiliaries << sanitize_source(casadi_lsqr_str, inst);
1772  break;
1773  case AUX_QP:
1774  this->auxiliaries << sanitize_source(casadi_qp_str, inst);
1775  break;
1776  case AUX_SOCP:
1778  this->auxiliaries << sanitize_source(casadi_socp_str, inst);
1779  break;
1780  case AUX_QRQP:
1795  add_include("stdarg.h");
1796  add_include("stdio.h");
1797  add_include("math.h");
1798 
1799  this->auxiliaries << sanitize_source(casadi_qrqp_str, inst);
1800  break;
1801  case AUX_NLP:
1803  this->auxiliaries << sanitize_source(casadi_nlp_str, inst);
1804  break;
1805  case AUX_SQPMETHOD:
1810  this->auxiliaries << sanitize_source(casadi_sqpmethod_str, inst);
1811  break;
1812  case AUX_FEASIBLESQPMETHOD:
1815  this->auxiliaries << sanitize_source(casadi_feasiblesqpmethod_str, inst);
1816  break;
1817  case AUX_LDL:
1818  this->auxiliaries << sanitize_source(casadi_ldl_str, inst);
1819  break;
1820  case AUX_NEWTON:
1825  this->auxiliaries << sanitize_source(casadi_newton_str, inst);
1826  break;
1827  case AUX_MAX_VIOL:
1829  this->auxiliaries << sanitize_source(casadi_max_viol_str, inst);
1830  break;
1831  case AUX_SUM_VIOL:
1832  this->auxiliaries << sanitize_source(casadi_sum_viol_str, inst);
1833  break;
1834  case AUX_SUM:
1835  this->auxiliaries << sanitize_source(casadi_sum_str, inst);
1836  break;
1837  case AUX_VFMIN:
1839  this->auxiliaries << sanitize_source(casadi_vfmin_str, inst);
1840  break;
1841  case AUX_VFMAX:
1843  this->auxiliaries << sanitize_source(casadi_vfmax_str, inst);
1844  break;
1845  case AUX_REGULARIZE:
1848  this->auxiliaries << sanitize_source(casadi_regularize_str, inst);
1849  break;
1854  this->auxiliaries << sanitize_source(casadi_bound_consistency_str, inst);
1855  break;
1856  case AUX_FILE_SLURP:
1857  add_include("stdio.h");
1858  this->auxiliaries << sanitize_source(casadi_file_slurp_str, inst);
1859  break;
1860  case AUX_CACHE:
1861  this->auxiliaries << sanitize_source(casadi_cache_str, inst);
1862  break;
1863  case AUX_CVX:
1870  this->auxiliaries << sanitize_source(casadi_cvx_str, inst);
1871  break;
1872  case AUX_CONVEXIFY:
1877  this->auxiliaries << sanitize_source(casadi_convexify_str, inst);
1878  break;
1879  case AUX_LOGSUMEXP:
1882  this->auxiliaries << sanitize_source(casadi_logsumexp_str, inst);
1883  break;
1884  case AUX_SPARSITY:
1885  this->auxiliaries << sanitize_source(casadi_sparsity_str, inst);
1886  break;
1887  case AUX_BFGS:
1896  this->auxiliaries << sanitize_source(casadi_bfgs_str, inst);
1897  break;
1898  case AUX_ORACLE:
1899  this->auxiliaries << sanitize_source(casadi_oracle_str, inst);
1900  break;
1901  case AUX_ORACLE_CALLBACK:
1902  this->auxiliaries << sanitize_source(casadi_oracle_callback_str, inst);
1903  break;
1904  case AUX_OCP_BLOCK:
1905  this->auxiliaries << sanitize_source(casadi_ocp_block_str, inst);
1906  break;
1907  case AUX_TO_DOUBLE:
1908  this->auxiliaries << "#define casadi_to_double(x) "
1909  << "(" << (this->cpp ? "static_cast<double>(x)" : "(double) x") << ")\n\n";
1910  break;
1911  case AUX_TO_INT:
1912  this->auxiliaries << "#define casadi_to_int(x) "
1913  << "(" << (this->cpp ? "static_cast<casadi_int>(x)" : "(casadi_int) x")
1914  << ")\n\n";
1915  break;
1916  case AUX_CAST:
1917  this->auxiliaries << "#define CASADI_CAST(x,y) "
1918  << "(" << (this->cpp ? "static_cast<x>(y)" : "(x) y") << ")\n\n";
1919  break;
1920  case AUX_SQ:
1921  this->auxiliaries << sanitize_source(
1922  "// SYMBOL \"sq\"\n"
1923  "casadi_real casadi_sq(casadi_real x) { return x*x;}\n\n",
1924  inst);
1925  break;
1926  case AUX_SIGN:
1927  this->auxiliaries << sanitize_source(
1928  "// SYMBOL \"sign\"\n"
1929  "casadi_real casadi_sign(casadi_real x) "
1930  "{ return x<0 ? -1 : x>0 ? 1 : x;}\n\n",
1931  inst);
1932  break;
1933  case AUX_IF_ELSE:
1934  this->auxiliaries << sanitize_source(
1935  "// SYMBOL \"if_else\"\n"
1936  "casadi_real casadi_if_else"
1937  "(casadi_real c, casadi_real x, casadi_real y) "
1938  "{ return c!=0 ? x : y;}\n\n",
1939  inst);
1940  break;
1941  case AUX_PRINTF:
1942  this->auxiliaries << "#ifndef CASADI_PRINTF\n";
1943  if (this->mex) {
1944  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1945  << " #define CASADI_PRINTF mexPrintf\n"
1946  << "#else\n"
1947  << " #define CASADI_PRINTF printf\n"
1948  << "#endif\n";
1949  } else {
1950  add_include("stdio.h");
1951  this->auxiliaries << "#define CASADI_PRINTF printf\n";
1952  this->auxiliaries << "#ifndef CASADI_SNPRINTF\n";
1953  this->auxiliaries << "#define CASADI_SNPRINTF snprintf\n";
1954  this->auxiliaries << "#endif\n\n";
1955  }
1956  this->auxiliaries << "#endif\n\n";
1957  break;
1958  case AUX_FMIN:
1959  this->auxiliaries << sanitize_source(
1960  "// SYMBOL \"fmin\"\n"
1961  "casadi_real casadi_fmin(casadi_real x, casadi_real y) {\n"
1962  "/* Pre-c99 compatibility */\n"
1963  "#if __STDC_VERSION__ < 199901L\n"
1964  " return x<y ? x : y;\n"
1965  "#else\n"
1966  " return fmin(x, y);\n"
1967  "#endif\n"
1968  "}\n\n",
1969  inst);
1970  break;
1971  case AUX_FMAX:
1972  this->auxiliaries << sanitize_source(
1973  "// SYMBOL \"fmax\"\n"
1974  "casadi_real casadi_fmax(casadi_real x, casadi_real y) {\n"
1975  "/* Pre-c99 compatibility */\n"
1976  "#if __STDC_VERSION__ < 199901L\n"
1977  " return x>y ? x : y;\n"
1978  "#else\n"
1979  " return fmax(x, y);\n"
1980  "#endif\n"
1981  "}\n\n",
1982  inst);
1983  break;
1984  case AUX_FABS:
1985  this->auxiliaries << sanitize_source(
1986  "// SYMBOL \"fabs\"\n"
1987  "casadi_real casadi_fabs(casadi_real x) {\n"
1988  "/* Pre-c99 compatibility */\n"
1989  "#if __STDC_VERSION__ < 199901L\n"
1990  " return x>0 ? x : -x;\n"
1991  "#else\n"
1992  " return fabs(x);\n"
1993  "#endif\n"
1994  "}\n\n",
1995  inst);
1996  break;
1997  case AUX_ISINF:
1998  this->auxiliaries << sanitize_source(
1999  "// SYMBOL \"isinf\"\n"
2000  "casadi_real casadi_isinf(casadi_real x) {\n"
2001  "/* Pre-c99 compatibility */\n"
2002  "#if __STDC_VERSION__ < 199901L\n"
2003  " return x== INFINITY || x==-INFINITY;\n"
2004  "#else\n"
2005  " return isinf(x);\n"
2006  "#endif\n"
2007  "}\n\n",
2008  inst);
2009  break;
2010  case AUX_ISFINITE:
2011  this->auxiliaries << sanitize_source(
2012  "// SYMBOL \"isfinite\"\n"
2013  "casadi_real casadi_isfinite(casadi_real x) {\n"
2014  "/* Pre-c99 compatibility */\n"
2015  "#if __STDC_VERSION__ < 199901L\n"
2016  " return x==x && x!=INFINITY && x!=-INFINITY;\n"
2017  "#else\n"
2018  " return isfinite(x);\n"
2019  "#endif\n"
2020  "}\n\n",
2021  inst);
2022  break;
2023  case AUX_MIN:
2024  this->auxiliaries << sanitize_source(
2025  "// SYMBOL \"min\"\n"
2026  "casadi_int casadi_min(casadi_int x, casadi_int y) {\n"
2027  " return x>y ? y : x;\n"
2028  "}\n\n",
2029  inst);
2030  break;
2031  case AUX_MAX:
2032  this->auxiliaries << sanitize_source(
2033  "// SYMBOL \"max\"\n"
2034  "casadi_int casadi_max(casadi_int x, casadi_int y) {\n"
2035  " return x>y ? x : y;\n"
2036  "}\n\n",
2037  inst);
2038  break;
2039  case AUX_MMIN:
2042  this->auxiliaries << sanitize_source(casadi_mmin_str, inst);
2043  break;
2044  case AUX_MMAX:
2047  this->auxiliaries << sanitize_source(casadi_mmax_str, inst);
2048  break;
2049  case AUX_INF:
2050  this->auxiliaries << "#ifndef casadi_inf\n"
2051  << " #define casadi_inf " << this->infinity << "\n"
2052  << "#endif\n\n";
2053  break;
2054  case AUX_NAN:
2055  this->auxiliaries << "#ifndef casadi_nan\n"
2056  << " #define casadi_nan " << this->nan << "\n"
2057  << "#endif\n\n";
2058  break;
2059  case AUX_REAL_MIN:
2060  this->auxiliaries << "#ifndef casadi_real_min\n"
2061  << " #define casadi_real_min " << this->real_min << "\n"
2062  << "#endif\n\n";
2063  break;
2064  case AUX_LOG1P:
2065  this->auxiliaries << sanitize_source(
2066  "// SYMBOL \"log1p\"\n"
2067  "casadi_real casadi_log1p(casadi_real x) {\n"
2068  "/* Pre-c99 compatibility */\n"
2069  "#if __STDC_VERSION__ < 199901L\n"
2070  " return log(1+x);\n"
2071  "#else\n"
2072  " return log1p(x);\n"
2073  "#endif\n"
2074  "}\n\n",
2075  inst);
2076  break;
2077  case AUX_EXPM1:
2078  this->auxiliaries << sanitize_source(
2079  "// SYMBOL \"expm1\"\n"
2080  "casadi_real casadi_expm1(casadi_real x) {\n"
2081  "/* Pre-c99 compatibility */\n"
2082  "#if __STDC_VERSION__ < 199901L\n"
2083  " return exp(x)-1;\n"
2084  "#else\n"
2085  " return expm1(x);\n"
2086  "#endif\n"
2087  "}\n\n",
2088  inst);
2089  break;
2090  case AUX_HYPOT:
2091  this->auxiliaries << sanitize_source(
2092  "// SYMBOL \"hypot\"\n"
2093  "casadi_real casadi_hypot(casadi_real x, casadi_real y) {\n"
2094  "/* Pre-c99 compatibility */\n"
2095  "#if __STDC_VERSION__ < 199901L\n"
2096  " return sqrt(x*x+y*y);\n"
2097  "#else\n"
2098  " return hypot(x, y);\n"
2099  "#endif\n"
2100  "}\n\n",
2101  inst);
2102  break;
2103  case AUX_BLAZING_COMMON:
2105  add_include("simde/x86/avx2.h");
2106  add_include("simde/x86/fma.h");
2107  this->auxiliaries << sanitize_source(casadi_blazing_common_str, inst);
2108  break;
2111  this->auxiliaries << sanitize_source(casadi_blazing_1d_boor_eval_str, inst);
2112  break;
2115  this->auxiliaries << sanitize_source(casadi_blazing_2d_boor_eval_str, inst);
2116  break;
2119  this->auxiliaries << sanitize_source(casadi_blazing_3d_boor_eval_str, inst);
2120  break;
2123  this->auxiliaries << sanitize_source(casadi_blazing_4d_boor_eval_str, inst);
2124  break;
2127  this->auxiliaries << sanitize_source(casadi_blazing_5d_boor_eval_str, inst);
2128  break;
2129  case AUX_PRINTME:
2131  this->auxiliaries << sanitize_source(casadi_printme_str, inst);
2132  break;
2133  case AUX_PRINT_SCALAR:
2135  this->auxiliaries << sanitize_source(casadi_print_scalar_str, inst);
2136  break;
2137  case AUX_PRINT_VECTOR:
2139  this->auxiliaries << sanitize_source(casadi_print_vector_str, inst);
2140  break;
2141  case AUX_PRINT_CANONICAL:
2143  this->auxiliaries << sanitize_source(casadi_print_canonical_str, inst);
2144  break;
2145  case AUX_FPRINTF_SCALAR:
2146  add_include("stdio.h");
2148  this->auxiliaries << sanitize_source(casadi_fprintf_scalar_str, inst);
2149  break;
2150  case AUX_FPRINTF_VECTOR:
2152  this->auxiliaries << sanitize_source(casadi_fprintf_vector_str, inst);
2153  break;
2154  case AUX_TO_FILE:
2155  add_include("stdio.h");
2157  this->auxiliaries << sanitize_source(casadi_to_file_str, inst);
2158  break;
2159  case AUX_THREADS:
2160  this->auxiliaries << sanitize_source(casadi_threads_str, inst);
2161  break;
2162  }
2163  }
2164 
2165  std::string CodeGenerator::to_mex(const Sparsity& sp, const std::string& arg) {
2167  std::stringstream s;
2168  s << "casadi_to_mex(" << sparsity(sp) << ", " << arg << ");";
2169  return s.str();
2170  }
2171 
2172  std::string CodeGenerator::from_mex(std::string& arg,
2173  const std::string& res, std::size_t res_off,
2174  const Sparsity& sp_res, const std::string& w) {
2175  // Handle offset with recursion
2176  if (res_off!=0) return from_mex(arg, res+"+"+str(res_off), 0, sp_res, w);
2177 
2179  std::stringstream s;
2180  s << "casadi_from_mex(" << arg
2181  << ", " << res << ", " << sparsity(sp_res) << ", " << w << ");";
2182  return s.str();
2183  }
2184 
2185  std::string CodeGenerator::fmu_helpers(const std::string& modelname) {
2186  // Process C++ source
2187  std::stringstream ret;
2188  std::string line;
2189  std::istringstream stream(casadi_fmu_str);
2190  while (std::getline(stream, line)) {
2191  // Replacements
2192  if (line.find("MODELNAME") != std::string::npos) {
2193  line = replace(line, "MODELNAME", modelname);
2194  }
2195  // Append to return
2196  ret << line << "\n";
2197  }
2198  return ret.str();
2199  }
2200 
2201  std::string CodeGenerator::constant(const std::string& v) {
2202  std::string ret = v;
2203  ret = replace(ret, "\\", "\\\\");
2204  ret = replace(ret, "\"", "\\\"");
2205  return "\"" + ret + "\"";
2206  }
2207 
2208  std::string CodeGenerator::constant(casadi_int v) {
2209  return str(v);
2210  }
2211 
2212  std::string CodeGenerator::constant(char v) {
2213  return constant(static_cast<casadi_int>(v));
2214  }
2215  std::string CodeGenerator::constant(double v) {
2216  std::stringstream s;
2217  if (isnan(v)) {
2219  s << "casadi_nan";
2220  } else if (isinf(v)) {
2222  if (v<0) s << "-";
2223  s << "casadi_inf";
2224  } else {
2225  casadi_int v_int = static_cast<casadi_int>(v);
2226  if (static_cast<double>(v_int)==v) {
2227  // Print integer
2228  s << v_int << ".";
2229  } else {
2230  // Print real
2231  std::ios_base::fmtflags fmtfl = s.flags(); // get current format flags
2232  s << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1) << v;
2233  s.flags(fmtfl); // reset current format flags
2234  }
2235  }
2236  return s.str();
2237  }
2238 
2239  std::string CodeGenerator::copy(const std::string& arg,
2240  std::size_t n, const std::string& res) {
2241  std::stringstream s;
2242  // Perform operation
2244  s << "casadi_copy(" << arg << ", " << n << ", " << res << ");";
2245  return s.str();
2246  }
2247 
2248  bool CodeGenerator::elide_copy(casadi_int sz) {
2249  if (casadi::GlobalOptions::copy_elision_min_size==-1) return false;
2251  }
2252 
2253  void CodeGenerator::copy_check(const std::string& arg, size_t n, const std::string& res,
2254  bool check_lhs, bool check_rhs) {
2255  std::vector<std::string> checks;
2256  if (check_lhs) checks.push_back(arg);
2257  if (check_rhs) checks.push_back(res);
2258  if (!checks.empty()) *this << "if (" << join(checks, " && ") << ") ";
2259  *this << copy(arg, n, res) << "\n";
2260  }
2261 
2262  void CodeGenerator::copy_default(const std::string& arg, size_t n, const std::string& res,
2263  const std::string& def, bool check_rhs) {
2264  *this << "if (" << arg << ") {\n";
2265  if (check_rhs) *this << "if (" << res << ") ";
2266  *this << copy(arg, n, res) << "\n";
2267  *this << "} else {\n";
2268  if (check_rhs) *this << "if (" << res << ") ";
2269  *this << fill(res, n, def) << "\n";
2270  *this << "}\n";
2271  }
2272 
2273  std::string CodeGenerator::clear(const std::string& res, std::size_t n) {
2274  std::stringstream s;
2275  // Perform operation
2277  s << "casadi_clear(" << res << ", " << n << ");";
2278  return s.str();
2279  }
2280 
2281  std::string CodeGenerator::arg(casadi_int i) const {
2282  return "arg[" + str(i) + "]";
2283  }
2284 
2285  std::string CodeGenerator::res(casadi_int i) const {
2286  return "res[" + str(i) + "]";
2287  }
2288 
2289  std::string CodeGenerator::mem(const Function& f) {
2290  std::string name = f->codegen_name(*this, false);
2291  std::string mem_array = shorthand(name + "_mem");
2292  return mem_array+"[mem]";
2293  }
2294 
2295  std::string CodeGenerator::fill(const std::string& res,
2296  std::size_t n, const std::string& v) {
2297  if (v=="0") return clear(res, n);
2298  std::stringstream s;
2299  // Perform operation
2301  s << "casadi_fill(" << res << ", " << n << ", " << v << ");";
2302  return s.str();
2303  }
2304 
2305  std::string CodeGenerator::dot(casadi_int n, const std::string& x,
2306  const std::string& y) {
2308  std::stringstream s;
2309  s << "casadi_dot(" << n << ", " << x << ", " << y << ")";
2310  return s.str();
2311  }
2312 
2313  std::string CodeGenerator::bilin(const std::string& A, const Sparsity& sp_A,
2314  const std::string& x, const std::string& y) {
2316  std::stringstream s;
2317  s << "casadi_bilin(" << A << ", " << sparsity(sp_A) << ", " << x << ", " << y << ")";
2318  return s.str();
2319  }
2320 
2321  std::string CodeGenerator::rank1(const std::string& A, const Sparsity& sp_A,
2322  const std::string& alpha, const std::string& x,
2323  const std::string& y) {
2325  std::stringstream s;
2326  s << "casadi_rank1(" << A << ", " << sparsity(sp_A) << ", "
2327  << alpha << ", " << x << ", " << y << ");";
2328  return s.str();
2329  }
2330 
2332  const std::string& res, casadi_int ndim, const std::string& grid,
2333  const std::string& offset,
2334  const std::string& values, const std::string& x,
2335  const std::string& lookup_mode, casadi_int m,
2336  const std::string& iw, const std::string& w) {
2338  std::stringstream s;
2339  s << "casadi_interpn(" << res << ", " << ndim << ", " << grid << ", " << offset << ", "
2340  << values << ", " << x << ", " << lookup_mode << ", " << m << ", " << iw << ", " << w << ");";
2341  return s.str();
2342  }
2343 
2344  std::string CodeGenerator::interpn_grad(const std::string& grad,
2345  casadi_int ndim, const std::string& grid, const std::string& offset,
2346  const std::string& values, const std::string& x,
2347  const std::string& lookup_mode, casadi_int m,
2348  const std::string& iw, const std::string& w) {
2350  std::stringstream s;
2351  s << "casadi_interpn_grad(" << grad << ", " << ndim << ", " << grid << ", " << offset << ", "
2352  << values << ", " << x << ", " << lookup_mode << "," << m << ", " << iw << ", " << w << ");";
2353  return s.str();
2354  }
2355 
2356  std::string CodeGenerator::trans(const std::string& x, const Sparsity& sp_x,
2357  const std::string& y, const Sparsity& sp_y,
2358  const std::string& iw) {
2360  return "casadi_trans(" + x + "," + sparsity(sp_x) + ", "
2361  + y + ", " + sparsity(sp_y) + ", " + iw + ")";
2362  }
2363 
2364  std::string CodeGenerator::declare(std::string s) {
2365  // Add c linkage
2366  std::string cpp_prefix = this->cpp ? "extern \"C\" " : "";
2367 
2368  // To header file
2369  if (this->with_header) {
2370  this->header << cpp_prefix << this->dll_import << s << ";\n";
2371  }
2372 
2373  // Return name with declarations
2374  return cpp_prefix + this->dll_export + s;
2375  }
2376 
2377  std::string
2378  CodeGenerator::project(const std::string& arg, const Sparsity& sp_arg,
2379  const std::string& res, const Sparsity& sp_res,
2380  const std::string& w) {
2381  // If sparsity match, simple copy
2382  if (sp_arg==sp_res) return copy(arg, sp_arg.nnz(), res);
2383 
2384  // Create call
2386  std::stringstream s;
2387  s << "casadi_project(" << arg << ", " << sparsity(sp_arg) << ", " << res << ", "
2388  << sparsity(sp_res) << ", " << w << ");";
2389  return s.str();
2390  }
2391 
2392  std::string
2393  CodeGenerator::tri_project(const std::string& arg, const Sparsity& sp_arg,
2394  const std::string& res, bool lower) {
2395  // Create call
2397  std::stringstream s;
2398  s << "casadi_tri_project(" << arg << ", " << sparsity(sp_arg) << ", ";
2399  s << res << ", " << (lower ? 1: 0) << ");";
2400  return s.str();
2401  }
2402 
2403  std::string
2404  CodeGenerator::densify(const std::string& arg, const Sparsity& sp_arg,
2405  const std::string& res, bool tr) {
2406  // Create call
2408  std::stringstream s;
2409  s << "casadi_densify(" << arg << ", " << sparsity(sp_arg) << ", " << res << ", "
2410  << (tr ? 1 : 0) << ");";
2411  return s.str();
2412  }
2413 
2414  std::string
2415  CodeGenerator::sparsify(const std::string& arg, const std::string& res,
2416  const Sparsity& sp_res, bool tr) {
2417  // Create call
2419  std::stringstream s;
2420  s << "casadi_sparsify(" << arg << ", " << res << ", "
2421  << sparsity(sp_res) << ", " << (tr ? 1 : 0) << ");";
2422  return s.str();
2423  }
2424 
2425  std::string CodeGenerator::printf(const std::string& str, const std::vector<std::string>& arg) {
2427  std::stringstream s;
2428  s << "CASADI_PRINTF(";
2429  // Loop over lines in str
2430  std::string::size_type pos = 0, prev = 0;
2431  while ((pos = str.find('\n', prev)) != std::string::npos) {
2432  // Any line containing a trailing new line
2433  s << "\"" << str.substr(prev, pos-prev) << "\\n\"\n";
2434  prev = pos + 1;
2435  }
2436  // Remainder without trailing new line
2437  s << "\"" << str.substr(prev) << "\"";
2438  for (casadi_int i=0; i<arg.size(); ++i) s << ", " << arg[i];
2439  s << ");";
2440  return s.str();
2441  }
2442 
2443  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1) {
2444  std::vector<std::string> arg;
2445  arg.push_back(arg1);
2446  return printf(str, arg);
2447  }
2448 
2449  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1,
2450  const std::string& arg2) {
2451  std::vector<std::string> arg;
2452  arg.push_back(arg1);
2453  arg.push_back(arg2);
2454  return printf(str, arg);
2455  }
2456 
2457  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1,
2458  const std::string& arg2, const std::string& arg3) {
2459  std::vector<std::string> arg;
2460  arg.push_back(arg1);
2461  arg.push_back(arg2);
2462  arg.push_back(arg3);
2463  return printf(str, arg);
2464  }
2465 
2466  std::string CodeGenerator::axpy(casadi_int n, const std::string& a,
2467  const std::string& x, const std::string& y) {
2469  return "casadi_axpy(" + str(n) + ", " + a + ", " + x + ", " + y + ");";
2470  }
2471 
2472  std::string CodeGenerator::clip_min(const std::string& x, casadi_int n,
2473  const std::string& min, const std::string& mask) {
2475  return "casadi_clip_min(" + x + ", " + str(n) + ", " + min + ", " + mask + ");";
2476  }
2477 
2478  std::string CodeGenerator::clip_max(const std::string& x, casadi_int n,
2479  const std::string& min, const std::string& mask) {
2481  return "casadi_clip_max(" + x + ", " + str(n) + ", " + min + ", " + mask + ");";
2482  }
2483 
2484  std::string CodeGenerator::vector_fmax(casadi_int n, const std::string& x,
2485  const std::string& y, const std::string& z) {
2487  return "casadi_vector_fmax(" + str(n) + ", " + x + ", " + y + ", " + z + ");";
2488  }
2489 
2490  std::string CodeGenerator::vector_fmin(casadi_int n, const std::string& x,
2491  const std::string& y, const std::string& z) {
2493  return "casadi_vector_fmin(" + str(n) + ", " + x + ", " + y + ", " + z + ");";
2494  }
2495 
2496  std::string CodeGenerator::masked_norm_inf(casadi_int n, const std::string& x,
2497  const std::string& mask) {
2499  return "casadi_masked_norm_inf(" + str(n) + ", " + x + ", " + mask + ")";
2500  }
2501 
2502  std::string CodeGenerator::scal(casadi_int n, const std::string& alpha, const std::string& x) {
2504  return "casadi_scal(" + str(n) + ", " + alpha + ", " + x + ");";
2505  }
2506 
2507  std::string CodeGenerator::mv(const std::string& x, const Sparsity& sp_x,
2508  const std::string& y, const std::string& z, bool tr) {
2510  return "casadi_mv(" + x + ", " + sparsity(sp_x) + ", " + y + ", "
2511  + z + ", " + (tr ? "1" : "0") + ");";
2512  }
2513 
2514  std::string CodeGenerator::mv(const std::string& x, casadi_int nrow_x, casadi_int ncol_x,
2515  const std::string& y, const std::string& z, bool tr) {
2517  return "casadi_mv_dense(" + x + ", " + str(nrow_x) + ", " + str(ncol_x) + ", "
2518  + y + ", " + z + ", " + (tr ? "1" : "0") + ");";
2519  }
2520 
2521  std::string CodeGenerator::mtimes(const std::string& x, const Sparsity& sp_x,
2522  const std::string& y, const Sparsity& sp_y,
2523  const std::string& z, const Sparsity& sp_z,
2524  const std::string& w, bool tr) {
2526  return "casadi_mtimes(" + x + ", " + sparsity(sp_x) + ", " + y + ", " + sparsity(sp_y) + ", "
2527  + z + ", " + sparsity(sp_z) + ", " + w + ", " + (tr ? "1" : "0") + ");";
2528  }
2529 
2530  std::string CodeGenerator::mtimes(const std::string& x, casadi_int nrow_x, casadi_int ncol_x,
2531  const std::string& y, casadi_int ncol_y,
2532  const std::string& z, bool tr) {
2534  return "casadi_mtimes_dense(" + x + ", " + str(nrow_x) + ", " + str(ncol_x) + ", "
2535  + y + ", " + str(ncol_y) + ", " + z + ", " + (tr ? "1" : "0") + ");";
2536  }
2537 
2538  std::string CodeGenerator::mtimes_dense_sparse(const std::string& x, casadi_int nrow_x,
2539  const std::string& y, const Sparsity& sp_y, const std::string& z) {
2541  return "casadi_mtimes_dense_sparse(" + x + ", " + str(nrow_x) + ", "
2542  + y + ", " + sparsity(sp_y) + ", " + z + ");";
2543  }
2544 
2545  std::string CodeGenerator::trilsolve(const Sparsity& sp_x, const std::string& x,
2546  const std::string& y, bool tr, bool unity, casadi_int nrhs) {
2548  return "casadi_trilsolve(" + sparsity(sp_x) + ", " + x + ", " + y + ", " + str(tr) + ", "
2549  + str(unity) + ", " + str(nrhs) + ");";
2550  }
2551 
2552  std::string CodeGenerator::triusolve(const Sparsity& sp_x, const std::string& x,
2553  const std::string& y, bool tr, bool unity, casadi_int nrhs) {
2555  return "casadi_triusolve(" + sparsity(sp_x) + ", " + x + ", " + y + ", " + str(tr) + ", "
2556  + str(unity) + ", " + str(nrhs) + ");";
2557  }
2558 
2559 
2560  std::string CodeGenerator::logsumexp(const std::string& A, casadi_int n) {
2562  std::stringstream s;
2563  s << "casadi_logsumexp(" << A << ", " << n << ");";
2564  return s.str();
2565  }
2566 
2567  void CodeGenerator::print_formatted(const std::string& s) {
2568  // Quick return if empty
2569  if (s.empty()) return;
2570 
2571  // If new line, add indentation
2572  if (newline_) {
2573  casadi_int shift = s.front()=='}' ? -1 : 0;
2574  casadi_assert_dev(current_indent_+shift>=0);
2575  this->buffer << std::string(indent_*(current_indent_+shift), ' ');
2576  newline_ = false;
2577  }
2578 
2579  // Print to body
2580  this->buffer << s;
2581 
2582  // Brackets change indentation for next row
2583  // NOTE(@jaeandersson): Should ignore strings, comments
2584  for (char c : s) {
2585  if (c=='{') {
2586  indent();
2587  } else if (c=='}') {
2588  unindent();
2589  }
2590  }
2591  }
2592 
2593  CodeGenerator& CodeGenerator::operator<<(const std::string& s) {
2594  // Loop over newline characters
2595  size_t off=0;
2596  while (true) {
2597  size_t pos = s.find('\n', off);
2598  if (pos==std::string::npos) {
2599  // No more newline characters
2600  print_formatted(s.substr(off));
2601  break;
2602  } else {
2603  // Ends with newline
2604  print_formatted(s.substr(off, pos-off));
2605  this->buffer << '\n';
2606  newline_ = true;
2607  off = pos+1;
2608  }
2609  }
2610 
2611  return *this;
2612  }
2613 
2614  void CodeGenerator::flush(std::ostream &s) {
2615  s << this->buffer.str();
2616  this->buffer.str(std::string());
2617  }
2618 
2619  void CodeGenerator::local(const std::string& name, const std::string& type,
2620  const std::string& ref) {
2621  // Check if the variable already exists
2622  auto it = local_variables_.find(name);
2623  if (it==local_variables_.end()) {
2624  // Add it
2625  local_variables_[name] = std::make_pair(type, ref);
2626  } else {
2627  // Consistency check
2628  casadi_assert(it->second.first==type, "Type mismatch for " + name);
2629  casadi_assert(it->second.second==ref, "Type mismatch for " + name);
2630  }
2631  }
2632 
2633  std::string CodeGenerator::sx_work(casadi_int i) {
2634  if (avoid_stack_) {
2635  return "w[" + str(i) + "]";
2636  } else {
2637  std::string name = "a"+format_padded(i);
2638 
2639  // Make sure work vector element has been declared
2640  local(name, "casadi_real");
2641 
2642  return name;
2643  }
2644  }
2645 
2646  void CodeGenerator::init_local(const std::string& name, const std::string& def) {
2647  auto it = local_default_.find(name);
2648  if (it!=local_default_.end()) {
2649  casadi_assert(it->second==def, "Initial value mismatch for " + name);
2650  }
2651  local_default_.insert(std::make_pair(name, def));
2652  }
2653 
2654  // Read the next double-quoted token from line, starting at pos.
2655  // Backslash escapes the next character, so \" and \\ may appear inside.
2656  // On return, pos points just past the closing quote.
2657  static std::string next_quoted_token(const std::string& line, size_t& pos) {
2658  size_t n1 = line.find('"', pos);
2659  casadi_assert(n1 != std::string::npos, "Missing quoted token in: " + line);
2660  std::string r;
2661  size_t i = n1 + 1;
2662  for (; i < line.size(); ++i) {
2663  if (line[i] == '\\' && i + 1 < line.size()) {
2664  r += line[++i];
2665  } else if (line[i] == '"') {
2666  break;
2667  } else {
2668  r += line[i];
2669  }
2670  }
2671  casadi_assert(i < line.size(), "Unterminated quoted token in: " + line);
2672  pos = i + 1;
2673  return r;
2674  }
2675 
2676  std::string CodeGenerator::
2677  sanitize_source(const std::string& src,
2678  const std::vector<std::string>& inst, bool add_shorthand) {
2679  // Create suffix if templates type are not all "casadi_real"
2680  std::string suffix;
2681  for (const std::string& s : inst) {
2682  if (s!="casadi_real") {
2683  for (const std::string& s : inst) suffix += "_" + s;
2684  break;
2685  }
2686  }
2687 
2688  // Construct map of name replacements
2689  std::vector<std::pair<std::string, std::string> > rep;
2690  for (casadi_int i=0; i<inst.size(); ++i) {
2691  rep.push_back(std::make_pair("T" + str(i+1), inst[i]));
2692  }
2693 
2694  // Return object
2695  std::stringstream ret;
2696  // Process C++ source
2697  std::string line;
2698  std::istringstream stream(src);
2699 
2700  bool filter_macros = true; // Macro definitions are ignored
2701 
2702  // Set by `// SYMBOL "X"` to "casadi_X"; cleared when the matching
2703  // function signature is found and the prefix is prepended.
2704  std::string active_symbol;
2705 
2706  while (std::getline(stream, line)) {
2707  size_t n1, n2;
2708 
2709  // C++ template declarations are ignored
2710  if (line.find("template")==0) continue;
2711 
2712  // Macro definitions are ignored
2713  if (filter_macros && line.find("#define")==0) continue;
2714  if (filter_macros && line.find("#undef")==0) continue;
2715 
2716  // casadi_assert and error are ignored
2717  if (line.find("casadi_assert") != std::string::npos) continue;
2718  if (line.find("casadi_error") != std::string::npos) continue;
2719  if (line.find("casadi_message") != std::string::npos) continue;
2720 
2721  // Inline declaration
2722  if (line == "inline") continue;
2723 
2724  // If line starts with "// SYMBOL", add shorthand and track the symbol
2725  if (line.find("// SYMBOL") != std::string::npos) {
2726  n1 = line.find("\"");
2727  n2 = line.find("\"", n1+1);
2728  std::string sym = line.substr(n1+1, n2-n1-1);
2729  if (add_shorthand) shorthand(sym + suffix);
2730  if (!suffix.empty()) {
2731  rep.push_back(std::make_pair(sym, sym + suffix));
2732  }
2733  active_symbol = "casadi_" + sym;
2734  continue;
2735  }
2736 
2737  // If line starts with "// C-REPLACE", add to list of replacements
2738  if (line.find("// C-REPLACE") != std::string::npos) {
2739  // Get C++ string, then C string; \" and \\ are unescaped
2740  size_t pos = line.find("// C-REPLACE");
2741  std::string key = next_quoted_token(line, pos);
2742  std::string sub = next_quoted_token(line, pos);
2743  // Add to replacements
2744  rep.push_back(std::make_pair(key, sub));
2745  continue;
2746  }
2747 
2748  // If line starts with "// C-VERBOSE", skip the next line
2749  if (!verbose_runtime && line.find("// C-VERBOSE") != std::string::npos) {
2750  // Ignore next line
2751  std::getline(stream, line);
2752  continue;
2753  }
2754 
2755  if (line.find("// FILTER-MACROS ON") != std::string::npos) {
2756  filter_macros = true;
2757  }
2758 
2759  if (line.find("// FILTER-MACROS OFF") != std::string::npos) {
2760  filter_macros = false;
2761  }
2762 
2763  // Ignore other C++ style comment
2764  n1 = line.find("//");
2765  if (n1 != std::string::npos) line.erase(n1);
2766 
2767  // Remove trailing spaces
2768  n1 = line.find_last_not_of(' ');
2769  if (n1 != std::string::npos) {
2770  line.erase(n1 + 1);
2771  } else {
2772  continue;
2773  }
2774 
2775  // Prepend storage-class/inline-hint to the symbol's signature line
2776  if (!active_symbol.empty() &&
2777  line.find(active_symbol + "(") != std::string::npos) {
2778  std::string sig_prefix;
2779  if (this->static_aux) sig_prefix += "static ";
2780  if (this->inline_aux) sig_prefix += "inline ";
2781  if (!sig_prefix.empty()) line = sig_prefix + line;
2782  active_symbol.clear();
2783  }
2784 
2785  // Perform string replacements
2786  for (auto&& it = rep.rbegin(); it!=rep.rend(); ++it) {
2787  line = replace(line, it->first, it->second);
2788  }
2789 
2790  // Append to return
2791  ret << line << "\n";
2792  }
2793 
2794  // Trailing newline
2795  ret << "\n";
2796  return ret.str();
2797  }
2798 
2799  void CodeGenerator::comment(const std::string& s) {
2800  if (verbose) {
2801  *this << "/* " << s << " */\n";
2802  }
2803  }
2804 
2806  add_io_sparsities(const std::string& name,
2807  const std::vector<Sparsity>& sp_in,
2808  const std::vector<Sparsity>& sp_out) {
2809  // Insert element, quick return if it already exists
2810  if (!sparsity_meta.insert(name).second) return;
2811 
2812  // Input sparsities
2813  *this << declare("const casadi_int* " + name + "_sparsity_in(casadi_int i)") << " {\n"
2814  << "switch (i) {\n";
2815  for (casadi_int i=0; i<sp_in.size(); ++i) {
2816  *this << "case " << i << ": return " << sparsity(sp_in[i], force_canonical) << ";\n";
2817  }
2818  *this << "default: return 0;\n}\n"
2819  << "}\n\n";
2820 
2821  // Output sparsities
2822  *this << declare("const casadi_int* " + name + "_sparsity_out(casadi_int i)") << " {\n"
2823  << "switch (i) {\n";
2824  for (casadi_int i=0; i<sp_out.size(); ++i) {
2825  *this << "case " << i << ": return " << sparsity(sp_out[i], force_canonical) << ";\n";
2826  }
2827  *this << "default: return 0;\n}\n"
2828  << "}\n\n";
2829  }
2830 
2831  std::string CodeGenerator::
2832  qr(const std::string& sp, const std::string& A, const std::string& w,
2833  const std::string& sp_v, const std::string& v, const std::string& sp_r,
2834  const std::string& r, const std::string& beta, const std::string& prinv,
2835  const std::string& pc) {
2837  return "casadi_qr(" + sp + ", " + A + ", " + w + ", "
2838  + sp_v + ", " + v + ", " + sp_r + ", " + r + ", "
2839  + beta + ", " + prinv + ", " + pc + ");";
2840  }
2841 
2842  std::string CodeGenerator::
2843  det(const std::string& sp_v, const std::string& v,
2844  const std::string& sp_r, const std::string& r, const std::string& beta) {
2846  return "casadi_det(" + sp_v + ", " + v + ", " + sp_r + ", " + r + ", " + beta + ")";
2847  }
2848 
2849  std::string CodeGenerator::
2850  qr_solve(const std::string& x, casadi_int nrhs, bool tr,
2851  const std::string& sp_v, const std::string& v,
2852  const std::string& sp_r, const std::string& r,
2853  const std::string& beta, const std::string& prinv,
2854  const std::string& pc, const std::string& w) {
2856  return "casadi_qr_solve(" + x + ", " + str(nrhs) + ", " + (tr ? "1" : "0") + ", "
2857  + sp_v + ", " + v + ", " + sp_r + ", " + r + ", "
2858  + beta + ", " + prinv + ", " + pc + ", " + w + ");";
2859  }
2860 
2861  std::string CodeGenerator::
2862  lsqr_solve(const std::string& A, const std::string&x,
2863  casadi_int nrhs, bool tr, const std::string& sp, const std::string& w) {
2865  return "casadi_lsqr_solve(" + A + ", " + x + ", " + str(nrhs) + ", "
2866  + (tr ? "1" : "0") + ", " + sp + ", " + w + ");";
2867  }
2868 
2869  std::string CodeGenerator::
2870  ldl(const std::string& sp_a, const std::string& a,
2871  const std::string& sp_lt, const std::string& lt, const std::string& d,
2872  const std::string& p, const std::string& w) {
2874  return "casadi_ldl(" + sp_a + ", " + a + ", " + sp_lt + ", " + lt + ", "
2875  + d + ", " + p + ", " + w + ");";
2876  }
2877 
2878  std::string CodeGenerator::
2879  ldl_solve(const std::string& x, casadi_int nrhs,
2880  const std::string& sp_lt, const std::string& lt, const std::string& d,
2881  const std::string& p, const std::string& w) {
2883  return "casadi_ldl_solve(" + x + ", " + str(nrhs) + ", " + sp_lt + ", "
2884  + lt + ", " + d + ", " + p + ", " + w + ");";
2885  }
2886 
2887  std::string CodeGenerator::
2888  fmax(const std::string& x, const std::string& y) {
2890  return "casadi_fmax(" + x + ", " + y + ");";
2891  }
2892 
2893  std::string CodeGenerator::
2894  fmin(const std::string& x, const std::string& y) {
2896  return "casadi_fmin(" + x + ", " + y + ");";
2897  }
2898 
2899  std::string CodeGenerator::
2900  vfmax(const std::string& x, casadi_int n, const std::string& y) {
2902  return "casadi_vfmax(" + x + ", " + str(n) + ", " + y + ");";
2903  }
2904 
2905  std::string CodeGenerator::
2906  vfmin(const std::string& x, casadi_int n, const std::string& y) {
2908  return "casadi_vfmin(" + x + ", " + str(n) + ", " + y + ");";
2909  }
2910 
2911  std::string CodeGenerator::
2912  vfmax(const std::string& x, const std::string& n, const std::string& y) {
2914  return "casadi_vfmax(" + x + ", " + n + ", " + y + ");";
2915  }
2916 
2917  std::string CodeGenerator::
2918  vfmin(const std::string& x, const std::string& n, const std::string& y) {
2920  return "casadi_vfmin(" + x + ", " + n + ", " + y + ");";
2921  }
2922 
2923  std::string CodeGenerator::
2924  max(const std::string& x, const std::string& y) {
2926  return "casadi_max(" + x + ", " + y + ")";
2927  }
2928 
2929  std::string CodeGenerator::
2930  min(const std::string& x, const std::string& y) {
2932  return "casadi_min(" + x + ", " + y + ")";
2933  }
2934 
2935  std::string CodeGenerator::
2936  mmax(const std::string& x, casadi_int n, bool is_dense) {
2938  return "casadi_mmax(" + x + ", " + str(n) + ", " + str(casadi_int(is_dense)) + ")";
2939  }
2940 
2941  std::string CodeGenerator::
2942  mmin(const std::string& x, casadi_int n, bool is_dense) {
2944  return "casadi_mmin(" + x + ", " + str(n) + ", " + str(casadi_int(is_dense)) + ")";
2945  }
2946 
2947  std::string CodeGenerator::
2948  max_viol(casadi_int n, const std::string& x, const std::string& lb, const std::string& ub) {
2950  return "casadi_max_viol(" + str(n) + ", " + x+ ", " + lb + ", " + ub + ")";
2951  }
2952 
2953  std::string CodeGenerator::
2954  sum_viol(casadi_int n, const std::string& x, const std::string& lb, const std::string& ub) {
2956  return "casadi_sum_viol(" + str(n) + ", " + x+ ", " + lb + ", " + ub + ")";
2957  }
2958 
2959  std::string CodeGenerator::
2960  norm_inf(casadi_int n, const std::string& x) {
2962  return "casadi_norm_inf(" + str(n) + ", " + x + ")";
2963  }
2964 
2965  std::string CodeGenerator::
2966  norm_1(casadi_int n, const std::string& x) {
2968  return "casadi_norm_1(" + str(n) + ", " + x + ")";
2969  }
2970 
2971  std::string CodeGenerator::
2972  norm_2(casadi_int n, const std::string& x) {
2974  return "casadi_norm_2(" + str(n) + ", " + x + ")";
2975  }
2976 
2977  std::string CodeGenerator::
2978  lb_eig(const Sparsity& sp_h, const std::string& h) {
2980  return "casadi_lb_eig(" + sparsity(sp_h) + ", " + h + ")";
2981  }
2982 
2983  std::string CodeGenerator::
2984  regularize(const Sparsity& sp_h, const std::string& h, const std::string& reg) {
2986  return "casadi_regularize(" + sparsity(sp_h) + ", " + h + ", " + reg + ");";
2987  }
2988 
2989  std::string CodeGenerator::
2991  const std::string& Hin, const std::string& Hout, const std::string& iw, const std::string& w) {
2993  return Convexify::generate(*this, d, Hin, Hout, iw, w);
2994  }
2995 
2996  std::string CodeGenerator::
2997  low(const std::string& x, const std::string& grid, casadi_int ng, casadi_int lookup_mode) {
2999  return "casadi_low(" + x + ", " + grid + ", " + str(ng) + ", " + str(lookup_mode) + ");";
3000  }
3001 
3002  std::string CodeGenerator::
3003  bound_consistency(casadi_int n, const std::string& x,
3004  const std::string& lam, const std::string& lbx, const std::string& ubx) {
3006  return "casadi_bound_consistency(" + str(n) + ", " + x + ", " + lam +
3007  ", " + lbx + ", " + ubx + ")";
3008  }
3009 
3010  std::string CodeGenerator::
3011  file_slurp(const std::string& fname, casadi_int n, const std::string& a) {
3013  return "casadi_file_slurp(\"" + fname + "\", " + str(n) + ", " + a + ")";
3014  }
3015 
3016  std::string CodeGenerator::
3017  to_file(const std::string& f, const Sparsity& sp, const std::string& x) {
3019  return "casadi_to_file(" + f + ", " + sparsity(sp) + ", " + x + ")";
3020  }
3021 
3023  generate_dump(const Function& f, const std::string& arr, bool is_input) {
3024  casadi_int n = is_input ? f.n_in() : f.n_out();
3025  std::string dump_format = f->dump_format_.empty() ? "mtx" : f->dump_format_;
3026  std::string effective_dir = dump_dir_prefix + f->dump_dir_ + dump_dir_suffix;
3027  std::string prefix;
3028  if (!effective_dir.empty()) prefix = effective_dir + "/";
3029  std::string inout = is_input ? "in" : "out";
3030 
3031  // Ensure directory exists at codegen time
3032  if (!effective_dir.empty() && Filesystem::is_enabled()) {
3033  std::string dir = Filesystem::ensure_trailing_slash(effective_dir);
3034  casadi_assert(Filesystem::ensure_directory_exists(dir),
3035  "Unable to create the required directory for '" + dir + "'.");
3036  }
3037 
3038  // Assumes dump_id_local is declared in the enclosing scope
3039  // Per-input/output format files (e.g. .mtx)
3040  for (casadi_int i = 0; i < n; ++i) {
3041  std::string io_name = is_input ? f.name_in(i) : f.name_out(i);
3042  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3043  std::string fixed_part = prefix + f.name() + "." + inout + "." + io_name + "." + dump_format;
3044  casadi_int buf_size = fixed_part.size() + 1 + 6 + 1; // +7 for the counter field
3045  *this << "{\n";
3046  *this << "char dump_fname[" << buf_size << "];\n";
3047  *this << "FILE* dump_file;\n";
3048  *this << "snprintf(dump_fname, " << buf_size << ", \""
3049  << prefix << f.name() << ".%06d." << inout << "." << io_name
3050  << "." << dump_format << "\", dump_id_local);\n";
3051  if (f->verbose_) {
3052  *this << printf("dump -> %s\\n", "dump_fname") << "\n";
3053  }
3054  *this << "dump_file = fopen(dump_fname, \"w\");\n";
3055  *this << "if (dump_file) {\n";
3056  *this << to_file("dump_file", sp, arr + "[" + str(i) + "]") << ";\n";
3057  *this << "fclose(dump_file);\n";
3058  *this << "}\n";
3059  *this << "}\n";
3060  }
3061  // Combined .txt file (normalized doubles, one per line)
3062  {
3063  add_include("stdio.h");
3064  std::string fixed_part = prefix + f.name() + "." + inout + ".txt";
3065  casadi_int buf_size = fixed_part.size() + 1 + 6 + 1;
3066  *this << "{\n";
3067  *this << "char dump_fname[" << buf_size << "];\n";
3068  *this << "FILE* dump_file;\n";
3069  *this << "casadi_int dump_k;\n";
3070  *this << "snprintf(dump_fname, " << buf_size << ", \""
3071  << prefix << f.name() << ".%06d." << inout << ".txt\", dump_id_local);\n";
3072  *this << "dump_file = fopen(dump_fname, \"w\");\n";
3073  *this << "if (dump_file) {\n";
3074  for (casadi_int i = 0; i < n; ++i) {
3075  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3076  casadi_int nnz = sp.nnz();
3077  std::string a = arr + "[" + str(i) + "]";
3078  if (nnz > 0) {
3079  *this << "if (" << a << ") {\n";
3080  *this << fprintf_vector("dump_file", nnz, a, "\\n") << "\n";
3081  *this << "fprintf(dump_file, \"\\n\");\n";
3082  *this << "} else {\n";
3083  std::string zero_str = is_input ? "0.0000000000000000e+00" : "nan";
3084  *this << "for (dump_k=0; dump_k<" << nnz << "; ++dump_k) "
3085  << "fprintf(dump_file, \"" << zero_str << "\\n\");\n";
3086  *this << "}\n";
3087  }
3088  }
3089  *this << "fclose(dump_file);\n";
3090  *this << "}\n";
3091  *this << "}\n";
3092  }
3093  }
3094 
3096  generate_print(const Function& f, const std::string& arr, bool is_input) {
3097  casadi_int n = is_input ? f.n_in() : f.n_out();
3098  std::string inout = is_input ? "Input" : "Output";
3099 
3100  *this << printf("Function " + f.name() + "\\n") << "\n";
3101  for (casadi_int i = 0; i < n; ++i) {
3102  std::string io_name = is_input ? f.name_in(i) : f.name_out(i);
3103  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3104  *this << printf(inout + " " + str(i) + " (" + io_name + "): ") << "\n";
3105  *this << print_canonical(sp, arr + "[" + str(i) + "]") << "\n";
3106  *this << printf("\\n") << "\n";
3107  }
3108  }
3109 
3110  std::string CodeGenerator::
3111  cache_check(const std::string& key, const std::string& cache, const std::string& loc,
3112  casadi_int stride, casadi_int sz, casadi_int key_sz, const std::string& val) {
3114  return "casadi_cache_check(" + key + ", " + cache + ", " + loc + ", " +
3115  str(stride) + ", " + str(sz) + ", " + str(key_sz) + ", " + val + ")";
3116  }
3117 
3118  void CodeGenerator::sz_work(size_t& sz_arg, size_t& sz_res, size_t& sz_iw, size_t& sz_w) const {
3119  sz_arg = sz_res = sz_iw = sz_w = 0;
3120  for (auto&& f : added_functions_) {
3121  sz_arg = std::max(sz_arg, f.f.sz_arg());
3122  sz_res = std::max(sz_res, f.f.sz_res());
3123  sz_iw = std::max(sz_iw, f.f.sz_iw());
3124  sz_w = std::max(sz_w, f.f.sz_w());
3125  }
3126  }
3127 
3128 } // namespace casadi
static bool codegen_dot_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:305
static bool codegen_norm_1_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:332
static void codegen_copy_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:283
static bool codegen_scal_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:314
static bool codegen_axpy_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:296
static bool codegen_norm_2_aux(CodeGenerator &g, const std::vector< std::string > &inst)
Definition: blas.cpp:323
Helper class for C code generation.
std::string triusolve(const Sparsity &sp_x, const std::string &x, const std::string &y, bool tr, bool unity, casadi_int nrhs)
Codegen upper triangular solve.
void define_pool_double(const std::string &name, const std::vector< double > &def)
Allocate file scope double writeable memory.
bool codegen_scalars
Codegen scalar.
std::string fill(const std::string &res, std::size_t n, const std::string &v)
Create a fill operation.
std::stringstream includes
std::string axpy(casadi_int n, const std::string &a, const std::string &x, const std::string &y)
Codegen axpy: y += a*x.
static std::string fmu_helpers(const std::string &modelname)
FMU helper functions.
std::string lsqr_solve(const std::string &A, const std::string &x, casadi_int nrhs, bool tr, const std::string &sp, const std::string &w)
std::set< std::string > added_externals_
std::string logsumexp(const std::string &A, casadi_int n)
std::string clip_min(const std::string &x, casadi_int n, const std::string &min, const std::string &mask)
Codegen clip_min: Clips the smaller entries in a vector than min to the min.
std::string project(const std::string &arg, const Sparsity &sp_arg, const std::string &res, const Sparsity &sp_res, const std::string &w)
Sparse assignment.
std::string add_dependency(const Function &f)
Add a function dependency.
std::string mmax(const std::string &x, casadi_int n, bool is_dense)
mmax
std::string work(casadi_int n, casadi_int sz, bool is_ref) const
void scope_add_cleanup(const std::string &code)
Add cleanup code to be executed upon scope exit.
std::set< std::string > external_names_
const std::set< std::string > & local_mutexes(const Function &f) const
Get all mutex names associated with a function.
std::string arg(casadi_int i) const
Refer to argument.
std::string dump()
Generate a file, return code as string.
std::string wrapper(const Function &base, const std::string &name)
std::vector< std::string > added_sfunctions
std::string pool_double(const std::string &name) const
Access file scope double writeable memory.
void add_io_sparsities(const std::string &name, const std::vector< Sparsity > &sp_in, const std::vector< Sparsity > &sp_out)
Add io sparsity patterns of a function.
void scope_enter()
Enter a local scope.
std::string rom_integer(const void *id) const
Access file scope integer read-only memory.
std::string norm_2(casadi_int n, const std::string &x)
norm_2
std::string copy(const std::string &arg, std::size_t n, const std::string &res)
Create a copy operation.
std::map< std::string, casadi_int > pool_double_
void comment(const std::string &s)
Write a comment line (ignored if not verbose)
void reserve_work(casadi_int n)
Reserve a maximum size of work elements, used for padding of index.
std::string masked_norm_inf(casadi_int n, const std::string &x, const std::string &mask)
codegen masked_norm_inf: The mask tells what entry is used in the inf-norm.
std::set< std::string > added_includes_
std::string constant(const std::vector< casadi_int > &v)
Represent an array constant; adding it when new.
void add(const Function &f, bool with_jac_sparsity=false)
Add a function (name generated)
void flush(std::ostream &s)
Flush the buffer to a stream of choice.
casadi_int add_sparsity(const Sparsity &sp, bool canonical=true)
std::string scal(casadi_int n, const std::string &alpha, const std::string &x)
What does scal do??
static void stream_open(std::ostream &f, bool cpp)
Print file header.
std::string rank1(const std::string &A, const Sparsity &sp_A, const std::string &alpha, const std::string &x, const std::string &y)
Rank-1 update.
std::string low(const std::string &x, const std::string &grid, casadi_int ng, casadi_int lookup_mode)
low
std::multimap< Auxiliary, std::vector< std::string > > added_auxiliaries_
CodeGenerator(const std::string &name, const Dict &opts=Dict())
Constructor.
std::string fmin(const std::string &x, const std::string &y)
fmin
static void stream_close(std::ostream &f, bool cpp)
Print file header.
std::string sum_viol(casadi_int n, const std::string &x, const std::string &lb, const std::string &ub)
sum_viol
std::string to_mex(const Sparsity &sp, const std::string &arg)
Create matrix in MATLAB's MEX format.
std::string printf(const std::string &str, const std::vector< std::string > &arg=std::vector< std::string >())
Printf.
std::string print_op(casadi_int op, const std::string &a0)
Print an operation to a c file.
std::map< std::string, std::pair< std::string, std::string > > local_variables_
std::string max(const std::string &x, const std::string &y)
max
void indent()
Increase indentation.
std::string rom_double(const void *id) const
Access file scope double read-only memory.
bool thread_safe() const
Emit thead safe code chekout/release?
std::vector< std::string > local_cleanup_
std::map< std::string, std::string > local_default_
std::map< const FunctionInternal *, std::set< std::string > > local_mutexes_
std::vector< std::vector< char > > char_constants_
static std::string array(const std::string &type, const std::string &name, casadi_int len, const std::string &def=std::string())
std::string bilin(const std::string &A, const Sparsity &sp_A, const std::string &x, const std::string &y)
Codegen bilinear form.
void generate_dump(const Function &f, const std::string &arr, bool is_input)
Generate dump_in or dump_out code for a function call.
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
std::string vector_fmax(casadi_int n, const std::string &x, const std::string &y, const std::string &z)
Codegen vector_fmax: Takes vectorwise max of a vector and writes the result to second vector.
std::string to_file(const std::string &f, const Sparsity &sp, const std::string &x)
Write matrix to file in MatrixMarket format.
std::string sparsify(const std::string &arg, const std::string &res, const Sparsity &sp_res, bool tr=false)
Sparsify.
std::string mv(const std::string &x, const Sparsity &sp_x, const std::string &y, const std::string &z, bool tr)
Codegen sparse matrix-vector multiplication.
static size_t hash(const std::vector< double > &v)
std::vector< std::vector< double > > pool_double_defaults_
std::string ldl_solve(const std::string &x, casadi_int nrhs, const std::string &sp_lt, const std::string &lt, const std::string &d, const std::string &p, const std::string &w)
LDL solve.
CodeGenerator & operator<<(const std::string &s)
Print a string to buffer.
std::string generate(const std::string &prefix="")
Generate file(s)
std::string fprintf_scalar(const std::string &f, const std::string &arg)
fprintf a normalized scalar (canonical nan/inf) to a file
std::string ldl(const std::string &sp_a, const std::string &a, const std::string &sp_lt, const std::string &lt, const std::string &d, const std::string &p, const std::string &w)
LDL factorization.
std::string lb_eig(const Sparsity &sp_h, const std::string &h)
lb_eig
std::string operator()(const Function &f, const std::string &arg, const std::string &res, const std::string &iw, const std::string &w, const std::string &failure_ret="1")
Generate a call to a function (generic signature)
std::stringstream buffer
void generate_print(const Function &f, const std::string &arr, bool is_input)
Generate print_in or print_out code for a function call.
std::string mmin(const std::string &x, casadi_int n, bool is_dense)
mmin
std::string densify(const std::string &arg, const Sparsity &sp_arg, const std::string &res, bool tr=false)
Densify.
std::multimap< size_t, size_t > added_double_constants_
void local(const std::string &name, const std::string &type, const std::string &ref="")
Declare a local variable.
std::string workel(casadi_int n) const
std::string min(const std::string &x, const std::string &y)
min
void setup_callback(const std::string &s, const Function &f)
Setup a callback.
casadi_int max_initializer_elements_per_line
std::string mem(const Function &f)
Access thread-local memory.
void print_vector(std::ostream &s, const std::string &name, const std::vector< casadi_int > &v)
Print casadi_int vector to a c file.
std::stringstream header
void unindent()
Decrease indentation.
std::string from_mex(std::string &arg, const std::string &res, std::size_t res_off, const Sparsity &sp_res, const std::string &w)
Get matrix from MATLAB's MEX format.
std::string fprintf_vector(const std::string &f, casadi_int sz, const std::string &arg, const std::string &sep)
fprintf a normalized vector to a file with a separator
std::vector< std::vector< double > > double_constants_
std::map< const FunctionInternal *, size_t > codegen_sz_w_
std::string res(casadi_int i) const
Refer to resuly.
std::vector< std::vector< casadi_int > > integer_constants_
std::string interpn(const std::string &res, casadi_int ndim, const std::string &grid, const std::string &offset, const std::string &values, const std::string &x, const std::string &lookup_mode, casadi_int m, const std::string &iw, const std::string &w)
Multilinear interpolation.
void sz_work(size_t &sz_arg, size_t &sz_res, size_t &sz_iw, size_t &sz_w) const
Get number of temporary variables needed for all functions.
std::multimap< size_t, size_t > added_char_constants_
std::vector< std::vector< std::string > > string_constants_
std::string vfmax(const std::string &x, casadi_int n, const std::string &y)
vfmax
std::string norm_inf(casadi_int n, const std::string &x)
norm_inf
std::string ones(casadi_int sz)
std::string vector_fmin(casadi_int n, const std::string &x, const std::string &y, const std::string &z)
Codegen vector_fmin: Takes vectorwise min of a vector and writes the result to second vector.
void add_external(const std::string &new_external, const std::string &name="")
Add an external function declaration.
std::map< const void *, casadi_int > file_scope_integer_
std::string declare(std::string s)
Declare a function.
std::string mtimes(const std::string &x, const Sparsity &sp_x, const std::string &y, const Sparsity &sp_y, const std::string &z, const Sparsity &sp_z, const std::string &w, bool tr)
Codegen sparse matrix-matrix multiplication.
std::string mtimes_dense_sparse(const std::string &x, casadi_int nrow_x, const std::string &y, const Sparsity &sp_y, const std::string &z)
Codegen dense-sparse matrix-matrix multiplication (z, x dense)
void scope_exit()
Exit a local scope.
std::string vfmin(const std::string &x, casadi_int n, const std::string &y)
vfmin
void init_local(const std::string &name, const std::string &def)
Specify the default value for a local variable.
std::string local_mutex(const Function &f, const std::string &name) const
Access a static mutex associated with a function.
std::string cache_check(const std::string &key, const std::string &cache, const std::string &loc, casadi_int stride, casadi_int sz, casadi_int key_sz, const std::string &val)
cache check
void define_rom_integer(const void *id, casadi_int size)
Allocate file scope integer read-only memory.
std::string qr_solve(const std::string &x, casadi_int nrhs, bool tr, const std::string &sp_v, const std::string &v, const std::string &sp_r, const std::string &r, const std::string &beta, const std::string &prinv, const std::string &pc, const std::string &w)
QR solve.
std::string det(const std::string &sp_v, const std::string &v, const std::string &sp_r, const std::string &r, const std::string &beta)
Determinant from sparse QR factors.
casadi_int max_declarations_per_line
bool get_codegen_sz_w(const FunctionInternal *f, size_t &sz_w) const
Retrieve a work vector size registered by set_codegen_sz_w.
std::string sanitize_source(const std::string &src, const std::vector< std::string > &inst, bool add_shorthand=true)
Sanitize source files for codegen.
std::string dot(casadi_int n, const std::string &x, const std::string &y)
Codegen inner product.
std::vector< FunctionMeta > added_functions_
std::string clip_max(const std::string &x, casadi_int n, const std::string &min, const std::string &mask)
Codegen clip_max: Clips the larger entries in a vector than max to the max.
static std::string casadi_version()
Current CasADi version as string.
void define_rom_double(const void *id, casadi_int size)
Allocate file scope double read-only memory.
std::string interpn_grad(const std::string &grad, casadi_int ndim, const std::string &grid, const std::string &offset, const std::string &values, const std::string &x, const std::string &lookup_mode, casadi_int m, const std::string &iw, const std::string &w)
Multilinear interpolation - calculate gradient.
void add_include(const std::string &new_include, bool relative_path=false, const std::string &use_ifdef=std::string())
Add an include file optionally using a relative path "..." instead of an absolute path <....
std::string shorthand(const std::string &name) const
Get a shorthand.
Auxiliary
Auxiliary functions.
void constant_copy(const std::string &var_name, const std::vector< casadi_int > &v, const std::string &type="casadi_int")
Represent an array constant; adding it when new.
std::map< std::string, std::map< FunctionInternal *, casadi_int > > added_wrappers_
void copy_check(const std::string &arg, std::size_t n, const std::string &res, bool check_lhs=true, bool check_rhs=true)
std::stringstream body
std::string tri_project(const std::string &arg, const Sparsity &sp_arg, const std::string &res, bool lower)
Project triangular part.
std::multimap< size_t, size_t > added_integer_constants_
std::multimap< size_t, size_t > added_string_constants_
std::map< const void *, casadi_int > file_scope_double_
std::string file_slurp(const std::string &fname, casadi_int n, const std::string &a)
Slurp a file.
std::string initializer(const std::vector< T > &v)
Print an initializer.
std::string norm_1(casadi_int n, const std::string &x)
norm_1
std::set< std::string > sparsity_meta
std::string max_viol(casadi_int n, const std::string &x, const std::string &lb, const std::string &ub)
max_viol
std::string convexify_eval(const ConvexifyData &d, const std::string &Hin, const std::string &Hout, const std::string &iw, const std::string &w)
convexify
std::vector< std::string > exposed_fname
std::string sparsity(const Sparsity &sp, bool canonical=true)
std::string print_scalar(const std::string &arg)
Print canonical representaion of a scalar.
void copy_default(const std::string &arg, std::size_t n, const std::string &res, const std::string &def, bool check_rhs=true)
std::string trans(const std::string &x, const Sparsity &sp_x, const std::string &y, const Sparsity &sp_y, const std::string &iw)
Transpose.
casadi_int get_constant(const std::vector< double > &v, bool allow_adding=false)
Get or add a constant.
casadi_int get_sparsity(const Sparsity &sp) const
Get the index of an existing sparsity pattern.
void print_formatted(const std::string &s)
Print without newline characters.
void scope_return()
Return from a scope without a value.
bool elide_copy(casadi_int sz)
std::string zeros(casadi_int sz)
std::string trilsolve(const Sparsity &sp_x, const std::string &x, const std::string &y, bool tr, bool unity, casadi_int nrhs)
Codegen lower triangular solve.
std::set< std::string > added_shorthands_
static bool equal(const std::vector< T > &v1, const std::vector< T > &v2)
std::stringstream auxiliaries
void set_codegen_sz_w(const FunctionInternal *f, size_t sz_w)
Register the work vector size a function needs in generated code.
std::string qr(const std::string &sp, const std::string &A, const std::string &w, const std::string &sp_v, const std::string &v, const std::string &sp_r, const std::string &r, const std::string &beta, const std::string &prinv, const std::string &pc)
QR factorization.
std::string fmax(const std::string &x, const std::string &y)
fmax
std::string clear(const std::string &res, std::size_t n)
Create a fill operation.
std::string print_canonical(const Sparsity &sp, const std::string &arg)
Print canonical representaion of a matrix.
std::string format_padded(casadi_int i) const
std::string regularize(const Sparsity &sp_h, const std::string &h, const std::string &reg)
regularize
void add_auxiliary(Auxiliary f, const std::vector< std::string > &inst={"casadi_real"})
Add a built-in auxiliary function.
void define_local_mutex(const Function &f, const std::string &name)
Declare a static mutex associated with a function.
std::string sx_work(casadi_int i)
Declare a work vector element.
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: convexify.cpp:157
static std::string ensure_trailing_slash(const std::string &path)
Definition: filesystem.cpp:155
static bool ensure_directory_exists(const std::string &path)
Definition: filesystem.cpp:105
static bool is_enabled()
Definition: filesystem.cpp:83
static std::unique_ptr< std::ostream > ofstream_ptr(const std::string &path, std::ios_base::openmode mode=std::ios_base::out)
Definition: filesystem.cpp:115
Internal class for Function.
std::vector< Sparsity > sparsity_in_
Input and output sparsity.
virtual void codegen_decref(CodeGenerator &g) const
Codegen decref for dependencies.
virtual bool codegen_mem_is_opaque() const
Is thread-local memory object managed by checkout/release.
virtual void codegen_free_mem(CodeGenerator &g) const
Codegen for free_mem.
std::string signature_unrolled(const std::string &fname) const
Code generate the function.
bool has_refcount_in_deps_
Reference counting in dependent functions.
virtual std::string codegen_name(const CodeGenerator &g, bool ns=true) const
Get name in codegen.
void codegen(CodeGenerator &g, const std::string &fname) const
Generate code the function.
virtual void codegen_release(CodeGenerator &g) const
Codegen for release.
virtual void codegen_alloc_mem(CodeGenerator &g) const
Codegen decref for alloc_mem.
virtual void codegen_checkout(CodeGenerator &g) const
Codegen for checkout.
virtual bool codegen_needs_mem() const
Is thread-local memory object needed?
virtual void codegen_declarations(CodeGenerator &g) const
Generate code for the declarations of the C function.
std::string signature(const std::string &fname) const
Code generate the function.
void codegen_meta(CodeGenerator &g) const
Generate meta-information allowing a user to evaluate a generated function.
virtual void codegen_init_mem(CodeGenerator &g) const
Codegen decref for init_mem.
virtual void codegen_incref(CodeGenerator &g) const
Codegen incref for dependencies.
Function object.
Definition: function.hpp:60
const Sparsity & sparsity_out(casadi_int ind) const
Get sparsity of a given output.
Definition: function.cpp:1183
FunctionInternal * get() const
Definition: function.cpp:505
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
static bool check_name(const std::string &name)
Check if a string is a valid function name.
Definition: function.cpp:1513
const Sparsity & sparsity_in(casadi_int ind) const
Get sparsity of a given input.
Definition: function.cpp:1167
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
const std::vector< Sparsity > & jac_sparsity(bool compact=false) const
Get, if necessary generate, the sparsity of all Jacobian blocks.
Definition: function.cpp:1092
const std::vector< std::string > & name_out() const
Get output scheme.
Definition: function.cpp:1117
static casadi_int copy_elision_min_size
bool verbose_
Verbose printout.
General sparsity class.
Definition: sparsity.hpp:106
casadi_int nnz() const
Get the number of (structural) non-zeros.
Definition: sparsity.cpp:148
std::vector< casadi_int > compress(bool canonical=true) const
Compress a sparsity pattern.
Definition: sparsity.cpp:1321
The casadi namespace.
Definition: archiver.cpp:28
static const std::set< std::string > empty_mutex_set_
std::string join(const std::vector< std::string > &l, const std::string &delim)
CASADI_EXPORT std::string replace(const std::string &s, const std::string &p, const std::string &r)
Replace all occurences of p with r in s.
std::string str(const T &v)
String representation, any type.
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
void hash_combine(std::size_t &seed, T v)
Generate a hash value incrementally (function taken from boost)
static std::string next_quoted_token(const std::string &line, size_t &pos)
@ OP_SIGN
Definition: calculus.hpp:71
@ OP_FMAX
Definition: calculus.hpp:72
@ OP_LOG1P
Definition: calculus.hpp:202
@ OP_PRINTME
Definition: calculus.hpp:190
@ OP_HYPOT
Definition: calculus.hpp:206
@ OP_FMIN
Definition: calculus.hpp:72
@ OP_EXPM1
Definition: calculus.hpp:204
@ OP_FABS
Definition: calculus.hpp:71
@ OP_SQ
Definition: calculus.hpp:67
static std::string print(unsigned char op, const std::string &x, const std::string &y)
Print.
Definition: calculus.hpp:1651