CoDiPack  2.2.0
A Code Differentiation Package
SciComp TU Kaiserslautern
Loading...
Searching...
No Matches
Example 7 - Primal tape evaluation

Goal: Reevaluate a tape at a different position.

Prerequisite: Tutorial 2 - Reverse mode AD

Function:

Real func(const Real& x) {
return x * x * x;
}

Full code:

#include <codi.hpp>
#include <iostream>
using Real = codi::RealReversePrimal; // Step 1: Use a primal value taping approach
using Tape = typename Real::Tape;
Real func(const Real& x) {
return x * x * x;
}
int main(int nargs, char** args) {
Real x = 4.0;
Tape& tape = Real::getTape();
// Step 2: Do a normal recording and evaluation
tape.setActive();
tape.registerInput(x);
Real y = func(x);
tape.registerOutput(y);
tape.setPassive();
y.setGradient(1.0);
tape.evaluate();
std::cout << "f(4.0) = " << y << std::endl;
std::cout << "df/dx(4.0) = " << x.getGradient() << std::endl;
tape.clearAdjoints();
tape.setPrimal(x.getIdentifier(), 10.0);
tape.evaluatePrimal();
y.setGradient(1.0);
tape.evaluate();
std::cout << "f(3.0) = " << tape.getPrimal(y.getIdentifier()) << std::endl;
std::cout << "df/dx(3.0) = " << x.getGradient() << std::endl;
tape.reset();
return 0;
}
RealReversePrimalGen< double > RealReversePrimal
Definition codi.hpp:177

A primal reevaluation follows the same rules as an evaluation of the tape. There are a few things to consider:

  • A primal value taping approach needs to be used, e.g. codi::RealReversePrimal
  • The primal value needs to be changed on the tape with setPrimal.
  • New primal values of the outputs have to be received with getPrimal.
  • CoDiPack does not record branching statements. These changes are not considered in a primal reevaluation.