/home/coin/SVN-release/OS-2.4.2/OS/src/OSSolverInterfaces/OSKnitroSolver.cpp

Go to the documentation of this file.
00001 /* $Id: OSKnitroSolver.cpp 4292 2011-09-21 05:47:18Z kmartin $ */
00021 #include "OSKnitroSolver.h"
00022 #include "OSCommonUtil.h"
00023 
00024 using std::cout;
00025 using std::endl;
00026 using std::ostringstream;
00027 using namespace std;
00028 
00029 #if defined(_WIN32)
00030 #include  <windows.h>     //-- FOR LoadLibrary
00031 #else
00032 #include  <dlfcn.h>       //-- FOR dlopen
00033 #endif
00034 
00035 
00036 //--------------------------------------------------------------------
00037 //  Static variables and data
00038 //--------------------------------------------------------------------
00039 
00040 static NlpProblemDef *  g_pTheNlpProblemDefInstance = NULL;
00041 
00042 //for calling the solver and feeding the nlp problem
00043 static NlpProblemDef *  g_pOptProblem = NULL;
00044 
00045 static int  wrapperEvalFC (const int             evalRequestCode,
00046                            const int             n,
00047                            const int             m,
00048                            const int             nnzJ,
00049                            const int             nnzH,
00050                            const double * const  daX,
00051                            const double * const  daLambda,
00052                            double * const  dObj,
00053                            double * const  daC,
00054                            double * const  daG,
00055                            double * const  daJ,
00056                            double * const  daH,
00057                            double * const  daHV,
00058                            void   *        userParams)
00059 {
00060     if (g_pOptProblem == NULL)
00061     {
00062         cout << "*** Problem not defined  <wrapperEvalFC>\n";
00063         return( -1 );
00064     }
00065     if (evalRequestCode != KTR_RC_EVALFC)
00066     {
00067         cout << "*** Bad request code " << evalRequestCode
00068              << "  <wrapperEvalFC>\n";
00069         return( -1 );
00070     }
00071     return( g_pOptProblem->evalFC (daX, dObj, daC, userParams) );
00072 }//wrapperEvalFC
00073 
00074 
00075 //--------------------------------------------------------------------
00076 //  Internal Function:  wrapperEvalGA
00077 //--------------------------------------------------------------------
00081 static int  wrapperEvalGA (const int             evalRequestCode,
00082                            const int             n,
00083                            const int             m,
00084                            const int             nnzJ,
00085                            const int             nnzH,
00086                            const double * const  daX,
00087                            const double * const  daLambda,
00088                            double * const  dObj,
00089                            double * const  daC,
00090                            double * const  daG,
00091                            double * const  daJ,
00092                            double * const  daH,
00093                            double * const  daHV,
00094                            void   *        userParams)
00095 {
00096     if (g_pOptProblem == NULL)
00097     {
00098         cout << "*** Problem not defined  <wrapperEvalGA>\n";
00099         return( -1 );
00100     }
00101     if (evalRequestCode != KTR_RC_EVALGA)
00102     {
00103         cout << "*** Bad request code " << evalRequestCode
00104              << "  <wrapperEvalGA>\n";
00105         return( -1 );
00106     }
00107     return( g_pOptProblem->evalGA (daX, daG, daJ, userParams) );
00108 }//wrapperEvalGA
00109 
00110 
00111 //--------------------------------------------------------------------
00112 //  Internal Function:  wrapperEvalHorHV
00113 //--------------------------------------------------------------------
00117 static int  wrapperEvalHorHV (const int             evalRequestCode,
00118                               const int             n,
00119                               const int             m,
00120                               const int             nnzJ,
00121                               const int             nnzH,
00122                               const double * const  daX,
00123                               const double * const  daLambda,
00124                               double * const  dObj,
00125                               double * const  daC,
00126                               double * const  daG,
00127                               double * const  daJ,
00128                               double * const  daH,
00129                               double * const  daHV,
00130                               void   *        userParams)
00131 {
00132     if (g_pOptProblem == NULL)
00133     {
00134         cout << "*** Problem not defined  <wrapperEvalHorHV>\n";
00135         return( -1 );
00136     }
00137     if (evalRequestCode == KTR_RC_EVALH)
00138     {
00139         if (g_pOptProblem->areDerivativesImplemented (nCAN_COMPUTE_H) == false)
00140         {
00141             cout << "*** This problem not evaluate H  <wrapperEvalHorHV>\n";
00142             return( -1 );
00143         }
00144         return( g_pOptProblem->evalH (daX, daLambda, daH, userParams) );
00145     }
00146     else if (evalRequestCode == KTR_RC_EVALHV)
00147     {
00148         if (g_pOptProblem->areDerivativesImplemented (nCAN_COMPUTE_HV) == false)
00149         {
00150             cout << "*** This problem not evaluate H*v  <wrapperEvalHorHV>\n";
00151             return( -1 );
00152         }
00153         return( g_pOptProblem->evalHV (daX, daLambda, daHV, userParams) );
00154     }
00155     else
00156     {
00157         cout << "*** Bad request code " << evalRequestCode
00158              << "  <wrapperEvalHorHV>\n";
00159         return( -1 );
00160     }
00161 }//wrapperEvalHorHV
00162 
00163 
00164 
00165 //--------------------------------------------------------------------
00166 //  Exported Function:  getNlpProblemDef
00167 //--------------------------------------------------------------------
00168 //++ Export a function that returns the static pointer to this class.
00169 #ifdef __cplusplus
00170 extern "C"
00171 {
00172 #if defined(_WIN32)
00173     __declspec(dllexport) NlpProblemDef *  getNlpProblemDef (void)
00174 #else
00175     NlpProblemDef *  getNlpProblemDef (void)
00176 #endif
00177     {
00178         if (g_pTheNlpProblemDefInstance == NULL)
00179             g_pTheNlpProblemDefInstance = new KnitroProblem(NULL, NULL);
00180 
00181         return( g_pTheNlpProblemDefInstance );
00182     }
00183 }
00184 #endif
00185 
00186 
00187 KnitroProblem::KnitroProblem(OSInstance *osinstance_,  OSResult *osresult_ )
00188 {
00189 
00190     _daXInit = NULL;
00191     osinstance = osinstance_;
00192     osresult = osresult_;
00193 }
00194 
00195 
00196 
00197 KnitroProblem::~KnitroProblem()
00198 {
00199     delete [] _daXInit;
00200     _daXInit = NULL;
00201 }
00202 
00203 
00204 
00205 //--------------------------------------------------------------------
00206 //  Simple access methods
00207 //--------------------------------------------------------------------
00208 
00209 int  KnitroProblem::getN (void)
00210 {
00211     return( _nN );
00212 }//getN
00213 
00214 
00215 int  KnitroProblem::getM (void)
00216 {
00217     return( _nM );
00218 }//getM
00219 
00220 
00221 void  KnitroProblem::getInitialX (double * const  daX)
00222 {
00223     if (_daXInit == NULL)
00224     {
00225         cout << "*** Must call 'loadProblemIntoKnitro' before 'KnitroSolver::getInitialX'\n";
00226         exit( EXIT_FAILURE );
00227     }
00228 
00229     for (int  i = 0; i < _nN; i++)
00230     {
00231         daX[i] = _daXInit[i];
00232     }
00233     return;
00234 }//getM
00235 
00236 //--------------------------------------------------------------------
00237 //  Method:  loadProblemIntoKnitro
00238 //--------------------------------------------------------------------
00242 bool  KnitroProblem::loadProblemIntoKnitro (KTR_context_ptr  kc)
00243 {
00244     int i;
00245     if(osinstance->getObjectiveNumber() <= 0) throw ErrorClass("Knitro NEEDS AN OBJECTIVE FUNCTION");
00246     // number of variables
00247     _nN = osinstance->getVariableNumber();
00248     // number of constraints
00249     _nM = osinstance->getConstraintNumber();
00250     cout << "number variables  !!!!!!!!!!!!!!!!!!!!!!!!!!!"   <<   _nN << endl;
00251     cout << "number constraints  !!!!!!!!!!!!!!!!!!!!!!!!!!!" <<   _nM << endl;
00252     try
00253     {
00254         osinstance->initForAlgDiff( );
00255     }
00256     catch(const ErrorClass& eclass)
00257     {
00258         knitroErrorMsg = eclass.errormsg;
00259         throw;
00260     }
00261 
00262     // variables lower bounds
00263     double * mdVarLB = osinstance->getVariableLowerBounds();
00264     std::cout << "GET BOUNDS INFORMATION FOR KNITRO!!!!!!!!!!!!!!!" << std::endl;
00265     // variables upper bounds
00266     double * mdVarUB = osinstance->getVariableUpperBounds();
00267 
00268     _daXLo  = new double[_nN];
00269     _daXUp  = new double[_nN];
00270     for(i = 0; i < _nN; i++)
00271     {
00272         if( mdVarLB[ i] == -OSDBL_MAX) _daXLo[i] = -KTR_INFBOUND;
00273         else _daXLo[i] = mdVarLB[ i];
00274         if( mdVarUB[ i] == OSDBL_MAX) _daXUp[i] = KTR_INFBOUND;
00275         else _daXUp[i] = mdVarUB[ i];
00276         //cout << "x_l !!!!!!!!!!!!!!!!!!!!!!!!!!!" << x_l[i] << endl;
00277         //cout << "x_u !!!!!!!!!!!!!!!!!!!!!!!!!!!" << x_u[i] << endl;
00278     }
00279 
00280     //constraint lower bounds
00281     double * mdConLB = osinstance->getConstraintLowerBounds();
00282     //constraint upper bounds
00283     double * mdConUB = osinstance->getConstraintUpperBounds();
00284 
00285     _naCType = new int[ _nM];
00286     _daCLo   = new double[ _nM];
00287     _daCUp   = new double[ _nM];
00288     _naCType[0] = KTR_CONTYPE_LINEAR;
00289     for(i = 0; i < _nM; i++)
00290     {
00291         if( mdConLB[ i] == -OSDBL_MAX) _daCLo[i] = -KTR_INFBOUND;
00292         else _daCLo[i] = mdConLB[ i];
00293         if( mdConUB[ i] == OSDBL_MAX) _daCUp[i] = KTR_INFBOUND;
00294         else _daCUp[i] = mdConUB[ i];
00295         //cout << "lower !!!!!!!!!!!!!!!!!!!!!!!!!!!" << _daCLo[i] << endl;
00296         //cout << "upper !!!!!!!!!!!!!!!!!!!!!!!!!!!" << _daCUp[i] << endl;
00297         _naCType[i] = KTR_CONTYPE_GENERAL; //need change
00298     }
00299 
00300     // use the OS Expression tree for function evaluations instead of CppAD
00301     osinstance->bUseExpTreeForFunEval = true;
00302     std::cout << "Call sparse jacobian" << std::endl;
00303     SparseJacobianMatrix *sparseJacobian = NULL;
00304     try
00305     {
00306         sparseJacobian = osinstance->getJacobianSparsityPattern();
00307     }
00308     catch(const ErrorClass& eclass)
00309     {
00310         knitroErrorMsg = eclass.errormsg;
00311         throw;
00312     }
00313     std::cout << "Done calling sparse jacobian" << std::endl;
00314     _nNnzJ = sparseJacobian->valueSize;
00315     //cout << "_nNnzJ  !!!!!!!!!!!!!!!!!!!!!!!!!!!" << _nNnzJ << endl;
00316     _naJacIndexVars = new int[_nNnzJ];
00317     _naJacIndexCons = new int[_nNnzJ];
00318     int k, idx;
00319     i = 0;
00320     for(idx = 0; idx < _nM; idx++)
00321     {
00322         for(k = *(sparseJacobian->starts + idx); k < *(sparseJacobian->starts + idx + 1); k++)
00323         {
00324             _naJacIndexCons[i] = idx;
00325             _naJacIndexVars[i] = *(sparseJacobian->indexes + k);
00326             //cout << "ROW IDX  !!!!!!!!!!!!!!!!!!!!!!!!!!!"  << _naJacIndexCons[i] << endl;
00327             //cout << "COL IDX  !!!!!!!!!!!!!!!!!!!!!!!!!!!"  << _naJacIndexVars[i] << endl;
00328             i++;
00329         }
00330     }
00331 
00332 
00333     // nonzeros in upper hessian
00334     if( (osinstance->getNumberOfNonlinearExpressions() == 0) && (osinstance->getNumberOfQuadraticTerms() == 0) )
00335     {
00336         cout << "This is a linear program"  << endl;
00337         _nNnzH = 0;
00338     }
00339     else
00340     {
00341         std::cout << "Get Lagrangain Hessian Sparsity Pattern " << std::endl;
00342         SparseHessianMatrix *sparseHessian = osinstance->getLagrangianHessianSparsityPattern();
00343         std::cout << "Done Getting Lagrangain Hessian Sparsity Pattern " << std::endl;
00344         _nNnzH = sparseHessian->hessDimension;
00345         _naHessRows = new int[_nNnzH];
00346         _naHessCols = new int[_nNnzH];
00347         for(i = 0; i < _nNnzH; i++)
00348         {
00349             _naHessCols[i] = *(sparseHessian->hessColIdx + i);
00350             _naHessRows[i] = *(sparseHessian->hessRowIdx + i);
00351             cout << "ROW HESS IDX  !!!!!!!!!!!!!!!!!!!!!!!!!!!"  << _naHessRows[i] << endl;
00352             cout << "COL HESS IDX  !!!!!!!!!!!!!!!!!!!!!!!!!!!"  << _naHessCols[i] << endl;
00353         }
00354     }
00355     //---- INITIAL GUESS FOR x AND lambda.
00356     // Here, we assume we only have starting values for x, if you code
00357     // your own NLP, you can provide starting values for the dual variables
00358     // if you wish
00359     //cout << "get initial values !!!!!!!!!!!!!!!!!!!!!!!!!! " << endl;
00360     double *mdXInit = osinstance->getVariableInitialValues();
00361     _daXInit = new double[_nN];
00362     if( mdXInit != NULL)
00363     {
00364         for(i = 0; i < _nN; i++)
00365         {
00366             if(  CommonUtil::ISOSNAN( mdXInit[ i])  == true)
00367             {
00368                 _daXInit[ i] = 1.7171;
00369             }
00370             else _daXInit[ i] = mdXInit[ i];
00371         }
00372     }
00373     else
00374     {
00375         for(i = 0; i < _nN; i++)
00376         {
00377             _daXInit[ i] = 1.7171;
00378         }
00379     }
00380     //cout << "got initial values !!!!!!!!!!!!!!!!!!!!!!!!!! " << endl;
00381 
00382     double *  daLambdaInit = new double[_nM + _nN];
00383     for (i = 0; i < _nM + _nN; i++)
00384         daLambdaInit[i] = 0.0;
00385 
00386     // set obj type
00387     int iObjSense = KTR_OBJGOAL_MINIMIZE;
00388     if( osinstance->instanceData->objectives->obj[ 0]->maxOrMin.compare("max") == 0)
00389     {
00390         iObjSense = KTR_OBJGOAL_MAXIMIZE;
00391     }
00392     int iObjType = KTR_OBJTYPE_GENERAL; //KTR_OBJTYPE_LINEAR, KTR_OBJTYPE_QUADRATIC
00393     i = KTR_init_problem (kc, _nN,
00394                           iObjSense, iObjType,
00395                           _daXLo, _daXUp,
00396                           _nM, _naCType, _daCLo, _daCUp,
00397                           _nNnzJ, _naJacIndexVars, _naJacIndexCons,
00398                           _nNnzH, _naHessRows, _naHessCols,
00399                           _daXInit, daLambdaInit);
00400 
00401     delete [] _daXLo;
00402     delete [] _daXUp;
00403     delete [] _naCType;
00404     delete [] _daCLo;
00405     delete [] _daCUp;
00406     delete [] _naJacIndexVars;
00407     delete [] _naJacIndexCons;
00408     delete [] _naHessRows;
00409     delete [] _naHessCols;
00410     delete [] daLambdaInit;
00411 
00412     if (i != 0)
00413     {
00414         cout << "*** KTR_init_problem() returned " << i << "\n";
00415         return( false );
00416     }
00417 
00418     return( true );
00419 }//loadProblemIntoKnitro
00420 
00421 //--------------------------------------------------------------------
00422 //  Method:  areDerivativesImplemented
00423 //--------------------------------------------------------------------
00424 bool  KnitroProblem::areDerivativesImplemented(const DerivativesImplementedType  nWhichDers)
00425 {
00426     if (nWhichDers == nCAN_COMPUTE_GA)
00427         return( true );
00428     if (nWhichDers == nCAN_COMPUTE_H)
00429         return( true );
00430     if (nWhichDers == nCAN_COMPUTE_HV)
00431         return( false);
00432     return( false );
00433 }//areDerivativesImplemented
00434 
00435 
00436 //--------------------------------------------------------------------
00437 //  Method:  evalFC
00438 //--------------------------------------------------------------------
00439 int  KnitroProblem::evalFC (const double * const  daX,
00440                             double * const  dObj,
00441                             double * const  daC,
00442                             void   *        userParams)
00443 {
00444     try
00445     {
00446         *dObj  = osinstance->calculateAllObjectiveFunctionValues((double*)daX, NULL, NULL, true, 0 )[0];
00447     }
00448     catch(const ErrorClass& eclass)
00449     {
00450         knitroErrorMsg = eclass.errormsg;
00451         return (-1);
00452     }
00453     if( CommonUtil::ISOSNAN( *dObj )) return (-1);
00454 
00455 
00456 
00457     try
00458     {
00459         double *conVals = osinstance->calculateAllConstraintFunctionValues((double*)daX, NULL, NULL, true, 0 );
00460         int i;
00461         for(i = 0; i < _nM; i++)
00462         {
00463             if( CommonUtil::ISOSNAN( (double)conVals[ i] ) ) return (-1);
00464             daC[i] = conVals[ i]  ;
00465         }
00466     }
00467     catch(const ErrorClass& eclass)
00468     {
00469         knitroErrorMsg = eclass.errormsg;
00470         return (-1);
00471     }
00472 
00473 
00474     return( 0 );
00475 }//evalFC
00476 
00477 
00478 //--------------------------------------------------------------------
00479 //  Method:  evalGA
00480 //--------------------------------------------------------------------
00481 int  KnitroProblem::evalGA (const double * const  daX,
00482                             double * const  daG,
00483                             double * const  daJ,
00484                             void   *        userParams)
00485 {
00486     try
00487     {
00488         double *objGrad = osinstance->calculateAllObjectiveFunctionGradients((double*)daX, NULL, NULL, true, 1 )[0];
00489         int i;
00490         std::cout << "EVALUATING OBJ GRADIENT" << std::endl;
00491         for(i = 0; i < _nN; i++)
00492         {
00493             if( CommonUtil::ISOSNAN( (double)objGrad[ i] ) ) return (-1);
00494             daG[i] = objGrad[ i]  ;
00495         }
00496     }
00497     catch(const ErrorClass& eclass)
00498     {
00499         knitroErrorMsg = eclass.errormsg;
00500         return (-1);
00501     }
00502 
00503     SparseJacobianMatrix *sparseJacobian;
00504     std::cout << "EVALUATING JACOBIAN" << std::endl;
00505     try
00506     {
00507         sparseJacobian = osinstance->calculateAllConstraintFunctionGradients((double*)daX, NULL, NULL,  true, 1);
00508     }
00509     catch(const ErrorClass& eclass)
00510     {
00511         knitroErrorMsg = eclass.errormsg;
00512         return (-1);
00513     }
00514     //osinstance->getIterateResults( (double*)x, 0.0, NULL, -1, true,  1);
00515     for(int i = 0; i < _nNnzJ; i++)
00516     {
00517         daJ[ i] = sparseJacobian->values[i];
00518         //daJ[ i] = osinstance->m_mdJacValue[ i];
00519         cout << "daJ[i]:!!!!!!!!!!!!  " <<  daJ[ i] << endl;
00520         //cout << "m_mdJacValue[ i]:!!!!!!!!!!!!  " <<  osinstance->m_mdJacValue[ i] << endl;
00521     }
00522 
00523     return( 0 );
00524 }//evalGA
00525 
00526 
00527 //--------------------------------------------------------------------
00528 //  Method:  evalH
00529 //--------------------------------------------------------------------
00530 int  KnitroProblem::evalH (const double * const  daX,
00531                            const double * const  daLambda,
00532                            double * const  daH,
00533                            void   *        userParams)
00534 {
00535     SparseHessianMatrix *sparseHessian;
00536     int i;
00537     double* objMultipliers = new double[1];
00538     objMultipliers[0] = 1;
00539     try
00540     {
00541         sparseHessian = osinstance->calculateLagrangianHessian((double*)daX, objMultipliers, (double*)daLambda ,  true, 2);
00542     }
00543     catch(const ErrorClass& eclass)
00544     {
00545         knitroErrorMsg = eclass.errormsg;
00546         return (-1);
00547     }
00548     for(i = 0; i < _nNnzH; i++)
00549     {
00550         daH[ i]  = *(sparseHessian->hessValues + i);
00551         std::cout << "Hessian Value = " << daH[ i] << std::endl;
00552     }
00553     delete[] objMultipliers;
00554     return( 0 );
00555 }//evalH
00556 
00557 
00558 //--------------------------------------------------------------------
00559 //  Method:  evalHV
00560 //--------------------------------------------------------------------
00561 int  KnitroProblem::evalHV (const double * const  daX,
00562                             const double * const  daLambda,
00563                             double * const  daHV,
00564                             void   *        userParams)
00565 {
00566 
00567     return( 0 );
00568 }//evalHV
00569 
00570 //OS specific default solver methods
00571 
00572 
00573 KnitroSolver::KnitroSolver()
00574 {
00575     osrlwriter = new OSrLWriter();
00576     osresult = new OSResult();
00577     knitroErrorMsg = "";
00578 
00579 }
00580 
00581 
00582 void KnitroSolver::buildSolverInstance() throw (ErrorClass)
00583 {
00584     try
00585     {
00586 
00587     }
00588     catch(const ErrorClass& eclass)
00589     {
00590         std::cout << "THERE IS AN ERROR" << std::endl;
00591         osresult->setGeneralMessage( eclass.errormsg);
00592         osresult->setGeneralStatusType( "error");
00593         osrl = osrlwriter->writeOSrL( osresult);
00594         throw ErrorClass( osrl) ;
00595     }
00596 }//end buildSolverInstance()
00597 
00598 
00599 
00600 
00601 void Knitro::setSolverOptions() throw (ErrorClass)
00602 {
00603     try
00604     {
00605 
00606     }
00607     catch(const ErrorClass& eclass)
00608     {
00609         std::cout << "THERE IS AN ERROR" << std::endl;
00610         osresult->setGeneralMessage( eclass.errormsg);
00611         osresult->setGeneralStatusType( "error");
00612         osrl = osrlwriter->writeOSrL( osresult);
00613         throw ErrorClass( osrl) ;
00614     }
00615 }//end setSolverOptions()
00616 
00617 KnitroSolver::~KnitroSolver()
00618 {
00619 #ifdef DEBUG
00620     cout << "inside KnitroSolver destructor" << endl;
00621 #endif
00622     delete osresult;
00623     osresult = NULL;
00624     delete osrlwriter;
00625     osrlwriter = NULL;
00626     //delete osinstance;
00627     //osinstance = NULL;
00628 #ifdef DEBUG
00629     cout << "leaving KnitroSolver destructor" << endl;
00630 #endif
00631 }
00632 
00633 void KnitroSolver::solve() throw (ErrorClass)
00634 {
00635     try
00636     {
00637         OSiLReader* osilreader = NULL;
00638         //osresult = new OSResult();
00639         if(osil.length() == 0 && osinstance == NULL) throw ErrorClass("there is no instance");
00640         clock_t start, finish;
00641         double duration;
00642         start = clock();
00643         bool newOSiLReader = false;
00644         if( osinstance == NULL)
00645         {
00646             osilreader = new OSiLReader();
00647             osinstance = osilreader->readOSiL( osil);
00648             newOSiLReader = true;
00649         }
00650         OSiLWriter osilwriter;
00651         //cout << osilwriter.writeOSiL( osinstance) << endl;
00652         if(osinstance->getVariableNumber() <= 0)throw ErrorClass("Knitro requires decision variables");
00653         finish = clock();
00654         duration = (double) (finish - start) / CLOCKS_PER_SEC;
00655         cout << "Parsing took (seconds): "<< duration << endl;
00656         //dataEchoCheck();
00657 
00658         /***************now the Knitro invokation*********************/
00659         // Create a new instance of your nlp
00660         NlpProblemDef *pOptProb = new KnitroProblem(osinstance, osresult);
00661         bool bWantToSolve;
00662 
00663         //---- OPEN A NEW INSTANCE OF KNITRO.
00664         KTR_context  *kc;
00665         kc = KTR_new();
00666         if (kc == NULL)
00667         {
00668             cout << "*** KTR_new failed, maybe a license issue?\n";
00669             exit( EXIT_FAILURE );
00670         }
00671 
00672         //---- APPLY ANY USER OPTIONS (PROCEED EVEN IF THERE IS AN ERROR).
00673         KTR_load_param_file (kc, "knitro.opt");
00674         //---- LOAD THE PROBLEM INTO KNITRO.
00675         if (pOptProb->loadProblemIntoKnitro ( kc) == false)
00676         {
00677             cout << "*** loadProblemIntoKnitro failed\n";
00678             exit( EXIT_FAILURE );
00679         }
00680 
00681         //---- SET CALLBACK POINTERS FOR EVALUATION OF PROBLEM INFORMATION.
00682         //---- IF THE TEST CODE DOES NOT SUPPLY DERIVATIVES, THEN THE
00683         //---- USER OPTIONS IN "knitro.opt" SHOULD REQUEST AN ALTERNATIVE,
00684         //---- SUCH AS FINITE DIFFERENCES.
00685         g_pOptProblem = pOptProb;
00686         if (KTR_set_func_callback (kc, wrapperEvalFC) != 0)
00687         {
00688             cout << "*** KTR_set_func_callback failed\n";
00689             exit( EXIT_FAILURE );
00690         }
00691         if (pOptProb->areDerivativesImplemented (nCAN_COMPUTE_GA) == true)
00692         {
00693             if (KTR_set_grad_callback (kc, wrapperEvalGA) != 0)
00694             {
00695                 cout << "*** KTR_set_grad_callback failed\n";
00696                 exit( EXIT_FAILURE );
00697             }
00698         }
00699         if ((pOptProb->areDerivativesImplemented (nCAN_COMPUTE_H) == true)
00700                 || (pOptProb->areDerivativesImplemented (nCAN_COMPUTE_HV) == true))
00701         {
00702             if (KTR_set_hess_callback (kc, wrapperEvalHorHV) != 0)
00703             {
00704                 cout << "*** KTR_set_hess_callback failed\n";
00705                 exit( EXIT_FAILURE );
00706             }
00707         }
00708 
00709         //---- ALLOCATE ARRAYS
00710         double *  daX      = new double[pOptProb->getN()];
00711         double *  daLambda = new double[pOptProb->getM() + pOptProb->getN()];
00712         double* mdObjValues = new double[1];
00713         bWantToSolve = true;
00714         if (bWantToSolve == true)
00715         {
00716             //---- CALL KNITRO AND SOLVE.
00717             double  dFinalObj;
00718             int  nStatus = KTR_solve (kc, daX, daLambda, 0, &dFinalObj,
00719                                       NULL, NULL, NULL, NULL, NULL, NULL);
00720             std::cout << "dFinalObj =  " << dFinalObj << std::endl;
00721             cout << "*** Final KNITRO status = " << nStatus << "\n";
00722             cout << "dax[0] = " << daX[0] << "\n";
00723 
00724             //construct osresult
00725             int solIdx = 0;
00726 
00727             std::string message = "Knitro solver finishes to the end.";
00728             std::string solutionDescription = "";
00729 
00730             // resultHeader infomration
00731             if(osresult->setServiceName( "Knitro solver service") != true)
00732                 throw ErrorClass("OSResult error: setServiceName");
00733             if(osresult->setInstanceName(  osinstance->getInstanceName()) != true)
00734                 throw ErrorClass("OSResult error: setInstanceName");
00735 
00736             //if(osresult->setJobID( osoption->jobID) != true)
00737             //  throw ErrorClass("OSResult error: setJobID");
00738 
00739             // set basic problem parameters
00740             if(osresult->setVariableNumber( osinstance->getVariableNumber()) != true)
00741                 throw ErrorClass("OSResult error: setVariableNumer");
00742             if(osresult->setObjectiveNumber( 1) != true)
00743                 throw ErrorClass("OSResult error: setObjectiveNumber");
00744             if(osresult->setConstraintNumber( osinstance->getConstraintNumber()) != true)
00745                 throw ErrorClass("OSResult error: setConstraintNumber");
00746             if(osresult->setSolutionNumber(  1) != true)
00747                 throw ErrorClass("OSResult error: setSolutionNumer");
00748 
00749 
00750             if(osresult->setGeneralMessage( message) != true)
00751                 throw ErrorClass("OSResult error: setGeneralMessage");
00752             std::cout << "START CASES  " << 0 << endl;
00753             switch( nStatus)
00754             {
00755             case 0:
00756                 std::cout << "WE ARE IN CASE " << 0 << endl;
00757                 solutionDescription = "LOCALLY OPTIMAL SOLUTION FOUND[KNITRO STATUS 0]: Knitro found a locally optimal point which satisfies the stopping criterion.If the problem is convex (for example, a linear program), then this point corresponds to a globally optimal solution.";
00758                 osresult->setSolutionStatus(solIdx,  "locallyOptimal", solutionDescription);
00759                 std::cout << "SET SOLUTION STATUS " << endl;
00760                 osresult->setPrimalVariableValuesDense(solIdx, daX);
00761                 std::cout << "SET PRIMAL VALUES " << endl;
00762                 osresult->setDualVariableValuesDense(solIdx, daLambda);
00763                 mdObjValues[0] = dFinalObj;
00764                 osresult->setObjectiveValuesDense(solIdx, mdObjValues);
00765                 std::cout << "SET OBJECTIVE VALUES " << endl;
00766                 break;
00767             case -1:
00768                 solutionDescription = "Iteration limit reached[KNITRO STATUS -1]: The iteration limit was reached before being able to satisfy the required stopping criteria.";
00769                 osresult->setSolutionStatus(solIdx,  "stoppedByLimit", solutionDescription);
00770                 osresult->setPrimalVariableValuesDense(solIdx, daX);
00771                 osresult->setDualVariableValuesDense(solIdx, daLambda);
00772                 mdObjValues[0] = dFinalObj;
00773                 osresult->setObjectiveValuesDense(solIdx, mdObjValues);
00774                 break;
00775             case -2:
00776                 solutionDescription = "Convergence to an infeasible point[KNITRO STATUS -2]: Problem may be locally infeasible.The algorithm has converged to an infeasible point from which it cannot further decrease the infeasibility measure. This happens when the problem is infeasible, but may also occur on occasion for feasible problems with nonlinear constraints or badly scaled problems. It is recommended to try various initial points. If this occurs for a variety of initial points, it is likely the problem is infeasible.";
00777                 osresult->setSolutionStatus(solIdx,  "infeasible", solutionDescription);
00778                 break;
00779             case -3:
00780                 solutionDescription = "Problem appears to be unbounded[KNITRO STATUS -3]: Iterate is feasible and objective magnitude > objrange. The objective function appears to be decreasing without bound, while satisfying the constraints.If the problem really is bounded, increase the size of the parameter objrange to avoid terminating with this message.";
00781                 osresult->setSolutionStatus(solIdx,  "unbounded", solutionDescription);
00782                 break;
00783             case -4:
00784                 solutionDescription = "Relative change in solution estimate < xtol[KNITRO STATUS -4]: The relative change in the solution estimate is less than that specified by the paramater xtol.To try to get more accuracy one may decrease xtol. If xtol is very small already, it is an indication that no more significant progress can be made. If the current point is feasible, it is possible it may be optimal, however the stopping tests cannot be satisfied (perhaps because of degeneracy, ill-conditioning or bad scaling).";
00785                 osresult->setSolutionStatus(solIdx,  "stoppedByLimit", solutionDescription);
00786                 osresult->setPrimalVariableValuesDense(solIdx, daX);
00787                 osresult->setDualVariableValuesDense(solIdx, daLambda);
00788                 mdObjValues[0] = dFinalObj;
00789                 osresult->setObjectiveValuesDense(solIdx, mdObjValues);
00790                 break;
00791             case -5:
00792                 solutionDescription = "Current solution estimate cannot be improved. Point appears to be optimal, but desired accuracy could not be achieved.[KNITRO  STATUS -5]: No more progress can be made, but the stopping tests are close to being satisfied (within a factor of 100) and so the current approximate solution is believed to be optimal.";
00793                 osresult->setSolutionStatus(solIdx,  "locallyOptimal", solutionDescription);
00794                 osresult->setPrimalVariableValuesDense(solIdx, daX);
00795                 osresult->setDualVariableValuesDense(solIdx, daLambda);
00796                 mdObjValues[0] = dFinalObj;
00797                 osresult->setObjectiveValuesDense(solIdx, mdObjValues);
00798                 break;
00799             case -6:
00800                 solutionDescription = "Time limit reached[KNITRO STATUS -6]: The time limit was reached before being able to satisfy the required stopping criteria.";
00801                 osresult->setSolutionStatus(solIdx,  "stoppedByLimit", solutionDescription);
00802                 osresult->setPrimalVariableValuesDense(solIdx, daX);
00803                 osresult->setDualVariableValuesDense(solIdx, daLambda);
00804                 mdObjValues[0] = dFinalObj;
00805                 osresult->setObjectiveValuesDense(solIdx, mdObjValues);
00806                 break;
00807             case -50:
00808             case -51:
00809             case -52:
00810             case -53:
00811             case -54:
00812             case -55:
00813             case -56:
00814             case -57:
00815             case -58:
00816             case -59:
00817             case -60:
00818                 solutionDescription = "Input Error[KNITRO STATUS -50 to -60]: Termination values in this range imply some input error. If outlev>0 details of this error will be printed to standard output or the file knitro.log depending on the value of outmode.";
00819                 osresult->setSolutionStatus(solIdx,  "error", solutionDescription);
00820                 break;
00821             case -90:
00822                 solutionDescription = "Callback function error[KNITRO STATUS -90]: This termination value indicates that an error (i.e., negative return value) occurred in a user provided callback routine.";
00823                 osresult->setSolutionStatus(solIdx,  "error", solutionDescription);
00824                 break;
00825             case -97:
00826                 solutionDescription = "LP solver error[KNITRO STATUS -97]: This termination value indicates that an unrecoverable error occurred in the LP solver used in the active-set algorithm preventing the optimization from continuing.";
00827                 osresult->setSolutionStatus(solIdx,  "error", solutionDescription);
00828                 break;
00829             case -98:
00830                 solutionDescription = "Evaluation error[KNITRO STATUS -98]: This termination value indicates that an evaluation error occurred (e.g., divide by 0, taking the square root of a negative number), preventing the optimization from continuing.";
00831                 osresult->setSolutionStatus(solIdx,  "error", solutionDescription);
00832                 break;
00833             case -99:
00834                 solutionDescription = "Not enough memory available to solve problem[KNITRO STATUS -99]: This termination value indicates that there was not enough memory available to solve the problem.";
00835                 osresult->setSolutionStatus(solIdx,  "error", solutionDescription);
00836                 break;
00837             default:
00838                 solutionDescription = "OTHER[KNITRO]: other unknown solution status from Knitro solver";
00839                 osresult->setSolutionStatus(solIdx,  "other", solutionDescription);
00840             }
00841 
00842             osresult->setGeneralStatusType("normal");
00843             osrl = osrlwriter->writeOSrL( osresult);
00844         }
00845         else
00846         {
00847             //---- USE KNITRO TO CHECK THE DERIVATIVES CODED IN THE TEST PROBLEM.
00848             pOptProb->getInitialX (daX);
00849             KTR_check_first_ders (kc, daX, 2, 1.0e-14, 1.0e-14,
00850                                   0, 0.0, NULL, NULL, NULL, NULL);
00851         }
00852 
00853         if(newOSiLReader == true)
00854         {
00855             delete osilreader;
00856             osilreader = NULL;
00857         }
00858         delete [] daX;
00859         delete [] daLambda;
00860         delete [] mdObjValues;
00861 
00862         KTR_free( &kc);
00863         delete pOptProb;
00864 
00865 
00866         //return( EXIT_SUCCESS );       //to do
00867     }
00868     catch(const ErrorClass& eclass)
00869     {
00870         osresult->setGeneralMessage( eclass.errormsg);
00871         osresult->setGeneralStatusType( "error");
00872         osrl = osrlwriter->writeOSrL( osresult);
00873         //throw ErrorClass( osrl) ; //to do
00874     }
00875 }//solve
00876 
00877 
00878 void KnitroSolver::dataEchoCheck()
00879 {
00880 
00881     int i;
00882 
00883     // print out problem parameters
00884     cout << "This is problem:  " << osinstance->getInstanceName() << endl;
00885     cout << "The problem source is:  " << osinstance->getInstanceSource() << endl;
00886     cout << "The problem description is:  " << osinstance->getInstanceDescription() << endl;
00887     cout << "number of variables = " << osinstance->getVariableNumber() << endl;
00888     cout << "number of Rows = " << osinstance->getConstraintNumber() << endl;
00889 
00890     // print out the variable information
00891     if(osinstance->getVariableNumber() > 0)
00892     {
00893         for(i = 0; i < osinstance->getVariableNumber(); i++)
00894         {
00895             if(osinstance->getVariableNames() != NULL) cout << "variable Names  " << osinstance->getVariableNames()[ i]  << endl;
00896             if(osinstance->getVariableTypes() != NULL) cout << "variable Types  " << osinstance->getVariableTypes()[ i]  << endl;
00897             if(osinstance->getVariableLowerBounds() != NULL) cout << "variable Lower Bounds  " << osinstance->getVariableLowerBounds()[ i]  << endl;
00898             if(osinstance->getVariableUpperBounds() != NULL) cout << "variable Upper Bounds  " <<  osinstance->getVariableUpperBounds()[i] << endl;
00899         }
00900     }
00901 
00902     // print out objective function information
00903     if(osinstance->getVariableNumber() > 0 || osinstance->instanceData->objectives->obj != NULL || osinstance->instanceData->objectives->numberOfObjectives > 0)
00904     {
00905         if( osinstance->getObjectiveMaxOrMins()[0] == "min")  cout <<  "problem is a minimization" << endl;
00906         else cout <<  "problem is a maximization" << endl;
00907         for(i = 0; i < osinstance->getVariableNumber(); i++)
00908         {
00909             cout << "OBJ COEFFICIENT =  " <<  osinstance->getDenseObjectiveCoefficients()[0][i] << endl;
00910         }
00911     }
00912     // print out constraint information
00913     if(osinstance->getConstraintNumber() > 0)
00914     {
00915         for(i = 0; i < osinstance->getConstraintNumber(); i++)
00916         {
00917             if(osinstance->getConstraintNames() != NULL) cout << "row name = " << osinstance->getConstraintNames()[i] <<  endl;
00918             if(osinstance->getConstraintLowerBounds() != NULL) cout << "row lower bound = " << osinstance->getConstraintLowerBounds()[i] <<  endl;
00919             if(osinstance->getConstraintUpperBounds() != NULL) cout << "row upper bound = " << osinstance->getConstraintUpperBounds()[i] <<  endl;
00920         }
00921     }
00922 
00923     // print out linear constraint data
00924     cout << endl;
00925     cout << "number of nonzeros =  " << osinstance->getLinearConstraintCoefficientNumber() << endl;
00926     for(i = 0; i <= osinstance->getVariableNumber(); i++)
00927     {
00928         cout << "Start Value =  " << osinstance->getLinearConstraintCoefficientsInColumnMajor()->starts[ i] << endl;
00929     }
00930     cout << endl;
00931     for(i = 0; i < osinstance->getLinearConstraintCoefficientNumber(); i++)
00932     {
00933         cout << "Index Value =  " << osinstance->getLinearConstraintCoefficientsInColumnMajor()->indexes[i] << endl;
00934         cout << "Nonzero Value =  " << osinstance->getLinearConstraintCoefficientsInColumnMajor()->values[i] << endl;
00935     }
00936 
00937     // print out quadratic data
00938     cout << "number of qterms =  " <<  osinstance->getNumberOfQuadraticTerms() << endl;
00939     for(int i = 0; i <  osinstance->getNumberOfQuadraticTerms(); i++)
00940     {
00941         cout << "Row Index = " <<  osinstance->getQuadraticTerms()->rowIndexes[i] << endl;
00942         cout << "Var Index 1 = " << osinstance->getQuadraticTerms()->varOneIndexes[ i] << endl;
00943         cout << "Var Index 2 = " << osinstance->getQuadraticTerms()->varTwoIndexes[ i] << endl;
00944         cout << "Coefficient = " << osinstance->getQuadraticTerms()->coefficients[ i] << endl;
00945     }
00946 } // end dataEchoCheck
00947 
00948 
00949 NlpProblemDef::~NlpProblemDef (void)
00950 {
00951     //---- DO NOTHING.
00952     //return;
00953 }
00954 
00955 
00956 
00957 

Generated on Wed Nov 30 03:04:24 2011 by  doxygen 1.4.7