/Users/kmartin/Documents/files/code/cpp/OScpp/COIN-OS/OS/src/OSSolverInterfaces/OSKnitroSolver.cpp

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

Generated on Sat Mar 29 22:38:02 2008 by  doxygen 1.5.3