24#include "OSCommonUtil.h"
27#include "BonOsiTMINLPInterface.hpp"
30#include "CoinTime.hpp"
34using std::ostringstream;
48 cout <<
"inside BonminSolver destructor" << endl;
61 cout <<
"leaving BonminSolver destructor" << endl;
75 for(i = 0; i < n; i++){
76 if( varType[i] ==
'B') {
77 var_types[i] = BINARY;
80 if( varType[i] ==
'I') {
84 var_types[i] = CONTINUOUS;
95 std::cout <<
"Initialize Nonlinear Structures" << std::endl;
108 std::map<int, int> varIndexMap;
109 std::map<int, int>::iterator posVarIndexMap;
115 for(i = 0; i < n; i++){
116 var_types[ i] = Ipopt::TNLP::LINEAR;
122 for(posVarIndexMap = varIndexMap.begin(); posVarIndexMap != varIndexMap.end(); ++posVarIndexMap){
123 std::cout <<
"Variable Index = " << posVarIndexMap->first << std::endl ;
124 var_types[ posVarIndexMap->first] = Ipopt::TNLP::NON_LINEAR;
126 std::cout <<
"Number of nonlinear variables = " << varIndexMap.size() << std::endl;
135 for(i = 0; i < m; i++){
136 const_types[ i] = Ipopt::TNLP::LINEAR;
144 for(i = 0; i < mm; i++){
158 Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style)
165 cout <<
"Bonmin number variables !!!!!!!!!!!!!!!!!!!!!!!!!!!" << n << endl;
166 cout <<
"Bonmin number constraints !!!!!!!!!!!!!!!!!!!!!!!!!!!" << m << endl;
187 cout <<
"nnz_jac_g !!!!!!!!!!!!!!!!!!!!!!!!!!!" << nnz_jac_g << endl;
191 cout <<
"This is a linear program" << endl;
200 cout <<
"print nnz_h_lag (OSBonminSolver.cpp)" << endl;
201 cout <<
"nnz_h_lag !!!!!!!!!!!!!!!!!!!!!!!!!!!" << nnz_h_lag << endl;
202 cout <<
"set index_style (OSBonminSolver.cpp)" << endl;
204 index_style = TNLP::C_STYLE;
205 cout <<
"return from get_nlp_info (OSBonminSolver.cpp)" << endl;
214 Index m, Number* g_l, Number* g_u){
222 for(i = 0; i < n; i++){
223 x_l[ i] = mdVarLB[ i];
224 x_u[ i] = mdVarUB[ i];
225 cout <<
"x_l !!!!!!!!!!!!!!!!!!!!!!!!!!!" << x_l[i] << endl;
226 cout <<
"x_u !!!!!!!!!!!!!!!!!!!!!!!!!!!" << x_u[i] << endl;
238 for(
int i = 0; i < m; i++){
239 g_l[ i] = mdConLB[ i];
240 g_u[ i] = mdConUB[ i];
241 cout <<
"lower !!!!!!!!!!!!!!!!!!!!!!!!!!!" << g_l[i] << endl;
242 cout <<
"upper !!!!!!!!!!!!!!!!!!!!!!!!!!!" << g_u[i] << endl;
250 bool init_z, Number* z_L, Number* z_U, Index m,
bool init_lambda,
255 assert(init_x ==
true);
256 assert(init_z ==
false);
257 assert(init_lambda ==
false);
261 cout <<
"get initial values !!!!!!!!!!!!!!!!!!!!!!!!!! " << endl;
266 cout <<
"get number of initial values !!!!!!!!!!!!!!!!!!!!!!!!!! " << endl;
267 cout <<
"Is osoption = NULL? " << (
osoption == NULL) << endl;
275 cout <<
"number of variables initialed: " << m1 << endl;
280 initialed =
new bool[n1];
282 cout <<
"number of variables in total: " << n1 << endl;
286 for(k = 0; k < n1; k++)
287 initialed[k] =
false;
292 cout <<
"get initial values " << endl;
297 cout <<
"done " << endl;
303 for(k = 0; k < m1; k++)
305 i = initVarVector[k]->
idx;
306 if (initVarVector[k]->idx > n1)
307 throw ErrorClass (
"Illegal index value in variable initialization");
309 initval = initVarVector[k]->
value;
312 throw ErrorClass (
"Initial value outside of bounds");
317 throw ErrorClass (
"Initial value outside of bounds");
322 throw ErrorClass (
"Initial value outside of bounds");
325 x[initVarVector[k]->
idx] = initval;
326 initialed[initVarVector[k]->idx] =
true;
330 { cout <<
"Error in BonminProblem::get_starting_point (OSBonminSolver.cpp)";
331 cout << endl << endl << endl;
335 double default_initval;
336 default_initval = 1.7171;
338 for(k = 0; k < n1; k++)
343 x[k] = default_initval;
349 x[k] = default_initval;
355 x[k] = default_initval;
362 for(i = 0; i < n1; i++){
363 std::cout <<
"INITIAL VALUE !!!!!!!!!!!!!!!!!!!! " << x[ i] << std::endl;
382 if( CommonUtil::ISOSNAN( (
double)obj_value) )
return false;
399 for(i = 0; i < n; i++){
400 grad_f[ i] = objGrad[ i];
403 std::cout <<
"DONE WITH Calculate Objective function gradient " << std::endl;
412 for(i = 0; i < m; i++){
413 if( CommonUtil::ISOSNAN( (
double)conVals[ i] ) )
return false;
427 Index m, Index nele_jac, Index* iRow, Index *jCol,
430 if (values == NULL) {
445 for(idx = 0; idx < m; idx++){
446 for(k = *(sparseJacobian->
starts + idx); k < *(sparseJacobian->
starts + idx + 1); k++){
448 jCol[i] = *(sparseJacobian->
indexes + k);
465 for(
int i = 0; i < nele_jac; i++){
466 values[ i] = sparseJacobian->
values[i];
477 Number obj_factor, Index m,
const Number* lambda,
478 bool new_lambda, Index nele_hess, Index* iRow,
479 Index* jCol, Number* values){
485 if (values == NULL) {
496 for(i = 0; i < nele_hess; i++){
506 double* objMultipliers =
new double[1];
507 objMultipliers[0] = obj_factor;
510 delete[] objMultipliers;
514 delete[] objMultipliers;
517 for(i = 0; i < nele_hess; i++){
518 values[ i] = *(sparseHessian->
hessValues + i);
526 bool& use_x_scaling, Index n,
528 bool& use_g_scaling, Index m,
547 Index n,
const Number* x, Number obj_value)
551 std::cout<<
"Problem status: "<<
status<<std::endl;
552 std::cout<<
"Objective value: "<<obj_value<<std::endl;
554 std::cout<<
"Solution:"<<std::endl;
555 for(
int i = 0 ; i < n ; i++){
556 std::cout<<
"x["<<i<<
"] = "<<x[i];
557 if(i < n-1) std::cout<<
", ";
559 std::cout<<std::endl;
562 printf(
"\n\nObjective value\n");
563 printf(
"f(x*) = %e\n", obj_value);
565 ostringstream outStr;
566 double* mdObjValues =
new double[1];
567 std::string message =
"Bonmin solver finishes to the end.";
568 std::string solutionDescription =
"";
574 throw ErrorClass(
"OSResult error: setServiceName");
576 throw ErrorClass(
"OSResult error: setInstanceName");
583 throw ErrorClass(
"OSResult error: setVariableNumer");
585 throw ErrorClass(
"OSResult error: setObjectiveNumber");
587 throw ErrorClass(
"OSResult error: setConstraintNumber");
589 throw ErrorClass(
"OSResult error: setSolutionNumer");
593 throw ErrorClass(
"OSResult error: setGeneralMessage");
597 solutionDescription =
"SUCCESS[BONMIN]: Algorithm terminated successfully at a locally optimal point, satisfying the convergence tolerances.";
601 mdObjValues[0] = obj_value;
604 case MAXITER_EXCEEDED:
605 solutionDescription =
"MAXITER_EXCEEDED[BONMIN]: Maximum number of iterations exceeded.";
609 mdObjValues[0] = obj_value;
612 case STOP_AT_TINY_STEP:
613 solutionDescription =
"STOP_AT_TINY_STEP[BONMIN]: Algorithm proceeds with very little progress.";
617 mdObjValues[0] = obj_value;
620 case STOP_AT_ACCEPTABLE_POINT:
621 solutionDescription =
"STOP_AT_ACCEPTABLE_POINT[BONMIN]: Algorithm stopped at a point that was converged, not to _desired_ tolerances, but to _acceptable_ tolerances";
625 mdObjValues[0] = obj_value;
628 case LOCAL_INFEASIBILITY:
629 solutionDescription =
"LOCAL_INFEASIBILITY[BONMIN]: Algorithm converged to a point of local infeasibility. Problem may be infeasible.";
632 case USER_REQUESTED_STOP:
633 solutionDescription =
"USER_REQUESTED_STOP[BONMIN]: The user call-back function intermediate_callback returned false, i.e., the user code requested a premature termination of the optimization.";
636 case DIVERGING_ITERATES:
637 solutionDescription =
"DIVERGING_ITERATES[BONMIN]: It seems that the iterates diverge.";
640 case RESTORATION_FAILURE:
641 solutionDescription =
"RESTORATION_FAILURE[BONMIN]: Restoration phase failed, algorithm doesn't know how to proceed.";
644 case ERROR_IN_STEP_COMPUTATION:
645 solutionDescription =
"ERROR_IN_STEP_COMPUTATION[BONMIN]: An unrecoverable error occurred while IPOPT tried to compute the search direction.";
648 case INVALID_NUMBER_DETECTED:
649 solutionDescription =
"INVALID_NUMcatBER_DETECTED[BONMIN]: Algorithm received an invalid number (such as NaN or Inf) from the NLP; see also option check_derivatives_for_naninf.";
653 solutionDescription =
"INTERNAL_ERROR[BONMIN]: An unknown internal error occurred. Please contact the IPOPT authors through the mailing list.";
657 solutionDescription =
"OTHER[BONMIN]: other unknown solution status from Bonmin solver";
662 delete[] mdObjValues;
674 delete[] mdObjValues;
696 std::cout <<
"THERE IS AN ERROR" << std::endl;
710 bonmin.initializeOptionsAndJournalist();
712 bonmin.roptions()->AddStringOption2(
"print_solution",
"Do we print the solution or not?",
714 "no",
"No, we don't.",
715 "yes",
"Yes, we do.",
716 "A longer comment can be put here");
719 bonmin.options()->SetNumericValue(
"bonmin.time_limit", 1000);
720 bonmin.options()->SetStringValue(
"mu_oracle",
"loqo");
723 bonmin.readOptionsFile(
"Mybonmin.opt");
724 bonmin.readOptionsFile();
727 bonmin.readOptionsString(
"bonmin.algorithm B-BB\n");
731 bonmin.options()->GetEnumValue(
"print_solution", printSolution,
"");
732 if(printSolution == 1){
733 tminlp->printSolutionAtEndOfAlgorithm();
744 std::vector<SolverOption*> optionsVector;
748 int num_bonmin_options = optionsVector.size();
749 for(i = 0; i < num_bonmin_options; i++){
750 std::cout <<
"bonmin solver option " << optionsVector[ i]->name << std::endl;
751 if(optionsVector[ i]->type ==
"numeric" ){
752 std::cout <<
"FOUND A NUMERIC OPTION " <<
os_strtod( optionsVector[ i]->value.c_str(), &pEnd ) << std::endl;
753 bonmin.options()->SetNumericValue(optionsVector[ i]->name,
os_strtod( optionsVector[ i]->value.c_str(), &pEnd ) );
755 else if(optionsVector[ i]->type ==
"integer" ){
756 std::cout <<
"FOUND AN INTEGER OPTION " << atoi( optionsVector[ i]->value.c_str() ) << std::endl;
757 bonmin.options()->SetIntegerValue(optionsVector[ i]->name, atoi( optionsVector[ i]->value.c_str() ) );
759 else if(optionsVector[ i]->type ==
"string" ){
760 bonmin.options()->SetStringValue(optionsVector[ i]->name, optionsVector[ i]->value);
768 std::cout <<
"THERE IS AN ERROR" << std::endl;
780 std::cout <<
"set Solver Options for Gus" << std::endl;
782 std::cout <<
"done setting set Solver Options for Gus" << std::endl;
785 double start = CoinCpuTime();
793 double duration = CoinCpuTime() - start;
794 cout <<
"Parsing took (seconds): "<< duration << endl;
802 catch(TNLPSolver::UnsolvedError *E) {
804 std::cerr<<
"Ipopt has failed to solve a problem"<<std::endl;
806 catch(OsiTMINLPInterface::SimpleError &E) {
807 std::cerr<<E.className()<<
"::"<<E.methodName()
809 <<E.message()<<std::endl;
811 catch(CoinError &E) {
812 std::cerr<<E.className()<<
"::"<<E.methodName()
814 <<E.message()<<std::endl;
827 std::cout <<
"Finish Bonmin Optimize" << std::endl;
829 std::cout <<
"Finish writing the osrl" << std::endl;
866 else cout <<
"problem is a maximization" << endl;
U * GetRawPtr(const OSSmartPtr< U > &smart_ptr)
double os_strtod(const char *s00, char **se)
bool printSol_
Method called by Ipopt at the end of optimization.
virtual ~BonminProblem()
the BonminProblem class destructor
virtual bool get_constraints_linearity(Ipopt::Index m, Ipopt::TNLP::LinearityType *const_types)
Pass the type of the constraints (LINEAR, NON_LINEAR) to the optimizer.
virtual bool eval_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Number *g)
Method to return the constraint residuals.
virtual void finalize_solution(Bonmin::TMINLP::SolverReturn status_, Ipopt::Index n, const Ipopt::Number *x, Ipopt::Number obj_value)
Method called by Ipopt at the end of optimization.
virtual bool get_nlp_info(Ipopt::Index &n, Ipopt::Index &m, Ipopt::Index &nnz_jac_g, Ipopt::Index &nnz_h_lag, Ipopt::TNLP::IndexStyleEnum &index_style)
Method to pass the main dimensions of the problem to Ipopt.
virtual bool eval_grad_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number *grad_f)
Method to return the gradient of the objective.
virtual bool get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number *x, bool init_z, Ipopt::Number *z_L, Ipopt::Number *z_U, Ipopt::Index m, bool init_lambda, Ipopt::Number *lambda)
Method to return the starting point for the algorithm.
virtual bool get_variables_types(Ipopt::Index n, VariableType *var_types)
Pass the type of the variables (INTEGER, BINARY, CONTINUOUS) to the optimizer.
virtual bool eval_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number &obj_value)
Method to return the objective value.
virtual bool get_variables_linearity(Ipopt::Index n, Ipopt::TNLP::LinearityType *var_types)
Pass info about linear and nonlinear variables.
virtual bool get_bounds_info(Ipopt::Index n, Ipopt::Number *x_l, Ipopt::Number *x_u, Ipopt::Index m, Ipopt::Number *g_l, Ipopt::Number *g_u)
Bonmin specific methods for defining the nlp problem.
std::string bonminErrorMsg
Bonmin::TMINLP::SolverReturn status
BonminProblem(OSInstance *osinstance_, OSOption *osoption_)
the BonminProblemclass constructor
virtual bool eval_h(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number obj_factor, Ipopt::Index m, const Ipopt::Number *lambda, bool new_lambda, Ipopt::Index nele_hess, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values)
Method to return: 1) The structure of the hessian of the lagrangian (if "values" is NULL) 2) The valu...
virtual bool get_scaling_parameters(Ipopt::Number &obj_scaling, bool &use_x_scaling, Ipopt::Index n, Ipopt::Number *x_scaling, bool &use_g_scaling, Ipopt::Index m, Ipopt::Number *g_scaling)
Method to pass the main dimensions of the problem to Ipopt.
virtual bool eval_jac_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Index nele_jac, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values)
Method to return: 1) The structure of the jacobian (if "values" is NULL) 2) The values of the jacobia...
std::string bonminErrorMsg
Ipopt::SmartPtr< BonminProblem > tminlp
virtual void setSolverOptions()
The implementation of the virtual functions.
virtual void buildSolverInstance()
buildSolverInstance is a virtual function – the actual solvers will implement their own buildSolverIn...
void dataEchoCheck()
use this for debugging, print out the instance that the solver thinks it has and compare this with th...
OSiLReader * m_osilreader
m_osilreader is an OSiLReader object used to create an osinstance from an osil string if needed
OSoLReader * m_osolreader
m_osolreader is an OSoLReader object used to create an osoption from an osol string if needed
~BonminSolver()
the IpoptSolver class destructor
virtual void solve()
solve results in an instance being read into the Bonmin data structrues and optimized
BonminSolver()
the BonminSolver class constructor
std::string osol
osol holds the options for the solver
bool bSetSolverOptions
bSetSolverOptions is set to true if setSolverOptions has been called, false otherwise
std::string osrl
osrl holds the solution or result of the model
OSInstance * osinstance
osinstance holds the problem instance in-memory as an OSInstance object
bool bCallbuildSolverInstance
bCallbuildSolverInstance is set to true if buildSolverService has been called
std::string osil
osil holds the problem instance as a std::string
OSOption * osoption
osoption holds the solver options in-memory as an OSOption object
OSResult * osresult
osresult holds the solution or result of the model in-memory as an OSResult object
used for throwing exceptions.
std::string errormsg
errormsg is the error that is causing the exception to be thrown
double value
initial value
Variables * variables
variables is a pointer to a Variables object
Objectives * objectives
objectives is a pointer to a Objectives object
The in-memory representation of an OSiL instance..
SparseJacobianMatrix * calculateAllConstraintFunctionGradients(double *x, double *objLambda, double *conLambda, bool new_x, int highestOrder)
Calculate the gradient of all constraint functions.
double * getConstraintLowerBounds()
Get constraint lower bounds.
int getNumberOfQuadraticTerms()
Get the number of specified (usually nonzero) qTerms in the quadratic coefficients.
double * getVariableUpperBounds()
Get variable upper bounds.
SparseJacobianMatrix * getJacobianSparsityPattern()
int getNumberOfNonlinearExpressionTreeModIndexes()
Get the number of unique nonlinear expression tree indexes after modifying the expression tree to con...
bool bUseExpTreeForFunEval
bUseExpTreeForFunEval is set to true if you wish to use the OS Expression Tree for function evaluatio...
std::string getInstanceDescription()
Get instance description.
std::string getInstanceSource()
Get instance source.
int getConstraintNumber()
Get number of constraints.
double * calculateAllConstraintFunctionValues(double *x, double *objLambda, double *conLambda, bool new_x, int highestOrder)
Calculate all of the constraint function values.
int getLinearConstraintCoefficientNumber()
Get number of specified (usually nonzero) linear constraint coefficient values.
char * getVariableTypes()
Get variable initial values.
double * calculateAllObjectiveFunctionValues(double *x, double *objLambda, double *conLambda, bool new_x, int highestOrder)
Calculate all of the objective function values.
SparseMatrix * getLinearConstraintCoefficientsInColumnMajor()
Get linear constraint coefficients in column major.
double * calculateObjectiveFunctionGradient(double *x, double *objLambda, double *conLambda, int objIdx, bool new_x, int highestOrder)
Calculate the gradient of the objective function indexed by objIdx.
int * getNonlinearExpressionTreeModIndexes()
Get all the nonlinear expression tree indexes, i.e., indexes of rows (objectives or constraints) that...
double ** getDenseObjectiveCoefficients()
getDenseObjectiveCoefficients.
bool initForAlgDiff()
This should be called by nonlinear solvers using callback functions.
InstanceData * instanceData
A pointer to an InstanceData object.
int getNumberOfNonlinearExpressions()
Get number of nonlinear expressions.
SparseHessianMatrix * getLagrangianHessianSparsityPattern()
std::map< int, int > getAllNonlinearVariablesIndexMap()
QuadraticTerms * getQuadraticTerms()
Get all the quadratic terms in the instance.
double * getVariableLowerBounds()
Get variable lower bounds.
int getVariableNumber()
Get number of variables.
std::string * getVariableNames()
Get variable names.
std::string getInstanceName()
Get instance name.
SparseHessianMatrix * calculateLagrangianHessian(double *x, double *objLambda, double *conLambda, bool new_x, int highestOrder)
Calculate the Hessian of the Lagrangian Expression Tree This method will build the CppAD expression t...
std::string * getConstraintNames()
Get constraint names.
std::string * getObjectiveMaxOrMins()
Get objective maxOrMins.
double * getConstraintUpperBounds()
Get constraint upper bounds.
int getObjectiveNumber()
Get number of objectives.
InitVarValue ** getInitVarValuesSparse()
Get the initial values associated with the variables in sparse form.
int getNumberOfInitVarValues()
Get the number of initial variable values.
std::vector< SolverOption * > getSolverOptions(std::string solver_name)
Get the options associated with a given solver.
int getNumberOfSolverOptions()
Get the number of solver options.
bool setGeneralMessage(std::string message)
Set the general message.
bool setPrimalVariableValues(int solIdx, double *x, int n)
Set the [i]th optimization solution's primal variable values, where i equals the given solution index...
bool setSolutionNumber(int number)
set the number of solutions.
bool setInstanceName(std::string instanceName)
Set instance name.
bool setGeneralStatusType(std::string type)
Set the general status type, which can be: success, error, warning.
bool setObjectiveNumber(int objectiveNumber)
Set the objective number.
bool setObjectiveValues(int solIdx, double *objectiveValues, int n)
Set the [i]th optimization solution's objective values, where i equals the given solution index.
bool setServiceName(std::string serviceName)
Set service name.
bool setVariableNumber(int variableNumber)
Set the variable number.
bool setSolutionStatus(int solIdx, std::string type, std::string description)
Set the [i]th optimization solution status, where i equals the given solution index.
bool setConstraintNumber(int constraintNumber)
Set the constraint number.
Used to read an OSiL string.
OSInstance * readOSiL(const std::string &osil)
parse the OSiL model instance.
Used to read an OSoL string.
OSOption * readOSoL(const std::string &osol)
parse the OSoL solver options.
Take an OSResult object and write a string that validates against OSrL.
std::string writeOSrL(OSResult *theosresult)
create an osrl string from an OSResult object
std::string maxOrMin
declare the objective function to be a max or a min
int numberOfObjectives
numberOfObjectives is the number of objective functions in the instance
Objective ** obj
coef is pointer to an array of ObjCoef object pointers
int * varTwoIndexes
varTwoIndexes holds an integer array of the second variable indexes of all the quadratic terms.
int * rowIndexes
rowIndexes holds an integer array of row indexes of all the quadratic terms.
double * coefficients
coefficients holds a double array all the quadratic term coefficients.
int * varOneIndexes
varOneIndexes holds an integer array of the first variable indexes of all the quadratic terms.
The in-memory representation of a SparseHessianMatrix..
int * hessRowIdx
hessRowIdx is an integer array of row indices in the range 0, ..., n - 1.
int hessDimension
hessDimension is the number of nonzeros in each array.
double * hessValues
hessValues is a double array of the Hessian values.
int * hessColIdx
hessColIdx is an integer array of column indices in the range 0, ..., n - 1.
a sparse Jacobian matrix data structure
int * indexes
indexes holds an integer array of variable indices.
int valueSize
valueSize is the dimension of the values array
int * starts
starts holds an integer array of start elements, each start element points to the start of partials f...
double * values
values holds a double array of nonzero partial derivatives
int * indexes
indexes holds an integer array of rowIdx (or colIdx) elements in coefMatrix (AMatrix).
int * starts
starts holds an integer array of start elements in coefMatrix (AMatrix), which points to the start of...
double * values
values holds a double array of value elements in coefMatrix (AMatrix), which contains nonzero element...
double ub
ub corresponds to the optional attribute that holds the variable upper bound.
double lb
lb corresponds to the optional attribute that holds the variable lower bound.
Variable ** var
Here we define a pointer to an array of var pointers.