Include AMPL model in C++ files


I’m using AMPL through the C++ API.
I wrote a .mod file that I am able to read with"model.mod").
However, I would like my final executable not to depend on additional files, while keeping the model in a .mod file. I can think of ways to convert my .mod file to a .hpp header file where the model is converted into strings that become available at compile time, and read them with ampl.eval(). But that seems convoluted. Is there a recommended practice for the case?


1 Like

Hi @fontanf,

You can either use some tool to embed the model file into C++ code (e.g., GitHub - end2endzone/bin2cpp: bin2cpp: The easiest way to embed small files into a c++ executable. bin2cpp converts text or binary files to C++ files (*.h, *.cpp) for easy access within the code.) or you can use multi-line strings as follows:

ampl::AMPL ampl;
set NUTR; \
set FOOD; \
param cost {FOOD} > 0; \
param f_min {FOOD} >= 0; \
param f_max {j in FOOD} >= f_min[j]; \
param n_min {NUTR} >= 0; \
param n_max {i in NUTR} >= n_min[i]; \
param amt {NUTR,FOOD} >= 0; \
var Buy {j in FOOD} >= f_min[j], <= f_max[j]; \
minimize Total_Cost:  sum {j in FOOD} cost[j] * Buy[j]; \
subject to Diet {i in NUTR}: \
  n_min[i] <= sum {j in FOOD} amt[i,j] * Buy[j] <= n_max[i]; \

You need to end every line with “\”. In order to keep your .mod file you can write a small program to generate the multiline string and place it into some header file (e.g., model.h with const char *model = "...";) that you include in your application.

Hi @fdabrandao,

I didn’t know about bin2cpp. I tried and it seems to work very well.
Thank you for the quick answer.

1 Like