### General Installation - Get Sources Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Clones the CppADCodeGen repository from GitHub. ```sh git clone https://github.com/joaoleal/CppADCodeGen.git CppADCodeGen ``` -------------------------------- ### General Installation - Install Project Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Installs the project to the system's default location. ```sh make install ``` -------------------------------- ### Main Examples Target Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines a main custom target 'examples' that depends on all individual example targets. ```cmake ADD_CUSTOM_TARGET(examples) ADD_DEPENDENCIES(examples example_source_generation_c) ADD_DEPENDENCIES(examples example_source_generation_latex) ADD_DEPENDENCIES(examples example_source_generation_mathml) ADD_DEPENDENCIES(examples example_source_generation_dot) IF(UNIX) ADD_DEPENDENCIES(examples example_atomic) ADD_DEPENDENCIES(examples example_dynamic_linux) ADD_DEPENDENCIES(examples example_lagrangian) ENDIF() ``` -------------------------------- ### Source Generation MathML Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for the MathML source generation example and a custom target to run it. ```cmake ADD_EXECUTABLE(source_generation_mathml source_generation_mathml.cpp) SET(EXAMPLES_COMMAND "COMMAND source_generation_mathml") ADD_CUSTOM_TARGET(example_source_generation_mathml COMMAND source_generation_mathml) ``` -------------------------------- ### Source Generation C Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for the C source generation example and a custom target to run it. ```cmake ADD_EXECUTABLE(source_generation_c source_generation_c.cpp) SET(EXAMPLES_COMMAND "COMMAND source_generation_c") ADD_CUSTOM_TARGET(example_source_generation_c COMMAND source_generation_c) ``` -------------------------------- ### Installation Paths Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Defines installation paths for headers, libraries, documentation, and Python scripts. ```cmake IF(UNIX) SET(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "Default install path prefix") ENDIF() SET(install_cppadcg_include_location "${CMAKE_INSTALL_PREFIX}/include/cppad") SET(install_cppadcg_include_pkg_location "${CMAKE_INSTALL_PREFIX}/include") SET(install_cppad_include_location "${CMAKE_INSTALL_PREFIX}/include/cppad") SET(install_cppad_include_pkg_location "${CMAKE_INSTALL_PREFIX}/include") SET(install_library_pkg_location "${CMAKE_INSTALL_PREFIX}/share/pkgconfig") SET(install_doc_location "${CMAKE_INSTALL_PREFIX}/share/doc/cppadcg") SET(install_python_location "${CMAKE_INSTALL_PREFIX}/share/cppadcg/python") ``` -------------------------------- ### General Installation - Install to Other Folder Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Installs the project to a specified alternative folder. ```sh make DESTDIR=someotherfolder install ``` -------------------------------- ### Source Generation LaTeX Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for the LaTeX source generation example and a custom target to run it. Includes conditional compilation for PDFLaTeX. ```cmake ADD_EXECUTABLE(source_generation_latex source_generation_latex.cpp) SET(EXAMPLES_COMMAND "COMMAND source_generation_latex") ADD_CUSTOM_TARGET(example_source_generation_latex COMMAND source_generation_latex) IF(PDFLATEX_COMPILER) ADD_DEFINITIONS(-DPDFLATEX_COMPILER=\"${PDFLATEX_COMPILER}\") ENDIF() link_file("${CMAKE_CURRENT_SOURCE_DIR}/resources" "${CMAKE_CURRENT_BINARY_DIR}/resources") # copy template (if required) ADD_CUSTOM_TARGET(link_or_copy_resources DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/resources") ADD_DEPENDENCIES(source_generation_latex link_or_copy_resources) ``` -------------------------------- ### Install Main Header File Source: https://github.com/joaoleal/cppadcodegen/blob/master/include/CMakeLists.txt Installs the main CppADCodeGen header file. ```cmake INSTALL(FILES "${CMAKE_CURRENT_SOURCE_DIR}/cppad/cg.hpp" DESTINATION "${install_cppadcg_include_location}/" ) ``` -------------------------------- ### General Installation - Create Build Folder Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Creates a new folder for building the project. ```sh mkdir cppadcg-build ``` -------------------------------- ### GCC Compilation and Usage Example Source: https://github.com/joaoleal/cppadcodegen/wiki/LibGeneration An example demonstrating how to generate, compile, and link a dynamic library using GCC with CppADCodegen. ```C++ #include #include #include using namespace CppAD; using namespace CppAD::cg; int main(void) { // use a special object for source code generation typedef CG CGD; typedef AD ADCG; /*************************************************************************** * the model **************************************************************************/ // independent variable vector std::vector x(2); Independent(x); // dependent variable vector std::vector y(1); // the model equation ADCG a = x[0] / 1. + x[1] * x[1]; y[0] = a / 2; ADFun fun(x, y); /*************************************************************************** * Create the dynamic library * (generates and compiles source code) **************************************************************************/ // generates source code ModelCSourceGen cgen(fun, "my_model"); cgen.setCreateJacobian(true); cgen.setCreateForwardOne(true); cgen.setCreateReverseOne(true); cgen.setCreateReverseTwo(true); ModelLibraryCSourceGen libcgen(cgen); // compile source code DynamicModelLibraryProcessor p(libcgen); GccCompiler compiler; std::unique_ptr> dynamicLib = p.createDynamicLibrary(compiler); // save to files (not really required) SaveFilesModelLibraryProcessor p2(libcgen); p2.saveSources(); /*************************************************************************** * Use the dynamic library **************************************************************************/ std::unique_ptr> model = dynamicLib->model("my_model"); std::vector xv {2.5, 3.5}; std::vector jac = model->Jacobian(xv); // print out the result std::cout << jac[0] << " " << jac[1] << std::endl; } ``` -------------------------------- ### LLVM JIT Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Configures an executable for JIT compilation using LLVM, including include/library paths and definitions. Links against DL, LLVM, and Clang libraries conditionally. ```cmake IF(CPPADCG_USE_LLVM) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${LLVM_INCLUDE_DIRS} ${Clang_INCLUDE_DIRS} ${DL_INCLUDE_DIRS}) LINK_DIRECTORIES(${LLVM_LIBRARY_DIRS}) ADD_DEFINITIONS(${LLVM_CFLAGS_NO_NDEBUG} -DLLVM_WITH_NDEBUG=${LLVM_WITH_NDEBUG}) ADD_EXECUTABLE(jit_linux jit_linux.cpp) SET(EXAMPLES_COMMAND "${EXAMPLES_COMMAND} COMMAND dynamic_linux") TARGET_LINK_LIBRARIES(jit_linux ${DL_LIBRARIES}) ADD_CUSTOM_TARGET(example_jit_linux COMMAND jit_linux) IF("${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}" MATCHES "^(${CPPADCG_LLVM_LINK_LIB})$") TARGET_LINK_LIBRARIES(jit_linux ${Clang_LIBS}) ENDIF() TARGET_LINK_LIBRARIES(jit_linux ${LLVM_MODULE_LIBS} ${LLVM_LDFLAGS}) ENDIF() ``` -------------------------------- ### Source Generation Example (DOT) Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for source generation in DOT format and a custom target to run it. ```cmake ADD_EXECUTABLE(source_generation_dot source_generation_dot.cpp) SET(EXAMPLES_COMMAND "COMMAND source_generation_dot") ADD_CUSTOM_TARGET(example_source_generation_dot COMMAND source_generation_dot) ``` -------------------------------- ### Interactive Mode Notice Source: https://github.com/joaoleal/cppadcodegen/blob/master/gpl3.txt Example of a short notice to display when a program starts in interactive mode, indicating its free software status and warranty conditions. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Patterns Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for pattern matching and a custom target to run it, linking against the DL library. ```cmake ADD_EXECUTABLE(patterns patterns.cpp) SET(EXAMPLES_COMMAND "${EXAMPLES_COMMAND} COMMAND patterns") TARGET_LINK_LIBRARIES(patterns ${DL_LIBRARIES}) ADD_CUSTOM_TARGET(example_patterns COMMAND patterns) ``` -------------------------------- ### Lagrangian Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for Lagrangian calculations and a custom target to run it, linking against the DL library. ```cmake ADD_EXECUTABLE(lagrangian lagrangian.cpp) SET(EXAMPLES_COMMAND "${EXAMPLES_COMMAND} COMMAND lagrangian") TARGET_LINK_LIBRARIES(lagrangian ${DL_LIBRARIES}) ADD_CUSTOM_TARGET(example_lagrangian COMMAND lagrangian) ``` -------------------------------- ### Dynamic Linux Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for dynamic linking on Linux and a custom target to run it, linking against the DL library. ```cmake ADD_EXECUTABLE(dynamic_linux dynamic_linux.cpp) SET(EXAMPLES_COMMAND "${EXAMPLES_COMMAND} COMMAND dynamic_linux") TARGET_LINK_LIBRARIES(dynamic_linux ${DL_LIBRARIES}) ADD_CUSTOM_TARGET(example_dynamic_linux COMMAND dynamic_linux) ``` -------------------------------- ### Install Python Directory Source: https://github.com/joaoleal/cppadcodegen/blob/master/python/CMakeLists.txt Installs Python files from the 'gdb' directory to the specified installation location. ```cmake INSTALL( DIRECTORY "gdb" DESTINATION "${install_python_location}" FILES_MATCHING PATTERN "*.py") ``` -------------------------------- ### Configure and Install Header Source: https://github.com/joaoleal/cppadcodegen/blob/master/include/CMakeLists.txt Configures a header file and installs it to the specified include location. ```cmake CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/cppad/cg/configure.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/cppad/cg/configure.hpp ) INSTALL( FILES ${CMAKE_CURRENT_BINARY_DIR}/cppad/cg/configure.hpp DESTINATION "${install_cppadcg_include_location}/cg") ``` -------------------------------- ### Atomic Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/example/CMakeLists.txt Defines an executable for atomic operations and a custom target to run it, linking against the DL library. ```cmake ADD_EXECUTABLE(atomic atomic.cpp) SET(EXAMPLES_COMMAND "${EXAMPLES_COMMAND} COMMAND atomic") TARGET_LINK_LIBRARIES(atomic ${DL_LIBRARIES}) ADD_CUSTOM_TARGET(example_atomic COMMAND atomic) ``` -------------------------------- ### Install Header Directory Source: https://github.com/joaoleal/cppadcodegen/blob/master/include/CMakeLists.txt Installs all .hpp files from the 'cppad/cg/' directory to the destination. ```cmake INSTALL( DIRECTORY "cppad/cg/" DESTINATION "${install_cppadcg_include_location}/cg" FILES_MATCHING PATTERN "*.hpp") ``` -------------------------------- ### MathML Configuration Example Source: https://github.com/joaoleal/cppadcodegen/blob/master/test/cppad/cg/model/lang/mathml/head_extra.html Example of MathJax configuration for MathML rendering, including browser-specific preferences and display alignment. ```javascript // MathJax.Hub.Config({ MMLorHTML: { prefer: { Firefox: "MML" } } }); // use this to define a preferred browser renderer MathJax.Hub.Config({ jax: ["input/TeX","output/HTML-CSS"], displayAlign: "left" }); ``` -------------------------------- ### Install pkg-config file Source: https://github.com/joaoleal/cppadcodegen/blob/master/pkgconfig/CMakeLists.txt Installs the generated cppadcg.pc file to the specified destination. ```cmake INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/cppadcg.pc DESTINATION ${install_library_pkg_location} ) ``` -------------------------------- ### Debian/Ubuntu Installation Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Creates a Debian installation package at the root of the project. ```sh dpkg-buildpackage ``` -------------------------------- ### General Installation - Build Project Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Configures the build system using CMake. This step primarily generates header files. ```sh cd cppadcg-build cmake ../CppADCodeGen ``` -------------------------------- ### INSTALL command for generated header files Source: https://github.com/joaoleal/cppadcodegen/blob/master/include/cppad/cg/model/threadpool/CMakeLists.txt This snippet demonstrates the installation of the generated C++ header files into the appropriate include directory for the CppADCodeGen library. ```cmake INSTALL( FILES "${CMAKE_CURRENT_BINARY_DIR}/pthread_pool_c.hpp" "${CMAKE_CURRENT_BINARY_DIR}/pthread_pool_h.hpp" "${CMAKE_CURRENT_BINARY_DIR}/openmp_c.hpp" "${CMAKE_CURRENT_BINARY_DIR}/openmp_h.hpp" DESTINATION "${install_cppadcg_include_location}/cg/model/threadpool/") ``` -------------------------------- ### Latex Source Generation Example Source: https://github.com/joaoleal/cppadcodegen/wiki/DirectSourceGeneration This C++ code demonstrates how to use CppADCodeGen to generate Latex source code for a given mathematical model. It includes setting up the model, generating the Latex code, and optionally compiling it into a PDF. ```C++ #include #include #include using namespace CppAD; using namespace CppAD::cg; int main(void) { // use a special object for source code generation using CGD = CG; using ADCG = AD; /*************************************************************************** * the model **************************************************************************/ // independent variable vector CppAD::vector x(2); x[0] = 2.; x[1] = 3.; Independent(x); // dependent variable vector CppAD::vector y(1); // the model ADCG a = x[0] / 1. + x[1] * x[1]; y[0] = a / 2; ADFun fun(x, y); // the model tape /*************************************************************************** * Generate the Latex source code **************************************************************************/ /** * start the special steps for source code generation */ CodeHandler handler; CppAD::vector xv(x.size()); handler.makeVariables(xv); CppAD::vector vals = fun.Forward(0, xv); LanguageLatex langLatex; LangLatexDefaultVariableNameGenerator nameGen; std::ofstream texfile; texfile.open("algorithm.tex"); handler.generateCode(texfile, langLatex, vals, nameGen); texfile.close(); /*************************************************************************** * Compile a PDF file **************************************************************************/ #ifdef PDFLATEX_COMPILER std::string dir = system::getWorkingDirectory(); system::callExecutable(PDFLATEX_COMPILER, {"-halt-on-error", "-shell-escape", system::createPath({dir, "resources"}, "latex_template.tex")}); #endif } ``` -------------------------------- ### HTML/MathML/Javascript Source Generation Example Source: https://github.com/joaoleal/cppadcodegen/wiki/DirectSourceGeneration C++ code demonstrating how to generate an HTML page with MathML and Javascript to navigate and inspect a CppAD model. This is suitable for smaller models due to potential size limitations. ```C++ #include #include #include using namespace CppAD; using namespace CppAD::cg; int main(void) { // use a special object for source code generation using CGD = CG; using ADCG = AD; // independent variable vector CppAD::vector x(2); x[0] = 2.; x[1] = 3.; Independent(x); // dependent variable vector CppAD::vector y(8); /*************************************************************************** * the model **************************************************************************/ ADCG a = x[0] / 1. + x[1] * x[1]; ADCG b = a / 2e-6; y[0] = b + 1 / (sign(b)*5 * a); y[1] = x[1]; y[2] = CondExpLt(ADCG(1.0), x[0], x[1], b); y[3] = CondExpLe(x[0], ADCG(2.0), x[1], b); y[4] = CondExpEq(x[0], x[1], x[1], b); ADCG c = CondExpGe(ADCG(3.0), x[0], a, b); y[5] = CondExpGt(ADCG(4.0), x[0], ADCG(5.0), c); y[6] = 5 * pow(4, x[0]); y[7] = 3; ADFun fun(x, y); // the model tape /*************************************************************************** * Generate the HTML/MathML source code **************************************************************************/ CodeHandler handler; CppAD::vector indVars(2); handler.makeVariables(indVars); CppAD::vector vals = fun.Forward(0, indVars); LanguageMathML langMathML; LangMathMLDefaultVariableNameGenerator nameGen; langMathML.setSaveVariableRelations(true); // add some additional code to select variables langMathML.setStyle(langMathML.getStyle() + "\n.selectedProp{background-color: #ccc;}" "\n.faded{\n" " opacity: 0.2;\n" " filter: alpha(opacity=20); /* For IE8 and earlier */\n" ``` -------------------------------- ### C Source Generation Example Source: https://github.com/joaoleal/cppadcodegen/wiki/DirectSourceGeneration A C++ program demonstrating how to generate C source code for a simple mathematical model using CppADCodeGen. ```C++ #include #include #include using namespace CppAD; using namespace CppAD::cg; int main() { // use a special object for source code generation typedef CG CGD; typedef AD ADCG; /*************************************************************************** * the model **************************************************************************/ // independent variable vector CppAD::vector x(2); x[0] = 2.; x[1] = 3.; Independent(x); // dependent variable vector CppAD::vector y(1); // the model ADCG a = x[0] / 1. + x[1] * x[1]; y[0] = a / 2; ADFun fun(x, y); // the model tape /*************************************************************************** * Generate the C source code **************************************************************************/ /** * start the special steps for source code generation for a Jacobian */ CodeHandler handler; CppAD::vector indVars(2); handler.makeVariables(indVars); CppAD::vector jac = fun.SparseJacobian(indVars); LanguageC langC("double"); LangCDefaultVariableNameGenerator nameGen; std::ostringstream code; handler.generateCode(code, langC, jac, nameGen); std::cout << code.str(); } ``` -------------------------------- ### Subdirectory Inclusion Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Includes various subdirectories for building the project, including include files, examples, speed tests, Python bindings, pkgconfig, documentation, and tests. ```cmake ADD_SUBDIRECTORY(include) ADD_SUBDIRECTORY(example EXCLUDE_FROM_ALL) #ADD_SUBDIRECTORY(introduction EXCLUDE_FROM_ALL) ADD_SUBDIRECTORY(speed EXCLUDE_FROM_ALL) ADD_SUBDIRECTORY(python) ADD_SUBDIRECTORY(pkgconfig) ADD_SUBDIRECTORY(doc) # enable testing must be called here in order for the target test to be created ENABLE_TESTING() ADD_SUBDIRECTORY(test EXCLUDE_FROM_ALL) ``` -------------------------------- ### Complete Example Source: https://github.com/joaoleal/cppadcodegen/wiki/AtomicFunctions This C++ code demonstrates how to define, compile, and use atomic functions within CppADCodeGen. It includes defining inner and outer models, preparing them for compilation, compiling them into a dynamic library, and then using the compiled library. ```C++ #include #include using namespace CppAD; using namespace CppAD::cg; using CGD = CppAD::cg::CG; using ADCGD = CppAD::AD; const int MOuter = 6; const int NOuter = 3; const int MInner = 2; const int NInner = 2; const std::string LIBRARY_NAME = "./two_model_library"; const std::string LIBRARY_NAME_EXT = LIBRARY_NAME + system::SystemInfo<>::DYNAMIC_LIB_EXTENSION; std::vector innerModel(const std::vector& x) { std::vector y(MInner); for (size_t i = 0; i < x.size(); i++) { y[i] = x[i] * (i + 2); } return y; } std::vector outerModel(const std::vector& x, atomic_base& atomicfun) { std::vector z(MOuter); for (size_t k = 0; k < 2; k++) { std::vector y(MInner); std::vector xInner(x.begin() + k, x.begin() + k + NInner); atomicfun(xInner, y); for (size_t i = 0; i < y.size(); i++) { z[i + k * NInner] = y[i]; } } z[4] = x[1] * x[1]; z[5] = x[0] * x[2] + 1; return z; } std::unique_ptr> tapeInnerModel() { std::vector ax(NInner); CppAD::Independent(ax); std::vector ay = innerModel(ax); std::unique_ptr> funInner(new ADFun()); funInner->Dependent(ay); return funInner; } std::unique_ptr> tapeOuterModel(CGAtomicFunBridge& atomicFun) { std::vector ax(NOuter); CppAD::Independent(ax); std::vector az = outerModel(ax, atomicFun); std::unique_ptr> funOuter(new ADFun()); funOuter->Dependent(az); return funOuter; } std::unique_ptr> prepareInnerModelCompilation(ADFun& funInner) { auto cSourceInner = std::make_unique> (funInner, "my_inner_model"); cSourceInner->setCreateForwardZero(true); cSourceInner->setCreateForwardOne(true); cSourceInner->setCreateReverseOne(true); cSourceInner->setCreateReverseTwo(true); return cSourceInner; } std::unique_ptr> prepareOuterModelCompilation(ADFun& funOuter) { auto cSourceOuter = std::make_unique>(funOuter, "my_outer_model"); cSourceOuter->setCreateForwardZero(true); cSourceOuter->setCreateSparseJacobian(true); cSourceOuter->setCreateSparseHessian(true); return cSourceOuter; } void compileLibrary() { auto funInner = tapeInnerModel(); CGAtomicFunBridge atomicFun("my_inner_model", *funInner, true); auto funOuter = tapeOuterModel(atomicFun); auto cSourceInner = prepareInnerModelCompilation(*funInner); auto cSourceOuter = prepareOuterModelCompilation(*funOuter); ModelLibraryCSourceGen libSourceGen(*cSourceInner, *cSourceOuter); GccCompiler compiler; // the following options are used so that it is easier to debug generated sources compiler.setCompileFlags({"-O0", "-g", "-ggdb", "-D_FORTIFY_SOURCE=2"}); compiler.setSaveToDiskFirst(true); DynamicModelLibraryProcessor p(libSourceGen, LIBRARY_NAME); bool loadLib = false; p.createDynamicLibrary(compiler, loadLib); } void useLibrary() { LinuxDynamicLib dynamicLib(LIBRARY_NAME_EXT); std::unique_ptr> outerModel = dynamicLib.model("my_outer_model"); std::unique_ptr> innerModel = dynamicLib.model("my_inner_model"); outerModel->addExternalModel(*innerModel); std::vector xv{1.1, 2.5, 3.5}; std::vector jac; std::vector row, col; outerModel->SparseJacobian(xv, jac, row, col); // print out the result for (size_t i = 0; i < jac.size(); ++i) std::cout << "dz[" << row[i] << "]/dx[" << col[i] << "] = " << jac[i] << ";" << std::endl; } int main() { if (!system::isFile(LIBRARY_NAME_EXT)) { std::cout << "Creating a new library" << std::endl; compileLibrary(); } else { std::cout << "Reusing existing library" << std::endl; } useLibrary(); } ``` -------------------------------- ### Project and Version Information Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Sets the minimum required CMake version, project name, and defines variables for the project's version, URL, and description. ```cmake CMAKE_MINIMUM_REQUIRED(VERSION 3.5.0...3.27.4) PROJECT(cppadcg CXX C) SET(cppadcg_version "2.5.0" ) SET(cppadcg_url "https://github.com/joaoleal/CppADCodeGen" ) SET(cppadcg_description "A C++ Algorithmic Differentiation Package with Source Code Generation" ) ``` -------------------------------- ### Applying GPL to New Programs Source: https://github.com/joaoleal/cppadcodegen/blob/master/gpl3.txt Template for applying the GNU GPL to new software projects, including copyright notices and warranty disclaimers. ```text Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Doxygen Documentation Option Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Configures an option to build Doxygen documentation. ```cmake OPTION(CREATE_DOXYGEN_DOC "Build documentation" OFF) IF(${CREATE_DOXYGEN_DOC}) FIND_PACKAGE(Doxygen REQUIRED) ELSE() FIND_PACKAGE(Doxygen) ENDIF() ``` -------------------------------- ### Uninstall Target Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Defines a custom target 'uninstall' to execute a script for removing installed files. ```cmake ADD_CUSTOM_TARGET(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/cppadcodegen_uninstall.cmake) ``` -------------------------------- ### Benchmark Plugflow Execution Source: https://github.com/joaoleal/cppadcodegen/blob/master/speed/cppad/cg/patterns/CMakeLists.txt Configures custom commands to execute the 'speed_plugflow' benchmark with varying numbers of constraints and redirects output to files. ```cmake FOREACH(nCstr 100 90 80 70 60 50 40 30 20 10) SET(outputStatFile "speed_plugflow_stat_${nCstr}.txt") SET(outputDataFile "speed_plugflow_data_${nCstr}.txt") LIST(APPEND outputFiles ${outputStatFile} ${outputDataFile}) ADD_CUSTOM_COMMAND(OUTPUT ${outputStatFile} ${outputDataFile} COMMAND speed_plugflow ${nCstr} > ${outputStatFile} 2> ${outputDataFile} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") ENDFOREACH() ADD_CUSTOM_TARGET(benchmark_plugflow DEPENDS ${outputFiles}) ``` -------------------------------- ### Include Directories Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Sets the include directories for the project, including CppAD, project headers, and build directory headers. ```cmake INCLUDE_DIRECTORIES(${CPPAD_INCLUDE_DIRS} "${CMAKE_SOURCE_DIR}/include" "${CMAKE_BINARY_DIR}/include" ${DL_INCLUDE_DIRS}) IF(EIGEN3_FOUND) INCLUDE_DIRECTORIES(${EIGEN3_INCLUDE_DIR}) ENDIF() ``` -------------------------------- ### Generated C Source Code Output Source: https://github.com/joaoleal/cppadcodegen/wiki/DirectSourceGeneration The output C source code generated by the CppADCodeGen example. ```C y[1] = 0.5 * x[1] + 0.5 * x[1]; // dependent variables without operations y[0] = 0.5; ``` -------------------------------- ### CMake Build Configuration Source: https://github.com/joaoleal/cppadcodegen/blob/master/test/cppad/cg/model/lang/latex/CMakeLists.txt This snippet shows the basic CMake build configuration, including setting the build type and adding definitions. ```cmake SET(CMAKE_BUILD_TYPE DEBUG) ################################################################################ ADD_DEFINITIONS(-DPDFLATEX_COMPILER="${PDFLATEX_COMPILER}") ################################################################################ link_file("${CMAKE_CURRENT_SOURCE_DIR}/latexTemplate.tex" "${CMAKE_CURRENT_BINARY_DIR}/latexTemplate.tex") ################################################################################ # add latex test function ################################################################################ FUNCTION(add_cppadcg_latex_test source_file) add_cppadcg_test("${source_file}") GET_FILENAME_COMPONENT(test_target_name "${source_file}" NAME_WE) ADD_CUSTOM_TARGET(link_or_copy_latexTemplate DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/latexTemplate.tex") ADD_DEPENDENCIES("${test_target_name}" link_or_copy_latexTemplate) ENDFUNCTION() ################################################################################ # tests ################################################################################ add_cppadcg_latex_test(latex.cpp) add_cppadcg_test(lang_latex_reset.cpp) ``` -------------------------------- ### CMake Build Configuration Source: https://github.com/joaoleal/cppadcodegen/blob/master/speed/CMakeLists.txt This snippet shows the basic CMake command to add a subdirectory for the CppAD build. ```cmake ADD_SUBDIRECTORY(cppad) ``` -------------------------------- ### Benchmark Collocation Execution Source: https://github.com/joaoleal/cppadcodegen/blob/master/speed/cppad/cg/patterns/CMakeLists.txt Configures custom commands to execute the 'speed_collocation' benchmark with varying numbers of time intervals and constraints, redirecting output to files. ```cmake SET(outputFiles "") FOREACH(nCstr 50 30 10) FOREACH(nTimeInt 50 40 30 20 10 5) SET(outputStatFile "speed_collocation_stat_${nTimeInt}int_${nCstr}el.txt") SET(outputDataFile "speed_collocation_data_${nTimeInt}int_${nCstr}el.txt") LIST(APPEND outputFiles ${outputStatFile} ${outputDataFile}) ADD_CUSTOM_COMMAND(OUTPUT ${outputStatFile} ${outputDataFile} COMMAND speed_collocation ${nTimeInt} ${nCstr} > ${outputStatFile} 2> ${outputDataFile} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") ENDFOREACH() ENDFOREACH() ADD_CUSTOM_TARGET(benchmark_collocation DEPENDS ${outputFiles}) ``` -------------------------------- ### LLVM/Clang JIT Check Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Determines whether to enable LLVM/Clang for Just-In-Time (JIT) compilation based on LLVM version and Clang availability. ```cmake SET(CPPADCG_LLVM_LINK_LIB "3.2|3.6|3.8|4.0|5.0|6.0|7.0|8.0|9.0|10.0") IF((("${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}" MATCHES "^(${CPPADCG_LLVM_LINK_LIB})$") AND Clang_FOUND) OR ("${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}" MATCHES "^(3.3|3.4)$") ) SET(CPPADCG_USE_LLVM ON) ELSE() SET(CPPADCG_USE_LLVM OFF) ENDIF() ``` -------------------------------- ### CMakeLists.txt Configuration Source: https://github.com/joaoleal/cppadcodegen/blob/master/test/cppad/cg/model/dynamiclib/CMakeLists.txt This snippet shows the CMake configuration for building CppADCodeGen tests on UNIX systems, including adding test executables. ```cmake # -------------------------------------------------------------------------- # CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation: # Copyright (C) 2012 Ciengis # # CppADCodeGen is distributed under multiple licenses: # # - Eclipse Public License Version 1.0 (EPL1), and # - GNU General Public License Version 3 (GPL3). # # EPL1 terms and conditions can be found in the file "epl-v10.txt", while # terms and conditions for the GPL3 can be found in the file "gpl3.txt". # ---------------------------------------------------------------------------- # # Author: Joao Leal # # ---------------------------------------------------------------------------- INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) IF( UNIX ) add_cppadcg_test(dynamic.cpp) add_cppadcg_test(cg_atomic_generic_model.cpp) # add_cppadcg_test(dynamic_atomic_nonlinear_outer.cpp) # not supported yet add_cppadcg_test(dynamic_atomic.cpp) add_cppadcg_test(dynamic_atomic_2.cpp) add_cppadcg_test(dynamic_atomic_3.cpp) add_cppadcg_test(dynamic_cond_exp.cpp) add_cppadcg_test(dynamic_forward_reverse.cpp) add_cppadcg_test(dynamic_forward_reverse_2.cpp) ENDIF() ``` -------------------------------- ### Testing - Create Build Folder Source: https://github.com/joaoleal/cppadcodegen/blob/master/doc/mainpage.md Creates a new folder for building the tests. ```sh cd make-build-debug cmake ../CppADCodeGen ``` -------------------------------- ### Cppcheck and Utilities Includes Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Includes CMake modules for cppcheck and other utilities. ```cmake INCLUDE(cmake/cppcheck.cmake) INCLUDE(cmake/util.cmake) INCLUDE(cmake/textfile2h.cmake) ``` -------------------------------- ### Add Subdirectory Source: https://github.com/joaoleal/cppadcodegen/blob/master/include/CMakeLists.txt Adds a subdirectory for building. ```cmake ADD_SUBDIRECTORY(cppad/cg/model/threadpool) ``` -------------------------------- ### Download and Compile GTest Source: https://github.com/joaoleal/cppadcodegen/blob/master/test/CMakeLists.txt This snippet shows how to find, download, and make GTest available for the project using CMake's FetchContent module. ```cmake find_package(GTest) if(NOT GTEST_FOUND) INCLUDE(ExternalProject) # Download from GitHub INCLUDE(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/refs/tags/v1.14.0.zip) # For Windows: Prevent overriding the parent project's compiler/linker settings SET(gtest_force_shared_crt ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) INCLUDE(GoogleTest) endif() ``` -------------------------------- ### Basic Test Configuration Source: https://github.com/joaoleal/cppadcodegen/blob/master/test/cppad/cg/dae_index_reduction/CMakeLists.txt Adds C++ test files for the DAE index reduction module using the add_cppadcg_test macro. ```cmake SET(CMAKE_BUILD_TYPE DEBUG) add_cppadcg_test(pantelides.cpp) add_cppadcg_test(pantelides_flash.cpp) add_cppadcg_test(soares_secchi.cpp) add_cppadcg_test(soares_secchi_flash.cpp) add_cppadcg_test(soares_secchi_destil.cpp) ``` -------------------------------- ### Build Options Source: https://github.com/joaoleal/cppadcodegen/blob/master/CMakeLists.txt Defines options for enabling CppCheck in tests and thread pool tests. ```cmake OPTION(ENABLE_TEST_CPPCHECKS "Use CppCheck to verify source code in tests (very lengthy task!)" OFF) OPTION(ENABLE_THREAD_POOL_TESTS "Enables tests for thread pool" ON) ``` -------------------------------- ### Configure pkg-config files Source: https://github.com/joaoleal/cppadcodegen/blob/master/pkgconfig/CMakeLists.txt Configures the pkg-config files (.pc) from their input templates. ```cmake CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/cppadcg.pc.in ${CMAKE_CURRENT_BINARY_DIR}/cppadcg.pc ) CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/cppadcg-uninstalled.pc.in ${CMAKE_CURRENT_BINARY_DIR}/cppadcg-uninstalled.pc ) ``` -------------------------------- ### JavaScript Event Handler and Initialization Source: https://github.com/joaoleal/cppadcodegen/wiki/output/algorithm.html JavaScript code that handles user clicks to highlight variable dependencies and fade unrelated equations, along with initialization for the algorithm visualization. ```javascript var depConst = []; var depIsVar = []; var var2dep = { "5": [2, 3], "6": [5], "11": [5, 6], "12": [2, 3, 6], "13": [2, 3, 6], "14": [2, 3, 6], "15": [2, 5, 6], "16": [2, 15], "19": [2] }; var dep2var = { "2": [5, 12, 13, 14, 15, 16, 19], "3": [5, 12, 13, 14], "5": [6, 11, 15], "6": [11, 12, 13, 14, 15], "15": [16] }; function contains(arr, o) { if (usages === null || usages === undefined) { return false; } var l = arr.length; for (var i = 0; i < l; i++) { if (arr[i] === o) { return true; } } return false; } function findEquation(el) { if (el.classList.contains('indep')) return null; while (el != document) { if (el.classList.contains('equation')) { return el; } el = el.parentNode; } return null; } function isBranch(eq) { var el = eq.parentNode; while (el != document && el.id != 'algorithm') { if (el.classList.contains('condBody')) { return true; } el = el.parentNode; } return false; } function showEquations(eqId, level) { var el = document.getElementById('v' + eqId); if (el !== null) { var eq = findEquation(el); if (eq !== null && eq !== undefined) { eq.classList.remove('faded'); if (!eq.classList.contains('depEq')) { eq.classList.add('depEq'); if (level > 1) eq.classList.add('faded2'); } else { return; // been here already } } } var deps = var2dep[eqId]; if (deps === undefined || deps === null) { return; } for (var i = 0; i < deps.length; i++) { var id = deps[i]; showEquations(id, level + 1); } } function hideEquationForIds(ids, visibleId) { for (var co in ids) { if (visibleId === ids[co]) continue; var el = document.getElementById(ids[co]); if (el !== null && el !== undefined) { var eq = findEquation(el); if (eq !== null && eq !== undefined) eq.classList.add('faded'); } } } function clearAllClass(className) { var list = document.getElementsByClassName(className); if (list !== undefined) { while (list.length > 0) { list[0].classList.remove(className); } } } function clickHandler(e) { var t = e.target; clearAllClass('selectedProp'); clearAllClass('faded'); clearAllClass('faded2'); clearAllClass('depEq'); while (t != document) { if (t.id !== null && t.id !== '' && t.id.charAt(0) == 'v') { var baseId = t.id.split('_')[0]; var idval = baseId.substring(1); var el = document.getElementById(baseId); var n = 0; while (el !== null) { el.classList.add('selectedProp'); n++; el = document.getElementById(baseId + '_' + n); } // fade other equations which do not use this variable usages = dep2var[idval]; for (var i in var2dep) { if (i === idval) continue; var vi = parseInt(i); if (!contains(usages, vi)) { var el2 = document.getElementById('v' + i); n = 0; while (el2 !== null) { var eq = findEquation(el2); if (eq === null) break; eq.classList.add('faded'); if (!isBranch(eq)) break; n++; el2 = document.getElementById('v' + i + '_' + n); } } } // unfade equations used to create that variable showEquations(idval, 0); hideEquationForIds(depConst, t.id); hideEquationForIds(depIsVar, t.id); break; } t = t.parentNode; } } document.addEventListener('DOMContentLoaded', function () { document.getElementById('algorithm').onclick = clickHandler; }, false); ```