Coding the Executable (main)

Now that we have a problem representation, the HS071_NLP class, we need to code the main function that will call IPOPT and ask IPOPT to find a solution.

Here, we must create an instance of our problem (HS071_NLP), create an instance of the IPOPT solver (IpoptApplication), initialize it, and ask the solver to find a solution. We always use the SmartPtr template class instead of raw C++ pointers when creating and passing IPOPT objects. To find out more information about smart pointers and the SmartPtr implementation used in IPOPT, see Appendix B.

Create the file MyExample.cpp in the MyExample directory. Include HS071_NLP.hpp and IpIpoptApplication.hpp, tell the compiler to use the Ipopt namespace, and implement the main function.

#include "IpIpoptApplication.hpp"
#include "hs071_nlp.hpp"

using namespace Ipopt;

int main(int argv, char* argc[])
{
  // Create a new instance of your nlp 
  //  (use a SmartPtr, not raw)
  SmartPtr<TNLP> mynlp = new HS071_NLP();

  // Create a new instance of IpoptApplication
  //  (use a SmartPtr, not raw)
  // We are using the factory, since this allows us to compile this
  // example with an Ipopt Windows DLL
  SmartPtr<IpoptApplication> app = IpoptApplicationFactory();

  // Change some options
  // Note: The following choices are only examples, they might not be
  //       suitable for your optimization problem.
  app->Options()->SetNumericValue("tol", 1e-9);
  app->Options()->SetStringValue("mu_strategy", "adaptive");
  app->Options()->SetStringValue("output_file", "ipopt.out");

  // Intialize the IpoptApplication and process the options
  ApplicationReturnStatus status;
  status = app->Initialize();
  if (status != Solve_Succeeded) {
    printf("\n\n*** Error during initialization!\n");
    return (int) status;
  }

  // Ask Ipopt to solve the problem
  status = app->OptimizeTNLP(mynlp);

  if (status == Solve_Succeeded) {
    printf("\n\n*** The problem solved!\n");
  }
  else {
    printf("\n\n*** The problem FAILED!\n");
  }

  // As the SmartPtrs go out of scope, the reference count
  // will be decremented and the objects will automatically 
  // be deleted.

  return (int) status;
}

The first line of code in main creates an instance of HS071_NLP. We then create an instance of the IPOPT solver, IpoptApplication. You could use new to create a new application object, but if you want to make sure that your code would also work with a Windows DLL, you need to use the factory, as done in the example above. The call to app->Initialize(...) will initialize that object, process this options (particularly the output related options), and the call to app->OptimizeTNLP(...) will run IPOPT and try to solve the problem. By default, IPOPT will write to its progress to the console, and return the SolverReturn status.

Andreas Waechter 2010-12-22