Recently, I used Gurobi to solve an flow-based LP problem, in which the c++ interfaces were called in my project.
I packed the relevant c++ interfaces into a class ( class Cdtn_flow; ), where the key function is illustrated as follows:
void Cdtn_flow::try_to_solve_the_model( void )
{
try
{
// ============================= 0. Find all the possible flows.
find_all_possible_flows();
// ============================= 1. Add variables into Model.
// ---- Print-Test:
cout << "\t--- Before adding vars into model, "
<< "\n\tthe size of Bus_set: " << m_BIDSet.size()
<< "\n\tthe size of Hlp_set: " << m_HIDSet.size()
<< "\n\tthe size of Sub_set: " << m_SIDSet.size()
<< "\n\tthe size of allArcs: " << m_allArcs.size()
<< endl;
add_vars_into_model();
// ============================= 2. Set the objective of the model.
// The objective is to minimize the sum of flows sourced from S-node.
setObjective_of_the_model( GRB_MINIMIZE );
// ============================= 3. Add Constraints.
addConstrs();
// ============================= 4. Solve the model.
solve_the_model();
// ============================= 5. print Solution.
print_solution();
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
LogFile::instance()->m_of_opt_result
<< "Error code = " << e.getErrorCode() << endl;
LogFile::instance()->m_of_opt_result << e.getMessage() << endl;
}
catch (...)
{
cout << "Exception during optimization" << endl;
LogFile::instance()->m_of_opt_result
<< "Exception during optimization" << endl;
}
}
From this function, we can see the logic to solve an optimization.
Within which, there is a big error I made in the function setObjective_of_the_model( GRB_MINIMIZE ). This error is shown as:
void Cdtn_flow::setObjective_of_the_model( int nModel_sense )
{
GRBLinExpr sumOptimal = 0;
// ---ERROR-->| Index should be within both 1~10( Bus_IDs ) and 15~17( SUb_IDs ).
//for ( int j = 1; j <= m_nCNT_Flow_su; j++ )
//{
// sumOptimal += flow_su[j];
//}
// == RIGHT -->| Index is within both 1~10( Bus_IDs ) + 15~17( SUb_IDs ).
for ( vector<int>::iterator Bit = m_BIDSet.begin(); Bit != m_BIDSet.end(); ++Bit )
{
int nBusID = *Bit;
sumOptimal += flow_su[ nBusID ];
}
for ( vector<int>::iterator it = m_SIDSet.begin(); it != m_SIDSet.end(); ++it )
{
int nSubID = *it;
sumOptimal += flow_su[ nSubID ];
}
model.setObjective( sumOptimal, nModel_sense );
model.update();
}
The mistake is caused by misunderstanding of the index of the obj_flow_sum. As a result, it always shows the Error hints in console window:
Error Code: 20001
Variable not in model.
I find that, the exception is always thrown at the line 24 of the function setObjective_of_the_model(..).
That is because, the variable flow_su[idx] was calculated in a wrong way, it can not be added into the model of course.
// --- Davy_H
// --- 2013-02-14 :~