Operate with multidimensional data using Ampl C++ API

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

  1. 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值