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 
403  // Define function
404  *this << declare(f->signature(f.name())) << "{\n"
405  << "return " << codegen_name << "(arg, res, iw, w, mem);\n"
406  << "}\n\n";
407 
408  if (this->unroll_args) {
409  // Define function
410  *this << declare(f->signature_unrolled(f.name())) << "{\n";
411  for (casadi_int i=0; i<f.n_in(); ++i) {
412  *this << "arg[" << i << "] = " << f.name_in(i) << ";\n";
413  }
414  for (casadi_int i=0; i<f.n_out(); ++i) {
415  *this << "res[" << i << "] = " << f.name_out(i) << ";\n";
416  }
417  *this << "return " << codegen_name << "(arg, res, iw, w, mem);\n";
418  *this << "}\n\n";
419  // Flush buffers
420  flush(this->body);
421  }
422 
423  // Generate meta information
424  f->codegen_meta(*this);
425 
426  // Generate Jacobian sparsity information
427  if (with_jac_sparsity) {
428  // Generate/get Jacobian sparsity
429  std::vector<Sparsity> jac = f.jac_sparsity();
430  // Code generate the sparsity pattern
431  add_io_sparsities("jac_" + f.name(), f->sparsity_in_, jac);
432 
433  // Flush buffers
434  flush(this->body);
435  }
436 
437  // Generate function specific code for Simulink sfunction
438  if (this->with_sfunction) this->added_sfunctions.push_back( this->codegen_sfunction(f) );
439 
440  // Add to list of exposed symbols
441  this->exposed_fname.push_back(f.name());
442  }
443 
444  std::string CodeGenerator::dump() {
445  std::stringstream s;
446  dump(s);
447  return s.str();
448  }
449 
451  std::stringstream ss;
452  ss << CASADI_MAJOR_VERSION << "." << CASADI_MINOR_VERSION << "." << CASADI_PATCH_VERSION;
453  if (!CASADI_IS_RELEASE) ss << "+";
454  return ss.str();
455  }
456 
457  void CodeGenerator::stream_open(std::ostream& f, bool cpp) {
458 
459  // Print header
460  f << "/* This file was automatically generated by CasADi " << casadi_version() << ".\n"
461  << " * It consists of: \n"
462  << " * 1) content generated by CasADi runtime: not copyrighted\n"
463  << " * 2) template code copied from CasADi source: permissively licensed (MIT-0)\n"
464  << " * 3) user code: owned by the user\n"
465  << " *\n"
466  << " */\n";
467 
468  // C linkage
469  if (!cpp) {
470  f << "#ifdef __cplusplus\n"
471  << "extern \"C\" {\n"
472  << "#endif\n\n";
473  }
474  }
475 
476  void CodeGenerator::stream_close(std::ostream& f, bool cpp) {
477  // C linkage
478  if (!cpp) {
479  f << "#ifdef __cplusplus\n"
480  << "} /* extern \"C\" */\n"
481  << "#endif\n";
482  }
483  }
484 
485  void CodeGenerator::generate_casadi_real(std::ostream &s) const {
486  s << "#ifndef casadi_real\n"
487  << "#define casadi_real " << this->casadi_real_type << std::endl
488  << "#endif\n\n";
489  }
490 
491  void CodeGenerator::generate_export_symbol(std::ostream &s) const {
492  s << "/* Symbol visibility in DLLs */\n"
493  << "#ifndef CASADI_SYMBOL_EXPORT\n"
494  << " #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n"
495  << " #if defined(STATIC_LINKED)\n"
496  << " #define CASADI_SYMBOL_EXPORT\n"
497  << " #else\n"
498  << " #define CASADI_SYMBOL_EXPORT __declspec(dllexport)\n"
499  << " #endif\n"
500  << " #elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n"
501  << " #define CASADI_SYMBOL_EXPORT __attribute__ ((visibility (\"default\")))\n"
502  << " #else" << std::endl
503  << " #define CASADI_SYMBOL_EXPORT\n"
504  << " #endif\n"
505  << "#endif\n\n";
506  }
507 
508  void CodeGenerator::generate_import_symbol(std::ostream &s) const {
509  s << "/* Symbol visibility in DLLs */\n"
510  << "#ifndef CASADI_SYMBOL_IMPORT\n"
511  << " #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)\n"
512  << " #if defined(STATIC_LINKED)\n"
513  << " #define CASADI_SYMBOL_IMPORT\n"
514  << " #else\n"
515  << " #define CASADI_SYMBOL_IMPORT __declspec(dllimport)\n"
516  << " #endif\n"
517  << " #elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)\n"
518  << " #define CASADI_SYMBOL_IMPORT __attribute__ ((visibility (\"default\")))\n"
519  << " #else" << std::endl
520  << " #define CASADI_SYMBOL_IMPORT\n"
521  << " #endif\n"
522  << "#endif\n\n";
523  }
524 
525  void CodeGenerator::generate_casadi_int(std::ostream &s) const {
526  s << "#ifndef casadi_int\n"
527  << "#define casadi_int " << this->casadi_int_type << std::endl
528  << "#endif\n\n";
529  }
530 
531  std::string CodeGenerator::generate(const std::string& prefix) {
532  // Throw an error if the prefix contains the filename, since since syntax
533  // has changed
534  casadi_assert(prefix.find(this->name + this->suffix)==std::string::npos,
535  "The signature of CodeGenerator::generate has changed. "
536  "Instead of providing the filename, only provide the prefix.");
537 
538  // Create c file
539  std::string fullname = prefix + this->name + this->suffix;
540 
541  auto s_ptr = Filesystem::ofstream_ptr(fullname);
542  std::ostream& s = *s_ptr;
543  stream_open(s, this->cpp);
544 
545  // Dump code to file
546  dump(s);
547 
548  if (!pool_double_defaults_.empty()) {
549  s << "CASADI_SYMBOL_EXPORT casadi_real* CASADI_PREFIX(get_pool_double)(const char* name) {\n";
550  for (const auto& e : pool_double_) {
551  casadi_int i = e.second;
552  s << " if (strcmp(name, \"" + e.first + "\")==0) "
553  << "return casadi_pd" + str(i) + ";\n";
554  }
555  s << " return 0;\n";
556  s << "}\n";
557  }
558 
559  // Mex entry point
560  if (this->mex) generate_mex(s);
561 
562  // Main entry point
563  if (this->main) generate_main(s);
564 
565  // Finalize file
566  stream_close(s, this->cpp);
567  s_ptr.reset();
568 
569  // Generate s-function
570  if (this->with_sfunction) {
571  for (unsigned ii=0; ii<this->added_sfunctions.size(); ii++) {
572  std::string sfunction_code = this->added_sfunctions.at(ii);
573  std::string sfunction_name = this->exposed_fname.at(ii);
574  generate_sfunction(sfunction_name, sfunction_code);
575  }
576  }
577 
578  // Generate header
579  if (this->with_header) {
580  auto s_ptr = Filesystem::ofstream_ptr(prefix + this->name + ".h");
581  std::ostream& s = *s_ptr;
582  // Create a header file
583  stream_open(s, this->cpp);
584 
585  // Define the casadi_real type (typically double)
586  generate_casadi_real(s);
587 
588  // Define the casadi_int type
589  generate_casadi_int(s);
590 
591  // Generate export symbol macros
592  if (this->with_import) generate_import_symbol(s);
593 
594  // Add declarations
595  s << this->header.str();
596 
597  // Finalize file
598  stream_close(s, this->cpp);
599  s_ptr.reset();
600  }
601  return fullname;
602  }
603 
604  void CodeGenerator::generate_mex(std::ostream &s) const {
605  // Begin conditional compilation
606  s << "#ifdef MATLAB_MEX_FILE\n";
607 
608  // Function prototype
609  if (this->cpp) s << "extern \"C\"\n"; // C linkage
610  s << "void mexFunction(int resc, mxArray *resv[], int argc, const mxArray *argv[]) {"
611  << std::endl;
612 
613  // Create a buffer
614  size_t buf_len = 0;
615  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
616  buf_len = std::max(buf_len, exposed_fname[i].size());
617  }
618  s << " char buf[" << (buf_len+1) << "];\n";
619 
620  // Read std::string argument
621  s << " int buf_ok = argc > 0 && !mxGetString(*argv, buf, sizeof(buf));\n";
622 
623  // Create switch
624  s << " if (!buf_ok) {\n";
625  // Allow stringless call when unambiguous
626  if (exposed_fname.size()==1) {
627  s << " mex_" << exposed_fname[0] << "(resc, resv, argc, argv);\n"
628  << " return;\n";
629  } else {
630  s << " /* name error */\n";
631  }
632  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
633  s << " } else if (strcmp(buf, \"" << exposed_fname[i] << "\")==0) {\n"
634  << " mex_" << exposed_fname[i] << "(resc, resv, argc-1, argv+1);\n"
635  << " return;\n";
636  }
637  s << " }\n";
638 
639  // Error
640  s << " mexErrMsgTxt(\"First input should be a command string. Possible values:";
641  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
642  s << " '" << exposed_fname[i] << "'";
643  }
644  s << "\");\n";
645 
646  // End conditional compilation and function
647  s << "}\n"
648  << "#endif\n";
649  }
650 
651  void CodeGenerator::generate_sfunction(const std::string& name,
652  const std::string& sfunction) const {
653  // Create c file
654  auto f_ptr = Filesystem::ofstream_ptr("sfun_"+ name + ".c");
655  std::ostream& f = *f_ptr;
656 
657  // Print header
658  f << "// Must specify the S_FUNCTION_NAME as the name of the S-function\n"
659  << "#define S_FUNCTION_NAME sfun_" << name << "\n"
660  << "#define S_FUNCTION_LEVEL 2\n\n"
661  << "// Need to include simstruc.h for the definition of the SimStruct and its\n"
662  << "// associated macro definitions\n"
663  << "#ifndef __SIMSTRUC__\n"
664  << "#include \"simstruc.h\"\n"
665  << "#endif\n\n"
666  << "// Specific header file(s) required by the legacy code function\n"
667  << "#include \"" << this->name << ".h\"\n\n\n";
668 
669  // Codegenerate s-function
670  f << sfunction;
671 
672  }
673 
674  std::string CodeGenerator::codegen_sfunction(const Function& f) const {
675  std::stringstream g;
676  // TODO(@jaeandersson): These helper functions really should be moved
677  // to the runtime directory
678 
679  // Initialize function
680  g << "/* Function: mdlInitializeSizes ===========================================\n"
681  << "* Abstract:\n"
682  << "* The sizes information is used by Simulink to determine the S-function\n"
683  << "* blocks characteristics (number of inputs, outputs, states, etc.).\n"
684  << "*/\n"
685  << "static void mdlInitializeSizes(SimStruct *S)\n"
686  << "{\n\n"
687  << " /* Declare auxilary variables */\n"
688  << " int_T ii;\n"
689  << " const int_T* sp;\n\n"
690  << " /* Set number of simulink s-function block parameters "
691  "(the ones which appear by double click on simulink block) */\n"
692  << " ssSetNumSFcnParams(S, 0);\n\n"
693  << " /* Report if parameter mismatch occurs */\n"
694  << " if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) return;\n\n"
695  << " /* Specify the number of states for which a block detects "
696  "zero crossings that occur between sample points */\n"
697  << " ssSetNumNonsampledZCs(S, 0);\n\n"
698  << " /* Set number of simulink input ports */\n"
699  << " if (!ssSetNumInputPorts(S, " << f->n_in_ << ")) return;\n\n"
700  << " /* Configure simulink input ports (inputs are assumed to be dense "
701  "vectors or matrices) */\n"
702  << " for (ii=0; ii<" << f->n_in_ << "; ++ii) {\n"
703  << " sp = " << f.name() << "_sparsity_in(ii);\n"
704  << " if (sp[1]==1) {\n"
705  << " ssSetInputPortWidth(S, ii, sp[0]);\n"
706  << " }\n"
707  << " else {\n"
708  << " ssSetInputPortMatrixDimensions(S, ii, sp[0], sp[1]);\n"
709  << " }\n"
710  << " ssSetInputPortDirectFeedThrough(S, ii, 1);\n"
711  << " }\n\n"
712  << " /* Set number of simulink output ports */\n"
713  << " if (!ssSetNumOutputPorts(S, " << f->n_out_ << ")) return;\n\n"
714  << " /* Configure simulink output ports (dense or sparse vectors or matrices allowed) */\n"
715  << " for (ii=0; ii<" << f->n_out_ << "; ++ii) {\n"
716  << " sp = " << f.name() << "_sparsity_out(ii);\n"
717  << " if (sp[1]==1) {\n"
718  << " ssSetOutputPortWidth(S, ii, sp[0]);\n"
719  << " }\n"
720  << " else {\n"
721  << " ssSetOutputPortMatrixDimensions(S, ii, sp[0], sp[1]);\n"
722  << " }\n"
723  << " }\n"
724  << " ssSetOutputPortOutputExprInRTW(S, 0, 0);\n\n"
725  << " /* This S-function can be used in referenced model simulating in normal mode */\n"
726  << " ssSetModelReferenceNormalModeSupport(S, MDL_START_AND_MDL_PROCESS_PARAMS_OK);\n\n"
727  << " /* Set the number of sample time */\n"
728  << " ssSetNumSampleTimes(S, 1);\n\n"
729  << " /* Set the compliance with the SimState feature */\n"
730  << " ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);\n\n"
731  << " /**\n"
732  << " * All options have the form SS_OPTION_<name> and are documented in\n"
733  << " * matlabroot/simulink/include/simstruc.h. The options should be\n"
734  << " * bitwise ord together as in\n"
735  << " * ssSetOptions(S, (SS_OPTION_name1 | SS_OPTION_name2))\n"
736  << " */\n"
737  << "}\n\n\n";
738 
739  // Initialize sample times function
740  g << "/* Function: mdlInitializeSampleTimes =====================================\n"
741  << " * Abstract:\n"
742  << " * This function is used to specify the sample time(s) for your\n"
743  << " * S-function. You must register the same number of sample times as\n"
744  << " * specified in ssSetNumSampleTimes.\n"
745  << " */\n"
746  << "static void mdlInitializeSampleTimes(SimStruct *S)\n"
747  << "{\n"
748  << " ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);\n"
749  << " ssSetOffsetTime(S, 0, FIXED_IN_MINOR_STEP_OFFSET);\n"
750  << " #if defined(ssSetModelReferenceSampleTimeDefaultInheritance)\n"
751  << " ssSetModelReferenceSampleTimeDefaultInheritance(S);\n"
752  << " #endif\n"
753  << "}\n\n\n";
754 
755  // Model output function
756  g << "/* Function: mdlOutputs ===================================================\n"
757  << " * Abstract:\n"
758  << " * In this function, you compute the outputs of your S-function\n"
759  << " * block. Generally outputs are placed in the output vector(s),\n"
760  << " * ssGetOutputPortSignal.\n"
761  << " */\n"
762  << "static void mdlOutputs(SimStruct *S, int_T tid)\n"
763  << "{\n\n"
764  << " /* Declare auxilary variables */\n"
765  << " int_T ii, jj, row, col, nnz_col, ind_start_row_index, offset = 0, jj_total = 0;\n"
766  << " const int_T* sp;\n\n"
767  << " /* Allocate buffers for casadi input and output and simulink output */\n"
768  << " " + array("real_T", "w", f->sz_w()+f->nnz_out())
769  << " " + array("int_T", "iw", f->sz_iw())
770  << " const real_T* arg[" << f->sz_arg() <<"] = {0};\n"
771  << " real_T* res[" << f->sz_res() << "] = {0};\n"
772  << " real_T* y[" << f->n_out_ << "] = {0};\n\n"
773  << " /* Point inputs directly to casadi input buffer */\n"
774  << " for (ii=0; ii<" << f->n_in_ << ";++ii) {\n"
775  << " arg[ii] = *ssGetInputPortRealSignalPtrs( S, ii );\n"
776  << " }\n\n"
777  << " /* Point outputs to buffer */\n"
778  << " for (ii=0; ii<" << f->n_out_ << ";++ii) {\n"
779  << " y[ii] = ssGetOutputPortRealSignal( S, ii );\n"
780  << " }\n\n"
781  << " /* Point allocated working array to casadi output buffer */\n";
782  for (casadi_int ii=0; ii<f->n_out_; ++ii) {
783  g << " res[" << ii << "] = w + offset;\n"
784  << " offset += " << f.nnz_out(ii) << ";\n";
785  }
786  g << " \n"
787  << " /* Call CasADi function */\n"
788  << " " << f.name() << "( arg, res, iw, w+offset, 0 );\n\n"
789  << " /* Assign results to Simulink output array */\n"
790  << " for (ii=0; ii<" << f->n_out_ << "; ++ii){\n\n"
791  << " /* Get sparsity information of casadi function output "
792  "(sp[0] - n_rows, sp[1] - n_cols, sp[2] - dense/sparse) */\n"
793  << " sp = " << f.name() << "_sparsity_out(ii);\n\n"
794  << " /* Check if output is dense (sp[2]=1) or sparse (sp[2]=0) */\n"
795  << " if (sp[2]==0) {\n"
796  << " jj_total = 0;\n"
797  << " ind_start_row_index = 2 + sp[1] + 1;\n\n"
798  << " /* Distribute nonzero elements column by column */\n"
799  << " for (col=0; col<sp[1]; col++) {\n\n"
800  << " /* The cumulative sum of nonzero elements after each column starts at index 2, "
801  "after last entry of CCS array col_ptr; number of nonzero elements in current column is "
802  "obtained by the difference of two consecutive values */\n"
803  << " nnz_col = sp[2+col+1] - sp[2+col];\n\n"
804  << " /* Distribute nonzero elements of current column to correct row position */\n"
805  << " for (jj=0; jj<nnz_col; jj++) {\n"
806  << " row = sp[ind_start_row_index+jj_total];\n"
807  << " y[ii][row + sp[0]*col] = res[ii][jj_total];\n"
808  << " jj_total++;\n"
809  << " }\n"
810  << " }\n"
811  << " }\n"
812  << " else {\n"
813  << " y[ii] = res[ii];\n"
814  << " }\n"
815  << " }\n"
816  << "}\n\n\n";
817 
818  // Model terminate function
819  g << "/* Function: mdlTerminate =================================================\n"
820  << " * Abstract:\n"
821  << " * In this function, you should perform any actions that are necessary\n"
822  << " * at the termination of a simulation.\n"
823  << " */\n"
824  << "static void mdlTerminate(SimStruct *S)\n"
825  << "{\n"
826  << "}\n\n\n"
827  << "/* Required S-function trailer */\n"
828  << "#ifdef MATLAB_MEX_FILE\n"
829  << "# include \"simulink.c\"\n"
830  << "#else\n"
831  << "# include \"cg_sfun.h\"\n"
832  << "#endif";
833 
834  return g.str();
835  }
836 
837  void CodeGenerator::generate_main(std::ostream &s) const {
838  s << this->dll_export << "int main(int argc, char* argv[]) {\n";
839 
840  // Create switch
841  s << " if (argc<2) {\n"
842  << " /* name error */\n";
843  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
844  s << " } else if (strcmp(argv[1], \"" << exposed_fname[i] << "\")==0) {\n"
845  << " return main_" << exposed_fname[i] << "(argc-2, argv+2);\n";
846  }
847  s << " }\n";
848 
849  // Error
850  s << " fprintf(stderr, \"First input should be a command string. Possible values:";
851  for (casadi_int i=0; i<exposed_fname.size(); ++i) {
852  s << " '" << exposed_fname[i] << "'";
853  }
854  s << "\\n";
855  s << "Note: you may use function.generate_input to create a command string.";
856  s << "\\n\");\n";
857 
858  // End main
859  s << " return 1;\n"
860  << "}\n";
861  }
862 
863  void CodeGenerator::define_rom_double(const void* id, casadi_int size) {
864  auto it = file_scope_double_.find(id);
865  casadi_assert(it==file_scope_double_.end(), "Already defined.");
866  shorthand("rd" + str(file_scope_double_.size()));
867  file_scope_double_[id] = size;
868  }
869 
870  std::string CodeGenerator::rom_double(const void* id) const {
871  auto it = file_scope_double_.find(id);
872  casadi_assert(it!=file_scope_double_.end(), "Not defined.");
873  casadi_int size = std::distance(file_scope_double_.begin(), it);
874  return "casadi_rd" + str(size);
875  }
876 
877  void CodeGenerator::define_rom_integer(const void* id, casadi_int size) {
878  auto it = file_scope_double_.find(id);
879  casadi_assert(it==file_scope_double_.end(), "Already defined.");
880  shorthand("ri" + str(file_scope_double_.size()));
881  file_scope_double_[id] = size;
882  }
883 
884  std::string CodeGenerator::rom_integer(const void* id) const {
885  auto it = file_scope_double_.find(id);
886  casadi_assert(it!=file_scope_double_.end(), "Not defined.");
887  casadi_int size = std::distance(file_scope_double_.begin(), it);
888  return "casadi_ri" + str(size);
889  }
890 
891  void CodeGenerator::define_pool_double(const std::string& name, const std::vector<double>& def) {
892  auto it = pool_double_.find(name);
893  if (it==pool_double_.end()) {
894  casadi_int index = pool_double_defaults_.size();
895  pool_double_defaults_.push_back(def);
896  shorthand("pd" + str(index));
897  pool_double_[name] = index;
898  } else {
899  casadi_assert_dev(def==pool_double_defaults_[it->second]);
900  }
901  }
902 
903  std::string CodeGenerator::pool_double(const std::string& name) const {
904  auto it = pool_double_.find(name);
905  casadi_assert(it!=pool_double_.end(), "Not defined.");
906  return "casadi_pd" + str(it->second);
907  }
908 
910  const std::string& name) {
911  if (!thread_safe()) return;
912  if (!local_mutexes_[f.get()].insert(name).second) return; // already defined
913  std::string sh = shorthand(name);
914  auxiliaries << "#if CASADI_MUTEX_USE_STATIC_INIT == 0\n";
915  auxiliaries << "static CASADI_MUTEX_TYPE " << sh << ";\n";
916  auxiliaries << "#else\n";
917  auxiliaries << "static CASADI_MUTEX_TYPE " << sh
918  << " = CASADI_MUTEX_STATIC_INIT;\n";
919  auxiliaries << "#endif\n";
920  }
921 
922  std::string CodeGenerator::local_mutex(const Function& f,
923  const std::string& name) const {
924  auto it = local_mutexes_.find(f.get());
925  casadi_assert(it != local_mutexes_.end() && it->second.count(name),
926  "Mutex not defined: " + name);
927  return shorthand(name);
928  }
929 
930  static const std::set<std::string> empty_mutex_set_;
931 
932  const std::set<std::string>& CodeGenerator::local_mutexes(
933  const Function& f) const {
934  auto it = local_mutexes_.find(f.get());
935  if (it == local_mutexes_.end()) return empty_mutex_set_;
936  return it->second;
937  }
938 
939  void CodeGenerator::dump(std::ostream& s) {
940  // Consistency check
941  casadi_assert_dev(current_indent_ == 0);
942 
943  // Prefix internal symbols to avoid symbol collisions
944  s << "/* How to prefix internal symbols */\n"
945  << "#ifdef CASADI_CODEGEN_PREFIX\n"
946  << " #define CASADI_NAMESPACE_CONCAT(NS, ID) _CASADI_NAMESPACE_CONCAT(NS, ID)\n"
947  << " #define _CASADI_NAMESPACE_CONCAT(NS, ID) NS ## ID\n"
948  << " #define CASADI_PREFIX(ID) CASADI_NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)\n"
949  << "#else\n"
950  << " #define CASADI_PREFIX(ID) " << this->prefix << "_ ## ID\n"
951  << "#endif\n\n";
952 
953  s << this->includes.str();
954  s << std::endl;
955 
956  // Numeric types after includes: may depend on them. e.g. mex type
957  // Real type (usually double)
958  generate_casadi_real(s);
959 
960  // Integer type (usually long long)
961  generate_casadi_int(s);
962 
963  if (needs_mem_) {
964  s << "#ifndef CASADI_MAX_NUM_THREADS\n";
965  s << "#define CASADI_MAX_NUM_THREADS 1\n";
966  s << "#endif\n\n";
967  }
968 
969  // casadi/mem after numeric types to define derived types
970  // Memory struct entry point
971  if (this->with_mem) {
972  s << "#include <casadi/mem.h>\n" << std::endl;
973  }
974 
975  // Macros
976  if (!added_shorthands_.empty()) {
977  s << "/* Add prefix to internal symbols */\n";
978  for (auto&& i : added_shorthands_) {
979  s << "#define " << "casadi_" << i << " CASADI_PREFIX(" << i << ")\n";
980  }
981  s << std::endl;
982  }
983 
984  if (this->with_export) generate_export_symbol(s);
985 
986  // Check if inf/nan is needed
987  for (const auto& d : double_constants_) {
988  for (double e : d) {
989  if (isinf(e)) add_auxiliary(AUX_INF);
990  if (isnan(e)) add_auxiliary(AUX_NAN);
991  }
992  }
993 
994  // Codegen auxiliary functions
995  s << this->auxiliaries.str();
996 
997  // Print integer constants
998  if (!integer_constants_.empty()) {
999  for (casadi_int i=0; i<integer_constants_.size(); ++i) {
1000  print_vector(s, "casadi_s" + str(i), integer_constants_[i]);
1001  }
1002  s << std::endl;
1003  }
1004 
1005  // Print double constants
1006  if (!double_constants_.empty()) {
1007  for (casadi_int i=0; i<double_constants_.size(); ++i) {
1008  print_vector(s, "casadi_c" + str(i), double_constants_[i]);
1009  }
1010  s << std::endl;
1011  }
1012 
1013  // Print char constants
1014  if (!char_constants_.empty()) {
1015  for (casadi_int i=0; i<char_constants_.size(); ++i) {
1016  print_vector(s, "casadi_b" + str(i), char_constants_[i]);
1017  }
1018  s << std::endl;
1019  }
1020 
1021  // Print string constants
1022  if (!string_constants_.empty()) {
1023  for (casadi_int i=0; i<string_constants_.size(); ++i) {
1024  print_vector(s, "casadi_a" + str(i), string_constants_[i]);
1025  }
1026  s << std::endl;
1027  }
1028 
1029  if (sz_zeros_) {
1030  std::vector<double> sz_zeros(sz_zeros_, 0);
1031  print_vector(s, "casadi_zeros", std::vector<double>(sz_zeros));
1032  s << std::endl;
1033  }
1034 
1035  if (sz_ones_) {
1036  std::vector<double> sz_ones(sz_ones_, 0);
1037  print_vector(s, "casadi_ones", std::vector<double>(sz_ones));
1038  s << std::endl;
1039  }
1040 
1041  // Print file scope double work
1042  if (!file_scope_double_.empty()) {
1043  casadi_int i=0;
1044  for (const auto& it : file_scope_double_) {
1045  s << "static casadi_real casadi_rd" + str(i++) + "[" + str(it.second) + "];\n";
1046  }
1047  s << std::endl;
1048  }
1049 
1050  // Print file scope integer work
1051  if (!file_scope_integer_.empty()) {
1052  casadi_int i=0;
1053  for (const auto& it : file_scope_integer_) {
1054  s << "static casadi_real casadi_ri" + str(i++) + "[" + str(it.second) + "];\n";
1055  }
1056  s << std::endl;
1057  }
1058 
1059  // Print file scope double pool
1060  if (!pool_double_.empty()) {
1061  casadi_int i=0;
1062  for (const auto& v : pool_double_defaults_) {
1063  s << "casadi_real casadi_pd" + str(i) +
1064  "[" + str(v.size()) + "] = " + initializer(v) + ";\n";
1065  i++;
1066  }
1067  s << std::endl;
1068  }
1069 
1070  // External function declarations
1071  if (!added_externals_.empty()) {
1072  s << "/* External functions */\n";
1073  for (auto&& i : added_externals_) {
1074  s << i << std::endl;
1075  }
1076  s << std::endl << std::endl;
1077  }
1078 
1079  // Codegen body
1080  s << this->body.str();
1081 
1082  // End with new line
1083  s << std::endl;
1084  }
1085 
1086  std::string CodeGenerator::work(casadi_int n, casadi_int sz, bool is_ref) const {
1087  if (is_ref) {
1088  return "wr" + format_padded(n);
1089  }
1090  if (n<0 || sz==0) {
1091  return "0";
1092  } else if (sz==1 && !this->codegen_scalars) {
1093  return "(&w" + format_padded(n) + ")";
1094  } else {
1095  return "w" + format_padded(n);
1096  }
1097  }
1098 
1099  std::string CodeGenerator::workel(casadi_int n) const {
1100  if (n<0) return "0";
1101  std::stringstream s;
1102  if (this->codegen_scalars) s << "*";
1103  s << "w" << format_padded(n);
1104  return s.str();
1105  }
1106 
1107  void CodeGenerator::reserve_work(casadi_int n) {
1108  if (n == 0) {
1109  padding_length_ = 1;
1110  } else {
1111  // Zero based counting. The 10th entry is to be rendered as '9'
1112  padding_length_ = str(n-1).length();
1113  }
1114  }
1115 
1116  std::string CodeGenerator::format_padded(casadi_int i) const {
1117  std::stringstream ss;
1118  ss.str("");
1119  ss << std::setw(padding_length_) << std::setfill('0') << i;
1120  return ss.str();
1121  }
1122 
1123  std::string CodeGenerator::array(const std::string& type, const std::string& name, casadi_int len,
1124  const std::string& def) {
1125  std::stringstream s;
1126  s << type << " ";
1127  if (len==0) {
1128  s << "*" << name << " = 0";
1129  } else {
1130  s << name << "[" << len << "]";
1131  if (!def.empty()) s << " = " << def;
1132  }
1133  s << ";\n";
1134  return s.str();
1135  }
1136 
1137  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1138  const std::vector<casadi_int>& v) {
1139  s << array("static const casadi_int", name, v.size(), initializer(v));
1140  }
1141 
1142  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1143  const std::vector<char>& v) {
1144  s << array("static const char", name, v.size(), initializer(v));
1145  }
1146 
1147  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1148  const std::vector<double>& v) {
1149  s << array("static const casadi_real", name, v.size(), initializer(v));
1150  }
1151 
1152  void CodeGenerator::print_vector(std::ostream &s, const std::string& name,
1153  const std::vector<std::string>& v) {
1154  s << array("static const char*", name, v.size(), initializer(v));
1155  }
1156 
1157  std::string CodeGenerator::print_canonical(const Sparsity& sp, const std::string& arg) {
1159  std::stringstream s;
1160  s << "casadi_print_canonical(" << sparsity(sp) << ", " << arg << ");";
1161  return s.str();
1162  }
1163 
1164  std::string CodeGenerator::print_vector(casadi_int sz, const std::string& arg) {
1166  std::stringstream s;
1167  s << "casadi_print_vector(" << sz << ", " << arg << ");";
1168  return s.str();
1169  }
1170 
1171  std::string CodeGenerator::print_scalar(const std::string& arg) {
1173  std::stringstream s;
1174  s << "casadi_print_scalar(" << arg << ");";
1175  return s.str();
1176  }
1177 
1178  std::string CodeGenerator::fprintf_scalar(const std::string& f, const std::string& arg) {
1180  std::stringstream s;
1181  s << "casadi_fprintf_scalar(" << f << ", " << arg << ");";
1182  return s.str();
1183  }
1184 
1185  std::string CodeGenerator::fprintf_vector(const std::string& f, casadi_int sz,
1186  const std::string& arg, const std::string& sep) {
1188  std::stringstream s;
1189  s << "casadi_fprintf_vector(" << f << ", " << sz << ", " << arg << ", \"" << sep << "\");";
1190  return s.str();
1191  }
1192 
1193  std::string CodeGenerator::print_op(casadi_int op, const std::string& a0) {
1194  switch (op) {
1195  case OP_FABS:
1197  return "casadi_fabs("+a0+")";
1198  case OP_SQ:
1200  return "casadi_sq("+a0+")";
1201  case OP_SIGN:
1203  return "casadi_sign("+a0+")";
1204  case OP_LOG1P:
1206  return "casadi_log1p("+a0+")";
1207  case OP_EXPM1:
1209  return "casadi_expm1("+a0+")";
1210  default:
1211  return casadi_math<double>::print(op, a0);
1212  }
1213  }
1214  std::string CodeGenerator::print_op(casadi_int op, const std::string& a0, const std::string& a1) {
1215  switch (op) {
1216  case OP_FMIN:
1218  return "casadi_fmin("+a0+","+a1+")";
1219  case OP_FMAX:
1221  return "casadi_fmax("+a0+","+a1+")";
1222  case OP_HYPOT:
1224  return "casadi_hypot("+a0+","+a1+")";
1225  case OP_PRINTME:
1227  return "casadi_printme("+a0+","+a1+")";
1228  default:
1229  return casadi_math<double>::print(op, a0, a1);
1230  }
1231  }
1232 
1233  void CodeGenerator::add_include(const std::string& new_include, bool relative_path,
1234  const std::string& use_ifdef) {
1235  // Register the new element
1236  bool added = added_includes_.insert(new_include).second;
1237 
1238  // Quick return if it already exists
1239  if (!added) return;
1240 
1241  // Ifdef opening
1242  if (!use_ifdef.empty()) this->includes << "#ifdef " << use_ifdef << std::endl;
1243 
1244  // Print to the header section
1245  if (relative_path) {
1246  this->includes << "#include \"" << new_include << "\"\n";
1247  } else {
1248  this->includes << "#include <" << new_include << ">\n";
1249  }
1250 
1251  // Ifdef closing
1252  if (!use_ifdef.empty()) this->includes << "#endif\n";
1253  }
1254 
1255  void CodeGenerator::setup_callback(const std::string& s, const Function& f) {
1256  std::string name = add_dependency(f);
1257  bool needs_mem = f->codegen_needs_mem();
1258  if (needs_mem) {
1259  *this << s << ".checkout = " << name << "_checkout;\n";
1260  } else {
1261  *this << s << ".checkout = 0;\n";
1262  }
1263 
1264  *this << s << ".eval = " << name << ";\n";
1265  if (needs_mem) {
1266  *this << s << ".release = " << name << "_release;\n";
1267  } else {
1268  *this << s << ".release = 0;\n";
1269  }
1270  }
1271 
1272  std::string CodeGenerator::
1273  operator()(const Function& f, const std::string& arg,
1274  const std::string& res, const std::string& iw,
1275  const std::string& w, const std::string& failure_ret) {
1276  std::string name = add_dependency(f);
1277 
1278  std::string cg_name = f->codegen_name(*this, false);
1279  bool needs_mem = f->codegen_needs_mem();
1280  if (needs_mem) {
1281  std::string mem = "mid";
1282  local("flag", "int");
1283  local(mem, "int");
1284  std::string checkout = shorthand(cg_name + "_checkout");
1285  *this << mem << " = " << checkout << "();\n";
1286  if (failure_ret.empty()) {
1287  *this << "if (" << mem << "<0) {\n";
1288  *this << "flag = 1;\n";
1289  *this << "} else {\n";
1290  } else {
1291  *this << "if (" << mem << "<0) return " << failure_ret << ";\n";
1292  }
1293 
1294  *this << "flag = " + name + "(" + arg + ", " + res + ", "
1295  + iw + ", " + w + ", " << mem << ");\n";
1296 
1297  if (failure_ret.empty()) {
1298  *this << "}\n";
1299  }
1300 
1301  std::string release = shorthand(cg_name + "_release");
1302  *this << release << "(" << mem << ");\n";
1303  return "flag";
1304  } else {
1305  return name + "(" + arg + ", " + res + ", "
1306  + iw + ", " + w + ", 0)";
1307  }
1308  }
1309 
1310  void CodeGenerator::add_external(const std::string& new_external) {
1311  added_externals_.insert(new_external);
1312  }
1313 
1314  std::string CodeGenerator::shorthand(const std::string& name) const {
1315  casadi_assert(added_shorthands_.count(name), "No such macro: " + name);
1316  return "casadi_" + name;
1317  }
1318 
1319  std::string CodeGenerator::shorthand(const std::string& name, bool allow_adding) {
1320  bool added = added_shorthands_.insert(name).second;
1321  if (!allow_adding) {
1322  casadi_assert(added, "Duplicate macro: " + name);
1323  }
1324  return "casadi_" + name;
1325  }
1326 
1327  casadi_int CodeGenerator::add_sparsity(const Sparsity& sp, bool canonical) {
1328  return get_constant(sp.compress(canonical), true);
1329  }
1330 
1331  std::string CodeGenerator::sparsity(const Sparsity& sp, bool canonical) {
1332  return shorthand("s" + str(add_sparsity(sp, canonical)));
1333  }
1334 
1335  casadi_int CodeGenerator::get_sparsity(const Sparsity& sp) const {
1336  return const_cast<CodeGenerator&>(*this).get_constant(sp, false);
1337  }
1338 
1339  size_t CodeGenerator::hash(const std::vector<double>& v) {
1340  // Calculate a hash value for the vector
1341  std::size_t seed=0;
1342  if (!v.empty()) {
1343  casadi_assert_dev(sizeof(double) % sizeof(size_t)==0);
1344  const casadi_int int_len = v.size()*(sizeof(double)/sizeof(size_t));
1345  const size_t* int_v = reinterpret_cast<const size_t*>(&v.front());
1346  for (size_t i=0; i<int_len; ++i) {
1347  hash_combine(seed, int_v[i]);
1348  }
1349  }
1350  return seed;
1351  }
1352 
1353  size_t CodeGenerator::hash(const std::vector<casadi_int>& v) {
1354  size_t seed=0;
1355  hash_combine(seed, v);
1356  return seed;
1357  }
1358 
1359  size_t CodeGenerator::hash(const std::vector<char>& v) {
1360  size_t seed=0;
1361  hash_combine(seed, v);
1362  return seed;
1363  }
1364 
1365  size_t CodeGenerator::hash(const std::vector<std::string>& v) {
1366  size_t seed=0;
1367  hash_combine(seed, v);
1368  return seed;
1369  }
1370 
1371  casadi_int CodeGenerator::get_constant(const std::vector<double>& v, bool allow_adding) {
1372  // Hash the vector
1373  size_t h = hash(v);
1374 
1375  // Try to locate it in already added constants
1376  auto eq = added_double_constants_.equal_range(h);
1377  for (auto i=eq.first; i!=eq.second; ++i) {
1378  if (equal(v, double_constants_[i->second])) return i->second;
1379  }
1380 
1381  if (allow_adding) {
1382  // Add to constants
1383  casadi_int ind = double_constants_.size();
1384  double_constants_.push_back(v);
1385  added_double_constants_.insert(std::make_pair(h, ind));
1386  return ind;
1387  } else {
1388  casadi_error("Constant not found");
1389  return -1;
1390  }
1391  }
1392 
1393  casadi_int CodeGenerator::get_constant(const std::vector<casadi_int>& v, bool allow_adding) {
1394  // Hash the vector
1395  size_t h = hash(v);
1396 
1397  // Try to locate it in already added constants
1398  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1399  added_integer_constants_.equal_range(h);
1400  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1401  if (equal(v, integer_constants_[i->second])) return i->second;
1402  }
1403 
1404  if (allow_adding) {
1405  // Add to constants
1406  casadi_int ind = integer_constants_.size();
1407  integer_constants_.push_back(v);
1408  added_integer_constants_.insert(std::pair<size_t, size_t>(h, ind));
1409  return ind;
1410  } else {
1411  casadi_error("Constant not found");
1412  return -1;
1413  }
1414  }
1415 
1416  casadi_int CodeGenerator::get_constant(const std::vector<char>& v, bool allow_adding) {
1417  // Hash the vector
1418  size_t h = hash(v);
1419 
1420  // Try to locate it in already added constants
1421  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1422  added_char_constants_.equal_range(h);
1423  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1424  if (equal(v, char_constants_[i->second])) return i->second;
1425  }
1426 
1427  if (allow_adding) {
1428  // Add to constants
1429  casadi_int ind = char_constants_.size();
1430  char_constants_.push_back(v);
1431  added_char_constants_.insert(std::pair<size_t, size_t>(h, ind));
1432  return ind;
1433  } else {
1434  casadi_error("Constant not found");
1435  return -1;
1436  }
1437  }
1438 
1439  casadi_int CodeGenerator::get_constant(const std::vector<std::string>& v, bool allow_adding) {
1440  // Hash the vector
1441  size_t h = hash(v);
1442 
1443  // Try to locate it in already added constants
1444  std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> eq =
1445  added_string_constants_.equal_range(h);
1446  for (std::multimap<size_t, size_t>::iterator i=eq.first; i!=eq.second; ++i) {
1447  if (equal(v, string_constants_[i->second])) return i->second;
1448  }
1449 
1450  if (allow_adding) {
1451  // Add to constants
1452  casadi_int ind = string_constants_.size();
1453  string_constants_.push_back(v);
1454  added_string_constants_.insert(std::pair<size_t, size_t>(h, ind));
1455  return ind;
1456  } else {
1457  casadi_error("Constant not found");
1458  return -1;
1459  }
1460  }
1461 
1462  std::string CodeGenerator::constant(const std::vector<casadi_int>& v) {
1463  return shorthand("s" + str(get_constant(v, true)));
1464  }
1465 
1466  std::string CodeGenerator::constant(const std::vector<char>& v) {
1467  return shorthand("b" + str(get_constant(v, true)));
1468  }
1469 
1470  std::string CodeGenerator::constant(const std::vector<std::string>& v) {
1471  return shorthand("a" + str(get_constant(v, true)));
1472  }
1473 
1474  std::string CodeGenerator::zeros(casadi_int sz) {
1475  sz_zeros_ = std::max(sz_zeros_, sz);
1476  return shorthand("zeros");
1477  }
1478 
1479  std::string CodeGenerator::ones(casadi_int sz) {
1480  sz_ones_ = std::max(sz_ones_, sz);
1481  return shorthand("ones");
1482  }
1483 
1485  const std::string& name, const std::vector<casadi_int>& v, const std::string& type) {
1486  std::string ref = constant(v);
1487  if (!v.empty()) {
1488  local(name+"[" + str(v.size()) + "]", type);
1489  } else {
1490  local(name, type, "*");
1491  }
1492  if (!v.empty()) {
1493  local("i", type);
1494  (*this) << "for (i=0;i<" << v.size() << ";++i) " + name + "[i] = " + ref + "[i];\n";
1495  } else {
1496  init_local(name, "0");
1497  }
1498  }
1499 
1500  std::string CodeGenerator::constant(const std::vector<double>& v) {
1501  return shorthand("c" + str(get_constant(v, true)));
1502  }
1503 
1504  void CodeGenerator::add_auxiliary(Auxiliary f, const std::vector<std::string>& inst) {
1505  // Look for existing instantiations
1506  auto f_match = added_auxiliaries_.equal_range(f);
1507  // Look for duplicates
1508  for (auto it=f_match.first; it!=f_match.second; ++it) {
1509  if (it->second==inst) return;
1510  }
1511  added_auxiliaries_.insert(std::make_pair(f, inst));
1512 
1513  // Add the appropriate function
1514  switch (f) {
1515  case AUX_COPY:
1516  if (this->l1_blas) {
1517  Blas::codegen_copy_aux(*this, inst);
1518  } else {
1519  this->auxiliaries << sanitize_source(casadi_copy_str, inst);
1520  }
1521  break;
1522  case AUX_SCALED_COPY:
1523  this->auxiliaries << sanitize_source(casadi_scaled_copy_str, inst);
1524  break;
1525  case AUX_SWAP:
1526  this->auxiliaries << sanitize_source(casadi_swap_str, inst);
1527  break;
1528  case AUX_SCAL:
1529  if (!(this->l1_blas && Blas::codegen_scal_aux(*this, inst)))
1530  this->auxiliaries << sanitize_source(casadi_scal_str, inst);
1531  break;
1532  case AUX_AXPY:
1533  if (!(this->l1_blas && Blas::codegen_axpy_aux(*this, inst)))
1534  this->auxiliaries << sanitize_source(casadi_axpy_str, inst);
1535  break;
1536  case AUX_DOT:
1537  if (!(this->l1_blas && Blas::codegen_dot_aux(*this, inst)))
1538  this->auxiliaries << sanitize_source(casadi_dot_str, inst);
1539  break;
1540  case AUX_BILIN:
1541  this->auxiliaries << sanitize_source(casadi_bilin_str, inst);
1542  break;
1543  case AUX_KRON:
1544  this->auxiliaries << sanitize_source(casadi_kron_str, inst);
1545  break;
1546  case AUX_KRON_DENSE:
1547  this->auxiliaries << sanitize_source(casadi_kron_dense_str, inst);
1548  break;
1549  case AUX_KRON_DENSE_SPARSE:
1550  this->auxiliaries << sanitize_source(casadi_kron_dense_sparse_str, inst);
1551  break;
1552  case AUX_KRON_SPARSE_DENSE:
1553  this->auxiliaries << sanitize_source(casadi_kron_sparse_dense_str, inst);
1554  break;
1556  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_str, inst);
1557  break;
1559  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_dense_str, inst);
1560  break;
1562  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_dense_sparse_str, inst);
1563  break;
1565  this->auxiliaries << sanitize_source(casadi_kron_contract_inner_sparse_dense_str, inst);
1566  break;
1568  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_str, inst);
1569  break;
1571  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_dense_str, inst);
1572  break;
1574  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_dense_sparse_str, inst);
1575  break;
1577  this->auxiliaries << sanitize_source(casadi_kron_contract_outer_sparse_dense_str, inst);
1578  break;
1579  case AUX_RANK1:
1580  this->auxiliaries << sanitize_source(casadi_rank1_str, inst);
1581  break;
1582  case AUX_IAMAX:
1584  this->auxiliaries << sanitize_source(casadi_iamax_str, inst);
1585  break;
1586  case AUX_INTERPN:
1589  add_auxiliary(AUX_FLIP, {});
1591  add_auxiliary(AUX_CLEAR, {"casadi_int"});
1592  this->auxiliaries << sanitize_source(casadi_interpn_str, inst);
1593  break;
1594  case AUX_INTERPN_GRAD:
1596  this->auxiliaries << sanitize_source(casadi_interpn_grad_str, inst);
1597  break;
1598  case AUX_DE_BOOR:
1599  this->auxiliaries << sanitize_source(casadi_de_boor_str, inst);
1600  break;
1601  case AUX_TENSOR_TTV:
1602  this->auxiliaries << sanitize_source(casadi_tensor_ttv_str, inst);
1603  break;
1604  case AUX_ND_BOOR_EVAL:
1610  this->auxiliaries << sanitize_source(casadi_nd_boor_eval_str, inst);
1611  break;
1612  case AUX_FLIP:
1613  this->auxiliaries << sanitize_source(casadi_flip_str, inst);
1614  break;
1615  case AUX_LOW:
1616  this->auxiliaries << sanitize_source(casadi_low_str, inst);
1617  break;
1618  case AUX_INTERPN_WEIGHTS:
1620  this->auxiliaries << sanitize_source(casadi_interpn_weights_str, inst);
1621  break;
1623  this->auxiliaries << sanitize_source(casadi_interpn_interpolate_str, inst);
1624  break;
1625  case AUX_NORM_1:
1626  if (!(this->l1_blas && Blas::codegen_norm_1_aux(*this, inst))) {
1628  this->auxiliaries << sanitize_source(casadi_norm_1_str, inst);
1629  }
1630  break;
1631  case AUX_NORM_2:
1632  if (!(this->l1_blas && Blas::codegen_norm_2_aux(*this, inst))) {
1634  this->auxiliaries << sanitize_source(casadi_norm_2_str, inst);
1635  }
1636  break;
1637  case AUX_NORM_INF:
1640  this->auxiliaries << sanitize_source(casadi_norm_inf_str, inst);
1641  break;
1642  case AUX_VECTOR_FMAX:
1644  this->auxiliaries << sanitize_source(casadi_vector_fmax_str, inst);
1645  break;
1646  case AUX_VECTOR_FMIN:
1648  this->auxiliaries << sanitize_source(casadi_vector_fmin_str, inst);
1649  break;
1650  case AUX_MASKED_NORM_INF:
1653  this->auxiliaries << sanitize_source(casadi_masked_norm_inf_str, inst);
1654  break;
1655  case AUX_CLIP_MIN:
1656  // add_auxiliary(AUX_CLIP_MIN);
1657  this->auxiliaries << sanitize_source(casadi_clip_min_str, inst);
1658  break;
1659  case AUX_CLIP_MAX:
1660  // add_auxiliary(AUX_CLIP_MAX);
1661  this->auxiliaries << sanitize_source(casadi_clip_max_str, inst);
1662  break;
1663  case AUX_CLEAR:
1664  this->auxiliaries << sanitize_source(casadi_clear_str, inst);
1665  break;
1666  case AUX_FILL:
1667  this->auxiliaries << sanitize_source(casadi_fill_str, inst);
1668  break;
1669  case AUX_MV:
1670  this->auxiliaries << sanitize_source(casadi_mv_str, inst);
1671  break;
1672  case AUX_MV_DENSE:
1673  this->auxiliaries << sanitize_source(casadi_mv_dense_str, inst);
1674  break;
1675  case AUX_MTIMES:
1676  this->auxiliaries << sanitize_source(casadi_mtimes_str, inst);
1677  break;
1678  case AUX_MTIMES_DENSE:
1679  this->auxiliaries << sanitize_source(casadi_mtimes_dense_str, inst);
1680  break;
1682  this->auxiliaries << sanitize_source(casadi_mtimes_dense_sparse_str, inst);
1683  break;
1684  case AUX_TRILSOLVE:
1685  this->auxiliaries << sanitize_source(casadi_trilsolve_str, inst);
1686  break;
1687  case AUX_TRIUSOLVE:
1688  this->auxiliaries << sanitize_source(casadi_triusolve_str, inst);
1689  break;
1690  case AUX_PROJECT:
1691  this->auxiliaries << sanitize_source(casadi_project_str, inst);
1692  break;
1693  case AUX_TRI_PROJECT:
1694  this->auxiliaries << sanitize_source(casadi_tri_project_str, inst);
1695  break;
1696  case AUX_DENSIFY:
1699  {
1700  std::vector<std::string> inst2 = inst;
1701  if (inst.size()==1) inst2.push_back(inst[0]);
1702  this->auxiliaries << sanitize_source(casadi_densify_str, inst2);
1703  }
1704  break;
1705  case AUX_SPARSIFY:
1707  {
1708  std::vector<std::string> inst2 = inst;
1709  if (inst.size()==1) inst2.push_back(inst[0]);
1710  this->auxiliaries << sanitize_source(casadi_sparsify_str, inst2);
1711  }
1712  break;
1713  case AUX_TRANS:
1714  this->auxiliaries << sanitize_source(casadi_trans_str, inst);
1715  break;
1716  case AUX_TO_MEX:
1718  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1719  << sanitize_source(casadi_to_mex_str, inst)
1720  << "#endif\n\n";
1721  break;
1722  case AUX_FROM_MEX:
1724  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1725  << sanitize_source(casadi_from_mex_str, inst)
1726  << "#endif\n\n";
1727  break;
1728  case AUX_FINITE_DIFF:
1733  this->auxiliaries << sanitize_source(casadi_finite_diff_str, inst);
1734  break;
1735  case AUX_QR:
1740  this->auxiliaries << sanitize_source(casadi_qr_str, inst);
1741  break;
1742  case AUX_DET:
1743  this->auxiliaries << sanitize_source(casadi_det_str, inst);
1744  break;
1745  case AUX_LSQR:
1752  this->auxiliaries << sanitize_source(casadi_lsqr_str, inst);
1753  break;
1754  case AUX_QP:
1755  this->auxiliaries << sanitize_source(casadi_qp_str, inst);
1756  break;
1757  case AUX_SOCP:
1759  this->auxiliaries << sanitize_source(casadi_socp_str, inst);
1760  break;
1761  case AUX_QRQP:
1776  add_include("stdarg.h");
1777  add_include("stdio.h");
1778  add_include("math.h");
1779 
1780  this->auxiliaries << sanitize_source(casadi_qrqp_str, inst);
1781  break;
1782  case AUX_NLP:
1784  this->auxiliaries << sanitize_source(casadi_nlp_str, inst);
1785  break;
1786  case AUX_SQPMETHOD:
1791  this->auxiliaries << sanitize_source(casadi_sqpmethod_str, inst);
1792  break;
1793  case AUX_FEASIBLESQPMETHOD:
1796  this->auxiliaries << sanitize_source(casadi_feasiblesqpmethod_str, inst);
1797  break;
1798  case AUX_LDL:
1799  this->auxiliaries << sanitize_source(casadi_ldl_str, inst);
1800  break;
1801  case AUX_NEWTON:
1806  this->auxiliaries << sanitize_source(casadi_newton_str, inst);
1807  break;
1808  case AUX_MAX_VIOL:
1810  this->auxiliaries << sanitize_source(casadi_max_viol_str, inst);
1811  break;
1812  case AUX_SUM_VIOL:
1813  this->auxiliaries << sanitize_source(casadi_sum_viol_str, inst);
1814  break;
1815  case AUX_SUM:
1816  this->auxiliaries << sanitize_source(casadi_sum_str, inst);
1817  break;
1818  case AUX_VFMIN:
1820  this->auxiliaries << sanitize_source(casadi_vfmin_str, inst);
1821  break;
1822  case AUX_VFMAX:
1824  this->auxiliaries << sanitize_source(casadi_vfmax_str, inst);
1825  break;
1826  case AUX_REGULARIZE:
1829  this->auxiliaries << sanitize_source(casadi_regularize_str, inst);
1830  break;
1835  this->auxiliaries << sanitize_source(casadi_bound_consistency_str, inst);
1836  break;
1837  case AUX_FILE_SLURP:
1838  add_include("stdio.h");
1839  this->auxiliaries << sanitize_source(casadi_file_slurp_str, inst);
1840  break;
1841  case AUX_CACHE:
1842  this->auxiliaries << sanitize_source(casadi_cache_str, inst);
1843  break;
1844  case AUX_CVX:
1851  this->auxiliaries << sanitize_source(casadi_cvx_str, inst);
1852  break;
1853  case AUX_CONVEXIFY:
1858  this->auxiliaries << sanitize_source(casadi_convexify_str, inst);
1859  break;
1860  case AUX_LOGSUMEXP:
1863  this->auxiliaries << sanitize_source(casadi_logsumexp_str, inst);
1864  break;
1865  case AUX_SPARSITY:
1866  this->auxiliaries << sanitize_source(casadi_sparsity_str, inst);
1867  break;
1868  case AUX_BFGS:
1877  this->auxiliaries << sanitize_source(casadi_bfgs_str, inst);
1878  break;
1879  case AUX_ORACLE:
1880  this->auxiliaries << sanitize_source(casadi_oracle_str, inst);
1881  break;
1882  case AUX_ORACLE_CALLBACK:
1883  this->auxiliaries << sanitize_source(casadi_oracle_callback_str, inst);
1884  break;
1885  case AUX_OCP_BLOCK:
1886  this->auxiliaries << sanitize_source(casadi_ocp_block_str, inst);
1887  break;
1888  case AUX_TO_DOUBLE:
1889  this->auxiliaries << "#define casadi_to_double(x) "
1890  << "(" << (this->cpp ? "static_cast<double>(x)" : "(double) x") << ")\n\n";
1891  break;
1892  case AUX_TO_INT:
1893  this->auxiliaries << "#define casadi_to_int(x) "
1894  << "(" << (this->cpp ? "static_cast<casadi_int>(x)" : "(casadi_int) x")
1895  << ")\n\n";
1896  break;
1897  case AUX_CAST:
1898  this->auxiliaries << "#define CASADI_CAST(x,y) "
1899  << "(" << (this->cpp ? "static_cast<x>(y)" : "(x) y") << ")\n\n";
1900  break;
1901  case AUX_SQ:
1902  this->auxiliaries << sanitize_source(
1903  "// SYMBOL \"sq\"\n"
1904  "casadi_real casadi_sq(casadi_real x) { return x*x;}\n\n",
1905  inst);
1906  break;
1907  case AUX_SIGN:
1908  this->auxiliaries << sanitize_source(
1909  "// SYMBOL \"sign\"\n"
1910  "casadi_real casadi_sign(casadi_real x) "
1911  "{ return x<0 ? -1 : x>0 ? 1 : x;}\n\n",
1912  inst);
1913  break;
1914  case AUX_IF_ELSE:
1915  this->auxiliaries << sanitize_source(
1916  "// SYMBOL \"if_else\"\n"
1917  "casadi_real casadi_if_else"
1918  "(casadi_real c, casadi_real x, casadi_real y) "
1919  "{ return c!=0 ? x : y;}\n\n",
1920  inst);
1921  break;
1922  case AUX_PRINTF:
1923  this->auxiliaries << "#ifndef CASADI_PRINTF\n";
1924  if (this->mex) {
1925  this->auxiliaries << "#ifdef MATLAB_MEX_FILE\n"
1926  << " #define CASADI_PRINTF mexPrintf\n"
1927  << "#else\n"
1928  << " #define CASADI_PRINTF printf\n"
1929  << "#endif\n";
1930  } else {
1931  add_include("stdio.h");
1932  this->auxiliaries << "#define CASADI_PRINTF printf\n";
1933  this->auxiliaries << "#ifndef CASADI_SNPRINTF\n";
1934  this->auxiliaries << "#define CASADI_SNPRINTF snprintf\n";
1935  this->auxiliaries << "#endif\n\n";
1936  }
1937  this->auxiliaries << "#endif\n\n";
1938  break;
1939  case AUX_FMIN:
1940  this->auxiliaries << sanitize_source(
1941  "// SYMBOL \"fmin\"\n"
1942  "casadi_real casadi_fmin(casadi_real x, casadi_real y) {\n"
1943  "/* Pre-c99 compatibility */\n"
1944  "#if __STDC_VERSION__ < 199901L\n"
1945  " return x<y ? x : y;\n"
1946  "#else\n"
1947  " return fmin(x, y);\n"
1948  "#endif\n"
1949  "}\n\n",
1950  inst);
1951  break;
1952  case AUX_FMAX:
1953  this->auxiliaries << sanitize_source(
1954  "// SYMBOL \"fmax\"\n"
1955  "casadi_real casadi_fmax(casadi_real x, casadi_real y) {\n"
1956  "/* Pre-c99 compatibility */\n"
1957  "#if __STDC_VERSION__ < 199901L\n"
1958  " return x>y ? x : y;\n"
1959  "#else\n"
1960  " return fmax(x, y);\n"
1961  "#endif\n"
1962  "}\n\n",
1963  inst);
1964  break;
1965  case AUX_FABS:
1966  this->auxiliaries << sanitize_source(
1967  "// SYMBOL \"fabs\"\n"
1968  "casadi_real casadi_fabs(casadi_real x) {\n"
1969  "/* Pre-c99 compatibility */\n"
1970  "#if __STDC_VERSION__ < 199901L\n"
1971  " return x>0 ? x : -x;\n"
1972  "#else\n"
1973  " return fabs(x);\n"
1974  "#endif\n"
1975  "}\n\n",
1976  inst);
1977  break;
1978  case AUX_ISINF:
1979  this->auxiliaries << sanitize_source(
1980  "// SYMBOL \"isinf\"\n"
1981  "casadi_real casadi_isinf(casadi_real x) {\n"
1982  "/* Pre-c99 compatibility */\n"
1983  "#if __STDC_VERSION__ < 199901L\n"
1984  " return x== INFINITY || x==-INFINITY;\n"
1985  "#else\n"
1986  " return isinf(x);\n"
1987  "#endif\n"
1988  "}\n\n",
1989  inst);
1990  break;
1991  case AUX_ISFINITE:
1992  this->auxiliaries << sanitize_source(
1993  "// SYMBOL \"isfinite\"\n"
1994  "casadi_real casadi_isfinite(casadi_real x) {\n"
1995  "/* Pre-c99 compatibility */\n"
1996  "#if __STDC_VERSION__ < 199901L\n"
1997  " return x==x && x!=INFINITY && x!=-INFINITY;\n"
1998  "#else\n"
1999  " return isfinite(x);\n"
2000  "#endif\n"
2001  "}\n\n",
2002  inst);
2003  break;
2004  case AUX_MIN:
2005  this->auxiliaries << sanitize_source(
2006  "// SYMBOL \"min\"\n"
2007  "casadi_int casadi_min(casadi_int x, casadi_int y) {\n"
2008  " return x>y ? y : x;\n"
2009  "}\n\n",
2010  inst);
2011  break;
2012  case AUX_MAX:
2013  this->auxiliaries << sanitize_source(
2014  "// SYMBOL \"max\"\n"
2015  "casadi_int casadi_max(casadi_int x, casadi_int y) {\n"
2016  " return x>y ? x : y;\n"
2017  "}\n\n",
2018  inst);
2019  break;
2020  case AUX_MMIN:
2023  this->auxiliaries << sanitize_source(casadi_mmin_str, inst);
2024  break;
2025  case AUX_MMAX:
2028  this->auxiliaries << sanitize_source(casadi_mmax_str, inst);
2029  break;
2030  case AUX_INF:
2031  this->auxiliaries << "#ifndef casadi_inf\n"
2032  << " #define casadi_inf " << this->infinity << "\n"
2033  << "#endif\n\n";
2034  break;
2035  case AUX_NAN:
2036  this->auxiliaries << "#ifndef casadi_nan\n"
2037  << " #define casadi_nan " << this->nan << "\n"
2038  << "#endif\n\n";
2039  break;
2040  case AUX_REAL_MIN:
2041  this->auxiliaries << "#ifndef casadi_real_min\n"
2042  << " #define casadi_real_min " << this->real_min << "\n"
2043  << "#endif\n\n";
2044  break;
2045  case AUX_LOG1P:
2046  this->auxiliaries << sanitize_source(
2047  "// SYMBOL \"log1p\"\n"
2048  "casadi_real casadi_log1p(casadi_real x) {\n"
2049  "/* Pre-c99 compatibility */\n"
2050  "#if __STDC_VERSION__ < 199901L\n"
2051  " return log(1+x);\n"
2052  "#else\n"
2053  " return log1p(x);\n"
2054  "#endif\n"
2055  "}\n\n",
2056  inst);
2057  break;
2058  case AUX_EXPM1:
2059  this->auxiliaries << sanitize_source(
2060  "// SYMBOL \"expm1\"\n"
2061  "casadi_real casadi_expm1(casadi_real x) {\n"
2062  "/* Pre-c99 compatibility */\n"
2063  "#if __STDC_VERSION__ < 199901L\n"
2064  " return exp(x)-1;\n"
2065  "#else\n"
2066  " return expm1(x);\n"
2067  "#endif\n"
2068  "}\n\n",
2069  inst);
2070  break;
2071  case AUX_HYPOT:
2072  this->auxiliaries << sanitize_source(
2073  "// SYMBOL \"hypot\"\n"
2074  "casadi_real casadi_hypot(casadi_real x, casadi_real y) {\n"
2075  "/* Pre-c99 compatibility */\n"
2076  "#if __STDC_VERSION__ < 199901L\n"
2077  " return sqrt(x*x+y*y);\n"
2078  "#else\n"
2079  " return hypot(x, y);\n"
2080  "#endif\n"
2081  "}\n\n",
2082  inst);
2083  break;
2084  case AUX_BLAZING_COMMON:
2086  add_include("simde/x86/avx2.h");
2087  add_include("simde/x86/fma.h");
2088  this->auxiliaries << sanitize_source(casadi_blazing_common_str, inst);
2089  break;
2092  this->auxiliaries << sanitize_source(casadi_blazing_1d_boor_eval_str, inst);
2093  break;
2096  this->auxiliaries << sanitize_source(casadi_blazing_2d_boor_eval_str, inst);
2097  break;
2100  this->auxiliaries << sanitize_source(casadi_blazing_3d_boor_eval_str, inst);
2101  break;
2104  this->auxiliaries << sanitize_source(casadi_blazing_4d_boor_eval_str, inst);
2105  break;
2108  this->auxiliaries << sanitize_source(casadi_blazing_5d_boor_eval_str, inst);
2109  break;
2110  case AUX_PRINTME:
2112  this->auxiliaries << sanitize_source(casadi_printme_str, inst);
2113  break;
2114  case AUX_PRINT_SCALAR:
2116  this->auxiliaries << sanitize_source(casadi_print_scalar_str, inst);
2117  break;
2118  case AUX_PRINT_VECTOR:
2120  this->auxiliaries << sanitize_source(casadi_print_vector_str, inst);
2121  break;
2122  case AUX_PRINT_CANONICAL:
2124  this->auxiliaries << sanitize_source(casadi_print_canonical_str, inst);
2125  break;
2126  case AUX_FPRINTF_SCALAR:
2127  add_include("stdio.h");
2129  this->auxiliaries << sanitize_source(casadi_fprintf_scalar_str, inst);
2130  break;
2131  case AUX_FPRINTF_VECTOR:
2133  this->auxiliaries << sanitize_source(casadi_fprintf_vector_str, inst);
2134  break;
2135  case AUX_TO_FILE:
2136  add_include("stdio.h");
2138  this->auxiliaries << sanitize_source(casadi_to_file_str, inst);
2139  break;
2140  case AUX_THREADS:
2141  this->auxiliaries << sanitize_source(casadi_threads_str, inst);
2142  break;
2143  }
2144  }
2145 
2146  std::string CodeGenerator::to_mex(const Sparsity& sp, const std::string& arg) {
2148  std::stringstream s;
2149  s << "casadi_to_mex(" << sparsity(sp) << ", " << arg << ");";
2150  return s.str();
2151  }
2152 
2153  std::string CodeGenerator::from_mex(std::string& arg,
2154  const std::string& res, std::size_t res_off,
2155  const Sparsity& sp_res, const std::string& w) {
2156  // Handle offset with recursion
2157  if (res_off!=0) return from_mex(arg, res+"+"+str(res_off), 0, sp_res, w);
2158 
2160  std::stringstream s;
2161  s << "casadi_from_mex(" << arg
2162  << ", " << res << ", " << sparsity(sp_res) << ", " << w << ");";
2163  return s.str();
2164  }
2165 
2166  std::string CodeGenerator::fmu_helpers(const std::string& modelname) {
2167  // Process C++ source
2168  std::stringstream ret;
2169  std::string line;
2170  std::istringstream stream(casadi_fmu_str);
2171  while (std::getline(stream, line)) {
2172  // Replacements
2173  if (line.find("MODELNAME") != std::string::npos) {
2174  line = replace(line, "MODELNAME", modelname);
2175  }
2176  // Append to return
2177  ret << line << "\n";
2178  }
2179  return ret.str();
2180  }
2181 
2182  std::string CodeGenerator::constant(const std::string& v) {
2183  std::string ret = v;
2184  ret = replace(ret, "\\", "\\\\");
2185  ret = replace(ret, "\"", "\\\"");
2186  return "\"" + ret + "\"";
2187  }
2188 
2189  std::string CodeGenerator::constant(casadi_int v) {
2190  return str(v);
2191  }
2192 
2193  std::string CodeGenerator::constant(char v) {
2194  return constant(static_cast<casadi_int>(v));
2195  }
2196  std::string CodeGenerator::constant(double v) {
2197  std::stringstream s;
2198  if (isnan(v)) {
2200  s << "casadi_nan";
2201  } else if (isinf(v)) {
2203  if (v<0) s << "-";
2204  s << "casadi_inf";
2205  } else {
2206  casadi_int v_int = static_cast<casadi_int>(v);
2207  if (static_cast<double>(v_int)==v) {
2208  // Print integer
2209  s << v_int << ".";
2210  } else {
2211  // Print real
2212  std::ios_base::fmtflags fmtfl = s.flags(); // get current format flags
2213  s << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1) << v;
2214  s.flags(fmtfl); // reset current format flags
2215  }
2216  }
2217  return s.str();
2218  }
2219 
2220  std::string CodeGenerator::copy(const std::string& arg,
2221  std::size_t n, const std::string& res) {
2222  std::stringstream s;
2223  // Perform operation
2225  s << "casadi_copy(" << arg << ", " << n << ", " << res << ");";
2226  return s.str();
2227  }
2228 
2229  bool CodeGenerator::elide_copy(casadi_int sz) {
2230  if (casadi::GlobalOptions::copy_elision_min_size==-1) return false;
2232  }
2233 
2234  void CodeGenerator::copy_check(const std::string& arg, size_t n, const std::string& res,
2235  bool check_lhs, bool check_rhs) {
2236  std::vector<std::string> checks;
2237  if (check_lhs) checks.push_back(arg);
2238  if (check_rhs) checks.push_back(res);
2239  if (!checks.empty()) *this << "if (" << join(checks, " && ") << ") ";
2240  *this << copy(arg, n, res) << "\n";
2241  }
2242 
2243  void CodeGenerator::copy_default(const std::string& arg, size_t n, const std::string& res,
2244  const std::string& def, bool check_rhs) {
2245  *this << "if (" << arg << ") {\n";
2246  if (check_rhs) *this << "if (" << res << ") ";
2247  *this << copy(arg, n, res) << "\n";
2248  *this << "} else {\n";
2249  if (check_rhs) *this << "if (" << res << ") ";
2250  *this << fill(res, n, def) << "\n";
2251  *this << "}\n";
2252  }
2253 
2254  std::string CodeGenerator::clear(const std::string& res, std::size_t n) {
2255  std::stringstream s;
2256  // Perform operation
2258  s << "casadi_clear(" << res << ", " << n << ");";
2259  return s.str();
2260  }
2261 
2262  std::string CodeGenerator::arg(casadi_int i) const {
2263  return "arg[" + str(i) + "]";
2264  }
2265 
2266  std::string CodeGenerator::res(casadi_int i) const {
2267  return "res[" + str(i) + "]";
2268  }
2269 
2270  std::string CodeGenerator::mem(const Function& f) {
2271  std::string name = f->codegen_name(*this, false);
2272  std::string mem_array = shorthand(name + "_mem");
2273  return mem_array+"[mem]";
2274  }
2275 
2276  std::string CodeGenerator::fill(const std::string& res,
2277  std::size_t n, const std::string& v) {
2278  if (v=="0") return clear(res, n);
2279  std::stringstream s;
2280  // Perform operation
2282  s << "casadi_fill(" << res << ", " << n << ", " << v << ");";
2283  return s.str();
2284  }
2285 
2286  std::string CodeGenerator::dot(casadi_int n, const std::string& x,
2287  const std::string& y) {
2289  std::stringstream s;
2290  s << "casadi_dot(" << n << ", " << x << ", " << y << ")";
2291  return s.str();
2292  }
2293 
2294  std::string CodeGenerator::bilin(const std::string& A, const Sparsity& sp_A,
2295  const std::string& x, const std::string& y) {
2297  std::stringstream s;
2298  s << "casadi_bilin(" << A << ", " << sparsity(sp_A) << ", " << x << ", " << y << ")";
2299  return s.str();
2300  }
2301 
2302  std::string CodeGenerator::rank1(const std::string& A, const Sparsity& sp_A,
2303  const std::string& alpha, const std::string& x,
2304  const std::string& y) {
2306  std::stringstream s;
2307  s << "casadi_rank1(" << A << ", " << sparsity(sp_A) << ", "
2308  << alpha << ", " << x << ", " << y << ");";
2309  return s.str();
2310  }
2311 
2313  const std::string& res, casadi_int ndim, const std::string& grid,
2314  const std::string& offset,
2315  const std::string& values, const std::string& x,
2316  const std::string& lookup_mode, casadi_int m,
2317  const std::string& iw, const std::string& w) {
2319  std::stringstream s;
2320  s << "casadi_interpn(" << res << ", " << ndim << ", " << grid << ", " << offset << ", "
2321  << values << ", " << x << ", " << lookup_mode << ", " << m << ", " << iw << ", " << w << ");";
2322  return s.str();
2323  }
2324 
2325  std::string CodeGenerator::interpn_grad(const std::string& grad,
2326  casadi_int ndim, const std::string& grid, const std::string& offset,
2327  const std::string& values, const std::string& x,
2328  const std::string& lookup_mode, casadi_int m,
2329  const std::string& iw, const std::string& w) {
2331  std::stringstream s;
2332  s << "casadi_interpn_grad(" << grad << ", " << ndim << ", " << grid << ", " << offset << ", "
2333  << values << ", " << x << ", " << lookup_mode << "," << m << ", " << iw << ", " << w << ");";
2334  return s.str();
2335  }
2336 
2337  std::string CodeGenerator::trans(const std::string& x, const Sparsity& sp_x,
2338  const std::string& y, const Sparsity& sp_y,
2339  const std::string& iw) {
2341  return "casadi_trans(" + x + "," + sparsity(sp_x) + ", "
2342  + y + ", " + sparsity(sp_y) + ", " + iw + ")";
2343  }
2344 
2345  std::string CodeGenerator::declare(std::string s) {
2346  // Add c linkage
2347  std::string cpp_prefix = this->cpp ? "extern \"C\" " : "";
2348 
2349  // To header file
2350  if (this->with_header) {
2351  this->header << cpp_prefix << this->dll_import << s << ";\n";
2352  }
2353 
2354  // Return name with declarations
2355  return cpp_prefix + this->dll_export + s;
2356  }
2357 
2358  std::string
2359  CodeGenerator::project(const std::string& arg, const Sparsity& sp_arg,
2360  const std::string& res, const Sparsity& sp_res,
2361  const std::string& w) {
2362  // If sparsity match, simple copy
2363  if (sp_arg==sp_res) return copy(arg, sp_arg.nnz(), res);
2364 
2365  // Create call
2367  std::stringstream s;
2368  s << "casadi_project(" << arg << ", " << sparsity(sp_arg) << ", " << res << ", "
2369  << sparsity(sp_res) << ", " << w << ");";
2370  return s.str();
2371  }
2372 
2373  std::string
2374  CodeGenerator::tri_project(const std::string& arg, const Sparsity& sp_arg,
2375  const std::string& res, bool lower) {
2376  // Create call
2378  std::stringstream s;
2379  s << "casadi_tri_project(" << arg << ", " << sparsity(sp_arg) << ", ";
2380  s << res << ", " << (lower ? 1: 0) << ");";
2381  return s.str();
2382  }
2383 
2384  std::string
2385  CodeGenerator::densify(const std::string& arg, const Sparsity& sp_arg,
2386  const std::string& res, bool tr) {
2387  // Create call
2389  std::stringstream s;
2390  s << "casadi_densify(" << arg << ", " << sparsity(sp_arg) << ", " << res << ", "
2391  << (tr ? 1 : 0) << ");";
2392  return s.str();
2393  }
2394 
2395  std::string
2396  CodeGenerator::sparsify(const std::string& arg, const std::string& res,
2397  const Sparsity& sp_res, bool tr) {
2398  // Create call
2400  std::stringstream s;
2401  s << "casadi_sparsify(" << arg << ", " << res << ", "
2402  << sparsity(sp_res) << ", " << (tr ? 1 : 0) << ");";
2403  return s.str();
2404  }
2405 
2406  std::string CodeGenerator::printf(const std::string& str, const std::vector<std::string>& arg) {
2408  std::stringstream s;
2409  s << "CASADI_PRINTF(";
2410  // Loop over lines in str
2411  std::string::size_type pos = 0, prev = 0;
2412  while ((pos = str.find('\n', prev)) != std::string::npos) {
2413  // Any line containing a trailing new line
2414  s << "\"" << str.substr(prev, pos-prev) << "\\n\"\n";
2415  prev = pos + 1;
2416  }
2417  // Remainder without trailing new line
2418  s << "\"" << str.substr(prev) << "\"";
2419  for (casadi_int i=0; i<arg.size(); ++i) s << ", " << arg[i];
2420  s << ");";
2421  return s.str();
2422  }
2423 
2424  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1) {
2425  std::vector<std::string> arg;
2426  arg.push_back(arg1);
2427  return printf(str, arg);
2428  }
2429 
2430  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1,
2431  const std::string& arg2) {
2432  std::vector<std::string> arg;
2433  arg.push_back(arg1);
2434  arg.push_back(arg2);
2435  return printf(str, arg);
2436  }
2437 
2438  std::string CodeGenerator::printf(const std::string& str, const std::string& arg1,
2439  const std::string& arg2, const std::string& arg3) {
2440  std::vector<std::string> arg;
2441  arg.push_back(arg1);
2442  arg.push_back(arg2);
2443  arg.push_back(arg3);
2444  return printf(str, arg);
2445  }
2446 
2447  std::string CodeGenerator::axpy(casadi_int n, const std::string& a,
2448  const std::string& x, const std::string& y) {
2450  return "casadi_axpy(" + str(n) + ", " + a + ", " + x + ", " + y + ");";
2451  }
2452 
2453  std::string CodeGenerator::clip_min(const std::string& x, casadi_int n,
2454  const std::string& min, const std::string& mask) {
2456  return "casadi_clip_min(" + x + ", " + str(n) + ", " + min + ", " + mask + ");";
2457  }
2458 
2459  std::string CodeGenerator::clip_max(const std::string& x, casadi_int n,
2460  const std::string& min, const std::string& mask) {
2462  return "casadi_clip_max(" + x + ", " + str(n) + ", " + min + ", " + mask + ");";
2463  }
2464 
2465  std::string CodeGenerator::vector_fmax(casadi_int n, const std::string& x,
2466  const std::string& y, const std::string& z) {
2468  return "casadi_vector_fmax(" + str(n) + ", " + x + ", " + y + ", " + z + ");";
2469  }
2470 
2471  std::string CodeGenerator::vector_fmin(casadi_int n, const std::string& x,
2472  const std::string& y, const std::string& z) {
2474  return "casadi_vector_fmin(" + str(n) + ", " + x + ", " + y + ", " + z + ");";
2475  }
2476 
2477  std::string CodeGenerator::masked_norm_inf(casadi_int n, const std::string& x,
2478  const std::string& mask) {
2480  return "casadi_masked_norm_inf(" + str(n) + ", " + x + ", " + mask + ")";
2481  }
2482 
2483  std::string CodeGenerator::scal(casadi_int n, const std::string& alpha, const std::string& x) {
2485  return "casadi_scal(" + str(n) + ", " + alpha + ", " + x + ");";
2486  }
2487 
2488  std::string CodeGenerator::mv(const std::string& x, const Sparsity& sp_x,
2489  const std::string& y, const std::string& z, bool tr) {
2491  return "casadi_mv(" + x + ", " + sparsity(sp_x) + ", " + y + ", "
2492  + z + ", " + (tr ? "1" : "0") + ");";
2493  }
2494 
2495  std::string CodeGenerator::mv(const std::string& x, casadi_int nrow_x, casadi_int ncol_x,
2496  const std::string& y, const std::string& z, bool tr) {
2498  return "casadi_mv_dense(" + x + ", " + str(nrow_x) + ", " + str(ncol_x) + ", "
2499  + y + ", " + z + ", " + (tr ? "1" : "0") + ");";
2500  }
2501 
2502  std::string CodeGenerator::mtimes(const std::string& x, const Sparsity& sp_x,
2503  const std::string& y, const Sparsity& sp_y,
2504  const std::string& z, const Sparsity& sp_z,
2505  const std::string& w, bool tr) {
2507  return "casadi_mtimes(" + x + ", " + sparsity(sp_x) + ", " + y + ", " + sparsity(sp_y) + ", "
2508  + z + ", " + sparsity(sp_z) + ", " + w + ", " + (tr ? "1" : "0") + ");";
2509  }
2510 
2511  std::string CodeGenerator::mtimes(const std::string& x, casadi_int nrow_x, casadi_int ncol_x,
2512  const std::string& y, casadi_int ncol_y,
2513  const std::string& z, bool tr) {
2515  return "casadi_mtimes_dense(" + x + ", " + str(nrow_x) + ", " + str(ncol_x) + ", "
2516  + y + ", " + str(ncol_y) + ", " + z + ", " + (tr ? "1" : "0") + ");";
2517  }
2518 
2519  std::string CodeGenerator::mtimes_dense_sparse(const std::string& x, casadi_int nrow_x,
2520  const std::string& y, const Sparsity& sp_y, const std::string& z) {
2522  return "casadi_mtimes_dense_sparse(" + x + ", " + str(nrow_x) + ", "
2523  + y + ", " + sparsity(sp_y) + ", " + z + ");";
2524  }
2525 
2526  std::string CodeGenerator::trilsolve(const Sparsity& sp_x, const std::string& x,
2527  const std::string& y, bool tr, bool unity, casadi_int nrhs) {
2529  return "casadi_trilsolve(" + sparsity(sp_x) + ", " + x + ", " + y + ", " + str(tr) + ", "
2530  + str(unity) + ", " + str(nrhs) + ");";
2531  }
2532 
2533  std::string CodeGenerator::triusolve(const Sparsity& sp_x, const std::string& x,
2534  const std::string& y, bool tr, bool unity, casadi_int nrhs) {
2536  return "casadi_triusolve(" + sparsity(sp_x) + ", " + x + ", " + y + ", " + str(tr) + ", "
2537  + str(unity) + ", " + str(nrhs) + ");";
2538  }
2539 
2540 
2541  std::string CodeGenerator::logsumexp(const std::string& A, casadi_int n) {
2543  std::stringstream s;
2544  s << "casadi_logsumexp(" << A << ", " << n << ");";
2545  return s.str();
2546  }
2547 
2548  void CodeGenerator::print_formatted(const std::string& s) {
2549  // Quick return if empty
2550  if (s.empty()) return;
2551 
2552  // If new line, add indentation
2553  if (newline_) {
2554  casadi_int shift = s.front()=='}' ? -1 : 0;
2555  casadi_assert_dev(current_indent_+shift>=0);
2556  this->buffer << std::string(indent_*(current_indent_+shift), ' ');
2557  newline_ = false;
2558  }
2559 
2560  // Print to body
2561  this->buffer << s;
2562 
2563  // Brackets change indentation for next row
2564  // NOTE(@jaeandersson): Should ignore strings, comments
2565  for (char c : s) {
2566  if (c=='{') {
2567  indent();
2568  } else if (c=='}') {
2569  unindent();
2570  }
2571  }
2572  }
2573 
2574  CodeGenerator& CodeGenerator::operator<<(const std::string& s) {
2575  // Loop over newline characters
2576  size_t off=0;
2577  while (true) {
2578  size_t pos = s.find('\n', off);
2579  if (pos==std::string::npos) {
2580  // No more newline characters
2581  print_formatted(s.substr(off));
2582  break;
2583  } else {
2584  // Ends with newline
2585  print_formatted(s.substr(off, pos-off));
2586  this->buffer << '\n';
2587  newline_ = true;
2588  off = pos+1;
2589  }
2590  }
2591 
2592  return *this;
2593  }
2594 
2595  void CodeGenerator::flush(std::ostream &s) {
2596  s << this->buffer.str();
2597  this->buffer.str(std::string());
2598  }
2599 
2600  void CodeGenerator::local(const std::string& name, const std::string& type,
2601  const std::string& ref) {
2602  // Check if the variable already exists
2603  auto it = local_variables_.find(name);
2604  if (it==local_variables_.end()) {
2605  // Add it
2606  local_variables_[name] = std::make_pair(type, ref);
2607  } else {
2608  // Consistency check
2609  casadi_assert(it->second.first==type, "Type mismatch for " + name);
2610  casadi_assert(it->second.second==ref, "Type mismatch for " + name);
2611  }
2612  }
2613 
2614  std::string CodeGenerator::sx_work(casadi_int i) {
2615  if (avoid_stack_) {
2616  return "w[" + str(i) + "]";
2617  } else {
2618  std::string name = "a"+format_padded(i);
2619 
2620  // Make sure work vector element has been declared
2621  local(name, "casadi_real");
2622 
2623  return name;
2624  }
2625  }
2626 
2627  void CodeGenerator::init_local(const std::string& name, const std::string& def) {
2628  auto it = local_default_.find(name);
2629  if (it!=local_default_.end()) {
2630  casadi_assert(it->second==def, "Initial value mismatch for " + name);
2631  }
2632  local_default_.insert(std::make_pair(name, def));
2633  }
2634 
2635  // Read the next double-quoted token from line, starting at pos.
2636  // Backslash escapes the next character, so \" and \\ may appear inside.
2637  // On return, pos points just past the closing quote.
2638  static std::string next_quoted_token(const std::string& line, size_t& pos) {
2639  size_t n1 = line.find('"', pos);
2640  casadi_assert(n1 != std::string::npos, "Missing quoted token in: " + line);
2641  std::string r;
2642  size_t i = n1 + 1;
2643  for (; i < line.size(); ++i) {
2644  if (line[i] == '\\' && i + 1 < line.size()) {
2645  r += line[++i];
2646  } else if (line[i] == '"') {
2647  break;
2648  } else {
2649  r += line[i];
2650  }
2651  }
2652  casadi_assert(i < line.size(), "Unterminated quoted token in: " + line);
2653  pos = i + 1;
2654  return r;
2655  }
2656 
2657  std::string CodeGenerator::
2658  sanitize_source(const std::string& src,
2659  const std::vector<std::string>& inst, bool add_shorthand) {
2660  // Create suffix if templates type are not all "casadi_real"
2661  std::string suffix;
2662  for (const std::string& s : inst) {
2663  if (s!="casadi_real") {
2664  for (const std::string& s : inst) suffix += "_" + s;
2665  break;
2666  }
2667  }
2668 
2669  // Construct map of name replacements
2670  std::vector<std::pair<std::string, std::string> > rep;
2671  for (casadi_int i=0; i<inst.size(); ++i) {
2672  rep.push_back(std::make_pair("T" + str(i+1), inst[i]));
2673  }
2674 
2675  // Return object
2676  std::stringstream ret;
2677  // Process C++ source
2678  std::string line;
2679  std::istringstream stream(src);
2680 
2681  bool filter_macros = true; // Macro definitions are ignored
2682 
2683  // Set by `// SYMBOL "X"` to "casadi_X"; cleared when the matching
2684  // function signature is found and the prefix is prepended.
2685  std::string active_symbol;
2686 
2687  while (std::getline(stream, line)) {
2688  size_t n1, n2;
2689 
2690  // C++ template declarations are ignored
2691  if (line.find("template")==0) continue;
2692 
2693  // Macro definitions are ignored
2694  if (filter_macros && line.find("#define")==0) continue;
2695  if (filter_macros && line.find("#undef")==0) continue;
2696 
2697  // casadi_assert and error are ignored
2698  if (line.find("casadi_assert") != std::string::npos) continue;
2699  if (line.find("casadi_error") != std::string::npos) continue;
2700  if (line.find("casadi_message") != std::string::npos) continue;
2701 
2702  // Inline declaration
2703  if (line == "inline") continue;
2704 
2705  // If line starts with "// SYMBOL", add shorthand and track the symbol
2706  if (line.find("// SYMBOL") != std::string::npos) {
2707  n1 = line.find("\"");
2708  n2 = line.find("\"", n1+1);
2709  std::string sym = line.substr(n1+1, n2-n1-1);
2710  if (add_shorthand) shorthand(sym + suffix);
2711  if (!suffix.empty()) {
2712  rep.push_back(std::make_pair(sym, sym + suffix));
2713  }
2714  active_symbol = "casadi_" + sym;
2715  continue;
2716  }
2717 
2718  // If line starts with "// C-REPLACE", add to list of replacements
2719  if (line.find("// C-REPLACE") != std::string::npos) {
2720  // Get C++ string, then C string; \" and \\ are unescaped
2721  size_t pos = line.find("// C-REPLACE");
2722  std::string key = next_quoted_token(line, pos);
2723  std::string sub = next_quoted_token(line, pos);
2724  // Add to replacements
2725  rep.push_back(std::make_pair(key, sub));
2726  continue;
2727  }
2728 
2729  // If line starts with "// C-VERBOSE", skip the next line
2730  if (!verbose_runtime && line.find("// C-VERBOSE") != std::string::npos) {
2731  // Ignore next line
2732  std::getline(stream, line);
2733  continue;
2734  }
2735 
2736  if (line.find("// FILTER-MACROS ON") != std::string::npos) {
2737  filter_macros = true;
2738  }
2739 
2740  if (line.find("// FILTER-MACROS OFF") != std::string::npos) {
2741  filter_macros = false;
2742  }
2743 
2744  // Ignore other C++ style comment
2745  n1 = line.find("//");
2746  if (n1 != std::string::npos) line.erase(n1);
2747 
2748  // Remove trailing spaces
2749  n1 = line.find_last_not_of(' ');
2750  if (n1 != std::string::npos) {
2751  line.erase(n1 + 1);
2752  } else {
2753  continue;
2754  }
2755 
2756  // Prepend storage-class/inline-hint to the symbol's signature line
2757  if (!active_symbol.empty() &&
2758  line.find(active_symbol + "(") != std::string::npos) {
2759  std::string sig_prefix;
2760  if (this->static_aux) sig_prefix += "static ";
2761  if (this->inline_aux) sig_prefix += "inline ";
2762  if (!sig_prefix.empty()) line = sig_prefix + line;
2763  active_symbol.clear();
2764  }
2765 
2766  // Perform string replacements
2767  for (auto&& it = rep.rbegin(); it!=rep.rend(); ++it) {
2768  line = replace(line, it->first, it->second);
2769  }
2770 
2771  // Append to return
2772  ret << line << "\n";
2773  }
2774 
2775  // Trailing newline
2776  ret << "\n";
2777  return ret.str();
2778  }
2779 
2780  void CodeGenerator::comment(const std::string& s) {
2781  if (verbose) {
2782  *this << "/* " << s << " */\n";
2783  }
2784  }
2785 
2787  add_io_sparsities(const std::string& name,
2788  const std::vector<Sparsity>& sp_in,
2789  const std::vector<Sparsity>& sp_out) {
2790  // Insert element, quick return if it already exists
2791  if (!sparsity_meta.insert(name).second) return;
2792 
2793  // Input sparsities
2794  *this << declare("const casadi_int* " + name + "_sparsity_in(casadi_int i)") << " {\n"
2795  << "switch (i) {\n";
2796  for (casadi_int i=0; i<sp_in.size(); ++i) {
2797  *this << "case " << i << ": return " << sparsity(sp_in[i], force_canonical) << ";\n";
2798  }
2799  *this << "default: return 0;\n}\n"
2800  << "}\n\n";
2801 
2802  // Output sparsities
2803  *this << declare("const casadi_int* " + name + "_sparsity_out(casadi_int i)") << " {\n"
2804  << "switch (i) {\n";
2805  for (casadi_int i=0; i<sp_out.size(); ++i) {
2806  *this << "case " << i << ": return " << sparsity(sp_out[i], force_canonical) << ";\n";
2807  }
2808  *this << "default: return 0;\n}\n"
2809  << "}\n\n";
2810  }
2811 
2812  std::string CodeGenerator::
2813  qr(const std::string& sp, const std::string& A, const std::string& w,
2814  const std::string& sp_v, const std::string& v, const std::string& sp_r,
2815  const std::string& r, const std::string& beta, const std::string& prinv,
2816  const std::string& pc) {
2818  return "casadi_qr(" + sp + ", " + A + ", " + w + ", "
2819  + sp_v + ", " + v + ", " + sp_r + ", " + r + ", "
2820  + beta + ", " + prinv + ", " + pc + ");";
2821  }
2822 
2823  std::string CodeGenerator::
2824  det(const std::string& sp_v, const std::string& v,
2825  const std::string& sp_r, const std::string& r, const std::string& beta) {
2827  return "casadi_det(" + sp_v + ", " + v + ", " + sp_r + ", " + r + ", " + beta + ")";
2828  }
2829 
2830  std::string CodeGenerator::
2831  qr_solve(const std::string& x, casadi_int nrhs, bool tr,
2832  const std::string& sp_v, const std::string& v,
2833  const std::string& sp_r, const std::string& r,
2834  const std::string& beta, const std::string& prinv,
2835  const std::string& pc, const std::string& w) {
2837  return "casadi_qr_solve(" + x + ", " + str(nrhs) + ", " + (tr ? "1" : "0") + ", "
2838  + sp_v + ", " + v + ", " + sp_r + ", " + r + ", "
2839  + beta + ", " + prinv + ", " + pc + ", " + w + ");";
2840  }
2841 
2842  std::string CodeGenerator::
2843  lsqr_solve(const std::string& A, const std::string&x,
2844  casadi_int nrhs, bool tr, const std::string& sp, const std::string& w) {
2846  return "casadi_lsqr_solve(" + A + ", " + x + ", " + str(nrhs) + ", "
2847  + (tr ? "1" : "0") + ", " + sp + ", " + w + ");";
2848  }
2849 
2850  std::string CodeGenerator::
2851  ldl(const std::string& sp_a, const std::string& a,
2852  const std::string& sp_lt, const std::string& lt, const std::string& d,
2853  const std::string& p, const std::string& w) {
2855  return "casadi_ldl(" + sp_a + ", " + a + ", " + sp_lt + ", " + lt + ", "
2856  + d + ", " + p + ", " + w + ");";
2857  }
2858 
2859  std::string CodeGenerator::
2860  ldl_solve(const std::string& x, casadi_int nrhs,
2861  const std::string& sp_lt, const std::string& lt, const std::string& d,
2862  const std::string& p, const std::string& w) {
2864  return "casadi_ldl_solve(" + x + ", " + str(nrhs) + ", " + sp_lt + ", "
2865  + lt + ", " + d + ", " + p + ", " + w + ");";
2866  }
2867 
2868  std::string CodeGenerator::
2869  fmax(const std::string& x, const std::string& y) {
2871  return "casadi_fmax(" + x + ", " + y + ");";
2872  }
2873 
2874  std::string CodeGenerator::
2875  fmin(const std::string& x, const std::string& y) {
2877  return "casadi_fmin(" + x + ", " + y + ");";
2878  }
2879 
2880  std::string CodeGenerator::
2881  vfmax(const std::string& x, casadi_int n, const std::string& y) {
2883  return "casadi_vfmax(" + x + ", " + str(n) + ", " + y + ");";
2884  }
2885 
2886  std::string CodeGenerator::
2887  vfmin(const std::string& x, casadi_int n, const std::string& y) {
2889  return "casadi_vfmin(" + x + ", " + str(n) + ", " + y + ");";
2890  }
2891 
2892  std::string CodeGenerator::
2893  vfmax(const std::string& x, const std::string& n, const std::string& y) {
2895  return "casadi_vfmax(" + x + ", " + n + ", " + y + ");";
2896  }
2897 
2898  std::string CodeGenerator::
2899  vfmin(const std::string& x, const std::string& n, const std::string& y) {
2901  return "casadi_vfmin(" + x + ", " + n + ", " + y + ");";
2902  }
2903 
2904  std::string CodeGenerator::
2905  max(const std::string& x, const std::string& y) {
2907  return "casadi_max(" + x + ", " + y + ")";
2908  }
2909 
2910  std::string CodeGenerator::
2911  min(const std::string& x, const std::string& y) {
2913  return "casadi_min(" + x + ", " + y + ")";
2914  }
2915 
2916  std::string CodeGenerator::
2917  mmax(const std::string& x, casadi_int n, bool is_dense) {
2919  return "casadi_mmax(" + x + ", " + str(n) + ", " + str(casadi_int(is_dense)) + ")";
2920  }
2921 
2922  std::string CodeGenerator::
2923  mmin(const std::string& x, casadi_int n, bool is_dense) {
2925  return "casadi_mmin(" + x + ", " + str(n) + ", " + str(casadi_int(is_dense)) + ")";
2926  }
2927 
2928  std::string CodeGenerator::
2929  max_viol(casadi_int n, const std::string& x, const std::string& lb, const std::string& ub) {
2931  return "casadi_max_viol(" + str(n) + ", " + x+ ", " + lb + ", " + ub + ")";
2932  }
2933 
2934  std::string CodeGenerator::
2935  sum_viol(casadi_int n, const std::string& x, const std::string& lb, const std::string& ub) {
2937  return "casadi_sum_viol(" + str(n) + ", " + x+ ", " + lb + ", " + ub + ")";
2938  }
2939 
2940  std::string CodeGenerator::
2941  norm_inf(casadi_int n, const std::string& x) {
2943  return "casadi_norm_inf(" + str(n) + ", " + x + ")";
2944  }
2945 
2946  std::string CodeGenerator::
2947  norm_1(casadi_int n, const std::string& x) {
2949  return "casadi_norm_1(" + str(n) + ", " + x + ")";
2950  }
2951 
2952  std::string CodeGenerator::
2953  norm_2(casadi_int n, const std::string& x) {
2955  return "casadi_norm_2(" + str(n) + ", " + x + ")";
2956  }
2957 
2958  std::string CodeGenerator::
2959  lb_eig(const Sparsity& sp_h, const std::string& h) {
2961  return "casadi_lb_eig(" + sparsity(sp_h) + ", " + h + ")";
2962  }
2963 
2964  std::string CodeGenerator::
2965  regularize(const Sparsity& sp_h, const std::string& h, const std::string& reg) {
2967  return "casadi_regularize(" + sparsity(sp_h) + ", " + h + ", " + reg + ");";
2968  }
2969 
2970  std::string CodeGenerator::
2972  const std::string& Hin, const std::string& Hout, const std::string& iw, const std::string& w) {
2974  return Convexify::generate(*this, d, Hin, Hout, iw, w);
2975  }
2976 
2977  std::string CodeGenerator::
2978  low(const std::string& x, const std::string& grid, casadi_int ng, casadi_int lookup_mode) {
2980  return "casadi_low(" + x + ", " + grid + ", " + str(ng) + ", " + str(lookup_mode) + ");";
2981  }
2982 
2983  std::string CodeGenerator::
2984  bound_consistency(casadi_int n, const std::string& x,
2985  const std::string& lam, const std::string& lbx, const std::string& ubx) {
2987  return "casadi_bound_consistency(" + str(n) + ", " + x + ", " + lam +
2988  ", " + lbx + ", " + ubx + ")";
2989  }
2990 
2991  std::string CodeGenerator::
2992  file_slurp(const std::string& fname, casadi_int n, const std::string& a) {
2994  return "casadi_file_slurp(\"" + fname + "\", " + str(n) + ", " + a + ")";
2995  }
2996 
2997  std::string CodeGenerator::
2998  to_file(const std::string& f, const Sparsity& sp, const std::string& x) {
3000  return "casadi_to_file(" + f + ", " + sparsity(sp) + ", " + x + ")";
3001  }
3002 
3004  generate_dump(const Function& f, const std::string& arr, bool is_input) {
3005  casadi_int n = is_input ? f.n_in() : f.n_out();
3006  std::string dump_format = f->dump_format_.empty() ? "mtx" : f->dump_format_;
3007  std::string effective_dir = dump_dir_prefix + f->dump_dir_ + dump_dir_suffix;
3008  std::string prefix;
3009  if (!effective_dir.empty()) prefix = effective_dir + "/";
3010  std::string inout = is_input ? "in" : "out";
3011 
3012  // Ensure directory exists at codegen time
3013  if (!effective_dir.empty() && Filesystem::is_enabled()) {
3014  std::string dir = Filesystem::ensure_trailing_slash(effective_dir);
3015  casadi_assert(Filesystem::ensure_directory_exists(dir),
3016  "Unable to create the required directory for '" + dir + "'.");
3017  }
3018 
3019  // Assumes dump_id_local is declared in the enclosing scope
3020  // Per-input/output format files (e.g. .mtx)
3021  for (casadi_int i = 0; i < n; ++i) {
3022  std::string io_name = is_input ? f.name_in(i) : f.name_out(i);
3023  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3024  std::string fixed_part = prefix + f.name() + "." + inout + "." + io_name + "." + dump_format;
3025  casadi_int buf_size = fixed_part.size() + 1 + 6 + 1; // +7 for the counter field
3026  *this << "{\n";
3027  *this << "char dump_fname[" << buf_size << "];\n";
3028  *this << "FILE* dump_file;\n";
3029  *this << "snprintf(dump_fname, " << buf_size << ", \""
3030  << prefix << f.name() << ".%06d." << inout << "." << io_name
3031  << "." << dump_format << "\", dump_id_local);\n";
3032  if (f->verbose_) {
3033  *this << printf("dump -> %s\\n", "dump_fname") << "\n";
3034  }
3035  *this << "dump_file = fopen(dump_fname, \"w\");\n";
3036  *this << "if (dump_file) {\n";
3037  *this << to_file("dump_file", sp, arr + "[" + str(i) + "]") << ";\n";
3038  *this << "fclose(dump_file);\n";
3039  *this << "}\n";
3040  *this << "}\n";
3041  }
3042  // Combined .txt file (normalized doubles, one per line)
3043  {
3044  add_include("stdio.h");
3045  std::string fixed_part = prefix + f.name() + "." + inout + ".txt";
3046  casadi_int buf_size = fixed_part.size() + 1 + 6 + 1;
3047  *this << "{\n";
3048  *this << "char dump_fname[" << buf_size << "];\n";
3049  *this << "FILE* dump_file;\n";
3050  *this << "casadi_int dump_k;\n";
3051  *this << "snprintf(dump_fname, " << buf_size << ", \""
3052  << prefix << f.name() << ".%06d." << inout << ".txt\", dump_id_local);\n";
3053  *this << "dump_file = fopen(dump_fname, \"w\");\n";
3054  *this << "if (dump_file) {\n";
3055  for (casadi_int i = 0; i < n; ++i) {
3056  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3057  casadi_int nnz = sp.nnz();
3058  std::string a = arr + "[" + str(i) + "]";
3059  if (nnz > 0) {
3060  *this << "if (" << a << ") {\n";
3061  *this << fprintf_vector("dump_file", nnz, a, "\\n") << "\n";
3062  *this << "fprintf(dump_file, \"\\n\");\n";
3063  *this << "} else {\n";
3064  std::string zero_str = is_input ? "0.0000000000000000e+00" : "nan";
3065  *this << "for (dump_k=0; dump_k<" << nnz << "; ++dump_k) "
3066  << "fprintf(dump_file, \"" << zero_str << "\\n\");\n";
3067  *this << "}\n";
3068  }
3069  }
3070  *this << "fclose(dump_file);\n";
3071  *this << "}\n";
3072  *this << "}\n";
3073  }
3074  }
3075 
3077  generate_print(const Function& f, const std::string& arr, bool is_input) {
3078  casadi_int n = is_input ? f.n_in() : f.n_out();
3079  std::string inout = is_input ? "Input" : "Output";
3080 
3081  *this << printf("Function " + f.name() + "\\n") << "\n";
3082  for (casadi_int i = 0; i < n; ++i) {
3083  std::string io_name = is_input ? f.name_in(i) : f.name_out(i);
3084  Sparsity sp = is_input ? f.sparsity_in(i) : f.sparsity_out(i);
3085  *this << printf(inout + " " + str(i) + " (" + io_name + "): ") << "\n";
3086  *this << print_canonical(sp, arr + "[" + str(i) + "]") << "\n";
3087  *this << printf("\\n") << "\n";
3088  }
3089  }
3090 
3091  std::string CodeGenerator::
3092  cache_check(const std::string& key, const std::string& cache, const std::string& loc,
3093  casadi_int stride, casadi_int sz, casadi_int key_sz, const std::string& val) {
3095  return "casadi_cache_check(" + key + ", " + cache + ", " + loc + ", " +
3096  str(stride) + ", " + str(sz) + ", " + str(key_sz) + ", " + val + ")";
3097  }
3098 
3099  void CodeGenerator::sz_work(size_t& sz_arg, size_t& sz_res, size_t& sz_iw, size_t& sz_w) const {
3100  sz_arg = sz_res = sz_iw = sz_w = 0;
3101  for (auto&& f : added_functions_) {
3102  sz_arg = std::max(sz_arg, f.f.sz_arg());
3103  sz_res = std::max(sz_res, f.f.sz_res());
3104  sz_iw = std::max(sz_iw, f.f.sz_iw());
3105  sz_w = std::max(sz_w, f.f.sz_w());
3106  }
3107  }
3108 
3109 } // 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.
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.
void add_external(const std::string &new_external)
Add an external function declaration.
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::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.
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
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
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