In one of the previous posts I have described an API for reading .nl files. The NL reader API is now stable and documented at http://ampl.github.io/nl-reader.html. Also you can find a few examples of using it in nl-example.cc. It is still the way to go if you want to process .nl files in the most efficient way. However, if you want to load the complete optimization problem and work with it, the NL reader will require you to manage the data structures that represent the problem yourself. Fortunately, the AMPL/MP library now provides a new API for working with optimization problems and this post will introduce this new API.
The optimization problem is represented by the
mp::Problem type which provides methods
for accessing variables, objectives (multiple objectives are supported) and constraints.
It can handle all
types of optimization problems that the NL format can represent
including LP, MIP, quadratic, general nonlinear and constraint programming
Optimization problems can be constructed programmatically or read from .nl files (other input formats will be added in the future). Here’s an example of loading a problem from an .nl file:
As you can see, this example uses the NL reader API function
but passes a reference to the
Problem object instead of an NL handler as a second argument.
ReadNLFile automatically recognizes this and constructs an optimization problem
instead of sending notifications of NL constructs to it. Reading problems from memory
is also supported with
But why yet another API, doesn’t the AMPL Solver Library (ASL) have the same functionality? The difference from the ASL is that the new API is simpler, fully type-safe (no unsafe casts required), faster, and allows modification of the problem after it has been loaded that can be used to implement transformations. The new implementation is already ~36% faster on the CUTE test set and it hasn’t been even optimized yet. The current limitation is that it doesn’t provide support automatic differentiation, but this will be addressed in the future.
As for the API simplicity, here’s a concrete example of reading a problem from an .nl file and checking if the initial solution is feasible using AMPL/MP:
and the same using ASL:
Even this little example shows the advantage of the new API where you can work
with abstractions like variables and constraints rather than with a single big
ASL data structure. The new API provides iterators over problem components
which you can use with the C++ standard library algorithms. Here’s an example
that finds a variable with nonzero value:
The new API is nearly complete supporting all problems that can be represented in NL files but it is still being documented and finalized. For now you can refer to the source which is pretty straightforward and commented. Also feel free to leave questions or comments below.comments powered by Disqus