CppADCodeGen  2.3.0
A C++ Algorithmic Differentiation Package with Source Code Generation
lang_c_util.hpp
1 #ifndef CPPAD_CG_LANG_C_UTIL_INCLUDED
2 #define CPPAD_CG_LANG_C_UTIL_INCLUDED
3 /* --------------------------------------------------------------------------
4  * CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation:
5  * Copyright (C) 2016 Ciengis
6  *
7  * CppADCodeGen is distributed under multiple licenses:
8  *
9  * - Eclipse Public License Version 1.0 (EPL1), and
10  * - GNU General Public License Version 3 (GPL3).
11  *
12  * EPL1 terms and conditions can be found in the file "epl-v10.txt", while
13  * terms and conditions for the GPL3 can be found in the file "gpl3.txt".
14  * ----------------------------------------------------------------------------
15  * Author: Joao Leal
16  */
17 
18 namespace CppAD {
19 namespace cg {
20 
26 template<class Base>
27 inline void printModel(ADFun<CG<Base> >& fun) {
28  std::vector<std::string> depNames;
29  std::vector<std::string> indepNames;
30  printModel(fun, depNames, indepNames);
31 }
32 
40 template<class Base>
41 inline void printModel(ADFun<CG<Base> >& fun,
42  const std::vector<std::string>& depNames,
43  const std::vector<std::string>& indepNames) {
44  CPPADCG_ASSERT_UNKNOWN(depNames.size() <= fun.Range());
45  CPPADCG_ASSERT_UNKNOWN(indepNames.size() <= fun.Domain());
46 
47  CodeHandler<Base> handler;
48 
49  std::vector<CG<Base> > indep0(fun.Domain());
50  handler.makeVariables(indep0);
51 
52  std::vector<CG<Base> > dep0 = fun.Forward(0, indep0);
53 
54  LanguageC<Base> langC("double");
55 
59  LangCCustomVariableNameGenerator<Base> nameGen(depNames, indepNames,
60  "y", "x", "z", "array");
61 
62  std::ostringstream code;
63  handler.generateCode(code, langC, dep0, nameGen);
64  std::cout << "\n" << code.str() << std::endl;
65 }
66 
70 template<class Base>
71 inline void printExpression(const CG<Base>& dep,
72  std::ostream& out = std::cout) {
73  if(dep.getOperationNode() != nullptr) {
74  if(dep.getOperationNode()->getCodeHandler() == nullptr) {
75  throw CGException("Unable to print expression: found an operation node without a CodeHandler!");
76  }
77 
78  CodeHandler<Base>& handler = *dep.getOperationNode()->getCodeHandler();
79  LanguageC<double> langC("double");
80  LangCDefaultVariableNameGenerator<double> nameGen;
81 
82  std::vector<CG<Base> > depv(1);
83  depv[0] = dep;
84 
85  std::ostringstream code;
86  handler.generateCode(code, langC, depv, nameGen);
87  out << code.str();
88  } else {
89  out << "y[0] = " << dep.getValue() << ";" << std::endl;
90  }
91 }
92 
93 template<class Base>
94 inline void printExpression(OperationNode<Base>& dep,
95  std::ostream& out = std::cout) {
96  printExpression(CG<Base>(dep), out);
97 }
98 
99 } // END cg namespace
100 } // END CppAD namespace
101 
102 #endif