/home/coin/SVN-release/OS-1.0.0/OS/src/OSSolverInterfaces/KnitroSolver.cpp

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

Generated on Thu May 15 22:15:05 2008 by  doxygen 1.4.7