Operate with multidimensional data using Ampl C++ API
The exmaple of ampl C++ API
In the official webpage, the description of multi-dimentional arrays is not very clear.
This blog tries to give a more detailed tutorial for manipulating multidimensional data using Ampl C++ API.
How does Ampl represent a multidimensional data?
In Ampl, DataFrame is used to represent multidimensional data.
This is a 2-dimensional data represented in the structure of DataFrame.
(Use cout and DataFrame::to_string() we can output a data in DataFrame strucure).
index0 index1 | value
1 1 | 0.025
1 2 | 0.025
1 3 | 0.025
1 4 | 0.025
1 5 | 0.025
1 6 | 0.025
2 1 | 0.025
2 2 | 0.025
2 3 | 0.025
2 4 | 0.025
2 5 | 0.025
2 6 | 0.025
3 1 | 0.025
3 2 | 0.025
We can see that the first two columns represents the indexes of an entry and the last column represnet the value of the entry.
How to use Ampl manipulate a multidimensional data?
Set Data
After knowing how ampl represents multidimensional data, we can set our data using DataFrame (Take 2-d data as an example).
const char * headers[3] = { "index0","index1","value" };
ampl::DataFrame data(2, ampl::StringArgs(headers, 3));
data.addRow(1,1,1);
The first parameter in DataFrame construct function is the number of dimension (number of column) of your data, the second parameter is the header of each dimension.
Get Data
Follow the similar idea, we can get value from Ampl:
ampl::DataFrame x = ampl.getVariable("x").getValues();
for (int row_index = 0; row_index < x_vij.getNumRows(); row_index++)
{
ampl::DataFrame::Row row = x_vij.getRowByIndex(row_index);
int i_index = row[0].dbl() - 1;
int j_index = row[1].dbl() - 1;
double data = row[3].dbl();
x[i_index][j_index] = data;
}
Common Problems
- When setting data to DataFrame object, error “out_of_range(5)”
- When declare a DataFrame object, the header should be set. Or you can use AddColumn() to add headers for a DataFrame object.
- When addrow to a DataFrame object, the number of Variant should be consistent with the number of headers defined when initalize a DataFrame object.
- The index should start from 1 in Ampl.