/home/coin/SVN-release/OS-2.1.1/OS/src/OSCommonInterfaces/OSInstance.cpp

Go to the documentation of this file.
00001 /* $Id: OSInstance.cpp 3488 2010-04-29 20:16:06Z kmartin $ */
00020 #include "OSInstance.h"
00021 #include "OSMathUtil.h"
00022 #include "OSErrorClass.h"
00023 #include "OSParameters.h"
00024 
00025 #include<stack>
00026 #include<iostream>  
00027 #include<sstream>
00028 
00029 //#define DEBUG
00030  
00031 using namespace std;
00032 using std::ostringstream; 
00033 
00034 
00035 OSInstance::OSInstance(): 
00036         bVariablesModified(false),
00037         bObjectivesModified(false),
00038         bConstraintsModified(false),
00039         bAMatrixModified(false),
00040         m_sInstanceName(""),
00041         m_sInstanceSource(""),  
00042         m_sInstanceDescription(""),
00043         m_bProcessVariables(false),
00044         m_iVariableNumber(-1),
00045         m_iNumberOfIntegerVariables( 0),
00046         m_iNumberOfBinaryVariables( 0),
00047         m_iNumberOfStringVariables( 0),
00048         m_iNumberOfQuadraticRowIndexes( 0),
00049         m_bQuadraticRowIndexesProcessed( false),
00050         m_miQuadRowIndexes( NULL),
00051         m_iNumberOfNonlinearExpressionTreeIndexes( 0),
00052         m_bNonlinearExpressionTreeIndexesProcessed( false),
00053         m_miNonlinearExpressionTreeIndexes( NULL),
00054         m_iNumberOfNonlinearExpressionTreeModIndexes( 0),
00055         m_bNonlinearExpressionTreeModIndexesProcessed( false),
00056         m_miNonlinearExpressionTreeModIndexes( NULL),           
00057         m_msVariableNames(NULL),
00058         //m_mdVariableInitialValues(NULL), -- deprecated
00059         //m_msVariableInitialStringValues(NULL), -- deprecated
00060         m_mcVariableTypes(NULL),
00061         m_mdVariableLowerBounds(NULL),
00062         m_mdVariableUpperBounds(NULL),
00063         m_bProcessObjectives(false),
00064         m_iObjectiveNumber(-1),
00065         m_iObjectiveNumberNonlinear( 0),
00066         m_msObjectiveNames(NULL),
00067         m_msMaxOrMins(NULL),
00068         m_miNumberOfObjCoef(NULL),
00069         m_mdObjectiveConstants(NULL),
00070         m_mdObjectiveWeights(NULL),
00071         m_mObjectiveCoefficients(NULL),
00072         m_bGetDenseObjectives(false),
00073         m_mmdDenseObjectiveCoefficients(NULL),
00074         m_bProcessConstraints(false),
00075         m_iConstraintNumber(-1),
00076         m_iConstraintNumberNonlinear( 0),       
00077         m_msConstraintNames(NULL),
00078         m_mdConstraintLowerBounds(NULL),
00079         m_mdConstraintUpperBounds(NULL),
00080         m_mdConstraintConstants( NULL),
00081         m_mcConstraintTypes(NULL),
00082         m_bProcessLinearConstraintCoefficients(false),  
00083         m_iLinearConstraintCoefficientNumber(-1),
00084         m_bColumnMajor(true),
00085         m_binitForAlgDiff( false),      
00086         m_linearConstraintCoefficientsInColumnMajor(NULL),
00087         m_linearConstraintCoefficientsInRowMajor(NULL), 
00088         m_bProcessQuadraticTerms(false),
00089         m_iQuadraticTermNumber(-1),
00090         m_mdConstraintFunctionValues( NULL),
00091         m_mdObjectiveFunctionValues( NULL),
00092         m_iJacValueSize( 0),
00093         m_miJacStart( NULL),
00094         m_miJacIndex( NULL),
00095         m_mdJacValue( NULL),
00096         m_miJacNumConTerms( NULL),
00097         m_sparseJacMatrix( NULL),       
00098         m_iHighestTaylorCoeffOrder(-1), 
00099         m_quadraticTerms( NULL),        
00100         m_bQTermsAdded( false), 
00101         m_iNumberOfNonlinearVariables( 0),
00102         m_bProcessNonlinearExpressions( false),
00103         m_iNonlinearExpressionNumber( -1),              
00104         m_miNonlinearExpressionIndexes( NULL),
00105         m_bProcessExpressionTrees( false),
00106         m_bProcessExpressionTreesMod( false),
00107         m_LagrangianExpTree(NULL),
00108         m_bLagrangianExpTreeCreated( false),
00109         m_LagrangianSparseHessian( NULL),
00110         m_bLagrangianSparseHessianCreated( false),
00111         m_miNonLinearVarsReverseMap( NULL),
00112         m_bAllNonlinearVariablesIndex( false),
00113         m_bOSADFunIsCreated( false),
00114         m_bCppADTapesBuilt( false),
00115         m_bCppADMustReTape( false),
00116         m_bDuplicateExpressionTreesMap( false),
00117         m_bNonLinearStructuresInitialized( false),
00118         m_bSparseJacobianCalculated( false),
00119         m_iHighestOrderEvaluated( -1),
00120         m_mmdObjGradient( NULL),
00121         m_bProcessTimeDomain( false),
00122         m_bProcessTimeStages( false),
00123         m_bProcessTimeInterval( false),
00124         m_bFiniteTimeStages( false),
00125         m_iNumberOfTimeStages(-1),
00126         m_msTimeDomainStageNames(NULL),
00127         m_miTimeDomainStageVariableNumber(NULL),
00128         m_mmiTimeDomainStageVarList(NULL),
00129         m_miTimeDomainStageConstraintNumber(NULL),
00130         m_mmiTimeDomainStageConList(NULL),
00131         m_miTimeDomainStageObjectiveNumber(NULL),
00132         m_mmiTimeDomainStageObjList(NULL),
00133         bUseExpTreeForFunEval( false)
00134 
00135 {    
00136         #ifdef DEBUG
00137         cout << "Inside OSInstance Constructor" << endl;
00138         #endif
00139         this->instanceHeader = new InstanceHeader();
00140         this->instanceData = new InstanceData();
00141 }  
00142 
00143 OSInstance::~OSInstance(){
00144         #ifdef DEBUG
00145         cout << "OSInstance Destructor Called" << endl;
00146         #endif
00147         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
00148         // delete  the temporary arrays
00149         
00150         if(this->instanceData->variables->numberOfVariables > 0 && m_bProcessVariables == true){
00151                 delete[] m_msVariableNames;
00152                 m_msVariableNames = NULL;
00153                 delete[] m_mcVariableTypes;
00154                 m_mcVariableTypes = NULL;
00155                 delete[] m_mdVariableLowerBounds;
00156                 m_mdVariableLowerBounds = NULL;
00157                 delete[] m_mdVariableUpperBounds;
00158                 m_mdVariableUpperBounds = NULL;
00159         }
00160         
00161         
00162         if(m_bProcessConstraints == true){
00163                 delete[] m_msConstraintNames;
00164                 m_msConstraintNames = NULL;
00165                 delete[] m_mcConstraintTypes;
00166                 m_mcConstraintTypes = NULL;
00167                 delete[]  m_mdConstraintConstants;
00168                 m_mdConstraintConstants = NULL;
00169                 delete[] m_mdConstraintLowerBounds;
00170                 m_mdConstraintLowerBounds = NULL;
00171                 delete[] m_mdConstraintUpperBounds;
00172                 m_mdConstraintUpperBounds = NULL;
00173         }
00174         
00175         
00176         int i;
00177         //if(instanceData->objectives->numberOfObjectives > 0 && m_mObjectiveCoefficients != NULL){
00178         if(m_bProcessObjectives == true ){
00179                 for(i = 0; i < instanceData->objectives->numberOfObjectives; i++){
00180                         #ifdef DEBUG
00181                         std::cout <<  "Delete m_mObjectiveCoefficients[i]" << std::endl;
00182                         #endif
00183                         delete m_mObjectiveCoefficients[i];
00184                         m_mObjectiveCoefficients[i] = NULL;
00185                 }
00186                 #ifdef DEBUG
00187                 std::cout <<  "Delete m_msObjectiveNames" << std::endl;
00188                 std::cout <<  "Delete m_msMaxOrMins" << std::endl;
00189                 std::cout <<  "Delete m_miNumberOfObjCoef" << std::endl;
00190                 std::cout <<  "Delete m_mdObjectiveConstants" << std::endl;
00191                 std::cout <<  "Delete m_mdObjectiveWeights" << std::endl;
00192                 #endif          
00193                 delete[] m_msObjectiveNames;
00194                 m_msObjectiveNames = NULL;
00195                 delete[] m_msMaxOrMins;
00196                 m_msMaxOrMins = NULL;
00197                 delete[] m_miNumberOfObjCoef;
00198                 m_miNumberOfObjCoef = NULL;
00199                 delete[] m_mdObjectiveConstants; 
00200                 m_mdObjectiveConstants = NULL;
00201                 delete[] m_mdObjectiveWeights;
00202                 m_mdObjectiveWeights = NULL;
00203                 delete[] m_mObjectiveCoefficients;
00204                 m_mObjectiveCoefficients = NULL;
00205         }
00206         
00207         if(m_bGetDenseObjectives == true){
00208                 for(i = 0; i < instanceData->objectives->numberOfObjectives; i++){
00209                         //delete m_mmdDenseObjectiveCoefficients[i];
00210                         #ifdef DEBUG
00211                         std::cout <<  "delete m_mmdDenseObjectiveCoefficients[i]" << std::endl;
00212                         #endif
00213                     delete[] m_mmdDenseObjectiveCoefficients[i];
00214                         m_mmdDenseObjectiveCoefficients[i] = NULL;
00215                 }
00216                 delete[] m_mmdDenseObjectiveCoefficients;
00217                 m_mmdDenseObjectiveCoefficients = NULL;
00218         }
00219         
00220         
00221         
00222         //if(m_bProcessLinearConstraintCoefficients == true && m_bColumnMajor == true) delete m_linearConstraintCoefficientsInColumnMajor;
00223         //if(m_bProcessLinearConstraintCoefficients == true && m_bColumnMajor == false) delete m_linearConstraintCoefficientsInRowMajor;
00224         
00225         if( m_linearConstraintCoefficientsInColumnMajor != NULL) delete m_linearConstraintCoefficientsInColumnMajor;
00226         if (m_linearConstraintCoefficientsInRowMajor != NULL ) delete m_linearConstraintCoefficientsInRowMajor;
00227         
00228         
00229         if( (m_binitForAlgDiff == true)  ){     
00230                 delete[] m_miNonLinearVarsReverseMap;
00231                 m_miNonLinearVarsReverseMap = NULL;
00232                 if(instanceData->objectives->numberOfObjectives > 0 && m_mmdObjGradient != NULL){
00233                         
00234                         #ifdef DEBUG
00235                         std::cout <<  "The number of objectives =  " << instanceData->objectives->numberOfObjectives << std::endl;
00236                         #endif
00237                         for(i = 0; i < instanceData->objectives->numberOfObjectives; i++){
00238                                 #ifdef DEBUG
00239                                 std::cout << "deleting Objective function gradient " << i << std::endl;
00240                                 #endif
00241                                 delete[] m_mmdObjGradient[i];
00242 
00243                                 m_mmdObjGradient[i] = NULL;
00244                         }
00245                         delete[] m_mmdObjGradient;
00246                         m_mmdObjGradient = NULL;
00247                 }
00248         }
00249 
00250         //std::cout << "Do garbage collection for the nonlinear API" << std::endl;
00251         // garbage collection for the gradient
00252         if(m_bNonLinearStructuresInitialized == true ){
00253                 delete[] m_mdObjectiveFunctionValues; 
00254                 m_mdObjectiveFunctionValues = NULL;     
00255                 delete[] m_mdConstraintFunctionValues;
00256                 m_mdConstraintFunctionValues = NULL;
00257         }
00258         if(m_bSparseJacobianCalculated == true){
00259                 delete[] m_miJacStart;
00260                 m_miJacStart = NULL;
00261                 delete[] m_miJacIndex;
00262                 m_miJacIndex = NULL;
00263                 delete[] m_mdJacValue;
00264                 m_mdJacValue = NULL;
00265                 delete[] m_miJacNumConTerms;
00266                 m_miJacNumConTerms = NULL;
00267         }
00268         if( m_bLagrangianExpTreeCreated == true){
00269                 delete m_LagrangianExpTree;
00270                 m_LagrangianExpTree = NULL;
00271         }
00272         if( m_bLagrangianSparseHessianCreated == true){
00273                 delete m_LagrangianSparseHessian;
00274                 m_LagrangianSparseHessian = NULL;
00275         }
00276         if( m_bSparseJacobianCalculated == true){
00277                 delete m_sparseJacMatrix;
00278                 m_sparseJacMatrix = NULL;
00279         }
00280         if( (instanceData->quadraticCoefficients->qTerm != NULL) && (m_bProcessQuadraticTerms == true) ){
00281                 delete m_quadraticTerms;
00282                 m_quadraticTerms = NULL;
00283         }
00284         if( (instanceData->quadraticCoefficients->qTerm != NULL) && (m_bQuadraticRowIndexesProcessed == true) ){
00285                 delete[] m_miQuadRowIndexes;
00286                 m_miQuadRowIndexes = NULL;
00287         }
00288         //
00289         // delete the new expression trees that got created
00290         //if( m_bLagrangianExpTreeCreated == false  ||  m_bLagrangianExpTreeCreated == true){
00291         if( (m_bProcessExpressionTrees == true) && (m_bDuplicateExpressionTreesMap == false)  ) {
00292                 for(posMapExpTree = m_mapExpressionTrees.begin(); posMapExpTree != m_mapExpressionTrees.end(); ++posMapExpTree){
00293                         std::cout << "Deleting an expression tree from the map for row  " << posMapExpTree->first  << std::endl;
00294                         delete m_mapExpressionTrees[ posMapExpTree->first ];
00295                 }
00296         }
00297         if( m_bDuplicateExpressionTreesMap == true)   {
00298                 for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){          
00299                         #ifdef DEBUG
00300                                 std::cout << "Deleting an expression tree from m_mapExpressionTreesMod" << std::endl;
00301                         #endif
00302                         delete m_mapExpressionTreesMod[ posMapExpTree->first ];
00303                 }
00304         }
00305         //}
00307         if( (m_bNonlinearExpressionTreeIndexesProcessed == true) && (m_mapExpressionTrees.size() > 0) ){
00308                 std::cout << "Deleting  m_miNonlinearExpressionTreeIndexes" << std::endl;
00309                 delete[] m_miNonlinearExpressionTreeIndexes;
00310                 std::cout << "Done Deleting  m_miNonlinearExpressionTreeIndexes" << std::endl;
00311                 m_miNonlinearExpressionTreeIndexes = NULL;
00312         }
00313         if( (m_bNonlinearExpressionTreeModIndexesProcessed == true) && (m_mapExpressionTreesMod.size() > 0) ){
00314                 std::cout << "Deleting  m_miNonlinearExpressionTreeModIndexes" << std::endl;
00315                 delete[] m_miNonlinearExpressionTreeModIndexes;
00316                 std::cout << "Done Deleting  m_miNonlinearExpressionTreeModIndexes" << std::endl;
00317                 m_miNonlinearExpressionTreeModIndexes = NULL;
00318         }
00319         if(m_bOSADFunIsCreated == true){
00320                 try{
00321 #ifdef COIN_HAS_CPPAD
00322                         delete Fad;
00323                         Fad = NULL;
00324 #else
00325                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
00326 #endif
00327                 }
00328                 catch(const ErrorClass& eclass){
00329                         throw ErrorClass( eclass.errormsg);
00330                 }
00331         }
00332 //      if( (instanceData->timeDomain->stages->stage != NULL) && (m_bProcessTimeStages == true) ){
00333 //              delete m_Stages;
00334 //              m_Stages = NULL;
00335 //      }
00336 
00337         if (m_msTimeDomainStageNames != NULL) {
00338                 delete[] m_msTimeDomainStageNames;
00339                 m_msTimeDomainStageNames = NULL;
00340         }
00341 
00342         if (m_miTimeDomainStageVariableNumber != NULL) {
00343                 delete[] m_miTimeDomainStageVariableNumber;
00344                 m_miTimeDomainStageVariableNumber = NULL;
00345         }
00346 
00347         if (m_mmiTimeDomainStageVarList != NULL) {
00348                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
00349                         delete[] m_mmiTimeDomainStageVarList[i];
00350                 delete[] m_mmiTimeDomainStageVarList;
00351                 m_mmiTimeDomainStageVarList = NULL;
00352         }
00353 
00354         if (m_miTimeDomainStageConstraintNumber != NULL) {
00355                 delete[] m_miTimeDomainStageConstraintNumber;
00356                 m_miTimeDomainStageConstraintNumber = NULL;
00357         }
00358 
00359         if (m_mmiTimeDomainStageConList != NULL) {
00360                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
00361                         delete[] m_mmiTimeDomainStageConList[i];
00362                 delete[] m_mmiTimeDomainStageConList;
00363                 m_mmiTimeDomainStageConList = NULL;
00364         }
00365 
00366         if (m_miTimeDomainStageObjectiveNumber != NULL) {
00367                 delete[] m_miTimeDomainStageObjectiveNumber;
00368                 m_miTimeDomainStageObjectiveNumber = NULL;
00369         }
00370 
00371         if (m_mmiTimeDomainStageObjList != NULL) {
00372                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
00373                         delete[] m_mmiTimeDomainStageObjList[i];
00374                 delete[] m_mmiTimeDomainStageObjList;
00375                 m_mmiTimeDomainStageObjList = NULL;
00376         }
00377 
00378         // delete the two children of OSInstance
00379         //delete instanceHeader object
00380         delete instanceHeader;
00381         instanceHeader = NULL;
00382         //delete instanceData object
00383         delete instanceData;
00384         instanceData = NULL;
00385 }//OSInstance Destructor
00386 
00387 InstanceHeader::InstanceHeader():
00388         description(""),
00389         name(""),
00390         source("")
00391 
00392 { 
00393         #ifdef DEBUG
00394         cout << "Inside the InstanceHeader Constructor" << endl;
00395         #endif
00396 } 
00397 
00398 
00399 InstanceHeader::~InstanceHeader(){
00400         #ifdef DEBUG  
00401         cout << "Inside the InstanceHeader Destructor" << endl;
00402         #endif
00403 } 
00404 
00405 Variable::Variable():
00406         lb(0.0),
00407         ub(OSDBL_MAX),
00408         //init(OSNAN),  deprecated
00409         type('C'), 
00410         name("")
00411         //initString("") deprecated
00412 {  
00413         #ifdef DEBUG
00414         cout << "Inside the Variable Constructor" << endl;
00415         #endif 
00416 } 
00417 
00418 Variable::~Variable(){  
00419         #ifdef DEBUG
00420         cout << "Inside the Variable Destructor" << endl; 
00421         #endif
00422 } 
00423 
00424 Variables::Variables(){  
00425         #ifdef DEBUG
00426         cout << "Inside the Variables Constructor" << endl; 
00427         #endif 
00428         numberOfVariables = 0;
00429         var = NULL; 
00430 }
00431 
00432 Variables::~Variables(){ 
00433         #ifdef DEBUG 
00434         cout << "Inside the Variables Destructor" << endl;
00435         #endif
00436         int i;
00437         if(numberOfVariables > 0 && var != NULL){
00438                 for(i = 0; i < numberOfVariables; i++){
00439                         #ifdef DEBUG 
00440                         cout << "Deleting var[ i]" << endl;
00441                         #endif
00442                         delete var[i];
00443                         var[i] = NULL;
00444                 }
00445         }
00446         delete[] var;
00447         var = NULL; 
00448 }  
00449 
00450 ObjCoef::ObjCoef():
00451         idx(-1),
00452         value(0.0)  
00453 {  
00454         #ifdef DEBUG
00455         cout << "Inside the Coef Constructor" << endl;
00456         #endif 
00457 }
00458 
00459 ObjCoef::~ObjCoef(){ 
00460         #ifdef DEBUG
00461         cout << "Inside the ObjCoef Destructor" << endl;  
00462         #endif
00463 }
00464 
00465 Objective::Objective():
00466         name("") ,
00467         maxOrMin("min"),
00468         constant(0.0),
00469         weight(1.0),
00470         numberOfObjCoef(0),
00471         coef(NULL)
00472 { 
00473  
00474         #ifdef DEBUG
00475         cout << "Inside the Objective Constructor" << endl;
00476         #endif
00477 }
00478 
00479 Objective::~Objective(){
00480         #ifdef DEBUG  
00481         cout << "Inside the Objective Destructor" << endl;
00482         #endif
00483         int i;
00484         if(numberOfObjCoef > 0 && coef != NULL){
00485                 for(i = 0; i < numberOfObjCoef; i++){
00486                         delete coef[i];
00487                         coef[i] = NULL;
00488                 }
00489         }
00490         delete[] coef;
00491         coef = NULL;
00492 }  
00493 
00494 Objectives::Objectives()
00495 {  
00496         #ifdef DEBUG
00497         cout << "Inside the Objectives Constructor" << endl; 
00498         #endif
00499         numberOfObjectives = 0;
00500         obj = NULL;
00501 } 
00502 
00503 Objectives::~Objectives(){ 
00504         #ifdef DEBUG 
00505         cout << "Inside the Objectives Destructor" << endl;
00506         #endif
00507         int i;
00508         if(numberOfObjectives > 0 && obj != NULL){
00509                 for(i = 0; i < numberOfObjectives; i++){
00510                         delete obj[i];
00511                         obj[i] = NULL;
00512                 }
00513         }
00514         delete[] obj;
00515         obj = NULL;
00516 }
00517 
00518 Constraint::Constraint():
00519         name(""),
00520         constant(0.0),
00521         lb(-OSDBL_MAX),
00522         ub(OSDBL_MAX)
00523 
00524 {
00525         #ifdef DEBUG  
00526         cout << "Inside the Constraint Constructor" << endl;
00527         #endif
00528 } 
00529 
00530 Constraint::~Constraint(){  
00531         #ifdef DEBUG
00532         cout << "Inside the Constraint Destructor" << endl;
00533         #endif
00534 } 
00535 
00536 Constraints::Constraints():
00537         numberOfConstraints(0),
00538         con(NULL)
00539 {
00540         #ifdef DEBUG
00541         cout << "Inside the Constraints Constructor" << endl;
00542         #endif
00543 } 
00544 
00545 Constraints::~Constraints(){  
00546         #ifdef DEBUG
00547         cout << "Inside the Constraints Destructor" << endl;
00548         #endif
00549         int i;
00550         if(numberOfConstraints > 0 && con != NULL){
00551                 for( i = 0; i < numberOfConstraints; i++){
00552                         delete con[i];
00553                         con[i] = NULL;
00554                 }
00555         }
00556         delete[] con;
00557         con = NULL;
00558 } 
00559 
00560 
00561 
00562 LinearConstraintCoefficients::LinearConstraintCoefficients():
00563         numberOfValues(0) ,
00564         iNumberOfStartElements( 0)
00565 { 
00566         #ifdef DEBUG 
00567         cout << "Inside the LinearConstraintCoefficients Constructor" << endl; 
00568         #endif
00569         start = new IntVector();
00570         rowIdx = new IntVector();
00571         colIdx = new IntVector();
00572         value = new DoubleVector();
00573 
00574 } 
00575 
00576 
00577 LinearConstraintCoefficients::~LinearConstraintCoefficients(){  
00578         #ifdef DEBUG
00579         cout << "Inside the LinearConstraintCoefficients Destructor" << endl; 
00580         #endif
00581         delete start;
00582         start = NULL;
00583         delete rowIdx;
00584         rowIdx = NULL;
00585         delete colIdx;
00586         colIdx = NULL;
00587         delete value;
00588         value = NULL;
00589 }
00590 
00591 QuadraticTerm::QuadraticTerm():
00592 
00593         idx(0),   
00594         idxOne(-1),
00595         idxTwo(-1),
00596         coef(0.0)
00597 
00598 {
00599         #ifdef DEBUG  
00600         cout << "Inside the QuadraticTerm Constructor" << endl;
00601         #endif
00602 } 
00603 
00604 
00605 QuadraticTerm::~QuadraticTerm(){  
00606         #ifdef DEBUG
00607         cout << "Inside the QuadraticTerm Destructor" << endl;
00608         #endif
00609 }
00610 
00611 
00612 
00613 QuadraticCoefficients::QuadraticCoefficients():
00614         numberOfQuadraticTerms(0),
00615         qTerm(NULL)
00616 { 
00617         #ifdef DEBUG 
00618         cout << "Inside the QuadraticCoefficients Constructor" << endl;
00619         #endif
00620 }//end QuadraticCoefficients() 
00621 
00622 
00623 QuadraticCoefficients::~QuadraticCoefficients(){
00624         #ifdef DEBUG  
00625         cout << "Inside the QuadraticCoefficients Destructor" << endl;
00626         #endif
00627         int i;
00628         if(numberOfQuadraticTerms > 0 && qTerm != NULL){
00629                 for( i = 0; i < numberOfQuadraticTerms; i++){
00630                         delete qTerm[i];
00631                         qTerm[i] = NULL;
00632                 }
00633         }
00634         delete[] qTerm;
00635         qTerm = NULL;  
00636 }//end ~QuadraticCoefficients()  
00637 
00638 
00639 Nl::Nl(){
00640         idx = 0;
00641         osExpressionTree = NULL;
00642         m_bDeleteExpressionTree = true;
00643 }//end Nl
00644  
00645  
00646 Nl::~Nl(){
00647         #ifdef DEBUG  
00648         cout << "Inside the Nl Destructor" << endl;
00649         #endif
00650         // don't delete the expression tree if we created a map of the expression
00651         // trees, otherwise we would destroy twice
00652         if( m_bDeleteExpressionTree == true){
00653                 delete osExpressionTree;
00654                 osExpressionTree = NULL;
00655         }
00656 }//end ~Nl
00657 
00658 
00659 
00660 NonlinearExpressions::NonlinearExpressions():
00661         numberOfNonlinearExpressions(0) ,
00662         nl(NULL)
00663 { 
00664         #ifdef DEBUG 
00665         cout << "Inside the NonlinearExpressions Constructor" << endl;
00666         #endif
00667 }//end NonlinearExpressions() 
00668 
00669 NonlinearExpressions::~NonlinearExpressions(){
00670         #ifdef DEBUG  
00671         cout << "Inside the NonlinearExpressions Destructor" << endl;
00672         cout << "NUMBER OF NONLINEAR EXPRESSIONS = " << numberOfNonlinearExpressions << endl;
00673         #endif
00674         int i;
00675         if(numberOfNonlinearExpressions > 0 && nl != NULL){
00676                 for( i = 0; i < numberOfNonlinearExpressions; i++){
00677                         #ifdef DEBUG  
00678                                 cout << "DESTROYING EXPRESSION " << nl[ i]->idx << endl;
00679                         #endif
00680                         delete nl[i];
00681                         nl[i] = NULL;
00682                 }
00683         }
00684         delete[] nl;
00685         nl = NULL;  
00686 }//end ~NonlinearExpressions()  
00687 
00688 
00689 TimeDomainStageVar::TimeDomainStageVar():
00690         idx(0)
00691 {
00692         #ifdef DEBUG 
00693         cout << "Inside the Stage Objectives Var Constructor" << endl;
00694         #endif
00695 } // end TimeDomainStageVar
00696 
00697 
00698 TimeDomainStageVar::~TimeDomainStageVar()
00699 {
00700         #ifdef DEBUG 
00701         cout << "Inside the Stage Objectives Var Destructor" << endl;
00702         #endif
00703 } // end ~TimeDomainStageVar
00704 
00705 
00706 TimeDomainStageVariables::TimeDomainStageVariables():
00707         numberOfVariables(0),
00708         startIdx(-1)
00709 {
00710         #ifdef DEBUG 
00711         cout << "Inside the Stage Variables Constructor" << endl;
00712         #endif
00713         var = NULL;
00714 } // end TimeDomainStageVariables
00715 
00716 TimeDomainStageVariables::~TimeDomainStageVariables()
00717 {
00718         #ifdef DEBUG 
00719         cout << "Inside the Stage Variables Destructor" << endl;
00720         #endif
00721         if (numberOfVariables > 0 && var != NULL){
00722                 for (int i = 0; i < numberOfVariables; i++) {
00723                         delete var[i];
00724                         var[i] = NULL;
00725                 }
00726         }
00727         delete [] var;
00728         var = NULL;
00729 } // end ~TimeDomainStageVariables
00730 
00731 TimeDomainStageCon::TimeDomainStageCon():
00732         idx(0)
00733 {
00734         #ifdef DEBUG 
00735         cout << "Inside the Stage Objectives Con Constructor" << endl;
00736         #endif
00737 } // end TimeDomainStageCon
00738 
00739 
00740 TimeDomainStageCon::~TimeDomainStageCon()
00741 {
00742         #ifdef DEBUG 
00743         cout << "Inside the Stage Objectives Con Destructor" << endl;
00744         #endif
00745 } // end ~TimeDomainStageCon
00746 
00747 
00748 TimeDomainStageConstraints::TimeDomainStageConstraints():
00749         numberOfConstraints(0),
00750         startIdx(-1)
00751 {
00752         #ifdef DEBUG 
00753         cout << "Inside the Stage Constraints Constructor" << endl;
00754         #endif
00755         con = NULL;
00756 } // end TimeDomainStageConstraints
00757 
00758 TimeDomainStageConstraints::~TimeDomainStageConstraints()
00759 {
00760         #ifdef DEBUG 
00761         cout << "Inside the Stage Constraints Destructor" << endl;
00762         #endif
00763         if (numberOfConstraints > 0 && con != NULL){
00764                 for (int i = 0; i < numberOfConstraints; i++) {
00765                         delete con[i];
00766                         con[i] = NULL;
00767                 }
00768         }
00769         delete [] con;
00770         con = NULL;
00771 } // end ~TimeDomainStageConstraints
00772 
00773 TimeDomainStageObj::TimeDomainStageObj():
00774         idx(0)
00775 {
00776         #ifdef DEBUG 
00777         cout << "Inside the Stage Objectives Obj Constructor" << endl;
00778         #endif
00779 } // end TimeDomainStageObj
00780 
00781 
00782 TimeDomainStageObj::~TimeDomainStageObj()
00783 {
00784         #ifdef DEBUG 
00785         cout << "Inside the Stage Objectives Obj Destructor" << endl;
00786         #endif
00787 } // end ~TimeDomainStageObj
00788 
00789 
00790 TimeDomainStageObjectives::TimeDomainStageObjectives():
00791         numberOfObjectives(0),
00792         startIdx(-1)
00793 {
00794         #ifdef DEBUG 
00795         cout << "Inside the Stage Objectives Constructor" << endl;
00796         #endif
00797         obj = NULL;
00798 } // end TimeDomainStageObjectives
00799 
00800 TimeDomainStageObjectives::~TimeDomainStageObjectives()
00801 {
00802         #ifdef DEBUG 
00803         cout << "Inside the Stage Objectives Destructor" << endl;
00804         #endif
00805         if (numberOfObjectives > 0 && obj != NULL){
00806                 for (int i = 0; i < numberOfObjectives; i++) {
00807                         delete obj[i];
00808                         obj[i] = NULL;
00809                 }
00810         }
00811         delete [] obj;
00812         obj = NULL;
00813 } // end ~TimeDomainStageObjectives
00814 
00815 TimeDomainStage::TimeDomainStage():
00816         name("")
00817 { 
00818         #ifdef DEBUG 
00819         cout << "Inside the Stage Constructor" << endl;
00820         #endif
00821         variables   = NULL;
00822         constraints = NULL;
00823         objectives  = NULL;
00824 }//end TimeDomainStage() 
00825 
00826 
00827 TimeDomainStage::~TimeDomainStage(){
00828         #ifdef DEBUG  
00829         cout << "Inside the Stage Destructor" << endl;
00830         #endif
00831         if (variables != NULL)
00832         {       delete variables;
00833                 variables = NULL;
00834         }
00835         if (constraints != NULL)
00836         {       delete constraints;
00837                 constraints = NULL;
00838         }
00839         if (objectives != NULL)
00840         {       delete objectives;
00841                 objectives = NULL;
00842         }
00843 }//end ~TimeDomainStage()  
00844 
00845 
00846 TimeDomainStages::TimeDomainStages():
00847         numberOfStages(0),
00848         stage(NULL)
00849 {
00850         #ifdef DEBUG  
00851         cout << "Inside the Stages Constructor" << endl;
00852         #endif
00853 } 
00854 
00855 
00856 TimeDomainStages::~TimeDomainStages(){  
00857         #ifdef DEBUG
00858         cout << "Inside the Stages Destructor" << endl;
00859         #endif
00860         int i;
00861         if(numberOfStages > 0 && stage != NULL){
00862                 for( i = 0; i < numberOfStages; i++){
00863                         delete stage[i];
00864                         stage[i] = NULL;
00865                 }
00866         }
00867         delete[] stage;
00868         stage = NULL;  
00869 }
00870 
00871 TimeDomainInterval::TimeDomainInterval():
00872         start(0.0),
00873         horizon(0.0)
00874 {
00875         #ifdef DEBUG  
00876         cout << "Inside the Interval Constructor" << endl;
00877         #endif
00878 } 
00879 
00880 
00881 TimeDomainInterval::~TimeDomainInterval(){  
00882         #ifdef DEBUG
00883         cout << "Inside the Interval Destructor" << endl;
00884         #endif
00885 }
00886 
00887 TimeDomain::TimeDomain()
00888 {
00889         #ifdef DEBUG
00890         cout << "Inside the TimeDomain Constructor" << endl;
00891         #endif
00892         stages = NULL;
00893         interval = NULL;
00894 }
00895 
00896 TimeDomain::~TimeDomain()
00897 {  
00898         #ifdef DEBUG
00899         cout << "Inside the TimeDomain Destructor" << endl;
00900         #endif
00901         if (stages != NULL)
00902         {       delete stages;
00903                 stages = NULL;
00904         }
00905         if (interval != NULL)
00906         {       delete interval;
00907                 interval = NULL;
00908         }
00909 } 
00910 
00911 
00912 InstanceData::InstanceData(){ 
00913         #ifdef DEBUG 
00914         cout << "Inside the InstanceData Constructor" << endl;
00915         #endif 
00916         variables = new Variables();
00917         objectives = new Objectives();
00918         constraints = new Constraints();
00919         linearConstraintCoefficients = new LinearConstraintCoefficients();
00920         quadraticCoefficients = new QuadraticCoefficients();
00921         nonlinearExpressions = new NonlinearExpressions();
00922         timeDomain = NULL;
00923 } 
00924 
00925 InstanceData::~InstanceData(){  
00926         #ifdef DEBUG
00927         cout << "Inside the InstanceData Destructor" << endl; 
00928         #endif
00929         delete variables;
00930         variables = NULL;
00931         delete objectives;
00932         objectives = NULL;
00933         delete constraints;
00934         constraints = NULL;
00935         delete linearConstraintCoefficients;
00936         linearConstraintCoefficients = NULL;
00937         delete quadraticCoefficients;
00938         quadraticCoefficients = NULL;
00939         delete nonlinearExpressions;
00940         nonlinearExpressions = NULL;
00941         if (timeDomain != NULL)
00942         {   delete timeDomain;
00943                 timeDomain = NULL;
00944         }
00945 } 
00946 
00947 string OSInstance::getInstanceName(){
00948         if (m_sInstanceName.length() <= 0){
00949                 if (instanceHeader == NULL) 
00950                         throw ErrorClass("instanceHeader object undefined in method getInstanceName()");
00951                 m_sInstanceName = instanceHeader->name;
00952         }
00953         return m_sInstanceName;
00954 }//getInstanceName
00955 
00956 string OSInstance::getInstanceSource(){
00957         if (m_sInstanceSource.length() <= 0){
00958                 if (instanceHeader == NULL) 
00959                         throw ErrorClass("instanceHeader object undefined in method getInstanceSource()");
00960                 m_sInstanceSource = instanceHeader->source;
00961         }
00962         return m_sInstanceSource;
00963 }//getInstanceSource
00964 
00965 string OSInstance::getInstanceDescription(){
00966         if (m_sInstanceDescription.length() <= 0){
00967                 if (instanceHeader == NULL) 
00968                         throw ErrorClass("instanceHeader object undefined in method getInstanceDescription()");
00969                 m_sInstanceDescription = instanceHeader->description;
00970         }
00971         return m_sInstanceDescription;
00972 }//getInstanceDescription
00973 
00974 int OSInstance::getVariableNumber(){
00975         if (m_iVariableNumber == -1){
00976                 if (instanceData == NULL || instanceData->variables == NULL)
00977                         throw ErrorClass("data object undefined in method getVariableNumber()");
00978                 m_iVariableNumber = instanceData->variables->numberOfVariables;
00979         }
00980         return m_iVariableNumber;
00981 }//getVariableNumber
00982 
00983 bool OSInstance::processVariables() {
00984         if(m_bProcessVariables == true && bVariablesModified == false) return true;
00985         //m_bProcessVariables = true;
00986         string vartype ="CBIS";
00987         int i = 0;
00988         int n = getVariableNumber();
00989         try{
00990                 m_iNumberOfBinaryVariables = 0;
00991                 m_iNumberOfIntegerVariables = 0;
00992                 m_iNumberOfStringVariables = 0;
00993                 if(n > 0){
00994                         if(m_bProcessVariables != true ){
00995                                 m_mcVariableTypes = new char[n];
00996                                 m_mdVariableLowerBounds = new double[n];
00997                                 m_mdVariableUpperBounds = new double[n];
00998                                 m_msVariableNames = new string[n];
00999                                 m_bProcessVariables = true;
01000                         }
01001 
01002                         for(i = 0; i < n; i++){
01003                                 if(instanceData->variables->var[i] == NULL) throw ErrorClass("processVariables(): var element was never defined");
01004                                 if(vartype.find(instanceData->variables->var[i]->type) == string::npos) throw ErrorClass("wrong variable type");
01005                                 m_mcVariableTypes[i] = instanceData->variables->var[i]->type;
01006                                 if(m_mcVariableTypes[i] == 'B') m_iNumberOfBinaryVariables++;
01007                                 if(m_mcVariableTypes[i] == 'I') m_iNumberOfIntegerVariables++;
01008                                 if(m_mcVariableTypes[i] == 'S') m_iNumberOfStringVariables++;
01009                                 m_mdVariableLowerBounds[i] = instanceData->variables->var[i]->lb;
01010                                 m_mdVariableUpperBounds[i] = instanceData->variables->var[i]->ub;
01011                                 if(instanceData->variables->var[i]->name.length() > 0)
01012                                         m_msVariableNames[i] = instanceData->variables->var[i]->name;
01013                                 else
01014                                         m_msVariableNames[i] = "";
01015                         }
01016                 }
01017                 return true;
01018         } //end try
01019         catch(const ErrorClass& eclass){
01020                 throw ErrorClass( eclass.errormsg);
01021         } 
01022 }//processVariables
01023         
01024 string* OSInstance::getVariableNames() {
01025         processVariables();
01026         return m_msVariableNames;
01027 }//getVariableNames     
01028 
01029 /*
01030 double* OSInstance::getVariableInitialValues() {
01031         processVariables();
01032         return m_mdVariableInitialValues;
01033 }//getVariableInitialValues
01034 
01035 string* OSInstance::getVariableInitialStringValues() {
01036         processVariables();
01037         return m_msVariableInitialStringValues;
01038 }//getVariableInitialStringValues
01039 */
01040 
01041 char* OSInstance::getVariableTypes() {
01042         processVariables();
01043         return m_mcVariableTypes;
01044 }//getVariableTypes
01045 
01046 int OSInstance::getNumberOfIntegerVariables() {
01047         processVariables();
01048         return m_iNumberOfIntegerVariables;
01049 }//getNumberOfIntegerVariables
01050 
01051 int OSInstance::getNumberOfBinaryVariables() {
01052         processVariables();
01053         return m_iNumberOfBinaryVariables;
01054 }//getNumberOfBinaryVariables
01055 
01056 int OSInstance::getNumberOfStringVariables() {
01057         processVariables();
01058         return m_iNumberOfStringVariables;
01059 }//getNumberOfStringVariables
01060 
01061 double* OSInstance::getVariableLowerBounds() {
01062         processVariables();
01063         return m_mdVariableLowerBounds;
01064 }//getVariableLowerBounds
01065 
01066 double* OSInstance::getVariableUpperBounds() {
01067         processVariables();
01068         return m_mdVariableUpperBounds;
01069 }//getVariableUpperBounds
01070 
01071 
01072 int OSInstance::getObjectiveNumber(){
01073         if (m_iObjectiveNumber == -1){
01074                 if (instanceData == NULL || instanceData->objectives == NULL)
01075                         throw ErrorClass("data object undefined in method getObjectiveNumber()");
01076                 m_iObjectiveNumber = instanceData->objectives->numberOfObjectives;
01077         }
01078         return m_iObjectiveNumber;
01079 }//getObjectiveNumber
01080 
01081 bool OSInstance::processObjectives() {
01082         if(m_bProcessObjectives == true && bObjectivesModified == false) return true;
01083         //m_bProcessObjectives = true;
01084         int i = 0;
01085         int j = 0;
01086         int n = getObjectiveNumber();
01087         if (n == 0 || instanceData->objectives->obj == NULL) return true;
01088         try{
01089                 if (n > 0){
01090                         if(m_bProcessObjectives != true){
01091                                 m_msMaxOrMins = new string[n];
01092                                 m_miNumberOfObjCoef = new int[n];
01093                                 m_mdObjectiveConstants = new double[n];
01094                                 m_mdObjectiveWeights = new double[n];
01095                                 m_mObjectiveCoefficients = new SparseVector*[n];
01096                                 m_msObjectiveNames = new string[n];
01097                                 for(i = 0; i < n; i++){
01098                                         if(instanceData->objectives->obj[i] == NULL) throw ErrorClass("processObjectives(): obj element was never defined");
01099                                         m_mObjectiveCoefficients[i] = new SparseVector(instanceData->objectives->obj[i]->numberOfObjCoef);
01100                                         //m_mObjectiveCoefficients[i]->bDeleteArrays=false;
01101                                 }
01102                                 m_bProcessObjectives = true;
01103                         }
01104 
01105                         for(i = 0; i < n; i++){
01106                                 if(instanceData->objectives->obj[i] == NULL) throw ErrorClass("processObjectives(): obj element was never defined");
01107                                 if((instanceData->objectives->obj[i]->maxOrMin.compare("max") != 0) && (instanceData->objectives->obj[i]->maxOrMin.compare("min") != 0 )) throw ErrorClass("wrong objective maxOrMin");
01108                                 m_msMaxOrMins[i] = instanceData->objectives->obj[i]->maxOrMin;
01109                                 m_miNumberOfObjCoef[i] = instanceData->objectives->obj[i]->numberOfObjCoef;
01110                                 m_mdObjectiveConstants[i] = instanceData->objectives->obj[i]->constant;
01111                                 m_mdObjectiveWeights[i] = instanceData->objectives->obj[i]->weight;
01112                                 if(instanceData->objectives->obj[i]->coef == NULL && m_miNumberOfObjCoef[i] != 0){
01113                                         throw ErrorClass("objective coefficient number inconsistent with objective coefficient array");
01114                                 }
01115                                 if(instanceData->objectives->obj[i]->coef != NULL){
01116                                         for(j = 0; j < m_mObjectiveCoefficients[i]->number; j++){
01117                                                 m_mObjectiveCoefficients[i]->indexes[j] = instanceData->objectives->obj[i]->coef[j]->idx;
01118                                                 m_mObjectiveCoefficients[i]->values[j] = instanceData->objectives->obj[i]->coef[j]->value;                      
01119                                         }
01120                                 }
01121                                 if(instanceData->objectives->obj[i]->name.length() > 0)
01122                                         m_msObjectiveNames[i] = instanceData->objectives->obj[i]->name;
01123                                 else
01124                                         m_msObjectiveNames[i] = "";
01125                         }       
01126                 }
01127                 return true;
01128         } //end try
01129         catch(const ErrorClass& eclass){
01130                 throw ErrorClass( eclass.errormsg);
01131         }
01132 }//processObjectives
01133 
01134 string* OSInstance::getObjectiveNames() {
01135         processObjectives();
01136         return m_msObjectiveNames;
01137 }//getObjectiveNames
01138 
01139 string* OSInstance::getObjectiveMaxOrMins() {
01140         processObjectives();
01141         return m_msMaxOrMins;
01142 }//getObjectiveMaxOrMins
01143 
01144 int* OSInstance::getObjectiveCoefficientNumbers(){
01145         processObjectives();
01146         return m_miNumberOfObjCoef;
01147 }//getObjectiveCoefficientNumbers
01148 
01149 double* OSInstance::getObjectiveConstants() {
01150         processObjectives();
01151         return m_mdObjectiveConstants;
01152 }//getObjectiveConstants
01153 
01154 double* OSInstance::getObjectiveWeights() {
01155         processObjectives();
01156         return m_mdObjectiveWeights;
01157 }//getObjectiveWeights
01158 
01159 SparseVector** OSInstance::getObjectiveCoefficients() {
01160         processObjectives();
01161         return m_mObjectiveCoefficients;
01162 }//getObjectiveCoefficients
01163 
01164 
01165 double** OSInstance::getDenseObjectiveCoefficients() {
01166         if(m_bGetDenseObjectives == true && bObjectivesModified == false) return m_mmdDenseObjectiveCoefficients;
01167         int i, j, numobjcoef;
01168         SparseVector *sparsevec;
01169         int m = getObjectiveNumber();
01170         int n = getVariableNumber();
01171         if (m == 0 || instanceData->objectives->obj == NULL) return NULL;
01172         if (m_bGetDenseObjectives != true){
01173                 m_mmdDenseObjectiveCoefficients = new double*[m];
01174                 for(i = 0; i < m; i++){
01175                         m_mmdDenseObjectiveCoefficients[ i] = new double[n];
01176                 }
01177                 m_bGetDenseObjectives = true;
01178         }
01179 
01180         for(i = 0; i < m; i++){
01181                 sparsevec = this->getObjectiveCoefficients()[i];
01182                 for(j = 0; j < n; j++){
01183                         m_mmdDenseObjectiveCoefficients[ i][j] = 0.0;
01184                 }
01185                 sparsevec =  this->getObjectiveCoefficients()[i];
01186                 numobjcoef = sparsevec->number;
01187                 for(j = 0; j < numobjcoef; j++){
01188                         m_mmdDenseObjectiveCoefficients[i][ sparsevec->indexes[ j]]
01189                         = sparsevec->values[ j];
01190                 }
01191         }
01192         return m_mmdDenseObjectiveCoefficients;
01193 }//getDenseObjectiveCoefficients
01194 
01195 
01196 int OSInstance::getConstraintNumber(){
01197         if (m_iConstraintNumber == -1){
01198                 if (instanceData == NULL || instanceData->constraints == NULL)
01199                         throw ErrorClass("data object undefined in method getConstraintNumber()");
01200                 m_iConstraintNumber = instanceData->constraints->numberOfConstraints;
01201         }
01202         return m_iConstraintNumber;
01203 }//getConstraintNumber
01204 
01205 bool OSInstance::processConstraints() {
01206         if(m_bProcessConstraints == true && bConstraintsModified == false) return true;
01207         //m_bProcessConstraints = true;
01208         int i = 0;
01209         ostringstream outStr;
01210         int n = getConstraintNumber();
01211         if (n == 0 || instanceData->constraints->con == NULL) return true;
01212         try{
01213                 if(n > 0){
01214                         if(m_bProcessConstraints != true){
01215                                 m_mdConstraintLowerBounds = new double[n];
01216                                 m_mdConstraintUpperBounds = new double[n];
01217                                 m_mdConstraintConstants = new double[n];
01218                                 m_mcConstraintTypes = new char[n];
01219                                 m_msConstraintNames = new string[n];
01220                                 m_bProcessConstraints = true;
01221                         }
01222                         for(i = 0; i < n; i++){
01223                                 if(instanceData->constraints->con[i] == NULL) throw ErrorClass("processConstraints(): con element was never defined");
01224                                 m_mdConstraintLowerBounds[i] = instanceData->constraints->con[i]->lb;
01225                                 m_mdConstraintUpperBounds[i] = instanceData->constraints->con[i]->ub;
01226                                 m_mdConstraintConstants[i] = instanceData->constraints->con[i]->constant;
01227                                 if(m_mdConstraintLowerBounds[i] == OSDBL_MAX || m_mdConstraintUpperBounds[i] == -OSDBL_MAX) {
01228                                         outStr << "Constraint  " ;
01229                                         outStr << i;
01230                                         outStr << " is infeasible";
01231                                         throw ErrorClass( outStr.str() );
01232                                 }
01233                                 else if(m_mdConstraintLowerBounds[i] > m_mdConstraintUpperBounds[i]) {
01234                                         outStr << "Constraint  " ;
01235                                         outStr << i;
01236                                         outStr << " is infeasible";
01237                                         throw ErrorClass( outStr.str());
01238                                 }
01239                                 else if(m_mdConstraintLowerBounds[i] == -OSDBL_MAX && m_mdConstraintUpperBounds[i] == OSDBL_MAX)
01240                                         m_mcConstraintTypes[i] = 'U';
01241                                 else if(m_mdConstraintLowerBounds[i] == m_mdConstraintUpperBounds[i]) 
01242                                         m_mcConstraintTypes[i] = 'E';
01243                                 else if(m_mdConstraintLowerBounds[i] == -OSDBL_MAX)
01244                                         m_mcConstraintTypes[i] = 'L';
01245                                 else if(m_mdConstraintUpperBounds[i] == OSDBL_MAX)
01246                                         m_mcConstraintTypes[i] = 'G';
01247                                 else m_mcConstraintTypes[i] = 'R';
01248                                 if(instanceData->constraints->con[i]->name.length() > 0)
01249                                         m_msConstraintNames[i] = instanceData->constraints->con[i]->name;
01250                                 else
01251                                         m_msConstraintNames[i] = "";
01252                         }
01253                 }
01254                 return true;
01255         }
01256         catch(const ErrorClass& eclass){
01257                 throw ErrorClass( eclass.errormsg);
01258         }
01259 }//processConstraints
01260 
01261 
01262 string* OSInstance::getConstraintNames() {
01263         processConstraints();
01264         return m_msConstraintNames;
01265 }//getConstraintNames
01266 
01267 
01268 double* OSInstance::getConstraintLowerBounds() {
01269         processConstraints();
01270         return m_mdConstraintLowerBounds;
01271 }//getConstraintLowerBounds
01272 
01273 char* OSInstance::getConstraintTypes() {
01274         processConstraints();
01275         return m_mcConstraintTypes;
01276 }//getConstraintTypes
01277 
01278 double* OSInstance::getConstraintUpperBounds() {
01279         processConstraints();
01280         return m_mdConstraintUpperBounds;
01281 }//getConstraintUpperBounds
01282 
01283 
01284 int OSInstance::getLinearConstraintCoefficientNumber(){
01285         if(this->getVariableNumber() <= 0 || this->getConstraintNumber() <= 0) return 0;
01286         if(m_iLinearConstraintCoefficientNumber == -1){
01287                 if (instanceData == NULL || instanceData->linearConstraintCoefficients == NULL)
01288                         throw ErrorClass("data object undefined in method getLinearConstraintCoefficientNumber()");
01289                 m_iLinearConstraintCoefficientNumber = instanceData->linearConstraintCoefficients->numberOfValues;
01290         }
01291         return m_iLinearConstraintCoefficientNumber; 
01292 }//getLinearConstraintCoefficientNumber
01293 
01294 bool OSInstance::processLinearConstraintCoefficients() {
01295         if(m_bProcessLinearConstraintCoefficients == true && bAMatrixModified == false) return true;
01296         //m_bProcessLinearConstraintCoefficients = true;
01297         try{
01298                 int n = getLinearConstraintCoefficientNumber();
01299                 if((instanceData->linearConstraintCoefficients == NULL ) || (n == 0) ) return true;
01300                 //value array
01301                 if((instanceData->linearConstraintCoefficients->value == NULL ) || (n == 0) ) return true;
01302                 //index array
01303                 if((instanceData->linearConstraintCoefficients->colIdx != NULL && instanceData->linearConstraintCoefficients->colIdx->el != NULL) 
01304                 && (instanceData->linearConstraintCoefficients->rowIdx != NULL && instanceData->linearConstraintCoefficients->rowIdx->el != NULL))
01305                         throw ErrorClass("ambiguous linear constraint coefficient major");
01306                 else if(instanceData->linearConstraintCoefficients->value->el == NULL) return true;
01307                 else{
01308                         if(instanceData->linearConstraintCoefficients->rowIdx->el != NULL){
01309                                 m_bColumnMajor = true;
01310                                 if(m_bProcessLinearConstraintCoefficients != true){
01311                                         m_linearConstraintCoefficientsInColumnMajor = new SparseMatrix();
01312                                         m_linearConstraintCoefficientsInColumnMajor->bDeleteArrays = false;
01313                                         m_bProcessLinearConstraintCoefficients = true;
01314                                 }
01315                                 m_linearConstraintCoefficientsInColumnMajor->isColumnMajor = true;
01316                                 m_linearConstraintCoefficientsInColumnMajor->valueSize = n;
01317                                 m_linearConstraintCoefficientsInColumnMajor->startSize = instanceData->variables->numberOfVariables + 1;
01318                         }
01319                         else{ 
01320                                 m_bColumnMajor = false; 
01321                                 if(m_bProcessLinearConstraintCoefficients != true){
01322                                         m_linearConstraintCoefficientsInRowMajor = new SparseMatrix();
01323                                         m_linearConstraintCoefficientsInRowMajor->bDeleteArrays = false;
01324                                         m_bProcessLinearConstraintCoefficients = true;
01325                                 }
01326                                 m_linearConstraintCoefficientsInRowMajor->isColumnMajor = false;
01327                                 m_linearConstraintCoefficientsInRowMajor->valueSize = n;
01328                                 m_linearConstraintCoefficientsInRowMajor->startSize = instanceData->constraints->numberOfConstraints + 1;
01329                         }
01330                 }                       
01331                 if(m_bColumnMajor == true){
01332                         m_linearConstraintCoefficientsInColumnMajor->values = instanceData->linearConstraintCoefficients->value->el;
01333                         m_linearConstraintCoefficientsInColumnMajor->indexes = instanceData->linearConstraintCoefficients->rowIdx->el;
01334                         m_linearConstraintCoefficientsInColumnMajor->starts = instanceData->linearConstraintCoefficients->start->el;                    
01335                 }
01336                 else{
01337                         m_linearConstraintCoefficientsInRowMajor->values = instanceData->linearConstraintCoefficients->value->el;
01338                         m_linearConstraintCoefficientsInRowMajor->indexes = instanceData->linearConstraintCoefficients->colIdx->el;
01339                         m_linearConstraintCoefficientsInRowMajor->starts = instanceData->linearConstraintCoefficients->start->el;                                               
01340                 }
01341                 return true;
01342         }
01343         catch(const ErrorClass& eclass){
01344                 throw ErrorClass( eclass.errormsg);
01345         }
01346 }//processLinearConstraintCoefficients
01347 
01348 bool OSInstance::getLinearConstraintCoefficientMajor() {
01349         processLinearConstraintCoefficients();  
01350         return m_bColumnMajor;          
01351 }//getLinearConstraintCoefficientMajor
01352 
01353 SparseMatrix* OSInstance::getLinearConstraintCoefficientsInColumnMajor() {
01354         processLinearConstraintCoefficients();
01355         if(getVariableNumber() ==  0) return NULL;
01356         if(m_linearConstraintCoefficientsInColumnMajor != NULL) return m_linearConstraintCoefficientsInColumnMajor;
01357         if(!m_bColumnMajor){
01358                 if(m_linearConstraintCoefficientsInRowMajor == NULL) return NULL;
01359                 m_linearConstraintCoefficientsInColumnMajor = 
01360                         MathUtil::convertLinearConstraintCoefficientMatrixToTheOtherMajor(false,
01361                                           m_linearConstraintCoefficientsInRowMajor->startSize,
01362                                           m_linearConstraintCoefficientsInRowMajor->valueSize,
01363                                           m_linearConstraintCoefficientsInRowMajor->starts,
01364                                           m_linearConstraintCoefficientsInRowMajor->indexes,
01365                                           m_linearConstraintCoefficientsInRowMajor->values,
01366                                           getVariableNumber());
01367         }
01368         return m_linearConstraintCoefficientsInColumnMajor;             
01369 }//getLinearConstraintCoefficientsInColumnMajor
01370 
01371 SparseMatrix* OSInstance::getLinearConstraintCoefficientsInRowMajor() {
01372         processLinearConstraintCoefficients();
01373         if(m_linearConstraintCoefficientsInRowMajor != NULL) return m_linearConstraintCoefficientsInRowMajor;
01374         if(m_bColumnMajor){
01375                 if(m_linearConstraintCoefficientsInColumnMajor == NULL) return NULL;
01376                 m_linearConstraintCoefficientsInRowMajor = 
01377                 MathUtil::convertLinearConstraintCoefficientMatrixToTheOtherMajor(true,
01378                                   m_linearConstraintCoefficientsInColumnMajor->startSize,
01379                                   m_linearConstraintCoefficientsInColumnMajor->valueSize,
01380                                   m_linearConstraintCoefficientsInColumnMajor->starts,
01381                                   m_linearConstraintCoefficientsInColumnMajor->indexes,
01382                                   m_linearConstraintCoefficientsInColumnMajor->values,
01383                                   getConstraintNumber());
01384         }
01385         return m_linearConstraintCoefficientsInRowMajor; 
01386 }//getLinearConstraintCoefficientsInRowMajor
01387 
01388 
01389 int OSInstance::getNumberOfQuadraticTerms(){
01390         if(m_iQuadraticTermNumber == -1){
01391                 if (instanceData == NULL || instanceData->quadraticCoefficients == NULL)
01392                         throw ErrorClass("data object undefined in method getNumberOfQuadraticTerms()");
01393                 m_iQuadraticTermNumber = instanceData->quadraticCoefficients->numberOfQuadraticTerms;
01394         }
01395         return m_iQuadraticTermNumber;
01396 }//getNumberOfQuadraticTerms
01397 
01398 QuadraticTerms* OSInstance::getQuadraticTerms() {
01399         if(m_bProcessQuadraticTerms) return m_quadraticTerms;
01400         m_bProcessQuadraticTerms = true;
01401         int n = getNumberOfQuadraticTerms();
01402         if(instanceData->quadraticCoefficients->qTerm == NULL) return NULL;
01403         try{
01404                 int i = 0;
01405                 QuadraticCoefficients* quadraticCoefs = instanceData->quadraticCoefficients;
01406                         if(!quadraticCoefs->qTerm  && n != 0) 
01407                                         throw ErrorClass("quadratic term number inconsistent with quadratic term array");
01408                         m_quadraticTerms = new QuadraticTerms();
01409                         if(n > 0){
01410                                 m_quadraticTerms->rowIndexes = new int[n];
01411                                 m_quadraticTerms->varOneIndexes = new int[n];
01412                                 m_quadraticTerms->varTwoIndexes = new int[n];
01413                                 m_quadraticTerms->coefficients = new double[n];
01414                         }
01415                         for(i = 0; i < n; i++){
01416                                 m_quadraticTerms->rowIndexes[i]    = quadraticCoefs->qTerm[i]->idx;
01417                                 m_quadraticTerms->varOneIndexes[i] = quadraticCoefs->qTerm[i]->idxOne;
01418                                 m_quadraticTerms->varTwoIndexes[i] = quadraticCoefs->qTerm[i]->idxTwo;
01419                                 m_quadraticTerms->coefficients[i]  = quadraticCoefs->qTerm[i]->coef;
01420                         }
01421                 return m_quadraticTerms;
01422         }
01423         catch(const ErrorClass& eclass){
01424                 throw ErrorClass( eclass.errormsg);
01425         } 
01426 }//getQuadraticTerms
01427 
01428 int OSInstance::getNumberOfQuadraticRowIndexes() {
01429         if(m_bQuadraticRowIndexesProcessed == false) getQuadraticRowIndexes();
01430         return m_iNumberOfQuadraticRowIndexes;
01431 }//getNumberOfQuadraticRowIndexes
01432 
01433 int* OSInstance::getQuadraticRowIndexes() {
01434         if(m_bQuadraticRowIndexesProcessed == true) return m_miQuadRowIndexes;
01435         m_bQuadraticRowIndexesProcessed = true;
01436         int n = getNumberOfQuadraticTerms();    
01437         if(n <= 0) return NULL;
01438         QuadraticTerms *qTerms = NULL;
01439         qTerms = getQuadraticTerms();
01440         std::map<int, int> foundIdx;
01441         std::map<int, int>::iterator pos;
01442         int i;
01443         try{
01444                 for(i = 0; i < n; i++){
01445                         // add the terms
01446                         foundIdx[ qTerms->rowIndexes[ i] ];      
01447                 }
01448                 // now put the term into an array
01449                 m_iNumberOfQuadraticRowIndexes = foundIdx.size();
01450                 m_miQuadRowIndexes = new int[ m_iNumberOfQuadraticRowIndexes ]  ;
01451                 i = 0;
01452                 for(pos = foundIdx.begin(); pos != foundIdx.end(); ++pos){
01453                         m_miQuadRowIndexes[ i++] = pos->first;  
01454                 }
01455                 foundIdx.clear();       
01456                 return m_miQuadRowIndexes;
01457         }
01458         catch(const ErrorClass& eclass){
01459                 throw ErrorClass( eclass.errormsg);
01460         } 
01461 }//getQuadraticRowIndexes
01462 
01463 
01464 int OSInstance::getNumberOfNonlinearExpressions(){
01465         if(m_iNonlinearExpressionNumber == -1){
01466                 if (instanceData == NULL || instanceData->nonlinearExpressions == NULL)
01467                         throw ErrorClass("data object undefined in method getNumberOfNonlinearExpressions()");
01468                 m_iNonlinearExpressionNumber = instanceData->nonlinearExpressions->numberOfNonlinearExpressions;
01469         }
01470         return m_iNonlinearExpressionNumber;
01471 }//getNumberOfNonlinearExpressions
01472 
01473 int OSInstance::getNumberOfNonlinearExpressionTreeIndexes() {
01474         if(m_bNonlinearExpressionTreeIndexesProcessed == false) getNonlinearExpressionTreeIndexes();
01475         return m_iNumberOfNonlinearExpressionTreeIndexes;
01476 }//getNumberOfNonlinearExpressionTreeIndexes
01477 
01478 int* OSInstance::getNonlinearExpressionTreeIndexes(){
01479         if(m_bNonlinearExpressionTreeIndexesProcessed == true) return m_miNonlinearExpressionTreeIndexes;
01480         m_bNonlinearExpressionTreeIndexesProcessed = true;
01481         std::map<int, OSExpressionTree*> expTrees;
01482         expTrees = getAllNonlinearExpressionTrees();    
01483         std::map<int, OSExpressionTree*>::iterator pos;
01484         try{
01485                 // now put the term into an array
01486                 m_iNumberOfNonlinearExpressionTreeIndexes = expTrees.size();
01487                 m_miNonlinearExpressionTreeIndexes = new int[ m_iNumberOfNonlinearExpressionTreeIndexes ]       ;
01488                 int i = 0;
01489                 for(pos = expTrees.begin(); pos != expTrees.end(); ++pos){
01490                         m_miNonlinearExpressionTreeIndexes[ i++] = pos->first;  
01491                 }
01492                 expTrees.clear();       
01493                 return m_miNonlinearExpressionTreeIndexes;
01494         }
01495         catch(const ErrorClass& eclass){
01496                 throw ErrorClass( eclass.errormsg);
01497         } 
01498 }//getNonlinearExpressionTreeIndexes
01499 
01500 int OSInstance::getNumberOfNonlinearExpressionTreeModIndexes() {
01501         if(m_bNonlinearExpressionTreeModIndexesProcessed == false) getNonlinearExpressionTreeModIndexes();
01502         return m_iNumberOfNonlinearExpressionTreeModIndexes;
01503 }//getNumberOfNonlinearExpressionTreeModIndexes
01504 
01505 int* OSInstance::getNonlinearExpressionTreeModIndexes(){
01506         if(m_bNonlinearExpressionTreeModIndexesProcessed == true) return m_miNonlinearExpressionTreeModIndexes;
01507         m_bNonlinearExpressionTreeModIndexesProcessed = true;
01508         std::map<int, OSExpressionTree*> expTrees;
01509         expTrees = getAllNonlinearExpressionTreesMod(); 
01510         std::map<int, OSExpressionTree*>::iterator pos;
01511         try{
01512                 // now put the term into an array
01513                 m_iNumberOfNonlinearExpressionTreeModIndexes = expTrees.size();
01514                 m_miNonlinearExpressionTreeModIndexes = new int[ m_iNumberOfNonlinearExpressionTreeModIndexes ] ;
01515                 int i = 0;
01516                 for(pos = expTrees.begin(); pos != expTrees.end(); ++pos){
01517                         m_miNonlinearExpressionTreeModIndexes[ i++] = pos->first;       
01518                 }
01519                 expTrees.clear();       
01520                 return m_miNonlinearExpressionTreeModIndexes;
01521         }
01522         catch(const ErrorClass& eclass){
01523                 throw ErrorClass( eclass.errormsg);
01524         } 
01525 }//getNonlinearExpressionTreeModIndexes
01526 
01527 int OSInstance::getNumberOfNonlinearConstraints(){
01528         if( m_bProcessExpressionTrees == false )
01529                 getAllNonlinearExpressionTrees();
01530         return m_iConstraintNumberNonlinear;
01531 }//getNumberOfNonlinearConstraints
01532 
01533 int OSInstance::getNumberOfNonlinearObjectives(){
01534         if( m_bProcessExpressionTrees == false )
01535                 getAllNonlinearExpressionTrees();
01536         return m_iObjectiveNumberNonlinear;
01537 }//getNumberOfNonlinearObjectivess
01538 
01539 OSExpressionTree* OSInstance::getNonlinearExpressionTree(int rowIdx){
01540         if( m_bProcessExpressionTrees == false ){
01541                 getAllNonlinearExpressionTrees();
01542         } 
01543         if( m_mapExpressionTrees.find( rowIdx) != m_mapExpressionTrees.end()) return m_mapExpressionTrees[ rowIdx];
01544         else return NULL ;
01545         // check to make sure rowIdx has a nonlinear term and is in the map
01547         //std::map<int, OSExpressionTree*>::iterator pos;
01549         //      if(pos->first == rowIdx)return m_mapExpressionTrees[ rowIdx];
01550         //}
01551         // if we are rowIdx has no nonlinear terms so return a null
01552         //return NULL;
01553 }// getNonlinearExpressionTree for a specific index   
01554 
01555 OSExpressionTree* OSInstance::getNonlinearExpressionTreeMod(int rowIdx){
01556         if( m_bProcessExpressionTreesMod == false ){
01557                 getAllNonlinearExpressionTreesMod();
01558         } 
01559         if( m_mapExpressionTreesMod.find( rowIdx) != m_mapExpressionTreesMod.end()) return m_mapExpressionTreesMod[ rowIdx];
01560         else return NULL ;
01561         // check to make sure rowIdx has a nonlinear term and is in the map
01563         //std::map<int, OSExpressionTree*>::iterator pos;
01565         //      if(pos->first == rowIdx)return m_mapExpressionTrees[ rowIdx];
01566         //}
01567         // if we are rowIdx has no nonlinear terms so return a null
01568         //return NULL;
01569 }// getNonlinearExpressionTreeMod for a specific index 
01570 
01571 std::vector<OSnLNode*> OSInstance::getNonlinearExpressionTreeInPostfix( int rowIdx){
01572         //if( m_binitForAlgDiff == false) this->initForAlgDiff();
01573         if( m_bProcessExpressionTrees == false ) getAllNonlinearExpressionTrees();
01574         std::vector<OSnLNode*> postfixVec;
01575         try{
01576                 if( m_mapExpressionTrees.find( rowIdx) != m_mapExpressionTrees.end()){
01577                         OSExpressionTree* expTree = getNonlinearExpressionTree( rowIdx);
01578                         postfixVec = expTree->m_treeRoot->getPostfixFromExpressionTree();
01579                 }  
01580                 else{
01581                         throw ErrorClass("Error in getNonlinearExpressionTreeInPostfix, rowIdx not valid");
01582                 }
01583                 return postfixVec;      
01584         }
01585         catch(const ErrorClass& eclass){
01586                 throw ErrorClass( eclass.errormsg);
01587         } 
01588 }//getNonlinearExpressionTreeInPostfix
01589 
01590 std::string OSInstance::getNonlinearExpressionTreeInInfix( int rowIdx_){
01591         if( m_binitForAlgDiff == false) this->initForAlgDiff();
01592         if( m_bProcessExpressionTrees == false ) getAllNonlinearExpressionTrees();
01593         std::string resultString;
01594         resultString = "";
01595         unsigned int i;
01596         unsigned int j;
01597         unsigned int n;
01598         ostringstream outStr;
01599         std::vector<OSnLNode*> postfixVec;
01600         int rowIdx = rowIdx_;
01601         OSnLNode *nlnode = NULL ;
01602         OSnLNodeNumber *nlnodeNum = NULL;
01603         OSnLNodeVariable *nlnodeVar = NULL;
01604         OSnLNodeSum *nlnodeSum = NULL;
01605         OSnLNodeProduct *nlnodeProduct = NULL;
01606         OSnLNodeMin *nlnodeMin = NULL;
01607         OSnLNodeMax *nlnodeMax = NULL;
01608         std::string tmp1 = "";
01609         std::string tmp2 = "";
01610         std::string tmp3 = "";
01611         std::stack<OSnLNode*> opStack;
01612         std::stack<std::string> tmpStack;
01613         std::stack<std::string> sumStack;
01614         std::stack<std::string> productStack;
01615         std::stack<std::string> minStack;
01616         std::stack<std::string> maxStack;
01617         
01618         try{
01619                 if( m_mapExpressionTrees.find( rowIdx) != m_mapExpressionTrees.end()){
01620                         //get the nodes and separate into operators and operands, for now
01621                         //only the number and variable nodes are operator nodes
01622                         
01623                         OSExpressionTree* exptree = this->getNonlinearExpressionTree( rowIdx);
01624                         if(exptree != NULL) {
01625                                 postfixVec = this->getNonlinearExpressionTreeInPostfix( rowIdx);
01626                                 n  = postfixVec.size();
01627                                 //put vector in reverse order
01628                                 for (i = 0 ; i < n; i++){
01629                                         nlnode =  postfixVec[ n - 1 - i];
01630                                         opStack.push( nlnode);
01631                                         //std::cout << postfixVec[ i]->snodeName << std::endl;
01632                                 }
01633                                 
01634                                 #if 0
01635                                 std::cout << std::endl << std::endl << std::endl << std::endl;
01636                                 n = opStack.size();
01637                                 for(i = 0; i < n; i++){
01638                                         std::cout  << opStack.top()->getTokenName()  << std::endl;
01639                                 }
01640                                 
01641                                 #endif
01642                                 n = opStack.size();
01643                                 for(i = 0; i < n; i++){
01644                                         //std::cout << "NUMBER OF NODES LEFT =  " << operatorVec.size() << std::endl;
01645                                         nlnode = opStack.top();
01646                                         //std::cout << "EVALUATING NODE: " << nlnode->snodeName << std::endl;
01647                                         switch (nlnode->inodeInt) {
01648                                                 case OS_NUMBER:
01649                                                         nlnodeNum = (OSnLNodeNumber*)nlnode;
01650                                                         tmpStack.push( os_dtoa_format(nlnodeNum->value) );
01651                                                         break;
01652                                                         
01653                                                 case OS_PI:
01654                                                         tmpStack.push( "PI" );
01655                                                         break;
01656                                                         
01657                                                 case OS_E:
01658                                                         tmpStack.push( "E" );
01659                                                         break;
01660                                                         
01661                                                 case OS_VARIABLE:
01662                                                         outStr.str("");
01663                                                         // handle a variable
01664                                                         nlnodeVar = (OSnLNodeVariable*)nlnode;
01665                                                         // see if the coefficient is specified
01666                                                         if( (nlnodeVar->coef > 1.0) ||  (nlnodeVar->coef < 1.0) ){
01667                                                                 outStr << "(";
01668                                                                 outStr <<  os_dtoa_format(nlnodeVar->coef);
01669                                                                 outStr << "*x_";
01670                                                                 outStr << nlnodeVar->idx;
01671                                                                 outStr << ")";
01672                                                                 tmpStack.push(outStr.str() );
01673                                                                 //std::cout << "WE JUST PUSHED " << outStr.str() << std::endl;
01674                                                         }else{
01675                                                                 outStr << "x_";
01676                                                                 outStr << nlnodeVar->idx;
01677                                                                 tmpStack.push(outStr.str() );
01678                                                                 //std::cout << "WE JUST PUSHED " << outStr.str() << std::endl;
01679                                                         }
01680                                                         break;
01681                                                         
01682                                                 case OS_PLUS :
01683                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing plus operater");
01684                                                         tmp1 = tmpStack.top();
01685                                                         tmpStack.pop();
01686                                                         tmp2 = tmpStack.top();
01687                                                         tmpStack.pop();
01688                                                         tmpStack.push("(" + tmp2 +  " + "  + tmp1 + ")");
01689                                                         break;
01690                                                         
01691                                                 case OS_SUM :
01692                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing sum operater");
01693                                                         //std::cout << "INSIDE SUM NODE " << std::endl;
01694                                                         nlnodeSum = (OSnLNodeSum*)nlnode;
01695                                                         outStr.str("");
01696                                                         for(j = 0; j < nlnodeSum->inumberOfChildren; j++){
01697                                                                 sumStack.push( tmpStack.top() );
01698                                                                 tmpStack.pop();
01699                                                         }
01700                                                         outStr << "(";
01701                                                         for(j = 0; j < nlnodeSum->inumberOfChildren; j++){
01702                                                                 outStr << sumStack.top();
01703                                                                 if (j < nlnodeSum->inumberOfChildren - 1) outStr << " + ";
01704                                                                 sumStack.pop();
01705                                                         }
01706                                                         outStr << ")";
01707                                                         tmpStack.push( outStr.str() );
01708                                                         //std::cout << outStr.str() << std::endl;
01709                                                         break;
01710                                                         
01711                                                 case OS_MINUS :
01712                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing minus operater");
01713                                                         tmp1 = tmpStack.top();
01714                                                         tmpStack.pop();
01715                                                         tmp2 = tmpStack.top();
01716                                                         tmpStack.pop();
01717                                                         tmpStack.push("(" + tmp2 +  " - "  + tmp1 + ")");
01718                                                         break;                                          
01719                                                 
01720                                                 case OS_NEGATE :
01721                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- -- Problem writing negate operater");
01722                                                         tmp1 = tmpStack.top();
01723                                                         tmpStack.pop();
01724                                                         tmpStack.push( "-"+ tmp1 );
01725                                                         break;
01726                                                         
01727                                                 case OS_TIMES :
01728                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing times operater");
01729                                                         tmp1 = tmpStack.top();
01730                                                         tmpStack.pop();
01731                                                         tmp2 = tmpStack.top();
01732                                                         tmpStack.pop();
01733                                                         tmpStack.push("(" + tmp2 +  "*"  + tmp1 + ")");
01734                                                         break;
01735                                                 
01736                                                 case OS_DIVIDE :
01737                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing divide operater");
01738                                                         tmp1 = tmpStack.top();
01739                                                         tmpStack.pop();
01740                                                         tmp2 = tmpStack.top();
01741                                                         tmpStack.pop();
01742                                                         tmpStack.push("(" + tmp2 +  " / "  + tmp1 + ")");
01743                                                         break;
01744 
01745                                                 case OS_POWER :
01746                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing power operater");
01747                                                         tmp1 = tmpStack.top();
01748                                                         tmpStack.pop();
01749                                                         tmp2 = tmpStack.top();
01750                                                         tmpStack.pop();
01751                                                         tmpStack.push("(" + tmp2 +  " ^ "  + tmp1 + ")");
01752                                                         break;
01753                                                         
01754                                                 case OS_ABS :
01755                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing abs operater");
01756                                                         tmp1 = tmpStack.top();
01757                                                         tmpStack.pop();
01758                                                         tmpStack.push( "abs( "+ tmp1  + ")");
01759                                                         break;
01760                                                         
01761                                                 case OS_ERF :
01762                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing erf operater");
01763                                                         tmp1 = tmpStack.top();
01764                                                         tmpStack.pop();
01765                                                         tmpStack.push( "erf( "+ tmp1  + ")");
01766                                                         break;
01767 
01768                                                 
01769                                                 case OS_SQUARE :
01770                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing square operater ");
01771                                                         tmp1 = tmpStack.top();
01772                                                         tmpStack.pop();
01773                                                         tmpStack.push( "("+ tmp1  + ")^2");
01774                                                         break;
01775                                                                                                         
01776                                                 case OS_LN :
01777                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing ln operater");
01778                                                         tmp1 = tmpStack.top();
01779                                                         tmpStack.pop();
01780                                                         tmpStack.push( "ln( "+ tmp1  + ")");
01781                                                         break;
01782                                                         
01783                                                 case OS_EXP :
01784                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing exp operater");
01785                                                         tmp1 = tmpStack.top();
01786                                                         tmpStack.pop();
01787                                                         tmpStack.push( "exp( "+ tmp1  + ")");
01788                                                         break;
01789                                                         
01790                                                 case OS_SIN :
01791                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing sin operater");
01792                                                         tmp1 = tmpStack.top();
01793                                                         tmpStack.pop();
01794                                                         tmpStack.push( "sin( "+ tmp1  + ")");
01795                                                         break;
01796                                                         
01797                                                 case OS_COS :
01798                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing cos operater ");
01799                                                         tmp1 = tmpStack.top();
01800                                                         tmpStack.pop();
01801                                                         tmpStack.push( "cos( "+ tmp1  + ")");
01802                                                         break;
01803                                                         
01804                                                 case OS_SQRT :
01805                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing cos operater ");
01806                                                         tmp1 = tmpStack.top();
01807                                                         tmpStack.pop();
01808                                                         tmpStack.push( "sqrt( "+ tmp1  + ")");
01809                                                         break;
01810                                                         
01811                                                 case OS_MIN :
01812                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing min operater");
01813                                                         //std::cout << "INSIDE Min NODE " << std::endl;
01814                                                         nlnodeMin = (OSnLNodeMin*)nlnode;
01815                                                         outStr.str("");
01816                                                         for(j = 0; j < nlnodeMin->inumberOfChildren; j++){
01817                                                                 minStack.push( tmpStack.top() );
01818                                                                 tmpStack.pop();
01819                                                         }
01820                                                         outStr << "min(";
01821                                                         for(j = 0; j < nlnodeMin->inumberOfChildren; j++){
01822                                                                 outStr << minStack.top();
01823                                                                 if (j < nlnodeMin->inumberOfChildren - 1) outStr << " , ";
01824                                                                 minStack.pop();
01825                                                         }
01826                                                         outStr << ")";
01827                                                         tmpStack.push( outStr.str() );
01828                                                         break;
01829                                                         
01830                                                 case OS_MAX :
01831                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing max operater");
01832                                                         //std::cout << "INSIDE Max NODE " << std::endl;
01833                                                         nlnodeMax = (OSnLNodeMax*)nlnode;
01834                                                         outStr.str("");
01835                                                         for(j = 0; j < nlnodeMax->inumberOfChildren; j++){
01836                                                                 maxStack.push( tmpStack.top() );
01837                                                                 tmpStack.pop();
01838                                                         }
01839                                                         outStr << "max(";
01840                                                         for(j = 0; j < nlnodeMax->inumberOfChildren; j++){
01841                                                                 outStr << maxStack.top();
01842                                                                 if (j < nlnodeMax->inumberOfChildren - 1) outStr << " , ";
01843                                                                 maxStack.pop();
01844                                                         }
01845                                                         outStr << ")";
01846                                                         tmpStack.push( outStr.str() );
01847                                                         break;
01848                                                         
01849                                                 case OS_IF :
01850                                                 
01851                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing if operater ");
01852                                                         if(nlnode->inumberOfChildren != 3)throw  ErrorClass("The if node must have three children");
01853                                                         tmp1 = tmpStack.top();
01854                                                         tmpStack.pop();
01855                                                         tmp2 = tmpStack.top();
01856                                                         tmpStack.pop();
01857                                                         tmp3 = tmpStack.top();
01858                                                         tmpStack.pop();
01859                                                         tmpStack.push( "if(" + tmp3 + "," + tmp2 + "," + tmp1 +")" );
01860                                                         break;
01861                                                         
01862                                                 case OS_PRODUCT :
01863                                                         if( tmpStack.size() < nlnode->inumberOfChildren) throw  ErrorClass("There is an error in the OSExpression Tree -- Problem writing product operater");
01864                                                         //std::cout << "INSIDE Product NODE " << std::endl;
01865                                                         nlnodeProduct = (OSnLNodeProduct*)nlnode;
01866                                                         outStr.str("");
01867                                                         for(j = 0; j < nlnodeProduct->inumberOfChildren; j++){
01868                                                                 productStack.push( tmpStack.top() );
01869                                                                 tmpStack.pop();
01870                                                         }
01871                                                         outStr << "(";
01872                                                         for(j = 0; j < nlnodeProduct->inumberOfChildren; j++){
01873                                                                 outStr << productStack.top();
01874                                                                 if (j < nlnodeProduct->inumberOfChildren - 1) outStr << " * ";
01875                                                                 productStack.pop();
01876                                                         }
01877                                                         outStr << ")";
01878                                                         tmpStack.push( outStr.str() );
01879                                                         //std::cout << outStr.str() << std::endl;
01880                                                         break;
01881                                                         
01882                                                 default:
01883                                                          throw  ErrorClass("operator " + nlnode->getTokenName() + " not supported");
01884                                                 break;
01885                                   }
01886                                         opStack.pop();
01887                                 }
01888                                 postfixVec.clear();
01889                                 if(tmpStack.size() != 1) throw ErrorClass( "There is an error in the OSExpression Tree -- stack size should be 1 at end");
01890                                 resultString = tmpStack.top();
01891                                 //std::cout << resultString << std::endl;
01892                                 tmpStack.pop();
01893                                 
01894                                 return resultString;
01895                         }
01896                         else{
01897                                 //throw ErrorClass("Error in getNonlinearExpressionTreeInInfix, there is no expression tree for this index");
01898                                 return "";
01899                         }
01900                 }  
01901                 else{
01902                         throw ErrorClass("Error in getNonlinearExpressionTreeInInfix, rowIdx not valid");
01903                 }
01904                 return resultString;    
01905         }
01906         catch(const ErrorClass& eclass){
01907                 throw ErrorClass( eclass.errormsg);
01908         } 
01909 }//getNonlinearExpressionTreeInInfix
01910 
01911 
01912 std::string OSInstance::printModel( ){
01913         std::string resultString = "";
01914         ostringstream outStr;
01915         outStr << "";
01916         int numCon;
01917         int numObj;
01918         int numVar;
01919         int i;
01920         numCon = this->getConstraintNumber();
01921         numObj = this->getObjectiveNumber();
01922         numVar = this->getVariableNumber();
01923         this->initForAlgDiff( );
01924         outStr << std::endl;
01925         outStr << "Objectives:" << std::endl;           
01926         for(i = 0; i < numObj; i++){
01927                 if( this->getObjectiveMaxOrMins()[0] == "min"){
01928                         outStr << "min ";
01929                 }
01930                 else{
01931                         outStr << "max ";
01932                 }
01933                 outStr << this->printModel( i - numObj);
01934         }       
01935         outStr << std::endl;
01936         outStr << "Constraints:" << std::endl;          
01937         for(i = 0; i < numCon; i++){
01938                 outStr << this->printModel( i);
01939         }
01940         
01941         outStr << std::endl;
01942         outStr << "Variables:" << std::endl;
01943         if(m_bProcessVariables != true ) this->processVariables();
01944         for(i = 0; i < numVar; i++){
01945                 outStr << "x_";
01946                 outStr << i;
01947                 outStr << " Type = " ;
01948                 outStr <<  m_mcVariableTypes[i];
01949                 outStr << "  Lower Bound =  ";
01950                 outStr << os_dtoa_format( m_mdVariableLowerBounds[i])  ;
01951                 outStr << "  Upper Bound =  ";
01952                 outStr << os_dtoa_format( m_mdVariableUpperBounds[i])  ;
01953                 outStr << std::endl;
01954         }       
01955         
01956         // if model was originally in column matrix form we need to delete the new
01957         // matrix stored by row
01958         
01959         //if( this->instanceData->linearConstraintCoefficients != NULL && this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
01960         //      if(m_bColumnMajor == true){// we now have a duplication
01961         //              delete m_linearConstraintCoefficientsInRowMajor;
01962         //      }
01963         //}
01964         return outStr.str() ;
01965 }//printModel( )
01966 
01967 
01968 std::string OSInstance::printModel(int rowIdx ){
01969         std::string resultString = "";
01970         ostringstream outStr;
01971         outStr << "";
01972         //loop over the consraints first;
01973         int j;
01974         int row_nonz = 0;
01975         int obj_nonz = 0;
01976         int varIdx = 0;
01977         bool addedLinearTerm = false;
01978         
01979         // initialize all of the necessary nonlinear stuff
01980         this->initForAlgDiff( );        
01981         
01982         if( rowIdx >= 0){
01983                 if( m_bProcessConstraints != true ) this->processConstraints() ;
01984                 if( m_mdConstraintLowerBounds[ rowIdx] >  -OSDBL_MAX){
01985                         if(m_mdConstraintLowerBounds[ rowIdx] < m_mdConstraintUpperBounds[ rowIdx]){
01986                                 outStr << os_dtoa_format( m_mdConstraintLowerBounds[ rowIdx] );
01987                                 outStr << " <= ";
01988                         }
01989                 } 
01990                 //
01991                 if(this->instanceData->linearConstraintCoefficients != NULL && this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
01992                         if(m_linearConstraintCoefficientsInRowMajor == NULL) 
01993                                 m_linearConstraintCoefficientsInRowMajor = this->getLinearConstraintCoefficientsInRowMajor();
01994                         row_nonz = m_linearConstraintCoefficientsInRowMajor->starts[ rowIdx + 1] - m_linearConstraintCoefficientsInRowMajor->starts[ rowIdx];
01995                         
01996                         for(j = 0; j < row_nonz; j++){
01997                                 varIdx =  m_linearConstraintCoefficientsInRowMajor->indexes[ m_linearConstraintCoefficientsInRowMajor->starts[ rowIdx]  + j];
01998                                 
01999                                 if(m_bSparseJacobianCalculated == false  ||  (m_mapExpressionTreesMod.find( rowIdx) == m_mapExpressionTreesMod.end() ) ||
02000                                         ( (*m_mapExpressionTreesMod[ rowIdx]->mapVarIdx).find( varIdx) == (*m_mapExpressionTreesMod[ rowIdx]->mapVarIdx).end()) ){                                      
02001                                         outStr << os_dtoa_format( m_linearConstraintCoefficientsInRowMajor->values[ m_linearConstraintCoefficientsInRowMajor->starts[ rowIdx]  + j] );
02002                                         outStr << "*";
02003 
02004                                 if(this->instanceData->variables->numberOfVariables > 0 && this->instanceData->variables->var[  varIdx ]->name.size() > 0){
02005                                         outStr << this->instanceData->variables->var[  varIdx ]->name;
02006                                 }else{
02007                                         outStr << "x_";
02008                                         outStr << varIdx;
02009                                 }
02010 
02011 
02012                                         if( j < row_nonz - 1) outStr << " + ";
02013                                         addedLinearTerm = true;
02014                                 }
02015                         }
02016                 }
02017         }else{// process an objective function
02018                 if(m_bProcessObjectives != true ) this->processObjectives() ;
02019                 int obj_idx =  -rowIdx - 1;
02020                 obj_nonz = m_miNumberOfObjCoef[ obj_idx];
02021                 for(j = 0; j < obj_nonz; j++){
02022                         outStr << os_dtoa_format( m_mObjectiveCoefficients[obj_idx]->values[j] );
02023                         outStr << "*";
02024                         if(this->instanceData->variables->numberOfVariables > 0 && this->instanceData->variables->var[ m_mObjectiveCoefficients[obj_idx]->indexes[j] ]->name.size() > 0){
02025                                 outStr << this->instanceData->variables->var[ m_mObjectiveCoefficients[obj_idx]->indexes[j] ]->name;
02026                         }else{
02027                                 outStr << "x_";
02028                                 outStr << m_mObjectiveCoefficients[obj_idx]->indexes[j] ;
02029                         }
02030                         if( j < obj_nonz - 1) outStr << " + ";          
02031                 }
02032         }
02033         if( this->getNonlinearExpressionTree( rowIdx) != NULL){
02034                 if( (addedLinearTerm == true)  || (obj_nonz > 0) ) outStr << " + " ;
02035                 outStr << getNonlinearExpressionTreeInInfix( rowIdx);
02036                 //outStr << ")";
02037         }
02038                 
02039         if( rowIdx >= 0){
02040                 if( m_bProcessConstraints != true ) this->processConstraints() ;
02041                 if( m_mdConstraintUpperBounds[ rowIdx] <  OSDBL_MAX){
02042                         if(m_mdConstraintLowerBounds[ rowIdx] < m_mdConstraintUpperBounds[ rowIdx]){
02043                                 outStr << " <= ";
02044                          }else{
02045                                 outStr << " = ";
02046                          }
02047                         outStr << os_dtoa_format( m_mdConstraintUpperBounds[ rowIdx] ); 
02048                         outStr << "  ";
02049                         outStr << this->getConstraintNames()[ rowIdx] ;
02050                 }
02051         }
02052         outStr << std::endl;    
02053         resultString = outStr.str();
02054         return resultString;
02055 }//printModel( rowIdx )
02056 
02057 
02058 std::vector<OSnLNode*> OSInstance::getNonlinearExpressionTreeModInPostfix( int rowIdx){
02059         //if( m_binitForAlgDiff == false) this->initForAlgDiff();
02060         if( m_bProcessExpressionTreesMod == false ) getAllNonlinearExpressionTreesMod();
02061         std::vector<OSnLNode*> postfixVec;
02062         try{
02063                 if( m_mapExpressionTreesMod.find( rowIdx) != m_mapExpressionTreesMod.end()){
02064                         OSExpressionTree* expTree = getNonlinearExpressionTreeMod( rowIdx);
02065                         postfixVec = expTree->m_treeRoot->getPostfixFromExpressionTree();
02066                         
02067                 }  
02068                 else{
02069                         throw ErrorClass("Error in getNonlinearExpressionTreeModInPostfix, rowIdx not valid");
02070                 }
02071                 return postfixVec;      
02072         }
02073         catch(const ErrorClass& eclass){
02074                 throw ErrorClass( eclass.errormsg);
02075         } 
02076 }//getNonlinearExpressionTreeModInPostfix
02077 
02078 
02079 std::vector<OSnLNode*> OSInstance::getNonlinearExpressionTreeInPrefix( int rowIdx){
02080         //if( m_binitForAlgDiff == false) this->initForAlgDiff();
02081         if( m_bProcessExpressionTrees == false ) getAllNonlinearExpressionTrees();
02082         std::vector<OSnLNode*> prefixVec;
02083         try{
02084                 if( m_mapExpressionTrees.find( rowIdx) != m_mapExpressionTrees.end()){
02085                         OSExpressionTree* expTree = getNonlinearExpressionTree( rowIdx);
02086                         prefixVec = expTree->m_treeRoot->getPrefixFromExpressionTree();
02087                         
02088                 }  
02089                 else{
02090                         throw ErrorClass("Error in getNonlinearExpressionTreeInPrefix, rowIdx not valid");
02091                 }
02092                 return prefixVec;       
02093         }
02094         catch(const ErrorClass& eclass){
02095                 throw ErrorClass( eclass.errormsg);
02096         } 
02097 }//getNonlinearExpressionTreeInPrefix
02098 
02099 std::vector<OSnLNode*> OSInstance::getNonlinearExpressionTreeModInPrefix( int rowIdx){
02100         //if( m_binitForAlgDiff == false) this->initForAlgDiff();
02101         if( m_bProcessExpressionTreesMod == false ) getAllNonlinearExpressionTreesMod();
02102         std::vector<OSnLNode*> prefixVec;
02103         try{
02104                 if( m_mapExpressionTreesMod.find( rowIdx) != m_mapExpressionTreesMod.end()){
02105                         OSExpressionTree* expTree = getNonlinearExpressionTreeMod( rowIdx);
02106                         prefixVec = expTree->m_treeRoot->getPrefixFromExpressionTree();
02107                         
02108                 }  
02109                 else{
02110                         throw ErrorClass("Error in getNonlinearExpressionTreeInPrefix, rowIdx not valid");
02111                 }
02112                 return prefixVec;       
02113         }
02114         catch(const ErrorClass& eclass){
02115                 throw ErrorClass( eclass.errormsg);
02116         } 
02117 }//getNonlinearExpressionTreeInPrefix
02118 
02119 std::map<int, OSExpressionTree*> OSInstance::getAllNonlinearExpressionTrees(){
02120         //if( m_binitForAlgDiff == false) this->initForAlgDiff();
02121         if(m_bProcessExpressionTrees == true) return m_mapExpressionTrees;
02122         std::map<int, int> foundIdx;
02123         std::map<int, int>::iterator pos;
02124         OSnLNodePlus *nlNodePlus;
02125         OSExpressionTree *expTree;  
02126         m_iObjectiveNumberNonlinear = 0;   
02127         m_iConstraintNumberNonlinear = 0;    
02128         int i;   
02129         // important -- tell the nl nodes not to destroy the OSExpression Objects
02130         if( instanceData->nonlinearExpressions->numberOfNonlinearExpressions > 0 && instanceData->nonlinearExpressions->nl != NULL){
02131                 for( i = 0; i < instanceData->nonlinearExpressions->numberOfNonlinearExpressions; i++){
02132                         instanceData->nonlinearExpressions->nl[i]->m_bDeleteExpressionTree = false;
02133                 }
02134         }
02135         int index;  
02136         // kipp -- what should we return if instanceData->nonlinearExpressions->numberOfNonlinearExpressions is zero
02137         for(i = 0; i < instanceData->nonlinearExpressions->numberOfNonlinearExpressions; i++){
02138                 index = instanceData->nonlinearExpressions->nl[ i]->idx;
02139                 if(foundIdx.find( index) != foundIdx.end() ){  
02140                 //if(foundIdx[ index] > 0 ){ 
02141                         //std::cout << "OLD INDEX FOUND " << index << std::endl;
02142                         //std::cout << "foundIdx[ index] " << index << std::endl;
02143                         // found an existing index
02144                         // important -- at this time m_mapExpressionTrees[ index] points to 
02145                         // the last OSExpressionTree with this index, it does not point to the 
02146                         // the just found OSExpressionTree with this index
02147                         nlNodePlus = new OSnLNodePlus();
02148                         //expTree = new OSExpressionTree(); 
02149                         expTree =  instanceData->nonlinearExpressions->nl[ i]->osExpressionTree;
02150                         // set left child to old index and right child to new one 
02151                         nlNodePlus->m_mChildren[ 0] = m_mapExpressionTrees[ index]->m_treeRoot;
02152                         nlNodePlus->m_mChildren[ 1] = instanceData->nonlinearExpressions->nl[ i]->osExpressionTree->m_treeRoot;
02153                         // we must delete the Expression tree corresponding to the old index value but not the nl nodes
02154                         instanceData->nonlinearExpressions->nl[ foundIdx[ index]  ]->m_bDeleteExpressionTree = true;
02155                         instanceData->nonlinearExpressions->nl[ foundIdx[ index]  ]->osExpressionTree->bDestroyNlNodes = false;
02156                         //point to the new expression tree
02157                         m_mapExpressionTrees[ index] = expTree;
02158                         m_mapExpressionTrees[ index]->m_treeRoot = nlNodePlus;
02159                         foundIdx[ index] = i;
02160                 }
02161                 else{  
02162                         // we have a new index
02163                         m_mapExpressionTrees[ index] = instanceData->nonlinearExpressions->nl[ i]->osExpressionTree;
02164                         m_mapExpressionTrees[ index]->m_treeRoot = instanceData->nonlinearExpressions->nl[ i]->osExpressionTree->m_treeRoot;
02165                         foundIdx[ index] = i;
02166                 }
02167                 //foundIdx[ index]++;    
02168         }
02169         // count the number of constraints and objective functions with nonlinear terms.
02170         for(pos = foundIdx.begin(); pos != foundIdx.end(); ++pos){
02171                 if(pos->first == -1) {
02172                         m_iObjectiveNumberNonlinear++; 
02173                 }
02174                 else m_iConstraintNumberNonlinear++;
02175         }
02176         foundIdx.clear();
02177         m_bProcessExpressionTrees = true;
02178         return m_mapExpressionTrees;
02179 }// getAllNonlinearExpressionTrees
02180 
02181 std::map<int, OSExpressionTree*> OSInstance::getAllNonlinearExpressionTreesMod(){
02182         if( m_bProcessExpressionTreesMod == true ) return m_mapExpressionTreesMod;
02183         m_bProcessExpressionTreesMod = true;
02184         // make sure we have the modified map available
02185         if( m_bNonLinearStructuresInitialized == false) initializeNonLinearStructures( );
02186         return m_mapExpressionTreesMod;
02187 }// getAllNonlinearExpressionTreesMod
02188 
02189 
02190 std::string OSInstance::getTimeDomainFormat()
02191 {       if (instanceData->timeDomain == NULL)
02192                 return "";
02193         if (instanceData->timeDomain->interval != NULL)
02194                 return "interval";
02195         if (instanceData->timeDomain->stages != NULL)
02196                 return "stages";
02197         return "";
02198 }// getTimeDomainFormat
02199 
02200 int OSInstance::getTimeDomainStageNumber()
02201 {       if (instanceData->timeDomain == NULL)
02202                 return 1;
02203         if (instanceData->timeDomain->interval != NULL)
02204                 ; //throw an error
02205         if (instanceData->timeDomain->stages == NULL)
02206                 return 1;
02207         return instanceData->timeDomain->stages->numberOfStages;
02208 }// getTimeDomainStageNumber 
02209         
02210 std::string* OSInstance::getTimeDomainStageNames()
02211 {       if (instanceData->timeDomain == NULL)
02212                 return NULL;
02213         if (instanceData->timeDomain->interval != NULL)
02214                 return NULL; //throw an error
02215         if (instanceData->timeDomain->stages == NULL)
02216                 return NULL;
02217         if (m_msTimeDomainStageNames != NULL)
02218                 delete [] m_msTimeDomainStageNames;
02219         if (instanceData->timeDomain->stages->numberOfStages == 0)
02220                 return NULL;
02221         m_msTimeDomainStageNames = new std::string[instanceData->timeDomain->stages->numberOfStages]; 
02222         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02223                 m_msTimeDomainStageNames[i] = instanceData->timeDomain->stages->stage[i]->name;
02224         return m_msTimeDomainStageNames;
02225 }// getTimeDomainStageNames
02226         
02227 int* OSInstance::getTimeDomainStageNumberOfVariables()
02228 {       if (instanceData->timeDomain == NULL)
02229                 return NULL;
02230         if (instanceData->timeDomain->interval != NULL)
02231                 return NULL; //throw an error
02232         if (instanceData->timeDomain->stages == NULL)
02233                 return NULL;
02234         if (m_miTimeDomainStageVariableNumber != NULL) 
02235                 delete [] m_miTimeDomainStageVariableNumber;
02236         if (instanceData->timeDomain->stages->numberOfStages == 0)
02237                 return NULL;
02238         m_miTimeDomainStageVariableNumber = new int[instanceData->timeDomain->stages->numberOfStages];
02239         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++) 
02240                 m_miTimeDomainStageVariableNumber[i] = instanceData->timeDomain->stages->stage[i]->variables->numberOfVariables;
02241         return m_miTimeDomainStageVariableNumber;
02242 }// getTimeDomainStageNumberOfVariables 
02243         
02244 int* OSInstance::getTimeDomainStageNumberOfConstraints()
02245 {       if (instanceData->timeDomain == NULL)
02246                 return NULL;
02247         if (instanceData->timeDomain->interval != NULL)
02248                 return NULL; //throw an error
02249         if (instanceData->timeDomain->stages == NULL)
02250                 return NULL;
02251         if (m_miTimeDomainStageConstraintNumber != NULL)
02252                 delete [] m_miTimeDomainStageConstraintNumber;
02253         if (instanceData->timeDomain->stages->numberOfStages == 0)
02254                 return NULL;
02255         m_miTimeDomainStageConstraintNumber = new int[instanceData->timeDomain->stages->numberOfStages];
02256         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02257                 m_miTimeDomainStageConstraintNumber[i] = instanceData->timeDomain->stages->stage[i]->constraints->numberOfConstraints;
02258         return m_miTimeDomainStageConstraintNumber;
02259 }// getTimeDomainStageNumberOfConstraints
02260 
02261 int* OSInstance::getTimeDomainStageNumberOfObjectives()
02262 {       if (instanceData->timeDomain == NULL)
02263                 return NULL;
02264         if (instanceData->timeDomain->interval != NULL)
02265                 return NULL; //throw an error
02266         if (instanceData->timeDomain->stages == NULL)
02267                 return NULL;
02268         if (m_miTimeDomainStageObjectiveNumber != NULL)
02269                 delete [] m_miTimeDomainStageObjectiveNumber;
02270         if (instanceData->timeDomain->stages->numberOfStages == 0)
02271                 return NULL;
02272         m_miTimeDomainStageObjectiveNumber = new int[instanceData->timeDomain->stages->numberOfStages];
02273         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02274                 m_miTimeDomainStageObjectiveNumber[i] = instanceData->timeDomain->stages->stage[i]->objectives->numberOfObjectives;
02275         return m_miTimeDomainStageObjectiveNumber;
02276 }// getTimeDomainStageNumberOfObjectives
02277         
02278 int** OSInstance::getTimeDomainStageVarList()
02279 {       if (instanceData->timeDomain == NULL)
02280                 return NULL;
02281         if (instanceData->timeDomain->interval != NULL)
02282                 return NULL; //throw an error
02283         if (instanceData->timeDomain->stages == NULL)
02284                 return NULL;
02285         if (m_miTimeDomainStageVariableNumber == NULL)
02286                 return NULL;
02287         if (m_mmiTimeDomainStageVarList != NULL){
02288                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
02289                         delete[] m_mmiTimeDomainStageVarList[i];
02290                 delete[] m_mmiTimeDomainStageVarList;
02291                 m_mmiTimeDomainStageVarList = NULL;
02292         }
02293         
02294                 //delete [] m_mmiTimeDomainStageVarList;
02295         if (instanceData->timeDomain->stages->numberOfStages == 0)
02296                 return NULL;
02297         m_iNumberOfTimeStages = instanceData->timeDomain->stages->numberOfStages;
02298         m_mmiTimeDomainStageVarList = new int*[instanceData->timeDomain->stages->numberOfStages];
02299         int timeDomainStageNumberVar;
02300         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02301         {       
02302                 timeDomainStageNumberVar = m_miTimeDomainStageVariableNumber[i];
02303                 m_mmiTimeDomainStageVarList[i] = new int[ timeDomainStageNumberVar ];
02304                 if (instanceData->timeDomain->stages->stage[i]->variables->startIdx == -1)
02305                         for (int j = 0; j < m_miTimeDomainStageVariableNumber[i]; j++)
02306                                 m_mmiTimeDomainStageVarList[i][j] = instanceData->timeDomain->stages->stage[i]->variables->var[j]->idx;
02307                 else
02308                         for (int j = 0; j < m_miTimeDomainStageVariableNumber[i]; j++)
02309                                 m_mmiTimeDomainStageVarList[i][j] = instanceData->timeDomain->stages->stage[i]->variables->startIdx + j;
02310         }
02311         return m_mmiTimeDomainStageVarList;
02312 }// getTimeDomainStageVarList
02313         
02314 int** OSInstance::getTimeDomainStageConList()
02315 {       if (instanceData->timeDomain == NULL)
02316                 return NULL;
02317         if (instanceData->timeDomain->interval != NULL)
02318                 return NULL; //throw an error
02319         if (instanceData->timeDomain->stages == NULL)
02320                 return NULL;
02321         if (m_miTimeDomainStageConstraintNumber == NULL)
02322                 return NULL;
02323         if (m_mmiTimeDomainStageConList != NULL){
02324                 
02325                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
02326                         delete[] m_mmiTimeDomainStageConList[i];
02327                 delete[] m_mmiTimeDomainStageConList;
02328                 m_mmiTimeDomainStageConList = NULL;             
02329         }
02330                 
02331         if (instanceData->timeDomain->stages->numberOfStages == 0)
02332                 return NULL;
02333         m_iNumberOfTimeStages = instanceData->timeDomain->stages->numberOfStages;
02334         m_mmiTimeDomainStageConList = new int*[instanceData->timeDomain->stages->numberOfStages];
02335         int numTimeDomainStageCon;
02336         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02337         {       
02338                 numTimeDomainStageCon = m_miTimeDomainStageConstraintNumber[i];
02339                 m_mmiTimeDomainStageConList[i] = new int[ numTimeDomainStageCon];
02340                 if (instanceData->timeDomain->stages->stage[i]->constraints->startIdx == -1)
02341                         for (int j = 0; j < m_miTimeDomainStageConstraintNumber[i]; j++)
02342                                 m_mmiTimeDomainStageConList[i][j] = instanceData->timeDomain->stages->stage[i]->constraints->con[j]->idx;
02343                 else
02344                         for (int j = 0; j < m_miTimeDomainStageConstraintNumber[i]; j++)
02345                                 m_mmiTimeDomainStageConList[i][j] = instanceData->timeDomain->stages->stage[i]->constraints->startIdx + j;
02346         }
02347         return m_mmiTimeDomainStageConList;
02348 }// getTimeDomainStageConList
02349 
02350 int** OSInstance::getTimeDomainStageObjList()
02351 {       if (instanceData->timeDomain == NULL)
02352                 return NULL;
02353         if (instanceData->timeDomain->interval != NULL)
02354                 return NULL; //throw an error
02355         if (instanceData->timeDomain->stages == NULL)
02356                 return NULL;
02357         if (m_miTimeDomainStageObjectiveNumber == NULL)
02358                 return NULL;
02359         if (m_mmiTimeDomainStageObjList != NULL){
02360                 for (int i = 0; i < m_iNumberOfTimeStages; i ++) 
02361                         delete[] m_mmiTimeDomainStageObjList[i];
02362                 delete[] m_mmiTimeDomainStageObjList;
02363                 m_mmiTimeDomainStageObjList = NULL;
02364         }
02365         if (instanceData->timeDomain->stages->numberOfStages == 0)
02366                 return NULL;
02367         m_iNumberOfTimeStages = instanceData->timeDomain->stages->numberOfStages;
02368         m_mmiTimeDomainStageObjList = new int*[instanceData->timeDomain->stages->numberOfStages];
02369         int numTimeDomainStageObjNum;
02370         for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
02371         {       
02372                 numTimeDomainStageObjNum = m_miTimeDomainStageObjectiveNumber[i];
02373                 m_mmiTimeDomainStageObjList[i] = new int[ numTimeDomainStageObjNum];
02374                 if (instanceData->timeDomain->stages->stage[i]->objectives->startIdx == 0)
02375                         for (int j = 0; j < m_miTimeDomainStageObjectiveNumber[i]; j++)
02376                                 m_mmiTimeDomainStageObjList[i][j] = instanceData->timeDomain->stages->stage[i]->objectives->obj[j]->idx;
02377                 else
02378                         for (int j = 0; j < m_miTimeDomainStageObjectiveNumber[i]; j++)
02379                                 m_mmiTimeDomainStageObjList[i][j] = instanceData->timeDomain->stages->stage[i]->objectives->startIdx - j;
02380         }
02381         return m_mmiTimeDomainStageObjList;
02382 }// getTimeDomainStageObjList
02383 
02384 double OSInstance::getTimeDomainIntervalStart()
02385 {       if (instanceData->timeDomain == NULL)
02386                 return 0.0;
02387         if (instanceData->timeDomain->stages != NULL)
02388                 return 0.0; //throw an error
02389         if (instanceData->timeDomain->interval == NULL)
02390                 return 0.0;
02391         return instanceData->timeDomain->interval->start;
02392 }// getTimeDomainIntervalStart
02393 
02394 double OSInstance::getTimeDomainIntervalHorizon()
02395 {       if (instanceData->timeDomain == NULL)
02396                 return 0.0;
02397         if (instanceData->timeDomain->stages != NULL)
02398                 return 0.0; //throw an error
02399         if (instanceData->timeDomain->interval == NULL)
02400                 return 0.0;
02401         return instanceData->timeDomain->interval->horizon;
02402 }// getTimeDomainIntervalHorizon
02403 
02404 
02405 
02406 
02407 // the set() methods
02408 
02409 bool OSInstance::setInstanceSource(string source){
02410         instanceHeader->source = source;
02411         return true;
02412 }//setInstanceSource
02413 
02414 bool OSInstance::setInstanceDescription(string description){
02415         instanceHeader->description = description;
02416         return true;
02417 }//setInstanceDescription
02418 
02419 
02420 bool OSInstance::setInstanceName(string name){
02421          instanceHeader->name = name;
02422          return true;
02423 }//setInstanceName
02424 
02425 
02426 bool OSInstance::setVariableNumber(int number){
02427         // this method assume osinstance->instanceData->variables is not null
02428         if(number < 0) return false;
02429         //if(instanceData->variables->numberOfVariables != -1  && instanceData->variables->numberOfVariables != number){
02430         //      delete[] instanceData->variables->var;
02431         //      instanceData->variables->var = NULL;
02432         //} 
02433         if(instanceData->variables == NULL) instanceData->variables = new Variables();
02434         instanceData->variables->numberOfVariables = number;
02435         if(instanceData->variables->var == NULL && number > 0){
02436                 instanceData->variables->var = new Variable*[number];
02437         }
02438         return true;
02439 }//setVariableNumber
02440 
02441 
02442 bool OSInstance::addVariable(int index, string name, double lowerBound, double upperBound, char type){
02443         instanceData->variables->var[index] = new Variable();
02444         if(index < 0 || instanceData->variables->numberOfVariables <= 0 || index >= instanceData->variables->numberOfVariables) return false;
02445         instanceData->variables->var[index]->name = name;
02446         instanceData->variables->var[index]->lb = lowerBound;
02447         instanceData->variables->var[index]->ub = upperBound;
02448         instanceData->variables->var[index]->type = type;
02449         //if(init != OSNAN) instanceData->variables->var[index]->init = init;
02450         //instanceData->variables->var[index]->initString = initString;
02451         return true;
02452 }//addVariable
02453 
02454 
02455 bool OSInstance::setVariables(int number, string *names, double *lowerBounds, 
02456         double *upperBounds, char *types){
02457         if(number <= 0) return false;
02458         try{
02459                 if(instanceData->variables == NULL){
02460                         throw ErrorClass("There is no variables object");
02461                 }
02462                 if(instanceData->variables->numberOfVariables != number){
02463                         throw ErrorClass("input number of variables not equal to number in class");
02464                 }
02465                 //instanceData->variables->var = new Variable*[number];
02466                 int i;
02467                 for(i = 0; i < number; i++){
02468                         instanceData->variables->var[ i] = new Variable();
02469                 }
02470                 if(names  != NULL){
02471                         for(i = 0; i < number; i++) instanceData->variables->var[i]->name = names[i];                           
02472                 }
02473                 if(lowerBounds != NULL){
02474                         for(i = 0; i < number; i++){
02475                                 instanceData->variables->var[i]->lb = lowerBounds[i];  
02476                         }
02477                 }
02478                 if(upperBounds != NULL){
02479                         for(i = 0; i < number; i++){
02480                                 instanceData->variables->var[i]->ub = upperBounds[i]; 
02481                         }
02482                 }
02483                 if(types != NULL){
02484                         for(i = 0; i < number; i++){
02485                                 instanceData->variables->var[i]->type = types[i];
02486                                 if(types[i] != 'C' && types[i] != 'B' && types[i] != 'I' && types[i] != 'S') types[i] = 'C';
02487                         } 
02488                 }
02489                 /*
02490                 if(inits != NULL){
02491                         for(i = 0; i < number; i++) instanceData->variables->var[i]->init = inits[i];                           
02492                 }
02493                 if(initsString != NULL){
02494                         for(i = 0; i < number; i++) instanceData->variables->var[i]->initString = initsString[i];                       
02495                 }
02496                 */
02497                 return true;
02498         }
02499         catch(const ErrorClass& eclass){
02500                 throw ErrorClass(  eclass.errormsg); 
02501         }
02502 }//setVariables
02503 
02504 // begin checking again with Jun Ma
02505 
02506 bool OSInstance::setObjectiveNumber(int number){
02507         if(number < 0) return false;
02508         if(instanceData->objectives == NULL) instanceData->objectives = new Objectives();
02509         if(number == 0){
02510                 instanceData->objectives->numberOfObjectives = 0;
02511                 instanceData->objectives->obj = 0;
02512                 return true;
02513         }
02514         instanceData->objectives->numberOfObjectives = number;
02515         instanceData->objectives->obj = new Objective*[number];                         
02516         return true;
02517 }//setObjectiveNumber
02518 
02519 bool OSInstance::addObjective(int index, string name, string maxOrMin, double constant, double weight, SparseVector *objectiveCoefficients){
02520         if(index >= 0 || instanceData->objectives->numberOfObjectives <= 0 || abs(index) > instanceData->objectives->numberOfObjectives) return false;
02521         int arrayIndex = abs(index) -1;
02522         if(instanceData->objectives->obj == NULL) return false;
02523         instanceData->objectives->obj[arrayIndex] = new Objective();
02524         instanceData->objectives->obj[arrayIndex]->name = name;
02525         if( (maxOrMin != "max") && (maxOrMin != "min") ) return false;
02526         else instanceData->objectives->obj[arrayIndex]->maxOrMin = maxOrMin;
02527         instanceData->objectives->obj[arrayIndex]->constant = constant;
02528         instanceData->objectives->obj[arrayIndex]->weight = weight;
02529         int n = objectiveCoefficients->number;                  
02530         instanceData->objectives->obj[arrayIndex]->numberOfObjCoef = n;
02531         if(n == 0){
02532                 instanceData->objectives->obj[arrayIndex]->coef = 0;
02533         }
02534         else{
02535                 int i = 0;
02536                 instanceData->objectives->obj[arrayIndex]->coef = new ObjCoef*[n];
02537                 for(i = 0; i < n; i++) instanceData->objectives->obj[arrayIndex]->coef[i] = new ObjCoef();
02538                 for(i = 0; i < n; i++){
02539                         instanceData->objectives->obj[arrayIndex]->coef[i]->idx = objectiveCoefficients->indexes[i];
02540                         instanceData->objectives->obj[arrayIndex]->coef[i]->value = objectiveCoefficients->values[i];   
02541                 }                       
02542         }
02543         return true;
02544 }//addObjective
02545 
02546 bool OSInstance::setObjectives(int number, string *names, string *maxOrMins, double *constants, double *weights, SparseVector **objectiveCoefficients){
02547         if(number < 0) return false;
02548         try{
02549                 if(instanceData->objectives == NULL){
02550                         throw ErrorClass("there is no objectives object");              
02551                 }               
02552                 if(instanceData->objectives->numberOfObjectives != number){
02553                         throw ErrorClass("input number of objective not equal to number in class");             
02554                 }
02555                 if(number == 0) return true;
02556                 int i = 0;
02557                 for(i = 0; i < number; i++)instanceData->objectives->obj[i] = new Objective();
02558                 int j = 0;
02559                 if(names != NULL){
02560                         for(i = 0; i < number; i++) instanceData->objectives->obj[i]->name = names[i];                          
02561                 }       
02562                 if(maxOrMins != NULL){
02563                         for(i = 0; i < number; i++){
02564                                 if(maxOrMins[i] == "" || (maxOrMins[i].compare("max") != 0 && maxOrMins[i].compare("min") !=0)) return false;
02565                                 instanceData->objectives->obj[i]->maxOrMin = maxOrMins[i];                      
02566                         }
02567                 }
02568                 if(constants != NULL){
02569                         for(i = 0; i < number; i++) instanceData->objectives->obj[i]->constant = constants[i];                          
02570                 }
02571                 if(weights != NULL){
02572                         for(i = 0; i < number; i++) instanceData->objectives->obj[i]->weight = weights[i];                      
02573                 }
02574                 if(objectiveCoefficients != NULL){
02575                         for(i = 0; i < number; i++){
02576                                 int n = (&objectiveCoefficients[i] == NULL || objectiveCoefficients[i]->indexes == NULL)?0:objectiveCoefficients[i]->number;            
02577                                 instanceData->objectives->obj[i]->numberOfObjCoef = n;
02578                                 if(n == 0){
02579                                         instanceData->objectives->obj[i]->coef = NULL;
02580                                 }
02581                                 else{
02582                                         instanceData->objectives->obj[i]->coef = new ObjCoef*[n];
02583                                         for(j = 0; j < n; j++){
02584                                                 instanceData->objectives->obj[i]->coef[j] = new ObjCoef();
02585                                                 instanceData->objectives->obj[i]->coef[j]->idx  = objectiveCoefficients[i]->indexes[j];
02586                                                 instanceData->objectives->obj[i]->coef[j]->value = objectiveCoefficients[i]->values[j];                         
02587                                         }                       
02588                                 }                                                       
02589                         }
02590                 }
02591                 return true;
02592         }
02593         catch(const ErrorClass& eclass){
02594                 throw ErrorClass(  eclass.errormsg); 
02595         }
02596 }//setObjectives
02597 
02598 
02599 bool OSInstance::setConstraintNumber(int number){
02600         if(number < 0) return false;
02601         if(instanceData->constraints == NULL) instanceData->constraints = new Constraints();
02602         if(number == 0){
02603                 instanceData->constraints->numberOfConstraints = 0;
02604                 instanceData->constraints->con = 0;
02605                 return true;
02606         }
02607         instanceData->constraints->numberOfConstraints = number;
02608         if(instanceData->constraints->con == 0 ){
02609                 instanceData->constraints->con = new Constraint*[number];
02610         }
02611         return true;
02612 }//setConstraintNumber
02613 
02614 bool OSInstance::addConstraint(int index, string name, double lowerBound, double upperBound, double constant) {
02615         instanceData->constraints->con[ index] = new Constraint();
02616         if(index < 0 || instanceData->constraints->numberOfConstraints <= 0 || index >= instanceData->constraints->numberOfConstraints) return false;
02617         instanceData->constraints->con[ index]->name = name;
02618         if(lowerBound != -OSDBL_MAX && lowerBound != -OSDBL_MAX) instanceData->constraints->con[ index]->lb = lowerBound;
02619         if(upperBound != OSDBL_MAX && upperBound != OSDBL_MAX)instanceData->constraints->con[ index]->ub = upperBound;
02620         instanceData->constraints->con[ index]->constant = constant;
02621         return true;
02622 }//addConstraint
02623 
02624 
02625 bool OSInstance::setConstraints(int number, string* names, double* lowerBounds, double* upperBounds, double* constants){
02626         if(number < 0) return false;
02627         if(number == 0){
02628                 // this is done in setConstraintNumber
02629                 //instanceData->constraints = new Constraints();
02630                 //instanceData->constraints->numberOfConstraints = 0;
02631                 //instanceData->constraints->con = NULL;
02632                 return true;
02633         }
02634         try{
02635                 
02636                 if(instanceData->constraints  == NULL){
02637                         throw ErrorClass("there is no constraints object");             
02638                 }               
02639                 if(instanceData->constraints->numberOfConstraints != number){
02640                         throw ErrorClass("input number of constraints not equal to number in class");           
02641                 }
02642                 int i = 0;
02643                 for(i = 0; i < number; i++){
02644                         instanceData->constraints->con[i] = new Constraint();
02645                 }
02646                 if(names != NULL){
02647                         for(i = 0; i < number; i++) instanceData->constraints->con[i]->name = names[i];                         
02648                 }
02649                 if(lowerBounds != NULL){
02650                         for(i = 0; i < number; i++){
02651                                 if(lowerBounds[i] != -OSDBL_MAX && lowerBounds[i] != -OSDBL_MAX)instanceData->constraints->con[i]->lb = lowerBounds[i]; 
02652                         }
02653                 }
02654                 if(upperBounds != NULL){
02655                         for(i = 0; i < number; i++){
02656                                 if(upperBounds[i] != OSDBL_MAX && upperBounds[i] != OSDBL_MAX)instanceData->constraints->con[i]->ub = upperBounds[i]; 
02657                         }
02658                 }   
02659                 if(constants != NULL){
02660                         for(i = 0; i < number; i++) instanceData->constraints->con[i]->constant = constants[i];                         
02661                 }
02662                 return true;
02663         }
02664         catch(const ErrorClass& eclass){
02665                 throw ErrorClass(  eclass.errormsg); 
02666         }
02667 }//setConstraints
02668 
02669 bool OSInstance::setLinearConstraintCoefficients(int numberOfValues, bool isColumnMajor, 
02670                 double* values, int valuesBegin, int valuesEnd, 
02671                 int* indexes, int indexesBegin, int indexesEnd,                         
02672                 int* starts, int startsBegin, int startsEnd)
02673 {
02674         if(numberOfValues < 0) return false;
02675         if(instanceData->linearConstraintCoefficients == NULL) instanceData->linearConstraintCoefficients = new LinearConstraintCoefficients() ;
02676         if(numberOfValues == 0) return true;
02677         if((values == 0 ) ||
02678            (valuesBegin < 0 || (valuesEnd - valuesBegin + 1) != numberOfValues) ||
02679            (indexes == 0) ||
02680            (indexesBegin < 0 || (indexesEnd - indexesBegin + 1) != numberOfValues) ||
02681            (starts == 0 ) ||
02682            (startsBegin < 0  || startsBegin >= startsEnd)) return false;
02683         instanceData->linearConstraintCoefficients->numberOfValues = numberOfValues;
02684         int i = 0;
02685         //starts
02686         if(instanceData->linearConstraintCoefficients->start == NULL) instanceData->linearConstraintCoefficients->start = new IntVector();
02687         if(startsBegin == 0 ){
02688                 instanceData->linearConstraintCoefficients->start->el = starts;
02689         }
02690         else{
02691                 instanceData->linearConstraintCoefficients->start->el = new int[startsEnd - startsBegin + 1];
02692                 int k = 0;
02693                 for(i = startsBegin; i <= startsEnd; i++){
02694                         instanceData->linearConstraintCoefficients->start->el[k] = starts[i];
02695                         k++;
02696                 }
02697         }                
02698         //values
02699         if(instanceData->linearConstraintCoefficients->value == NULL) instanceData->linearConstraintCoefficients->value = new DoubleVector();
02700         if(valuesBegin == 0 ){
02701                 instanceData->linearConstraintCoefficients->value->el = values;
02702         }
02703         else{
02704                 instanceData->linearConstraintCoefficients->value->el = new double[numberOfValues];
02705                 int k = 0;
02706                 for(i = valuesBegin; i <= valuesEnd; i++){
02707                         instanceData->linearConstraintCoefficients->value->el[k] = values[i];
02708                         k++;
02709                 }
02710         }
02711         //indexes
02712         if(instanceData->linearConstraintCoefficients->rowIdx == NULL) instanceData->linearConstraintCoefficients->rowIdx = new IntVector();
02713         if(instanceData->linearConstraintCoefficients->colIdx == NULL) instanceData->linearConstraintCoefficients->colIdx = new IntVector();
02714         if(isColumnMajor){
02715                 if(indexesBegin == 0 ){
02716                         instanceData->linearConstraintCoefficients->rowIdx->el = indexes;
02717                 }
02718                 else{
02719                         instanceData->linearConstraintCoefficients->rowIdx->el = new int[numberOfValues];
02720                         int k = 0;
02721                         for(i = indexesBegin; i <= indexesEnd; i++){
02722                                 instanceData->linearConstraintCoefficients->rowIdx->el[k] = indexes[i];
02723                                 k++;
02724                         }
02725                 }
02726         } 
02727         else{
02728                 if(indexesBegin == 0 ){
02729                         instanceData->linearConstraintCoefficients->colIdx->el = indexes;
02730                 }
02731                 else{
02732                         instanceData->linearConstraintCoefficients->colIdx->el = new int[numberOfValues];
02733                         int k = 0;
02734                         for(i = indexesBegin; i <= indexesEnd; i++){
02735                                 instanceData->linearConstraintCoefficients->colIdx->el[k] = indexes[i];
02736                                 k++;
02737                         }
02738                 }
02739         }
02740         return true;
02741 }//setLinearConstraintCoefficients
02742 
02743 bool OSInstance::setQuadraticTerms(int number, 
02744                 int* rowIndexes, int* varOneIndexes, int* varTwoIndexes, double* coefficients,
02745                 int begin, int end){
02746         if(number < 0) return false;
02747         if(number != (end - begin) + 1) return false;
02748         if(number == 0){
02749                 instanceData->quadraticCoefficients = 0;
02750                 return true;
02751         }
02752         if( ((end - begin + 1) != number) ||
02753            (rowIndexes == 0) ||                    
02754            (varOneIndexes == 0) ||
02755            (varTwoIndexes == 0) ||
02756            (coefficients == 0) ) return false;
02757         instanceData->quadraticCoefficients = new QuadraticCoefficients();
02758         instanceData->quadraticCoefficients->numberOfQuadraticTerms = number;
02759         int i = 0;
02760         instanceData->quadraticCoefficients->qTerm = new QuadraticTerm*[number];
02761         for(i = 0; i < number; i++) instanceData->quadraticCoefficients->qTerm[i] = new QuadraticTerm();
02762         int k = 0;
02763         for(i = begin; i <= end; i++){
02764                         instanceData->quadraticCoefficients->qTerm[k]->idx = rowIndexes[i];
02765                         instanceData->quadraticCoefficients->qTerm[k]->idxOne = varOneIndexes[i];
02766                         instanceData->quadraticCoefficients->qTerm[k]->idxTwo = varTwoIndexes[i];
02767                         instanceData->quadraticCoefficients->qTerm[k]->coef = coefficients[i];
02768                         k++;
02769         }
02770         return true;
02771 }//setQuadraticTerms
02772 
02773 bool OSInstance::setQuadraticTermsInNonlinearExpressions(int numQPTerms, int* rowIndexes, int* varOneIndexes, int* varTwoIndexes, double* coefficients){
02774                 instanceData->nonlinearExpressions->numberOfNonlinearExpressions = numQPTerms;
02775                 instanceData->nonlinearExpressions->nl = new Nl*[ numQPTerms ];
02776                 // define the vectors
02777                 OSnLNode *nlNodePoint;
02778                 OSnLNodeVariable *nlNodeVariablePoint;
02779                 std::vector<OSnLNode*> nlNodeVec;
02780                 //
02781                 //
02782                 int i;
02783                 for(i = 0; i < numQPTerms; i++){
02784                         instanceData->nonlinearExpressions->nl[ i] = new Nl();
02785                         instanceData->nonlinearExpressions->nl[ i]->idx = rowIndexes[ i];
02786                         instanceData->nonlinearExpressions->nl[ i]->osExpressionTree = new OSExpressionTree();
02787                 // create a variable nl node for x0
02788                 nlNodeVariablePoint = new OSnLNodeVariable();
02789                 nlNodeVariablePoint->idx = varOneIndexes[ i];
02790                 // give this variable the coefficient
02791                 nlNodeVariablePoint->coef = coefficients[ i];
02792                 nlNodeVec.push_back( nlNodeVariablePoint);
02793                 // create the nl node for x1
02794                 nlNodeVariablePoint = new OSnLNodeVariable();
02795                 nlNodeVariablePoint->idx = varTwoIndexes[ i];
02796                 nlNodeVec.push_back( nlNodeVariablePoint);
02797                 // create the nl node for *
02798                 nlNodePoint = new OSnLNodeTimes();
02799                 nlNodeVec.push_back( nlNodePoint);
02800                 // the vectors are in postfix format
02801                 // now the expression tree
02802                 instanceData->nonlinearExpressions->nl[ i]->osExpressionTree->m_treeRoot =
02803                         nlNodeVec[ 0]->createExpressionTreeFromPostfix( nlNodeVec);
02804                 nlNodeVec.clear();
02805                 }
02806         return true;
02807 }//setQuadraticTermsInNonlinearExpressions
02808 
02809 bool OSInstance::initializeNonLinearStructures( ){
02810         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
02811         if( m_bNonLinearStructuresInitialized == true) return true;
02812         if( m_bProcessVariables == false) processVariables();
02813         if( m_bProcessObjectives == false) processObjectives();
02814         if( m_bProcessConstraints == false) processConstraints();
02815         m_iVariableNumber = instanceData->variables->numberOfVariables;
02816         m_iConstraintNumber = instanceData->constraints->numberOfConstraints;
02817         m_iObjectiveNumber = instanceData->objectives->numberOfObjectives;
02818         // get all of the expression trees
02819         if( m_bProcessExpressionTrees == false) getAllNonlinearExpressionTrees();
02820         // before proceeding get a copy of the map of the Expression Trees
02821         if( m_bDuplicateExpressionTreesMap == false) duplicateExpressionTreesMap();
02822         // now create all of the variable maps for each expression tree
02823         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){  
02824                 (posMapExpTree->second)->getVariableIndiciesMap() ;
02825         }
02826         // add the quadratic terms if necessary
02827         if(getNumberOfQuadraticTerms() > 0) addQTermsToExressionTree();
02828         // now get the map of all nonlinear variables
02829         getAllNonlinearVariablesIndexMap( );
02830         getDenseObjectiveCoefficients();
02831         m_mdConstraintFunctionValues = new double[ this->instanceData->constraints->numberOfConstraints];
02832         m_mdObjectiveFunctionValues = new double[ this->instanceData->objectives->numberOfObjectives];
02833         //m_mdObjGradient = new double[ this->instanceData->variables->numberOfVariables];
02834         m_bNonLinearStructuresInitialized = true;
02835         m_bProcessVariables = true;
02836         m_bProcessObjectives = true;
02837         m_bProcessConstraints = true;
02838         m_bProcessExpressionTrees = true;
02839         m_bDuplicateExpressionTreesMap = true;
02840         return true;
02841 }
02842 
02843 SparseJacobianMatrix *OSInstance::getJacobianSparsityPattern( ){
02844         //if(this->getVariableNumber() == 0 || this->getConstraintNumber() == 0) return NULL;
02845         // if already called return the sparse Jacobian
02846         // it is important that this method NOT get called twice -- if
02847         // there are linear terms in <linearConstraintCoefficients> that
02848         // also appear in <nonlinearExpressions> then they will keep getting added
02849         // to the modified expession tree with each call to this method
02850         if( m_bSparseJacobianCalculated == true) return m_sparseJacMatrix;
02851         //std::cout << "INSIDE GET JACOBIAN SPARSITY PATTERN" << std::endl;
02852         // determine if we are in column or row major
02853         getLinearConstraintCoefficientMajor();
02854         // make sure the data structures have been inialized
02855         if( m_bNonLinearStructuresInitialized == false) initializeNonLinearStructures( );
02856         try{
02857                 if( m_bColumnMajor == true){
02858                          if( getSparseJacobianFromColumnMajor( ) == false) throw ErrorClass("An error occurred in getSpareJacobianFromColumnMajor");
02859                 }
02860                 else {
02861                         if( getSparseJacobianFromRowMajor( ) == false) throw ErrorClass("An error occurred in getSpareJacobianFromRowMajor");
02862                 }
02863         }
02864         catch(const ErrorClass& eclass){
02865                 throw ErrorClass(  eclass.errormsg); 
02866         }
02867         // now fill in the arrays of the sparseJacMatrix
02868         m_sparseJacMatrix = new SparseJacobianMatrix();
02869         // we point to memory already created so don't 
02870         // destroy during garbage collection
02871         m_sparseJacMatrix->bDeleteArrays = false;
02872         m_sparseJacMatrix->valueSize =  m_iJacValueSize;
02873         m_sparseJacMatrix->starts = m_miJacStart;
02874         m_sparseJacMatrix->conVals = m_miJacNumConTerms;
02875         m_sparseJacMatrix->indexes = m_miJacIndex;
02876         m_sparseJacMatrix->values = m_mdJacValue;
02877         m_bSparseJacobianCalculated = true;
02878         return m_sparseJacMatrix;
02879 }//getJacobianSparsityPatter
02880 
02881 bool OSInstance::addQTermsToExressionTree(){
02882         int i, k, idx;
02883         // get the number of qTerms
02884         int numQTerms = instanceData->quadraticCoefficients->numberOfQuadraticTerms;    
02885         if(numQTerms <= 0 || m_bQTermsAdded == true) return true;
02886         OSnLNodeVariable* nlNodeVariableOne;
02887         OSnLNodeVariable* nlNodeVariableTwo;
02888         OSnLNodeTimes* nlNodeTimes;
02889         OSnLNodePlus* nlNodePlus;
02890         OSExpressionTree* expTree;
02891         getQuadraticTerms();    
02892         //std::cout << "PROCESSING QUADRATIC TERMS" << std::endl;
02893         for(i = 0; i < numQTerms; i++){
02894                 idx = m_quadraticTerms->rowIndexes[ i];
02895                 //std::cout << "PROCESSING QTERM  = "  << i <<std::endl;
02896                 // see if row idx is in the expression tree
02897                 if( m_mapExpressionTreesMod.find( idx) != m_mapExpressionTreesMod.end() ) {
02898                         // row idx is in the expression tree
02899                         // add the qTerm in row idx  to the expression tree     
02900                         // define two new OSnLVariable nodes, an OSnLnodeTimes, and OSnLnodePlus 
02901                         nlNodeVariableOne = new OSnLNodeVariable();
02902                         nlNodeVariableOne->idx = m_quadraticTerms->varOneIndexes[ i];
02903                         // see if the variable indexed by nlNodeVariableOne->idx is in the expression tree for row idx
02904                         // if not, add to mapVarIdx
02905                         expTree = m_mapExpressionTreesMod[ idx];
02906                         if(  expTree->m_bIndexMapGenerated == false) expTree->getVariableIndiciesMap();
02907                         if( (*expTree->mapVarIdx).find( nlNodeVariableOne->idx) == (*expTree->mapVarIdx).end()  ){
02908                                 // add to map
02909                                 k = (*expTree->mapVarIdx).size();
02910                                 (*expTree->mapVarIdx)[ nlNodeVariableOne->idx] =  k + 1;
02911                                 #ifdef DEBUG
02912                                 std::cout << "ADDED THE FOLLOWING VAIRABLE TO THE MAP" <<  nlNodeVariableOne->idx << std::endl;
02913                                 #endif
02914                         }
02915                         nlNodeVariableOne->coef = m_quadraticTerms->coefficients[ i];
02916                         nlNodeVariableTwo = new OSnLNodeVariable();
02917                         nlNodeVariableTwo->idx = m_quadraticTerms->varTwoIndexes[ i];
02918                         // see if the variable indexed by nlNodeVariableTwo->idx is in the expression tree for row idx
02919                         // if not, add to mapVarIdx
02920                         if( (*expTree->mapVarIdx).find( nlNodeVariableTwo->idx) == (*expTree->mapVarIdx).end()  ){
02921                                 // add to map
02922                                 k = (*expTree->mapVarIdx).size();
02923                                 (*expTree->mapVarIdx)[ nlNodeVariableTwo->idx] =  k + 1;
02924                                 #ifdef DEBUG
02925                                 std::cout << "ADDED THE FOLLOWING VAIRABLE TO THE MAP" <<  nlNodeVariableTwo->idx << std::endl;
02926                                 #endif
02927                         }
02928                         nlNodeVariableTwo->coef = 1.;
02929                         // now multiply the two new variable nodes together
02930                         nlNodeTimes = new OSnLNodeTimes();
02931                         nlNodeTimes->m_mChildren[ 0] = nlNodeVariableOne;
02932                         nlNodeTimes->m_mChildren[ 1] = nlNodeVariableTwo;               
02933                         // now add the result to the expression tree
02934                         nlNodePlus = new OSnLNodePlus();
02935                         nlNodePlus->m_mChildren[ 0] = expTree->m_treeRoot;
02936                         nlNodePlus->m_mChildren[ 1] = nlNodeTimes;
02937                         //expTree = new OSExpressionTree();
02938                         expTree->m_treeRoot = nlNodePlus ;
02939                         // get rid of old variable map
02940                         if(expTree->m_bIndexMapGenerated == true){
02941                                 delete expTree->mapVarIdx;
02942                                 expTree->mapVarIdx = NULL;
02943                                 expTree->m_bIndexMapGenerated = false;
02944                         }       
02945                         //expTree->m_bIndexMapGenerated = false;
02946                         //m_mapExpressionTreesMod[ idx ]  = expTree;    
02947                         //expTree->mapVarIdx = m_mapExpressionTreesMod[ idx]->mapVarIdx;
02948                 }
02949                 else{
02950                         // create the quadratic expression to add to the expression tree
02951                         nlNodeVariableOne = new OSnLNodeVariable();
02952                         nlNodeVariableOne->idx = m_quadraticTerms->varOneIndexes[ i];
02953                         nlNodeVariableOne->coef = m_quadraticTerms->coefficients[ i];
02954                         nlNodeVariableTwo = new OSnLNodeVariable();
02955                         nlNodeVariableTwo->idx = m_quadraticTerms->varTwoIndexes[ i];
02956                         nlNodeVariableTwo->coef = 1.;
02957                         // now multiply the two new variable nodes together
02958                         nlNodeTimes = new OSnLNodeTimes();
02959                         nlNodeTimes->m_mChildren[ 0] = nlNodeVariableOne;
02960                         nlNodeTimes->m_mChildren[ 1] = nlNodeVariableTwo;
02961                         // create a new expression tree corresponding to row idx.
02962                         expTree = new OSExpressionTree();                                               
02963                         expTree->m_treeRoot = nlNodeTimes ;
02964                         expTree->mapVarIdx = expTree->getVariableIndiciesMap();         
02965                         m_mapExpressionTreesMod[ idx ]  = expTree;
02966                         if(idx < 0){
02967                                 m_iObjectiveNumberNonlinear++;
02968                                 m_bProcessExpressionTrees = true;
02969                         }
02970                         else{
02971                                 m_iConstraintNumberNonlinear++;
02972                                 m_bProcessExpressionTrees = true;
02973                         }
02974                         #ifdef DEBUG
02975                         std::cout << "NUMBER OF EXPRESSION TREES = "  << m_mapExpressionTreesMod.size() <<std::endl;
02976                         std::cout << "NUMBER OF NONLINEAR OBJECTIVES = "  << getNumberOfNonlinearObjectives() <<std::endl;
02977                         #endif
02978                 } 
02979                 // if there were no nonlinear terms make this the expression tree
02980                 if(m_iNonlinearExpressionNumber <= 0) m_mapExpressionTrees = m_mapExpressionTreesMod;
02981                 m_bQTermsAdded =true;
02982         }
02983         return true;
02984 }
02985 
02986 double OSInstance::calculateFunctionValue(int idx, double *x, bool new_x){
02987         try{
02988 
02989                 int i, j;
02990                 double dvalue = 0;
02991                 if( m_binitForAlgDiff == false) initForAlgDiff();
02992                 if( m_bSparseJacobianCalculated == false) getJacobianSparsityPattern();
02993                 if(idx >= 0){ // we have a constraint
02994                         // make sure the index idx is valid
02995                         if( getConstraintNumber() <= idx  ) throw 
02996                         ErrorClass("constraint index not valid in OSInstance::calculateFunctionValue");
02997                         if( new_x == false) return *(m_mdConstraintFunctionValues + idx);
02998                         // get the nonlinear part
02999                         if( m_mapExpressionTreesMod.find( idx) != m_mapExpressionTreesMod.end() ){
03000                                 dvalue = m_mapExpressionTreesMod[ idx]->calculateFunction( x,  new_x);
03001                                 //dvalue = vdFunVals[ idx + 1];
03002                         }
03003                         // now the linear part
03004                         // be careful, loop over only the constant terms in sparseJacMatrix
03005                         i = m_sparseJacMatrix->starts[ idx];
03006                         j = m_sparseJacMatrix->starts[ idx + 1 ];
03007                         //while ( i <  j &&  (i - m_sparseJacMatrix->starts[ idx])  < m_sparseJacMatrix->conVals[ idx] ){
03008                         while ( (i - m_sparseJacMatrix->starts[ idx])  < m_sparseJacMatrix->conVals[ idx] ){
03009                                 //std::cout << "m_sparseJacMatrix->values[ i] " << m_sparseJacMatrix->values[ i] << std::endl;
03010                                 //std::cout << "m_sparseJacMatrix->indexes[ i] " << m_sparseJacMatrix->indexes[ i] << std::endl;
03011                                 dvalue += m_sparseJacMatrix->values[ i]*x[ m_sparseJacMatrix->indexes[ i] ];
03012                                 i++;
03013                         }       
03014                         // add in the constraint function constant
03015                         dvalue += m_mdConstraintConstants[ idx ];
03016                         return dvalue;
03017                 }
03018                 else{ // we have an objective function
03019                         // make sure the index idx is valid
03020                         if( getObjectiveNumber() <= ( abs( idx) - 1) ) throw 
03021                         ErrorClass("objective function index not valid in OSInstance::calculateFunctionValue");
03022                         if( new_x == false) return *(m_mdObjectiveFunctionValues + ( abs( idx) - 1));
03023                         // get the nonlinear part
03024                         if( m_mapExpressionTreesMod.find( idx) != m_mapExpressionTreesMod.end() ){
03025                                 dvalue = m_mapExpressionTreesMod[ idx]->calculateFunction( x,  new_x);
03026                         }
03027                         // get linear part
03028                         SparseVector **objCoef = getObjectiveCoefficients();
03029                         SparseVector *obj = objCoef[ abs( idx) - 1];
03030                         for(i = 0; i < obj->number; i++){
03031                                 dvalue += x[ obj->indexes[i]]*(obj->values[ i]);
03032                         }
03033                         // add in the objective function constant
03034                         dvalue += m_mdObjectiveConstants[ abs( idx) - 1 ];
03035                         // get the coefficients for objective function idx
03036                         *(m_mdObjectiveFunctionValues + ( abs( idx) - 1)) = dvalue;
03037                         return *(m_mdObjectiveFunctionValues + ( abs( idx) - 1));
03038                 }
03039         }
03040         catch(const ErrorClass& eclass){
03041                 throw ErrorClass( eclass.errormsg);
03042         } 
03043 }//calculateFunctionValue
03044 
03045 
03046 double *OSInstance::calculateAllConstraintFunctionValues( double* x, double *objLambda, double *conLambda,
03047         bool new_x, int highestOrder){  
03048         try{
03049                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) 
03050                         getIterateResults(x, objLambda, conLambda, new_x,  highestOrder);
03051         }
03052         catch(const ErrorClass& eclass){
03053                 throw ErrorClass( eclass.errormsg);
03054         } 
03055         return m_mdConstraintFunctionValues;
03056 }//calculateAllConstraintFunctionValues
03057 
03058 
03059 double *OSInstance::calculateAllConstraintFunctionValues(double* x, bool new_x){
03060         try{
03061                 m_iHighestOrderEvaluated = -1;
03062                 if( new_x == false) return m_mdConstraintFunctionValues;
03063                 int idx, numConstraints;
03064                 numConstraints = getConstraintNumber();
03065                 // loop over all constraints
03066                 for(idx = 0; idx < numConstraints; idx++){
03067                         m_mdConstraintFunctionValues[ idx]  = calculateFunctionValue(idx, x, new_x);    
03068                 }
03069                 
03070         }
03071         catch(const ErrorClass& eclass){
03072                 throw ErrorClass( eclass.errormsg);
03073         } 
03074         return m_mdConstraintFunctionValues;    
03075 }//end calculateAllConstraintFunctionValues
03076 
03077 
03078 double *OSInstance::calculateAllObjectiveFunctionValues( double* x, double *objLambda, double *conLambda,
03079         bool new_x, int highestOrder){  
03080         try{
03081                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) 
03082                         getIterateResults(x, objLambda, conLambda, new_x,  highestOrder);
03083         }
03084         catch(const ErrorClass& eclass){
03085                 throw ErrorClass( eclass.errormsg);
03086         } 
03087         return m_mdObjectiveFunctionValues;
03088 }//calculateAllConstraintFunctionValues
03089 
03090 
03091 double *OSInstance::calculateAllObjectiveFunctionValues( double* x, bool new_x){        
03092         try{
03093                 m_iHighestOrderEvaluated = -1;
03094                 
03095                 if( new_x == false) return m_mdObjectiveFunctionValues;
03096                 int idx, numObjectives;
03097                 numObjectives = getObjectiveNumber();
03098                 // loop over all constraints
03099                 for(idx = 0; idx < numObjectives; idx++){
03100                         m_mdObjectiveFunctionValues[ idx]  = calculateFunctionValue(-idx -1, x, new_x); 
03101                 }
03102         }
03103         catch(const ErrorClass& eclass){
03104                 throw ErrorClass( eclass.errormsg);
03105         } 
03106         return m_mdObjectiveFunctionValues;
03107 }//calculateAllObjectiveFunctionValues
03108 
03109 
03110 SparseJacobianMatrix *OSInstance::calculateAllConstraintFunctionGradients(double* x, double *objLambda, double *conLambda,
03111                 bool new_x, int highestOrder){
03112         try{
03113                 if(highestOrder < 1 ) throw ErrorClass("When calling calculateAllConstraintFunctionGradients highestOrder should be 1 or 2");
03114                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) 
03115                         getIterateResults(x, objLambda, conLambda,  new_x,  highestOrder);
03116         }//end try
03117         catch(const ErrorClass& eclass){
03118                 throw ErrorClass( eclass.errormsg);
03119         } 
03120         return m_sparseJacMatrix;
03121 }//calculateAllConstraintFunctionGradients      
03122 
03123 
03124 
03125 SparseVector *OSInstance::calculateConstraintFunctionGradient(double* x, double *objLambda, double *conLambda,
03126                 int idx, bool new_x, int highestOrder){
03127         try{
03128                 if(highestOrder < 1 ) throw ErrorClass("When calling calculateConstraintFunctionGradient highestOrder should be 1 or 2");
03129                 if(idx < 0 || idx >= instanceData->constraints->numberOfConstraints ) 
03130                         throw ErrorClass("invalid index passed to calculateConstraintFunctionGrad");
03131                 SparseVector *sp;
03132                 sp = new SparseVector();
03133                 sp->bDeleteArrays = true;
03134                 int i;
03135                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) 
03136                         getIterateResults(x, objLambda, conLambda,  new_x,  highestOrder);
03137                 sp->number = m_miJacStart[ idx + 1] - m_miJacStart[ idx];
03138                 sp->values = new double[ sp->number];
03139                 sp->indexes = new int[ sp->number];
03140                 for(i = 0; i < sp->number; i++){
03141                         sp->values[ i] = m_mdJacValue[ m_miJacStart[ idx] +  i];
03142                         sp->indexes[ i] = m_miJacIndex[ m_miJacStart[ idx] +  i];
03143                 }
03144                 return sp;
03145         }
03146         catch(const ErrorClass& eclass){
03147                 throw ErrorClass( eclass.errormsg);
03148         } 
03149 }//calculateConstraintFunctionGradient
03150 
03151 
03152 SparseVector *OSInstance::calculateConstraintFunctionGradient(double* x, int idx, bool new_x){
03153         try{
03154                 if(idx < 0 || idx >= instanceData->constraints->numberOfConstraints ) 
03155                         throw ErrorClass("invalid index passed to calculateConstraintFunctionGrad");
03156                 SparseVector *sp;
03157                 sp = new SparseVector();
03158                 sp->bDeleteArrays = true;
03159                 int i;
03160                 if( new_x == true || (1 > m_iHighestOrderEvaluated)  ) 
03161                         getIterateResults(x, NULL, NULL,  new_x,  1);
03162                 sp->number = m_miJacStart[ idx + 1] - m_miJacStart[ idx];
03163                 sp->values = new double[ sp->number];
03164                 sp->indexes = new int[ sp->number];
03165                 for(i = 0; i < sp->number; i++){
03166                         sp->values[ i] = m_mdJacValue[ m_miJacStart[ idx] +  i];
03167                         sp->indexes[ i] = m_miJacIndex[ m_miJacStart[ idx] + i];
03168                 }
03169                 return sp;
03170         }
03171         catch(const ErrorClass& eclass){
03172                 throw ErrorClass( eclass.errormsg);
03173         } 
03174 }//calculateConstraintFunctionGradient
03175 
03176 
03177 double **OSInstance::calculateAllObjectiveFunctionGradients(double* x, double *objLambda, double *conLambda,
03178                 bool new_x, int highestOrder){
03179         try{
03180                 if(highestOrder < 1 ) throw ErrorClass("When calling calculateAllObjectiveFunctionGradients highestOrder should be 1 or 2");
03181                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) {
03182                         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03183                         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03184                                 if(posMapExpTree->first < 0){ // this nonlinear expression indexes an objective function
03185                                         m_mmdObjGradient[ abs( posMapExpTree->first) - 1 ] = calculateObjectiveFunctionGradient(x, objLambda, conLambda, 
03186                                                         posMapExpTree->first, new_x, highestOrder);
03187                                 }       
03188                         }
03189                 }
03190         }
03191         catch(const ErrorClass& eclass){
03192                 throw ErrorClass( eclass.errormsg);
03193         } 
03194         return m_mmdObjGradient;
03195 }// calculateAllObjectiveFunctionGradients
03196 
03197 double *OSInstance::calculateObjectiveFunctionGradient(double* x, double *objLambda, double *conLambda,
03198                 int objIdx, bool new_x, int highestOrder){
03199         /* if we are just doing an objective function gradient we should do a zero order forward sweep
03200          * and a reverse first order reverse sweep
03201          */
03202         try{
03203                 if(highestOrder < 1 ) throw ErrorClass("When calling calculateObjectiveFunctionGradient highestOrder should be 1 or 2");        
03204                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) {
03205                         int domainIdx = 0;      
03206                         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03207                         std::map<int, int>::iterator posVarIndexMap;            
03208                         int iHighestOrderEvaluatedStore;
03209                         unsigned int i;
03210                         iHighestOrderEvaluatedStore = m_iHighestOrderEvaluated;
03211                         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03212                                 //kipp: modify for more than one obj
03213                                 if(posMapExpTree->first == objIdx){
03214                                         if( new_x == true ){
03215                                                 if( m_vdX.size() > 0) m_vdX.clear();
03216                                                 for(posVarIndexMap = m_mapAllNonlinearVariablesIndex.begin(); posVarIndexMap != m_mapAllNonlinearVariablesIndex.end(); ++posVarIndexMap){
03217                                                         m_vdX.push_back( x[ posVarIndexMap->first]) ;
03218                                                 }
03219                                                 if( (m_bOSADFunIsCreated == false || m_bCppADMustReTape == true )  && (m_mapExpressionTreesMod.size() > 0) ) {
03220                                                         createOSADFun( m_vdX);
03221                                                 }                                               
03222                                         }       
03223                                         
03224                                         if(( new_x == true ) || (m_iHighestOrderEvaluated < 0) )this->forwardAD(0, m_vdX);
03225                                         
03226                                         if(( new_x == true ) || (m_iHighestOrderEvaluated < 1) ) {
03227                                                 m_vdRangeUnitVec[ domainIdx] = 1.;
03228                                                 m_vdYjacval = this->reverseAD(1, m_vdRangeUnitVec);
03229                                                 for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
03230                                                         m_mmdObjGradient[ abs( objIdx) - 1 ][ m_miNonLinearVarsReverseMap[ i]] = m_vdYjacval[ i] + 
03231                                                                 m_mmdDenseObjectiveCoefficients[  abs( objIdx) - 1][ m_miNonLinearVarsReverseMap[ i]];
03232                                                 }
03233                                         }
03234                                         m_iHighestOrderEvaluated = iHighestOrderEvaluatedStore;
03235                                         m_vdRangeUnitVec[ domainIdx] = 0.;
03236                                         // exit the loop
03237                                         break;
03238                                 }
03239                                 domainIdx++;
03240                         }
03241                 }                       
03242         }
03243         catch(const ErrorClass& eclass){
03244                 throw ErrorClass( eclass.errormsg);
03245         } 
03246         return m_mmdObjGradient[abs( objIdx) - 1];
03247 }//calculateObjectiveFunctionGradient
03248 
03249 
03250 double *OSInstance::calculateObjectiveFunctionGradient(double* x, int objIdx, bool new_x){
03251         try{
03252                 int domainIdx = 0;      
03253                 std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03254                 std::map<int, int>::iterator posVarIndexMap;    
03255                 unsigned int i;
03256                 int  iHighestOrderEvaluatedStore;       
03257                 iHighestOrderEvaluatedStore = m_iHighestOrderEvaluated;
03258                 for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03259                         if(posMapExpTree->first == objIdx){
03260                                 if( new_x == true ){
03261                                         if( m_vdX.size() > 0) m_vdX.clear();
03262                                         for(posVarIndexMap = m_mapAllNonlinearVariablesIndex.begin(); posVarIndexMap != m_mapAllNonlinearVariablesIndex.end(); ++posVarIndexMap){
03263                                                 m_vdX.push_back( x[ posVarIndexMap->first]) ;
03264                                         }
03265                                         if( (m_bOSADFunIsCreated == false || m_bCppADMustReTape == true )  && (m_mapExpressionTreesMod.size() > 0) ) {
03266                                                 createOSADFun( m_vdX);
03267                                         }                                               
03268                                 }       
03269                                 
03270                                 if(( new_x == true ) || (m_iHighestOrderEvaluated < 0) )this->forwardAD(0, m_vdX);
03271                                 
03272                                 if(( new_x == true ) || (m_iHighestOrderEvaluated < 1) ) {
03273                                         m_vdRangeUnitVec[ domainIdx] = 1.;
03274                                         m_vdYjacval = this->reverseAD(1, m_vdRangeUnitVec);
03275                                         for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
03276                                                 m_mmdObjGradient[ abs( objIdx) - 1 ][ m_miNonLinearVarsReverseMap[ i]] = m_vdYjacval[ i] + 
03277                                                         m_mmdDenseObjectiveCoefficients[  abs( objIdx) - 1][ m_miNonLinearVarsReverseMap[ i]];
03278                                         }
03279                                 }
03280                                 m_iHighestOrderEvaluated = iHighestOrderEvaluatedStore;
03281                                 m_vdRangeUnitVec[ domainIdx] = 0.;
03282                                 // exit the loop
03283                                 break;
03284                         }
03285                         domainIdx++;
03286                 }
03287         }       
03288         catch(const ErrorClass& eclass){
03289                 throw ErrorClass( eclass.errormsg);
03290         } 
03291         return m_mmdObjGradient[abs( objIdx) - 1];
03292 }//calculateObjectiveFunctionGradient   
03293 
03294 SparseHessianMatrix *OSInstance::calculateLagrangianHessian( double* x, double *objLambda, double *conLambda,
03295         bool new_x, int highestOrder){
03296         try{
03297                 if(highestOrder != 2 ) throw ErrorClass("When calling calculateLagrangianHessian highestOrder should be 2");
03298                 if( new_x == true || (highestOrder > m_iHighestOrderEvaluated)  ) {
03299                         //std::cout  << "CALL getIterateResults() FROM calculateLagrangianHessain" << std::endl;
03300                         getIterateResults(x, objLambda, conLambda,  new_x,  highestOrder);
03301                 }
03302         }
03303         catch(const ErrorClass& eclass){
03304                 throw ErrorClass( eclass.errormsg);
03305         } 
03306         return m_LagrangianSparseHessian;
03307 }//calculateLagrangianHessian
03308 
03309 SparseHessianMatrix *OSInstance::calculateHessian(double* x, int idx, bool new_x){
03310         try{
03311                 if(idx < -instanceData->objectives->numberOfObjectives || idx >= instanceData->constraints->numberOfConstraints ) 
03312                         throw ErrorClass("invalid index passed to calculateHessian");
03313                 double *objLambda = new double[ getObjectiveNumber() ];
03314                 double *conLambda = new double[ getConstraintNumber() ];
03315                 //std::cout << "NUMBER OF OBJECTIVES = " << getObjectiveNumber() << std::endl;
03316                 //std::cout << "NUMBER OF CONSTRAINTS = " << getConstraintNumber() << std::endl;
03317                 int i;
03318                 // initialize all to zero
03319                 for(i = 0; i < getObjectiveNumber(); i++){
03320                         objLambda[ i] = 0.0;
03321                 }
03322                 for(i = 0; i < getConstraintNumber(); i++){
03323                         conLambda[ i] = 0.0;
03324                 }
03325                 // see if we have the index of an objective function or a constraint
03326                 // and more corresponding component 1.0
03327                 if(idx < 0){
03328                         objLambda[ abs(idx) - 1] = 1.0;
03329                 }
03330                 else{
03331                         conLambda[ idx] = 1.0;
03332                 }
03333                 if( new_x == true || (2 > m_iHighestOrderEvaluated)  ) {
03334                         getIterateResults(x, objLambda, conLambda, new_x,  2);
03335 //                      std::cout  << "CALL getIterateResults() FROM calculateHessian" << std::endl;
03336                 }
03337                 delete[] objLambda;
03338                 delete[] conLambda;
03339         }
03340         catch(const ErrorClass& eclass){
03341                 throw ErrorClass( eclass.errormsg);
03342         } 
03343         return m_LagrangianSparseHessian;
03344 }//calculateHessian                     
03345 
03346 
03347 
03348 bool OSInstance::getSparseJacobianFromColumnMajor( ){
03349         // we assume column major matrix
03350         if( m_bColumnMajor == false) return false;
03351         int iNumRowStarts = getConstraintNumber() + 1;  
03352         int i,j, iTemp;
03353         int iNumVariableStarts = getVariableNumber() ;
03354         int *start = NULL;
03355         int *index = NULL;
03356         double *value = NULL;
03357         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03358                 start = this->instanceData->linearConstraintCoefficients->start->el;
03359                 index = this->instanceData->linearConstraintCoefficients->rowIdx->el;
03360                 value = this->instanceData->linearConstraintCoefficients->value->el;
03361         }
03362         m_miJacStart = new int[ iNumRowStarts];
03363         m_miJacNumConTerms = new int[ getConstraintNumber()];
03364         OSnLNodePlus *nlNodePlus;
03365         OSnLNodeVariable *nlNodeVariable;
03366         OSExpressionTree *expTree = NULL;
03367         // now initialize starts and variable index maps 
03368         for ( i = 0; i < iNumRowStarts; i++){                   
03369                 m_miJacStart [ i ] = 0;
03370                 // map the variables  in the nonlinear rows
03371                 if( m_mapExpressionTreesMod.find( i) != m_mapExpressionTreesMod.end() ){
03372                         // the following is equivalent to  m_treeRoot->getVariableIndexMap( i);
03373                         m_mapExpressionTreesMod[ i]->getVariableIndiciesMap();
03374                         
03375                 }
03376         }
03377         // only execute the following code if there are linear constraint coefficients
03378         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03379                 // i is indexing columns (variables) and j is indexing row numbers 
03380                 for (i = 0; i < iNumVariableStarts; i++){       
03381                         for (j = start[i]; j < start[ i + 1 ]; j++){
03382                                 // index[ j] is a row index, we have just found an occurance of row index[j]
03383                                 // therefore we increase by 1 (or push back) the start of the row indexed by index[j] + 1, 
03384                                 // i.e. the start of the next row
03385                                 // check to see if variable i is linear/constant in the row index[ j] 
03386                                 // if so, increment m_miJacStart[ index[j] + 1]
03387                                 //
03388                                 if( (m_mapExpressionTreesMod.find( index[ j]) != m_mapExpressionTreesMod.end() ) &&
03389                                         ( (*m_mapExpressionTreesMod[ index[ j]]->mapVarIdx).find( i) != (*m_mapExpressionTreesMod[ index[ j]]->mapVarIdx).end()) ){
03390                                         // variable i is appears in the expression tree for row index[ j]
03391                                         // add the coefficient corresponding to variable i in row index[ j] to the expression tree      
03392                                         // define a new OSnLVariable and OSnLnodePlus 
03393                                         // don't add a zero
03394                                         if( value[j] > 0 || value[j] < 0){
03395                                                 expTree = m_mapExpressionTreesMod[ index[j]  ];
03396                                                 nlNodeVariable = new OSnLNodeVariable();
03397                                                 nlNodeVariable->coef = value[ j];
03398                                                 nlNodeVariable->idx = i;
03399                                                 nlNodePlus = new OSnLNodePlus();
03400                                                 nlNodePlus->m_mChildren[ 0] = m_mapExpressionTreesMod[ index[ j] ]->m_treeRoot;
03401                                                 nlNodePlus->m_mChildren[ 1] = nlNodeVariable;
03402                                                 //expTree = new OSExpressionTree();
03403                                                 expTree->m_treeRoot = nlNodePlus ;
03404                                                 //expTree->mapVarIdx = m_mapExpressionTreesMod[ index[ j]]->mapVarIdx;
03405                                                 //m_mapExpressionTreesMod[ index[ j] ]  = expTree;      
03406                                                 //std::cout << m_mapExpressionTreesMod[ index[ j] ]->m_treeRoot->getNonlinearExpressionInXML() << std::endl;    
03407                                                 //std::cout << m_mapExpressionTrees[ index[ j] ]->m_treeRoot->getNonlinearExpressionInXML() << std::endl;
03408                                         }
03409                                 }
03410                                 else{ 
03411                                         m_miJacStart[ index[j] + 1] ++;
03412                                 }                               
03413                         }
03414                 }
03415         }
03416         // at this point, m_miJacStart[ i] holds the number of columns with a linear/constant nonzero in row i - 1
03417         // we are not done with the start indicies, if we are here, and we
03418         // knew the correct starting point of row i -1, the correct starting point
03419         // for row i is m_miJacStart[i] + m_miJacStart [i - 1]
03420         m_miJacStart[0] = 0;
03421         for (i = 1; i < iNumRowStarts; i++ ){
03422                 m_miJacNumConTerms[ i - 1] = m_miJacStart[i];
03423                 if( m_mapExpressionTreesMod.find( i - 1) != m_mapExpressionTreesMod.end() ){
03424                         m_miJacStart[i] += (m_miJacStart[i - 1] + (*m_mapExpressionTreesMod[ i - 1]->mapVarIdx).size() );
03425                 }
03426                 else{
03427                         m_miJacStart[i] += m_miJacStart[i - 1];
03428                 }       
03429         }
03430         // dimension miIndex and mdValue here
03431         m_iJacValueSize =       m_miJacStart[ iNumRowStarts - 1];
03432         m_miJacIndex = new int[  m_iJacValueSize];
03433         m_mdJacValue = new double[ m_iJacValueSize ];
03434         // now get the values of the constant terms if there are any
03435         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03436                 // loop over variables  
03437                 for (i = 0; i < iNumVariableStarts; i++){
03438                         // get row indices and values of the A matrix
03439                         // kipp -- should we have a check to see if start[i+1] > start[i]
03440                         for (j = start[i]; j < start[ i + 1 ]; j++){
03441                                 // store this variable index in every row where the variable appears
03442                                 // however, don't store this as constant term if it appears in mapVarIdx
03443                                 if( (m_mapExpressionTreesMod.find( index[ j]) == m_mapExpressionTreesMod.end() ) ||
03444                                         ( (*m_mapExpressionTreesMod[ index[ j]]->mapVarIdx).find( i) == (*m_mapExpressionTreesMod[ index[ j]]->mapVarIdx).end()) ){
03445                                         iTemp = m_miJacStart[ index[j]];
03446                                         m_miJacIndex[ iTemp] = i;
03447                                         m_mdJacValue[ iTemp] = value[j];
03448                                         m_miJacStart[ index[j]]++;      
03449                                 }               
03450                         }                       
03451                 } 
03452         }
03453         //
03454         std::map<int, int>::iterator posVarIdx;
03455         // m_miJacStart[ i] is now equal to the correct m_miJacStart[ i] + m_miJacNumConTerms[ i], so readjust
03456         for (i = 0; i < iNumRowStarts - 1; i++ ){
03457                 m_miJacStart[ i] = m_miJacStart [ i] - m_miJacNumConTerms[ i] ; 
03458                 iTemp = m_miJacStart[ i] + m_miJacNumConTerms[ i];
03459                 // if the row is in the list of expression trees read in idicies and values
03460                 if( m_mapExpressionTreesMod.find( i) != m_mapExpressionTreesMod.end() ){
03461                         for(posVarIdx = (*m_mapExpressionTreesMod[ i]->mapVarIdx).begin(); posVarIdx 
03462                         != (*m_mapExpressionTreesMod[ i]->mapVarIdx).end(); ++posVarIdx){
03463                                 m_miJacIndex[ iTemp] = posVarIdx->first;
03464                                 m_mdJacValue[ iTemp] = 0;
03465                                 iTemp++;
03466                         }
03467                 }
03468         }
03469         #ifdef DEBUG
03470         std::cout << "HERE ARE ROW STARTS:" << std::endl;
03471         for (i = 0; i < iNumRowStarts; i++ ){
03472                 std::cout <<  m_miJacStart[ i] << "  "; 
03473         }
03474         std::cout << std::endl << std::endl;
03475         std::cout << "HERE ARE VARIABLE INDICIES:" << std::endl;
03476         for (i = 0; i < m_miJacStart[ iNumRowStarts - 1]; i++ ){
03477                 std::cout <<  m_miJacIndex[ i] << "  "; 
03478         }
03479         std::cout << std::endl << std::endl;
03480         std::cout << "HERE ARE VALUES:" << std::endl;
03481         for (i = 0; i < m_miJacStart[ iNumRowStarts - 1]; i++ ){
03482                 std::cout <<  m_mdJacValue[ i] << "  "; 
03483         }
03484         std::cout << std::endl << std::endl;
03485 
03486         std::cout << "HERE ARE NUMBER OF CONSTANT TERMS:" << std::endl;
03487         for (i = 0; i < iNumRowStarts - 1; i++ ){
03488                 std::cout <<  m_miJacNumConTerms[ i ] << "  ";  
03489         }
03490         std::cout << std::endl << std::endl;
03491         #endif
03492         return true;
03493 }//getSparseJacobianFromColumnMajor
03494 
03495 
03496 
03497 bool OSInstance::getSparseJacobianFromRowMajor( ){
03498         // we assume row major matrix
03499         if( m_bColumnMajor == true) return false;
03500         int iNumJacRowStarts = getConstraintNumber() + 1;
03501         std::map<int, int>::iterator posVarIdx; 
03502         int i,j, k;
03503         int *start = NULL;
03504         int *index = NULL;
03505         double *value = NULL;
03506         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03507                 start = this->instanceData->linearConstraintCoefficients->start->el;
03508                 index = this->instanceData->linearConstraintCoefficients->colIdx->el;
03509                 value = this->instanceData->linearConstraintCoefficients->value->el;
03510         }
03511         m_miJacStart = new int[ iNumJacRowStarts];
03512         m_miJacNumConTerms = new int[ getConstraintNumber()];
03513         OSnLNodePlus *nlNodePlus;
03514         OSnLNodeVariable *nlNodeVariable;
03515         //OSExpressionTree *expTree = NULL;
03516         // now initialize starts and variable index maps 
03517         for ( i = 0; i < iNumJacRowStarts; i++){                        
03518                 m_miJacStart [ i ] = 0;
03519                 // map the variables  in the nonlinear rows
03520                 if( m_mapExpressionTreesMod.find( i) != m_mapExpressionTreesMod.end() ){
03521                         // the following is equivalent to  m_treeRoot->getVariableIndexMap( i);
03522                         m_mapExpressionTreesMod[ i]->getVariableIndiciesMap();
03523                         
03524                 }
03525         }
03526         int loopLimit =  getConstraintNumber();
03527         // only execute the following code if there are linear constraint coefficients
03528         // determine the number of terms in constraint with constant partial derivative
03529         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03530                 // i is indexing rows (constrains) and j is indexing column numbers 
03531                 for (i = 0; i < loopLimit; i++){
03532                         m_miJacNumConTerms[ i] = 0;
03533                         for (j = start[i]; j < start[ i + 1 ]; j++){
03534                                 // determine if variable index[j] appears in the Expression Tree for row i
03535                                 // if we pass if test below then variable i is in the expresssion tree and we add
03536                                 // the linear term to the expession tree
03537                                 if( (m_mapExpressionTreesMod.find( i) != m_mapExpressionTreesMod.end() ) &&
03538                                         ( (*m_mapExpressionTreesMod[ i]->mapVarIdx).find( index[ j]) != (*m_mapExpressionTreesMod[ i]->mapVarIdx).end()) ){
03539                                         // variable index[ j] appears in the expression tree for row i
03540                                         // add the coefficient corresponding to variable index[j] in row i to the expression tree       
03541                                         // define a new OSnLVariable and OSnLnodePlus 
03542                                         if(value[ j] > 0 || value[j] < 0){
03543                                                 nlNodeVariable = new OSnLNodeVariable();
03544                                                 nlNodeVariable->coef = value[ j];
03545                                                 nlNodeVariable->idx = index[ j];
03546                                                 nlNodePlus = new OSnLNodePlus();
03547                                                 nlNodePlus->m_mChildren[ 0] = m_mapExpressionTreesMod[ i ]->m_treeRoot;
03548                                                 nlNodePlus->m_mChildren[ 1] = nlNodeVariable;
03549                                                 //expTree = new OSExpressionTree();
03550                                                 //expTree->m_treeRoot = nlNodePlus ;
03551                                                 //expTree->mapVarIdx = m_mapExpressionTreesMod[ i]->mapVarIdx;
03552                                                 //m_mapExpressionTreesMod[ i ]  = expTree;      
03553                                                 m_mapExpressionTreesMod[ i ]->m_treeRoot = nlNodePlus;
03554                                         }
03555                                 }
03556                                 else{ 
03557                                         //the partial derivative of variable j in row i is constant
03558                                         m_miJacNumConTerms[ i]++;
03559                                 }                               
03560                         }
03561                 }
03562         }
03563         //
03564         m_miJacStart[0] = 0;
03565         for (i = 1; i < iNumJacRowStarts; i++ ){
03566                 if( m_mapExpressionTreesMod.find( i - 1) != m_mapExpressionTreesMod.end() ){
03567                         m_miJacStart[i] = m_miJacStart[i - 1] + (m_miJacNumConTerms[ i - 1] + (*m_mapExpressionTreesMod[ i - 1]->mapVarIdx).size() );
03568                 }
03569                 else{
03570                         m_miJacStart[i] = m_miJacStart[i - 1] + m_miJacNumConTerms[ i - 1];
03571                 }       
03572         }
03573         // we know how many constant terms and size of arrays
03574         // dimension miIndex and mdValue here
03575         m_iJacValueSize =       m_miJacStart[ iNumJacRowStarts - 1];
03576         m_miJacIndex = new int[  m_iJacValueSize];
03577         m_mdJacValue = new double[ m_iJacValueSize ];
03578         // now loop again and put in values and indicies
03579         // first put in the constant terms
03580         if(this->instanceData->linearConstraintCoefficients->numberOfValues > 0){
03581                 for (i = 0; i < loopLimit; i++){
03582                         k = 0;
03583                         for (j = start[i]; j < start[ i + 1 ]; j++){
03584                                 if( (m_mapExpressionTreesMod.find( i) == m_mapExpressionTreesMod.end() ) ||
03585                                         ( (*m_mapExpressionTreesMod[ i]->mapVarIdx).find( index[ j]) == (*m_mapExpressionTreesMod[ i]->mapVarIdx).end()) ){
03586                                                 m_miJacIndex[ m_miJacStart[i] + k ] = index[ j];
03587                                                 m_mdJacValue[ m_miJacStart[i] + k ] = value[ j];
03588                                                 k++;
03589                                         }                       
03590                         }
03591                 }
03592         }
03593         // put in terms from the modified nonlinear expression tree
03594         for (i = 0; i < loopLimit; i++ ){
03595                 k = m_miJacStart[i] + m_miJacNumConTerms[ i ];
03596                 // if the row is in the list of expression trees read in idicies and values
03597                 if( m_mapExpressionTreesMod.find( i) != m_mapExpressionTreesMod.end() ){
03598                         for(posVarIdx = (*m_mapExpressionTreesMod[ i]->mapVarIdx).begin(); posVarIdx 
03599                         != (*m_mapExpressionTreesMod[ i]->mapVarIdx).end(); ++posVarIdx){
03600                                 m_miJacIndex[ k] = posVarIdx->first;
03601                                 m_mdJacValue[ k] = 0;
03602                                 k++;
03603                         }
03604                 }
03605         }
03606         #ifdef DEBUG
03607         std::cout << "HERE ARE ROW STARTS:" << std::endl;
03608         for (i = 0; i < iNumJacRowStarts; i++ ){
03609                 std::cout <<  m_miJacStart[ i] << "  "; 
03610         }
03611         std::cout << std::endl << std::endl;
03612         std::cout << "HERE ARE VARIABLE INDICIES:" << std::endl;
03613         for (i = 0; i < m_miJacStart[ iNumJacRowStarts - 1]; i++ ){
03614                 std::cout <<  m_miJacIndex[ i] << "  "; 
03615         }
03616         std::cout << std::endl << std::endl;
03617         std::cout << "HERE ARE VALUES:" << std::endl;
03618         for (i = 0; i < m_miJacStart[ iNumJacRowStarts - 1]; i++ ){
03619                 std::cout <<  m_mdJacValue[ i] << "  "; 
03620         }
03621         std::cout << std::endl << std::endl;
03622 
03623         std::cout << "HERE ARE NUMBER OF CONSTANT TERMS:" << std::endl;
03624         for (i = 0; i < iNumJacRowStarts - 1; i++ ){
03625                 std::cout <<  m_miJacNumConTerms[ i ] << "  ";  
03626         }
03627         std::cout << std::endl << std::endl;
03628         #endif
03629         return true;
03630 }//getSparseJacobianFromRowMajor
03631 
03632 OSExpressionTree* OSInstance::getLagrangianExpTree( ){
03633         if( m_bLagrangianExpTreeCreated == true) return m_LagrangianExpTree;
03634         // we calculate the Lagrangian for all the objectives and constraints
03635         // with nonlinear terms
03636         // first initialize everything for nonlinear work
03637         if(m_bSparseJacobianCalculated == false) getJacobianSparsityPattern( ); 
03638         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03639         OSnLNodeTimes* nlNodeTimes = NULL;
03640         OSnLNodeVariable* nlNodeVariable = NULL;
03641         OSnLNodeSum* nlNodeSum = NULL;
03642         int numChildren = 0;
03643         int rowIdx;
03644         // create the sum node
03645         nlNodeSum = new OSnLNodeSum();
03646         nlNodeSum->inumberOfChildren = m_mapExpressionTreesMod.size();
03647         nlNodeSum->m_mChildren = new OSnLNode*[ nlNodeSum->inumberOfChildren];
03648         // create and expression tree for the sum node
03649         m_LagrangianExpTree = new OSExpressionTree();
03650         m_LagrangianExpTree->m_treeRoot = nlNodeSum;
03651         // now create the children of the sum node
03652         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03653                 // this variable is the Lagrange multiplier
03654                 nlNodeVariable = new OSnLNodeVariable();
03655                 nlNodeVariable->coef = 1.;
03656                 // get the correct index --
03657                 // for rowIdx = 0, ..., m - 1 set idx = numVar + rowIdx
03658                 rowIdx = posMapExpTree->first;
03659                 if(rowIdx >= 0){
03660                         nlNodeVariable->idx = instanceData->variables->numberOfVariables + rowIdx;
03661                 }
03662                 else{
03663                         nlNodeVariable->idx = instanceData->variables->numberOfVariables + 
03664                         instanceData->constraints->numberOfConstraints + (abs(rowIdx) - 1);
03665                 }
03666                 // now create a times multiply the new variable times the root of the expression tree
03667                 nlNodeTimes = new OSnLNodeTimes();
03668                 nlNodeTimes->m_mChildren[ 0] = nlNodeVariable;
03669                 nlNodeTimes->m_mChildren[ 1] = m_mapExpressionTreesMod[ posMapExpTree->first ]->m_treeRoot;     
03670                 // the times node is the new child
03671                 nlNodeSum->m_mChildren[ numChildren] = nlNodeTimes;
03672                 numChildren++;
03673         }       
03674         // get a variable index map for the expression tree
03675         m_LagrangianExpTree->getVariableIndiciesMap();
03676         // print out the XML for this puppy
03677         //std::cout << "Here comes the Lagrangian Tree" << std::endl;
03678         //std::cout << m_LagrangianExpTree->m_treeRoot->getNonlinearExpressionInXML() << std::endl;
03679         //
03680         m_bLagrangianExpTreeCreated = true;
03681         return m_LagrangianExpTree;
03682 }//getLagrangianExpTree
03683 
03684 std::map<int, int> OSInstance::getAllNonlinearVariablesIndexMap( ){
03685         if(m_bAllNonlinearVariablesIndex == true) return m_mapAllNonlinearVariablesIndex;
03686         //loop over the map of expression tree and get a unique listing of all variables
03687         // put these in the map m_mapAllNonlinearVariablesIndex
03688         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03689         std::map<int, int>::iterator posVarIdx;
03690         OSExpressionTree *expTree;
03691         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03692                 // get the index map for the expression tree
03693                 expTree = posMapExpTree->second;
03694                 if(expTree->m_bIndexMapGenerated == false)expTree->getVariableIndiciesMap();
03695                 for(posVarIdx = (*expTree->mapVarIdx).begin(); posVarIdx != (*expTree->mapVarIdx).end(); ++posVarIdx){
03696                         if( m_mapAllNonlinearVariablesIndex.find( posVarIdx->first) == m_mapAllNonlinearVariablesIndex.end() ){
03697                         // add the variable to the Lagragian map
03698                         m_mapAllNonlinearVariablesIndex[ posVarIdx->first] = 1;
03699                         }
03700                 }
03701         }
03702         m_miNonLinearVarsReverseMap = new int[m_mapAllNonlinearVariablesIndex.size()];
03703         // now order appropriately
03704         int kount = 0;
03705         //std::cout << "HERE IS THE LAGRANGIANN VARIABLE MAPPING" << std::endl;
03706         for(posVarIdx = m_mapAllNonlinearVariablesIndex.begin(); posVarIdx !=m_mapAllNonlinearVariablesIndex.end(); ++posVarIdx){
03707                 posVarIdx->second = kount;
03708                 m_miNonLinearVarsReverseMap[ kount] = posVarIdx->first;
03709                 kount++;
03710                 #ifdef DEBUG
03711                 std::cout <<  "POSITION FIRST =  "  << posVarIdx->first ;
03712                 std::cout <<  "   POSITION SECOND = "  << posVarIdx->second << std::endl;
03713                 #endif
03714         }
03715         m_iNumberOfNonlinearVariables = kount;
03716         //std::cout <<  "NUMBER OF NONLINEAR VARIABLES =  "  << kount ;
03717         m_bAllNonlinearVariablesIndex = true;
03718         return m_mapAllNonlinearVariablesIndex;
03719 }//getAllNonlinearVariablesIndexMap     
03720 
03721 SparseHessianMatrix* OSInstance::getLagrangianHessianSparsityPattern( ){
03722         // fill in the nonzeros in the sparse Hessian
03723         if( m_bLagrangianSparseHessianCreated == true) return m_LagrangianSparseHessian;
03724         if( m_iNumberOfNonlinearVariables == 0) return NULL;
03725         if( m_binitForAlgDiff == false ) initForAlgDiff();
03726         unsigned int i = 0;
03727         unsigned int j;
03728         int numNonz = 0;
03729         // Create the CppAD function if necessary
03730         //
03731         std::vector<double> vx;
03732         std::map<int, int>::iterator posMap1, posMap2;  
03733         if( (m_bOSADFunIsCreated == false || m_bCppADMustReTape == true )  && (m_mapExpressionTreesMod.size() > 0) ) {
03734                 for(posMap1 = m_mapAllNonlinearVariablesIndex.begin(); posMap1 != m_mapAllNonlinearVariablesIndex.end(); ++posMap1){
03735                         vx.push_back( 1.0) ;
03736                 }
03737                 createOSADFun( vx);
03738         }
03739         
03740         
03741         /*
03742         //
03743         // Use CppAD to do a forward sparsity calculation
03744         std::vector<bool> r(m_iNumberOfNonlinearVariables * m_iNumberOfNonlinearVariables);
03745         unsigned int j;
03746         for(i = 0; i < m_iNumberOfNonlinearVariables; i++) { 
03747                 for(j = 0; j < m_iNumberOfNonlinearVariables; j++)
03748                         r[ i * m_iNumberOfNonlinearVariables + j ] = false;
03749                         r[ i * m_iNumberOfNonlinearVariables + i] = true;
03750         }       
03751         // compute sparsity pattern for J(x) = F^{(1)} (x)
03752         (*Fad).ForSparseJac(m_iNumberOfNonlinearVariables, r);
03753         //
03754         //now the second derivative
03755         unsigned int m = m_mapExpressionTreesMod.size();
03756         std::vector<bool> e( m);
03757         //Vector s(m);
03758         for(i = 0; i < m; i++) e[i] = true;
03759         std::cout << "Computing Sparse Hessian" << std::endl;
03760         //m_vbLagHessNonz holds the sparsity pattern Lagrangian of the Hessian
03761         m_vbLagHessNonz = (*Fad).RevSparseHes(m_iNumberOfNonlinearVariables, e);
03762         for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
03763                 //std::cout << "Row " << i << "  of Hessian " << std::endl;
03764                 for(j = i; j < m_iNumberOfNonlinearVariables; j++){
03765                         if(m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j]  == true) numNonz++;
03766                         //std::cout << m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j] <<  "  " ;
03767                 }
03768                 //std::cout << std::endl;
03769         }
03770         
03771         */
03772         // note this function call also fills in m_vbLagHessNonz
03773         numNonz = getADSparsityHessian();
03774         
03775         //std::cout << "Lagrangian Hessian Nonzeros = " << numNonz << std::endl;
03776         i = 0;
03777         // now that we have the dimension create SparseHessianMatrix (upper triangular)
03778         m_LagrangianSparseHessian = new SparseHessianMatrix();
03779         m_LagrangianSparseHessian->bDeleteArrays = true;
03780         m_LagrangianSparseHessian->hessDimension = numNonz;
03781         //m_LagrangianSparseHessian->hessDimension = m_vbLagHessNonz.size();
03782         m_LagrangianSparseHessian->hessRowIdx = new int[m_LagrangianSparseHessian->hessDimension];
03783         m_LagrangianSparseHessian->hessColIdx = new int[m_LagrangianSparseHessian->hessDimension];
03784         m_LagrangianSparseHessian->hessValues = new double[m_LagrangianSparseHessian->hessDimension];
03785         //std::cout << "HESSIAN DIMENSION = " << m_LagrangianSparseHessian->hessDimension << std::endl;
03786         numNonz = 0;
03787         for(posMap1 = m_mapAllNonlinearVariablesIndex.begin(); posMap1 != m_mapAllNonlinearVariablesIndex.end(); ++posMap1){
03788                 //std::cout << "posMap1->first  " << posMap1->first << std::endl;
03789                 j = i;
03790                 for(posMap2 = posMap1; posMap2 != m_mapAllNonlinearVariablesIndex.end(); ++posMap2){
03791                         //std::cout << "posMap2->first  " << posMap2->first << std::endl;
03792                         if(m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j] == true){
03793                                 *(m_LagrangianSparseHessian->hessRowIdx + numNonz) = posMap1->first;
03794                                 *(m_LagrangianSparseHessian->hessColIdx + numNonz) = posMap2->first;
03795                                 numNonz++;
03796                         }
03797                         //std::cout << m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j] <<  "  " << std::endl;
03798                         j++;
03799                 }
03800                 i++;
03801         }
03802         #ifdef DEBUG
03803         std::cout << "HESSIAN SPARSITY PATTERN" << std::endl;
03804         int kj;
03805         for(kj = 0; kj < m_LagrangianSparseHessian->hessDimension; kj++){
03806                 std::cout <<  "Row Index = " << *(m_LagrangianSparseHessian->hessRowIdx + kj) << std::endl;
03807                 std::cout <<  "Column Index = " << *(m_LagrangianSparseHessian->hessColIdx + kj) << std::endl;
03808         }
03809         #endif
03810         //
03811         m_bLagrangianSparseHessianCreated = true;
03812         return m_LagrangianSparseHessian;
03813 }//getLagrangianHessianSparsityPattern
03814 
03815 
03816 void OSInstance::duplicateExpressionTreesMap(){
03817         //std::cout << "I AM IN DUPLICATE EXPRSSION TREES MAP" << std::endl;
03818         // we do this so that we can keep the integrity of the original formulation
03819         if(m_bDuplicateExpressionTreesMap == false){ 
03820                 // first make sure the map was created
03821                 if( m_bProcessExpressionTrees == false) getAllNonlinearExpressionTrees();
03822                 m_mapExpressionTreesMod = m_mapExpressionTrees;
03823                 m_bDuplicateExpressionTreesMap = true;
03824                 return;
03825         }
03826         else{
03827                 return;
03828         }
03829 }//duplicateExpressionTreesMap
03830 
03831 
03832 
03833 bool OSInstance::getIterateResults( double *x, double *objLambda, double* conMultipliers, 
03834                 bool new_x, int highestOrder){
03835         try{ 
03836                 if( m_binitForAlgDiff == false) initForAlgDiff();
03837                 std::map<int, int>::iterator posVarIndexMap;
03838                 
03839                 if(new_x == true){
03840                         if( m_vdX.size() > 0) m_vdX.clear();
03841                         for(posVarIndexMap = m_mapAllNonlinearVariablesIndex.begin(); posVarIndexMap != m_mapAllNonlinearVariablesIndex.end(); ++posVarIndexMap){
03842                                 m_vdX.push_back( x[ posVarIndexMap->first]) ;
03843                         }
03844                         if( (m_bOSADFunIsCreated == false || m_bCppADMustReTape == true )  && (m_mapExpressionTreesMod.size() > 0) ) {
03845                                 createOSADFun( m_vdX);
03846                         }       
03847                 }
03848                 else{ // make sure vector not empty -- this could happen if we have linear obj and nonlinear constraints
03849                         if( m_vdX.size() == 0) {
03850                                 for(posVarIndexMap = m_mapAllNonlinearVariablesIndex.begin(); posVarIndexMap != m_mapAllNonlinearVariablesIndex.end(); ++posVarIndexMap){
03851                                         m_vdX.push_back( x[ posVarIndexMap->first]) ;
03852                                 }
03853                                 if( (m_bOSADFunIsCreated == false || m_bCppADMustReTape == true )  && (m_mapExpressionTreesMod.size() > 0) ) {
03854                                         createOSADFun( m_vdX);
03855                                 }       
03856                         }
03857                 }
03858                 switch( highestOrder){          
03859                         case 0: 
03860                                 if(new_x == true || m_iHighestOrderEvaluated < 0){      
03861                                         if(bUseExpTreeForFunEval == true){
03862                                                 calculateAllConstraintFunctionValues( x, new_x);
03863                                                 calculateAllObjectiveFunctionValues( x, new_x);
03864                                         }
03865                                         else{
03866                                                 getZeroOrderResults(x, objLambda, conMultipliers);
03867                                         }
03868 
03869                                 }
03870                                 break;  
03871                         case 1:
03872                                 if(new_x == true || m_iHighestOrderEvaluated < 0)       
03873                                         getZeroOrderResults(x, objLambda, conMultipliers);
03874                                 if(new_x == true || m_iHighestOrderEvaluated < 1)       
03875                                         getFirstOrderResults(x, objLambda, conMultipliers);
03876                                 break;
03877                         case 2: 
03878                                 if(new_x == true || m_iHighestOrderEvaluated < 0)       
03879                                         getZeroOrderResults(x, objLambda, conMultipliers);
03880                                 if(new_x == true || m_iHighestOrderEvaluated < 2)       
03881                                         getSecondOrderResults(x, objLambda, conMultipliers);
03882                                 break;
03883                         default:
03884                                 throw ErrorClass("Derivative should be order 0, 1, or 2");      
03885                 }//end switch
03886                 return true;
03887         }
03888         catch(const ErrorClass& eclass){
03889                 throw ErrorClass( eclass.errormsg);
03890         }  
03891 }//end getIterateResults
03892 
03893 
03894 bool OSInstance::getZeroOrderResults(double *x, double *objLambda, double *conMultipliers){
03895         try{ 
03896                 // initialize everything
03897                 int i, j, rowNum, objNum;
03898                 if( m_mapExpressionTreesMod.size() > 0){
03899                         m_vdYval = this->forwardAD(0, m_vdX);   
03900                 }
03901                 // now get all function and constraint values using forward result
03902                 for(rowNum = 0; rowNum < m_iConstraintNumber; rowNum++){
03903                         m_mdConstraintFunctionValues[ rowNum] = 0.0;
03904                         if( m_mapExpressionTreesMod.find( rowNum) != m_mapExpressionTreesMod.end() ){
03905                                 m_mdConstraintFunctionValues[ rowNum] = m_vdYval[  m_mapOSADFunRangeIndex[ rowNum]];
03906                         }
03907                         // now the linear part
03908                         // be careful, loop over only the constant terms in sparseJacMatrix
03909                         i = m_sparseJacMatrix->starts[ rowNum];
03910                         j = m_sparseJacMatrix->starts[ rowNum + 1 ];
03911                         while ( (i - m_sparseJacMatrix->starts[ rowNum])  < m_sparseJacMatrix->conVals[ rowNum] ){
03912                                 m_mdConstraintFunctionValues[ rowNum] += m_sparseJacMatrix->values[ i]*x[ m_sparseJacMatrix->indexes[ i] ];
03913                                 i++;
03914                         }       
03915                         // add in the constraint function constant
03916                         m_mdConstraintFunctionValues[ rowNum] += m_mdConstraintConstants[ rowNum ];
03917                         #ifdef DEBUG
03918                         std::cout << "Constraint " <<  rowNum << " function value =  " << m_mdConstraintFunctionValues[ rowNum ] << std::endl;
03919                         #endif
03920                 }
03921                 // now get the objective function values from the forward result
03922                 for(objNum = 0; objNum < m_iObjectiveNumber; objNum++){
03923                         m_mdObjectiveFunctionValues[ objNum] = 0.0;
03924                         if( m_mapExpressionTreesMod.find( -objNum -1) != m_mapExpressionTreesMod.end() ){
03925                                 m_mdObjectiveFunctionValues[ objNum] = m_vdYval[ objNum];
03926                         }
03927                         for(i = 0; i < m_iVariableNumber; i++){
03928                                 m_mdObjectiveFunctionValues[ objNum] += m_mmdDenseObjectiveCoefficients[ objNum][i]*x[ i];
03929                         }
03930                         #ifdef DEBUG
03931                         std::cout << "Objective " << objNum << " function value =  " << m_mdObjectiveFunctionValues[ objNum] << std::endl;
03932                         #endif
03933                 }
03934         return true;
03935         }//end try
03936         catch(const ErrorClass& eclass){
03937                 throw ErrorClass( eclass.errormsg);
03938         }  
03939 }//end getZeroOrderResults
03940 
03941 
03942 
03943 bool OSInstance::getFirstOrderResults(double *x, double *objLambda, double *conMultipliers){
03944         try{
03945                 // initialize everything
03946                 unsigned int i, j;
03947                 int rowNum,  jacIndex;
03948                 unsigned int jstart, jend;
03949                 int idx;
03950                 OSExpressionTree *expTree = NULL;
03951                 int domainIdx = 0;      
03952                 std::map<int, OSExpressionTree*>::iterator posMapExpTree;
03953                 std::map<int, int>::iterator posVarIdx;
03954                 
03960                 if(m_iNumberOfNonlinearVariables >= m_mapExpressionTreesMod.size() ){
03961                         // calculate the gradient by doing a reverse sweep over each row
03962                         // loop over the constraints that have a nonlinear term and get their gradients
03963                         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
03964                                 idx = posMapExpTree->first;
03965                                 // we are considering only constraints, not objective function
03966                                 if(idx >= 0){
03967                                         m_vdRangeUnitVec[ domainIdx] = 1.;
03968                                         m_mapExpressionTreesMod[ idx]->getVariableIndiciesMap(); 
03969                                         m_vdYjacval = this->reverseAD(1, m_vdRangeUnitVec);
03970                                         // check size
03971                                         jstart = m_miJacStart[ idx] + m_miJacNumConTerms[ idx];
03972                                         jend = m_miJacStart[ idx + 1 ];
03973                                         if( (*m_mapExpressionTreesMod[ idx]->mapVarIdx).size() != (jend - jstart)) throw 
03974                                         ErrorClass("number of partials not consistent");
03975                                         j = 0;
03976                                         jacIndex = 0;
03977                                         for(posVarIdx = m_mapAllNonlinearVariablesIndex.begin(); posVarIdx 
03978                                                 != m_mapAllNonlinearVariablesIndex.end(); ++posVarIdx){
03979                                                 //std::cout << "Constraint Function Jacobian Values" << "For Constraint  " << idx  << std::endl;
03980                                                 //std::cout << "Jac Val for index " << posVarIdx->first  << " = " << m_vdYjacval[ jacIndex] << std::endl;
03981                                                 //if(m_miJacIndex[ jstart] != posVarIdx->first) throw ErrorClass("error calculating Jacobian matrix");
03982                                                 // we are working with variable posVarIdx->first in the original variable space
03983                                                 // we need to see which variable this is in the individual constraint map
03984                                                 if( (*m_mapExpressionTreesMod[ idx]->mapVarIdx).find( posVarIdx->first) != (*m_mapExpressionTreesMod[ idx]->mapVarIdx).end()){
03985                                                         m_mdJacValue[ jstart] = m_vdYjacval[ jacIndex];
03986                                                         jstart++;
03987                                                         j++;
03988                                                 }
03989                                                 jacIndex++;
03990                                         }
03991                                         
03992                                         m_vdRangeUnitVec[ domainIdx] = 0.;
03993                                         domainIdx++;
03994                                 }
03995                                 else{    // we have an objective function
03996                                         
03997 
03998                                         domainIdx++;
03999                                 }
04000                         }
04001                 }
04002                 else{  
04003                         // calculate the gradients using a forward sweep over all the variables.                
04004                         for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
04005                                 m_vdDomainUnitVec[i] = 1.;     
04006                                 rowNum = 0;
04007                                 if( m_mapExpressionTreesMod.size() > 0){          
04008                                         m_vdYjacval = this->forwardAD(1, m_vdDomainUnitVec);
04009                                 } 
04010                                 // fill in Jacobian here, we have column i 
04011                                 // start Jacobian calculation
04012                                 for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
04013                                         idx = posMapExpTree->first;
04014                                         // we are considering only constraints, not objective function
04015                                         if(idx >= 0){
04016                                                 //figure out original variable this corresponds to
04017                                                 //then use (*m_mapExpressionTreesMod[ idx]->mapVarIdx) to figure out which variable it is within row idx
04018                                                 //m_mapAllNonlinearVariablesIndex
04019                                                 //std::cout << "This is the following variable in the expression tree  " <<  (*m_mapExpressionTreesMod[ idx]->mapVarIdx)[ m_miNonLinearVarsReverseMap[ i]]<< std::endl;                         
04020                                                 expTree = m_mapExpressionTreesMod[ idx];                
04021                                                 if( (*expTree->mapVarIdx).find( m_miNonLinearVarsReverseMap[ i]) != (*expTree->mapVarIdx).end()  ){             
04022                                                         jacIndex = (*m_mapExpressionTreesMod[ idx]->mapVarIdx)[ m_miNonLinearVarsReverseMap[ i]];
04023                                                         jstart = m_miJacStart[ idx] + m_miJacNumConTerms[ idx];
04024                                                         // kipp change 1 to number of objective functions
04025                                                         m_mdJacValue[ jstart + jacIndex] = m_vdYjacval[m_iObjectiveNumberNonlinear + rowNum];
04026                                                 }
04027                                                 rowNum++;
04028                                         }//end Jacobian calculation
04029                         }                       
04030                         //
04031                         m_vdDomainUnitVec[i] = 0.;
04032                         }
04033                 }
04034                 #ifdef DEBUG
04035                 int k;
04036                 std::cout  << "JACOBIAN DATA " << std::endl;
04037                 for(idx = 0; idx < m_iConstraintNumber; idx++){
04038                         for(k = *(m_sparseJacMatrix->starts + idx); k < *(m_sparseJacMatrix->starts + idx + 1); k++){
04039                                 std::cout << "row idx = " << idx <<  "  col idx = "<< *(m_sparseJacMatrix->indexes + k)
04040                                 << " value = " << *(m_sparseJacMatrix->values + k) << std::endl;
04041                         }
04042                 }
04043                 #endif
04044                 return true;
04045         }//end try
04046         catch(const ErrorClass& eclass){
04047                 throw ErrorClass( eclass.errormsg);
04048         } 
04049 }// end getFirstOrderResults
04050                         
04051 
04052 bool OSInstance::getSecondOrderResults(double *x, double *objLambda, double *conMultipliers){
04053         try{
04054                 // initialize everything
04055                 unsigned int i, j;
04056                 int rowNum,  jacIndex;
04057                 int jstart,  idx;
04058                 OSExpressionTree *expTree = NULL;
04059                 int hessValuesIdx = 0;  
04060                 if( m_bLagrangianSparseHessianCreated == false) getLagrangianHessianSparsityPattern( );
04061                 std::map<int, OSExpressionTree*>::iterator posMapExpTree;
04062                 std::map<int, int>::iterator posVarIndexMap;
04063                 if( objLambda == NULL) throw ErrorClass("must have a multiplier for the objective function even if zero when calling getSecondOrderResults");
04064                 if( conMultipliers == NULL) throw ErrorClass("cannot have a null vector of lagrange multipliers when calling getSecondOrderResults -- okay if  zero");
04065                 if( m_vdLambda.size() > 0) m_vdLambda.clear();
04066                 for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){  
04067                         if( posMapExpTree->first >= 0){
04068                                 m_vdLambda.push_back( conMultipliers[ posMapExpTree->first]);
04069                         }
04070                         else{
04071                                 // kipp correct when there is more than one obj
04072                                 m_vdLambda.push_back( objLambda[ abs(posMapExpTree->first) - 1] );
04073                         }
04074                 }
04075                 for(i = 0; i < m_iNumberOfNonlinearVariables; i++){ 
04076                         m_vdDomainUnitVec[i] = 1.;     
04077                         rowNum = 0;
04078                         if( m_mapExpressionTreesMod.size() > 0){          
04079                                 m_vdYjacval = this->forwardAD(1, m_vdDomainUnitVec);
04080                         } 
04081                         // fill in Jacobian here, we have column i 
04082                         // start Jacobian calculation
04083                         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
04084                                 idx = posMapExpTree->first;
04085                                 // we are considering only constraints, not objective function
04086                                 if(idx >= 0){
04087                                         //figure out original variable this corresponds to
04088                                         //then use (*m_mapExpressionTreesMod[ idx]->mapVarIdx) to figure out which variable it is within row idx
04089                                         //m_mapAllNonlinearVariablesIndex
04090                                         //std::cout << "This is the following variable in the expression tree  " <<  (*m_mapExpressionTreesMod[ idx]->mapVarIdx)[ m_miNonLinearVarsReverseMap[ i]]<< std::endl;                         
04091                                         expTree = m_mapExpressionTreesMod[ idx];                
04092                                         if( (*expTree->mapVarIdx).find( m_miNonLinearVarsReverseMap[ i]) != (*expTree->mapVarIdx).end()  ){             
04093                                                 jacIndex = (*m_mapExpressionTreesMod[ idx]->mapVarIdx)[ m_miNonLinearVarsReverseMap[ i]];
04094                                                 jstart = m_miJacStart[ idx] + m_miJacNumConTerms[ idx];
04095                                                 m_mdJacValue[ jstart + jacIndex] = m_vdYjacval[m_iObjectiveNumberNonlinear + rowNum];
04096                                         }
04097                                         rowNum++;
04098                                 }//end Jacobian calculation
04099                                 else{
04100                                         // see if we have the objective function of interest
04101                                         //kipp fix if more than one obj
04102                                                 m_mmdObjGradient[  (abs( idx) - 1)][ m_miNonLinearVarsReverseMap[ i]] = m_vdYjacval[ (abs( idx) - 1)] + 
04103                                                 m_mmdDenseObjectiveCoefficients[  (abs( idx) - 1)][ m_miNonLinearVarsReverseMap[ i]];                                   
04104                         }//end Obj gradient calculation 
04105                 }                       
04106                 // now calculate the Hessian
04107                 if( m_mapExpressionTreesMod.size() > 0){   
04108                         m_vdw = reverseAD(2, m_vdLambda);   // derivative of partial
04109                 }
04110                 for(j = i; j < m_iNumberOfNonlinearVariables; j++){
04111                         if( m_vbLagHessNonz[i*m_iNumberOfNonlinearVariables + j] == true){
04112                                 m_LagrangianSparseHessian->hessValues[ hessValuesIdx] =  m_vdw[  j*2 + 1];
04113                                 #ifdef DEBUG
04114                                 std::cout << "reverse 2 " << m_LagrangianSparseHessian->hessValues[ hessValuesIdx] << std::endl;
04115                                 #endif
04116                                 hessValuesIdx++;
04117                         }
04118                 }
04119                 //
04120                 //
04121                 m_vdDomainUnitVec[i] = 0.;
04122         }
04123         #ifdef DEBUG
04124         int k;
04125         std::cout  << "JACOBIAN DATA " << std::endl;
04126         for(idx = 0; idx < m_iConstraintNumber; idx++){
04127                 for(k = *(m_sparseJacMatrix->starts + idx); k < *(m_sparseJacMatrix->starts + idx + 1); k++){
04128                         std::cout << "row idx = " << idx <<  "  col idx = "<< *(m_sparseJacMatrix->indexes + k)
04129                         << " value = " << *(m_sparseJacMatrix->values + k) << std::endl;
04130                 }
04131         }
04132         #endif
04133         return true;
04134         }//end try
04135         catch(const ErrorClass& eclass){
04136                 throw ErrorClass( eclass.errormsg);
04137         } 
04138 }// end getSecondOrderResults
04139 
04140 bool OSInstance::initForAlgDiff(){
04141         if( m_binitForAlgDiff == true ) return true;
04142         initializeNonLinearStructures( );
04143         initObjGradients();
04144         getAllNonlinearVariablesIndexMap( );
04145         //if(m_bSparseJacobianCalculated  == false) getJacobianSparsityPattern();
04146         //see if we need to retape 
04147         //loop over expression tree and see if one requires it
04148         std::map<int, OSExpressionTree*>::iterator posMapExpTree;
04149         for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){
04150                 if(posMapExpTree->second->bADMustReTape == true) m_bCppADMustReTape = true;
04151         }                               
04152 
04153         #ifdef DEBUG
04154         std::cout << "RETAPE ==  " << m_bCppADMustReTape << std::endl;
04155         #endif
04156         unsigned int i;
04157         for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
04158                 m_vdDomainUnitVec.push_back( 0.0 );
04159         }
04160         for(i = 0; i < m_mapExpressionTreesMod.size(); i++){
04161                 m_vdRangeUnitVec.push_back( 0.0 );
04162         }
04163         m_binitForAlgDiff = true;
04164         //m_bSparseJacobianCalculated = true;
04165         //m_bProcessExpressionTrees = true;
04166         return true;
04167 }//end initForAlgDiff
04168 
04169 bool OSInstance::initObjGradients(){
04170         int i, j;
04171         int m, n;
04172         m = getObjectiveNumber();
04173         n = getVariableNumber();
04174         getDenseObjectiveCoefficients();
04175         if(m <= 0){
04176                 m_mmdObjGradient = NULL;
04177                 return true;
04178         }
04179         m_mmdObjGradient = new double*[m];
04180         for(i = 0; i < m; i++){
04181                 m_mmdObjGradient[i] = new double[n];
04182                 for(j = 0; j < n; j++){
04183                         m_mmdObjGradient[i][j] =  m_mmdDenseObjectiveCoefficients[ i][j];
04184                         #ifdef DEBUG
04185                         std::cout << "m_mmdObjGradient[i][j] = " << m_mmdObjGradient[i][j]  << std::endl;
04186                         #endif
04187                 }
04188         }
04189         return true;
04190 }//end initObjGradients
04199 bool OSInstance::setTimeDomain(std::string format)
04200 {   if ((format != "stages") && (format != "interval") && (format != "none")) 
04201                 return false;
04202         if (instanceData->timeDomain == NULL)
04203         {       instanceData->timeDomain = new TimeDomain();
04204         }
04205         if (format == "stages")
04206         {       if (instanceData->timeDomain->interval != NULL)
04207                 {       delete instanceData->timeDomain->interval;
04208                         instanceData->timeDomain->interval = NULL;
04209                 }
04210                 if (instanceData->timeDomain->stages == NULL)
04211                         instanceData->timeDomain->stages = new TimeDomainStages();
04212                 m_sTimeDomainFormat = format;
04213         }
04214         if (format == "interval")
04215         {       if (instanceData->timeDomain->stages != NULL)
04216                 {       delete instanceData->timeDomain->stages;
04217                         instanceData->timeDomain->stages = NULL;
04218                 }
04219                 if (instanceData->timeDomain->interval == NULL)
04220                         instanceData->timeDomain->interval = new TimeDomainInterval();
04221                 m_sTimeDomainFormat = format;
04222         }
04223         if (format == "none")
04224         {       if (instanceData->timeDomain->stages != NULL)
04225                 {       delete instanceData->timeDomain->stages;
04226                         instanceData->timeDomain->stages = NULL;
04227                 }
04228                 if (instanceData->timeDomain->interval != NULL)
04229                 {       delete instanceData->timeDomain->interval;
04230                         instanceData->timeDomain->interval = NULL;
04231                 }
04232                 m_sTimeDomainFormat = "";
04233         }
04234         return true;
04235 } //end setTimeDomain
04236 
04240 bool OSInstance::setTimeDomainStages(int number, std::string *names)
04241 {   if (instanceData->timeDomain == NULL)
04242                 instanceData->timeDomain = new TimeDomain();
04243         if (instanceData->timeDomain->interval != NULL)
04244                 return false;
04245         if (instanceData->timeDomain->stages == NULL)
04246         {       instanceData->timeDomain->stages = new TimeDomainStages;
04247         }
04248         else
04249         {       if (instanceData->timeDomain->stages->numberOfStages != number)
04250                 {       for (int i = 0; i < instanceData->timeDomain->stages->numberOfStages; i++)
04251                         {       if (instanceData->timeDomain->stages->stage[i]->variables != NULL)
04252                                 {       delete instanceData->timeDomain->stages->stage[i]->variables;
04253                                         instanceData->timeDomain->stages->stage[i]->variables = NULL;
04254                                 }
04255                                 if (instanceData->timeDomain->stages->stage[i]->constraints != NULL)
04256                                 {       delete instanceData->timeDomain->stages->stage[i]->constraints;
04257                                         instanceData->timeDomain->stages->stage[i]->constraints = NULL;
04258                                 }
04259                                 if (instanceData->timeDomain->stages->stage[i]->objectives != NULL)
04260                                 {       delete instanceData->timeDomain->stages->stage[i]->objectives;
04261                                         instanceData->timeDomain->stages->stage[i]->objectives = NULL;
04262                                 }
04263                                 delete instanceData->timeDomain->stages->stage[i];
04264                                 instanceData->timeDomain->stages->stage[i] = NULL;
04265                         }
04266                         delete []instanceData->timeDomain->stages->stage;
04267                         instanceData->timeDomain->stages->stage = NULL;
04268                 }
04269         }
04270         if (number != 0 )
04271         {       if (instanceData->timeDomain->stages->stage == NULL)
04272                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[number];
04273                 for (int i = 0; i < number; i++)
04274                 {       instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04275                 }
04276                 instanceData->timeDomain->stages->numberOfStages = number;
04277         }
04278         for (int i = 0; i < number; i++)
04279         //initial or empty vars, cons, objectives and set default to all objectives
04280         {       if (instanceData->timeDomain->stages->stage[i]->variables != NULL)
04281                 {       delete instanceData->timeDomain->stages->stage[i]->variables;
04282                         instanceData->timeDomain->stages->stage[i]->variables = NULL;
04283                 }
04284                 instanceData->timeDomain->stages->stage[i]->variables = new TimeDomainStageVariables();
04285                 if (instanceData->timeDomain->stages->stage[i]->constraints != NULL)
04286                 {       delete instanceData->timeDomain->stages->stage[i]->constraints;
04287                         instanceData->timeDomain->stages->stage[i]->constraints = NULL;
04288                 }
04289                 instanceData->timeDomain->stages->stage[i]->constraints = new TimeDomainStageConstraints();
04290                 if (instanceData->timeDomain->stages->stage[i]->objectives != NULL)
04291                 {       delete instanceData->timeDomain->stages->stage[i]->objectives;
04292                         instanceData->timeDomain->stages->stage[i]->objectives = NULL;
04293                 }
04294                 instanceData->timeDomain->stages->stage[i]->objectives = new TimeDomainStageObjectives();
04295                 instanceData->timeDomain->stages->stage[i]->objectives->numberOfObjectives = instanceData->objectives->numberOfObjectives;
04296                 instanceData->timeDomain->stages->stage[i]->objectives->obj = new TimeDomainStageObj*[instanceData->objectives->numberOfObjectives];
04297                 for (int j = 0; j < instanceData->objectives->numberOfObjectives; j++)
04298                 {       instanceData->timeDomain->stages->stage[i]->objectives->obj[j] = new TimeDomainStageObj();
04299                         instanceData->timeDomain->stages->stage[i]->objectives->obj[j]->idx = -(j+1);
04300                 }
04301                 if (names != NULL)
04302                         instanceData->timeDomain->stages->stage[i]->name = names[i];
04303         }
04304         return true;
04305 } //end setTimeDomainStages
04306 
04310 bool OSInstance::setTimeDomainStageVariablesOrdered(int numberOfStages, int *numberOfVariables, int *startIdx)
04311 {       if (instanceData->timeDomain == NULL)
04312                 instanceData->timeDomain = new TimeDomain();
04313         if (instanceData->timeDomain->interval != NULL)
04314                 return false;
04315         if (instanceData->timeDomain->stages == NULL)
04316                 instanceData->timeDomain->stages = new TimeDomainStages();      
04317         if (instanceData->timeDomain->stages != NULL)
04318         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04319                         (instanceData->timeDomain->stages->numberOfStages != 0))
04320                          return false;
04321         }
04322         if (instanceData->timeDomain->stages->numberOfStages == 0)
04323         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04324                 if (instanceData->timeDomain->stages->stage == NULL)
04325                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04326                 for (int i = 0; i < numberOfStages; i++)
04327                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04328         }
04329         int checksum = 0;
04330         for (int i = 0; i < numberOfStages; i++)
04331         //initial or empty vars, cons, objectives and set default to all objectives
04332         {       if (instanceData->timeDomain->stages->stage[i]->variables != NULL)
04333                 {       delete instanceData->timeDomain->stages->stage[i]->variables;
04334                         instanceData->timeDomain->stages->stage[i]->variables = NULL;
04335                 }
04336                 instanceData->timeDomain->stages->stage[i]->variables = new TimeDomainStageVariables();
04337                 instanceData->timeDomain->stages->stage[i]->variables->startIdx = startIdx[i];
04338                 instanceData->timeDomain->stages->stage[i]->variables->numberOfVariables = numberOfVariables[i];
04339                 checksum += numberOfVariables[i];
04340         }
04341         return (checksum == instanceData->variables->numberOfVariables);
04342 } //end setTimeDomainVariablesOrdered
04343 
04347 bool OSInstance::setTimeDomainStageVariablesUnordered(int numberOfStages, int *numberOfVariables, int **varIndex)
04348 {   if (instanceData->timeDomain == NULL)
04349                 instanceData->timeDomain = new TimeDomain();
04350         if (instanceData->timeDomain->interval != NULL)
04351                 return false;
04352         if (instanceData->timeDomain->stages == NULL)
04353                 instanceData->timeDomain->stages = new TimeDomainStages();      
04354         if (instanceData->timeDomain->stages != NULL)
04355         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04356                         (instanceData->timeDomain->stages->numberOfStages != 0))
04357                          return false;
04358         }
04359         if (instanceData->timeDomain->stages->numberOfStages == 0 )
04360         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04361                 if (instanceData->timeDomain->stages->stage == NULL)
04362                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04363                 for (int i = 0; i < numberOfStages; i++)
04364                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04365         }
04366         int checksum = 0;
04367         for (int i = 0; i < numberOfStages; i++)
04368         //initial or empty vars, cons, objectives and set default to all objectives
04369         {       if (instanceData->timeDomain->stages->stage[i]->variables != NULL)
04370                 {       delete instanceData->timeDomain->stages->stage[i]->variables;
04371                         instanceData->timeDomain->stages->stage[i]->variables = NULL;
04372                 }
04373                 instanceData->timeDomain->stages->stage[i]->variables = new TimeDomainStageVariables();
04374                 instanceData->timeDomain->stages->stage[i]->variables->numberOfVariables = numberOfVariables[i];
04375                 instanceData->timeDomain->stages->stage[i]->variables->var = new TimeDomainStageVar*[numberOfVariables[i]];
04376                 for (int j = 0; j < numberOfVariables[i]; j++)
04377                 {       instanceData->timeDomain->stages->stage[i]->variables->var[j] = new TimeDomainStageVar();
04378                         instanceData->timeDomain->stages->stage[i]->variables->var[j]->idx = varIndex[i][j];
04379                 }
04380                 checksum += numberOfVariables[i];
04381         }
04382         if (checksum != instanceData->variables->numberOfVariables) return false;
04383         int *checkvar = new int[instanceData->variables->numberOfVariables];
04384         for (int j = 0; j < instanceData->variables->numberOfVariables; j++)
04385                 checkvar[j] = -1;
04386         int k;
04387         for (int i = 0; i < numberOfStages; i++)
04388                 for (int j = 0; j < instanceData->timeDomain->stages->stage[i]->variables->numberOfVariables; j++)
04389                 {       k = instanceData->timeDomain->stages->stage[i]->variables->var[j]->idx;
04390                         if (checkvar[k] != -1) 
04391                         {       delete [] checkvar;
04392                                 checkvar = NULL;
04393                                 return false;
04394                         }
04395                         checkvar[k] = instanceData->timeDomain->stages->stage[i]->variables->var[j]->idx;
04396                 }
04397         delete [] checkvar;
04398         checkvar = NULL;                        
04399         return true;
04400 } //end setTimeDomainVariablesUnordered
04401 
04405 bool OSInstance::setTimeDomainStageConstraintsOrdered(int numberOfStages, int *numberOfConstraints, int *startIdx)
04406 {   if (instanceData->timeDomain == NULL)
04407                 instanceData->timeDomain = new TimeDomain();
04408         if (instanceData->timeDomain->interval != NULL)
04409                 return false;
04410         if (instanceData->timeDomain->stages == NULL)
04411                 instanceData->timeDomain->stages = new TimeDomainStages();      
04412         if (instanceData->timeDomain->stages != NULL)
04413         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04414                         (instanceData->timeDomain->stages->numberOfStages != 0))
04415                          return false;
04416         }
04417         if (instanceData->timeDomain->stages->numberOfStages == 0 )
04418         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04419                 if (instanceData->timeDomain->stages->stage == NULL)
04420                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04421                 for (int i = 0; i < numberOfStages; i++)
04422                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04423         }
04424         int checksum = 0;
04425         for (int i = 0; i < numberOfStages; i++)
04426         //initial or empty vars, cons, objectives and set default to all objectives
04427         {       if (instanceData->timeDomain->stages->stage[i]->constraints != NULL)
04428                 {       delete instanceData->timeDomain->stages->stage[i]->constraints;
04429                         instanceData->timeDomain->stages->stage[i]->constraints = NULL;
04430                 }
04431                 instanceData->timeDomain->stages->stage[i]->constraints = new TimeDomainStageConstraints();
04432                 instanceData->timeDomain->stages->stage[i]->constraints->startIdx = startIdx[i];
04433                 instanceData->timeDomain->stages->stage[i]->constraints->numberOfConstraints = numberOfConstraints[i];
04434                 checksum += numberOfConstraints[i];
04435         }
04436         return (checksum == instanceData->constraints->numberOfConstraints);
04437 } // end of setTimeStageConstraintsOrdered
04438 
04442 bool OSInstance::setTimeDomainStageConstraintsUnordered(int numberOfStages, int *numberOfConstraints, int **conIndex)
04443 {   if (instanceData->timeDomain == NULL)
04444                 instanceData->timeDomain = new TimeDomain();
04445         if (instanceData->timeDomain->interval != NULL)
04446                 return false;
04447         if (instanceData->timeDomain->stages == NULL)
04448                 instanceData->timeDomain->stages = new TimeDomainStages();      
04449         if (instanceData->timeDomain->stages != NULL)
04450         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04451                         (instanceData->timeDomain->stages->numberOfStages != 0))
04452                          return false;
04453         }
04454         if ( instanceData->timeDomain->stages->numberOfStages == 0 )
04455         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04456                 if (instanceData->timeDomain->stages->stage == NULL)
04457                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04458                 for (int i = 0; i < numberOfStages; i++)
04459                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04460         }
04461         int checksum = 0;
04462         for (int i = 0; i < numberOfStages; i++)
04463         //initial or empty vars, cons, objectives and set default to all objectives
04464         {       if (instanceData->timeDomain->stages->stage[i]->constraints != NULL)
04465                 {       delete instanceData->timeDomain->stages->stage[i]->constraints;
04466                         instanceData->timeDomain->stages->stage[i]->constraints = NULL;
04467                 }
04468                 instanceData->timeDomain->stages->stage[i]->constraints = new TimeDomainStageConstraints();
04469                 instanceData->timeDomain->stages->stage[i]->constraints->numberOfConstraints = numberOfConstraints[i];
04470                 instanceData->timeDomain->stages->stage[i]->constraints->con = new TimeDomainStageCon*[numberOfConstraints[i]];
04471                 for (int j = 0; j < numberOfConstraints[i]; j++)
04472                 {       instanceData->timeDomain->stages->stage[i]->constraints->con[j] = new TimeDomainStageCon();
04473                         instanceData->timeDomain->stages->stage[i]->constraints->con[j]->idx = conIndex[i][j];
04474                 }
04475                 checksum += numberOfConstraints[i];
04476         }
04477         if (checksum != instanceData->constraints->numberOfConstraints) return false;
04478         int *checkvar = new int[instanceData->constraints->numberOfConstraints];
04479         for (int j = 0; j < instanceData->constraints->numberOfConstraints; j++)
04480                 checkvar[j] = -1;
04481         int k;
04482         for (int i = 0; i < numberOfStages; i++)
04483                 for (int j = 0; j < instanceData->timeDomain->stages->stage[i]->constraints->numberOfConstraints; j++)
04484                 {       k = instanceData->timeDomain->stages->stage[i]->constraints->con[j]->idx;
04485                         if (checkvar[k] != -1) 
04486                         {       delete [] checkvar;
04487                                 checkvar = NULL;
04488                                 return false;
04489                         }
04490                         checkvar[k] = instanceData->timeDomain->stages->stage[i]->constraints->con[j]->idx;
04491                 }
04492         delete [] checkvar;
04493         checkvar = NULL;                        
04494         return true;
04495 }// end setTimeDomainStageConstraintsUnordered()
04496 
04500 bool OSInstance::setTimeDomainStageObjectivesOrdered(int numberOfStages, int *numberOfObjectives, int *startIdx)
04501 {   if (instanceData->timeDomain == NULL)
04502                 instanceData->timeDomain = new TimeDomain();
04503         if (instanceData->timeDomain->interval != NULL)
04504                 return false;
04505         if (instanceData->timeDomain->stages == NULL)
04506                 instanceData->timeDomain->stages = new TimeDomainStages();      
04507         if (instanceData->timeDomain->stages != NULL)
04508         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04509                         (instanceData->timeDomain->stages->numberOfStages != 0))
04510                          return false;
04511         }
04512         if (instanceData->timeDomain->stages->numberOfStages == 0)
04513         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04514                 if (instanceData->timeDomain->stages->stage == NULL)
04515                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04516                 for (int i = 0; i < numberOfStages; i++)
04517                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04518         }
04519         for (int i = 0; i < numberOfStages; i++)
04520         //initial or empty vars, cons, objectives and set default to all objectives
04521         {       if (instanceData->timeDomain->stages->stage[i]->objectives != NULL)
04522                 {       delete instanceData->timeDomain->stages->stage[i]->objectives;
04523                         instanceData->timeDomain->stages->stage[i]->objectives = NULL;
04524                 }
04525                 instanceData->timeDomain->stages->stage[i]->objectives = new TimeDomainStageObjectives();
04526                 instanceData->timeDomain->stages->stage[i]->objectives->startIdx = startIdx[i];
04527                 instanceData->timeDomain->stages->stage[i]->objectives->numberOfObjectives = numberOfObjectives[i];
04528         }
04529         return true;
04530 }
04531 
04535 bool OSInstance::setTimeDomainStageObjectivesUnordered(int numberOfStages, int *numberOfObjectives, int **objIndex)
04536 {   if (instanceData->timeDomain == NULL)
04537                 instanceData->timeDomain = new TimeDomain();
04538         if (instanceData->timeDomain->interval != NULL)
04539                 return false;
04540         if (instanceData->timeDomain->stages == NULL)
04541                 instanceData->timeDomain->stages = new TimeDomainStages();      
04542         if (instanceData->timeDomain->stages != NULL)
04543         {       if ((instanceData->timeDomain->stages->numberOfStages != numberOfStages) &&
04544                         (instanceData->timeDomain->stages->numberOfStages != 0))
04545                          return false;
04546         }
04547         if (instanceData->timeDomain->stages->numberOfStages == 0)
04548         {       instanceData->timeDomain->stages->numberOfStages = numberOfStages;
04549                 if (instanceData->timeDomain->stages->stage == NULL)
04550                         instanceData->timeDomain->stages->stage = new TimeDomainStage*[numberOfStages];
04551                 for (int i = 0; i < numberOfStages; i++)
04552                         instanceData->timeDomain->stages->stage[i] = new TimeDomainStage();
04553         }
04554         for (int i = 0; i < numberOfStages; i++)
04555         //initial or empty vars, cons, objectives and set default to all objectives
04556         {       if (instanceData->timeDomain->stages->stage[i]->objectives != NULL)
04557                 {       delete instanceData->timeDomain->stages->stage[i]->objectives;
04558                         instanceData->timeDomain->stages->stage[i]->objectives = NULL;
04559                 }
04560                 instanceData->timeDomain->stages->stage[i]->objectives = new TimeDomainStageObjectives();
04561                 instanceData->timeDomain->stages->stage[i]->objectives->numberOfObjectives = numberOfObjectives[i];
04562                 instanceData->timeDomain->stages->stage[i]->objectives->obj = new TimeDomainStageObj*[numberOfObjectives[i]];
04563                 for (int j = 0; j < numberOfObjectives[i]; j++)
04564                 {       instanceData->timeDomain->stages->stage[i]->objectives->obj[j] = new TimeDomainStageObj();
04565                         instanceData->timeDomain->stages->stage[i]->objectives->obj[j]->idx = objIndex[i][j];
04566                 }
04567         }
04568         int *checkvar = new int[instanceData->objectives->numberOfObjectives];
04569         for (int j = 0; j < instanceData->objectives->numberOfObjectives; j++)
04570                 checkvar[j] = 0;
04571         int k;
04572         for (int i = 0; i < numberOfStages; i++)
04573                 for (int j = 0; j < instanceData->timeDomain->stages->stage[i]->objectives->numberOfObjectives; j++)
04574                 {       k = -instanceData->timeDomain->stages->stage[i]->objectives->obj[j]->idx-1;
04575                         checkvar[k] = instanceData->timeDomain->stages->stage[i]->objectives->obj[j]->idx;
04576                 }
04577         for (int i = 0; i < instanceData->objectives->numberOfObjectives; i++)
04578                 if (checkvar[i] == 0)
04579                 {       delete [] checkvar;
04580                         checkvar = NULL;
04581                         return false;
04582                 }
04583         delete [] checkvar;
04584         checkvar = NULL;                        
04585         return true;
04586 }
04587 
04591 bool OSInstance::setTimeDomainInterval(double start, double horizon)
04592 {   if (instanceData->timeDomain == NULL)
04593                 instanceData->timeDomain = new TimeDomain();
04594         if (instanceData->timeDomain->stages != NULL)
04595                 return false;
04596         if (instanceData->timeDomain->interval == NULL)
04597                 instanceData->timeDomain->interval = new TimeDomainInterval();  
04598         instanceData->timeDomain->interval->start = start;
04599         instanceData->timeDomain->interval->horizon = horizon;
04600         return true;
04601 } //end setTimeDomainInterval
04602 
04603 
04604 bool OSInstance::createOSADFun(std::vector<double> vdX){
04605         try{
04606                 if(m_bOSADFunIsCreated == true) return true;
04607                 //if( m_bNonLinearStructuresInitialized == false) initializeNonLinearStructures( );
04608                 if(m_binitForAlgDiff == false) initForAlgDiff();
04609                 
04610                 //if( m_bAllNonlinearVariablesIndex == false) getAllNonlinearVariablesIndexMap( );
04611                 std::map<int, OSExpressionTree*>::iterator posMapExpTree;
04612                 unsigned int i;
04613                 size_t n = vdX.size();
04614 #ifdef COIN_HAS_CPPAD
04615                 // declare a CppAD vector and fill it in
04616                 CppAD::vector< AD<double> > vdaX( n );
04617                 for(i = 0; i < n; i++){
04618                         vdaX[ i] = vdX[ i];
04619                         //std::cout << "vdX =  " << vdX[ i] << std::endl;
04620                 }
04621                 // declare the independent variables and start recording
04622                 CppAD::Independent( vdaX);
04628                 CppAD::vector< AD<double> > m_vFG;        
04629                 int kount = 0;
04630                 for(posMapExpTree = m_mapExpressionTreesMod.begin(); posMapExpTree != m_mapExpressionTreesMod.end(); ++posMapExpTree){  
04631                         m_vFG.push_back( (posMapExpTree->second)->m_treeRoot->constructADTape(&m_mapAllNonlinearVariablesIndex, &vdaX) );
04632                         //std::cout << "PUSHING BACK EXPRESSION NUMBER " << posMapExpTree->first << std::endl;
04633                         if( m_mapOSADFunRangeIndex.find( posMapExpTree->first) == m_mapOSADFunRangeIndex.end() ){
04634                                 // count which nonlinear obj/constraint this is
04635                                 m_mapOSADFunRangeIndex[ posMapExpTree->first] = kount;
04636                                 kount++;
04637                         }
04638                 }       
04639                 //create the function and stop recording
04640 //              std::cout << "create the function and stop recording"  << std::endl;
04641                 Fad = new CppAD::ADFun<double>(vdaX, m_vFG);
04642 //              std::cout << "range space dimension =  " << m_vFG.size() << std::endl;
04643                 // no forward sweeps done yet
04644                 m_iHighestTaylorCoeffOrder = -1;
04645                 m_bOSADFunIsCreated = true;
04646 #else
04647                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04648 #endif
04649                         
04650                 return true;
04651         }
04652         catch(const ErrorClass& eclass){
04653                 throw ErrorClass( eclass.errormsg);
04654         } 
04655 }//end createOSADFun
04656 
04657 
04658 std::vector<double> OSInstance::forwardAD(int p, std::vector<double> vdX){
04659         try{
04660                 // make sure a OSADFun has been created
04661                 if(m_bOSADFunIsCreated == false) createOSADFun( vdX);
04662                 if(p > (m_iHighestTaylorCoeffOrder + 1) ) throw 
04663                         ErrorClass( "trying to calculate a p order forward when p-1 Taylor coefficient not available");
04664                 // adjust the order of the Taylor coefficient
04665                 m_iHighestTaylorCoeffOrder = p; 
04666                 m_iHighestOrderEvaluated = p;
04667                 //for(int i  = 0; i < vdX.size(); i++){
04668                         //std::cout << "ForwardAD Primal Variables " << i   << " " << vdX[ i] << std::endl;
04669                 //}
04670 #ifdef COIN_HAS_CPPAD
04671                 return (*Fad).Forward(p, vdX);
04672 #else
04673                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04674 #endif
04675                 
04676         }
04677         catch(const ErrorClass& eclass){
04678                 throw ErrorClass( eclass.errormsg);
04679         }  
04680 }//end forwardAD
04681 
04682 
04683 std::vector<double> OSInstance::reverseAD(int p, std::vector<double> vdlambda){
04684         try{
04685 #ifndef COIN_HAS_CPPAD
04686                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04687 #endif
04688                 if(p == 0) throw 
04689                         ErrorClass( "reverseAD must have p >= 1");
04690                 if(p > (m_iHighestTaylorCoeffOrder + 1) ) throw 
04691                         ErrorClass( "trying to calculate a p order reverse when p-1 Taylor coefficient not available");
04692                 //for(int i  = 0; i < vdlambda.size(); i++){
04693                 //      std::cout << "ReverseAD Multiplier " << i   << " " << vdlambda[ i] << std::endl;
04694                 //}
04695                 m_iHighestOrderEvaluated = p;
04696 #ifdef COIN_HAS_CPPAD
04697                 return (*Fad).Reverse(p, vdlambda);
04698 #else
04699                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04700 #endif
04701                 
04702         }
04703         catch(const ErrorClass& eclass){
04704                 throw ErrorClass( eclass.errormsg);
04705         }  
04706 }//end forwardAD
04707 
04708 
04709 int  OSInstance::getADSparsityHessian(){
04710         
04711         unsigned int i;
04712         int numNonz;
04713         numNonz = 0;
04714         try{    
04715                 std::vector<bool> r(m_iNumberOfNonlinearVariables * m_iNumberOfNonlinearVariables);
04716                 unsigned int j;
04717                 for(i = 0; i < m_iNumberOfNonlinearVariables; i++) { 
04718                         for(j = 0; j < m_iNumberOfNonlinearVariables; j++)
04719                                 r[ i * m_iNumberOfNonlinearVariables + j ] = false;
04720                                 r[ i * m_iNumberOfNonlinearVariables + i] = true;
04721                 }       
04722                 // compute sparsity pattern for J(x) = F^{(1)} (x)
04723                 //should only be here if we have CppAD
04724 #ifdef COIN_HAS_CPPAD
04725                 (*Fad).ForSparseJac(m_iNumberOfNonlinearVariables, r);
04726 #else
04727                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04728 #endif
04729                 //
04730                 //now the second derivative
04731                 unsigned int m = m_mapExpressionTreesMod.size();
04732                 std::vector<bool> e( m);
04733                 //Vector s(m);
04734                 for(i = 0; i < m; i++) e[i] = true;
04735 //              std::cout << "Computing Sparse Hessian" << std::endl;
04736                 //m_vbLagHessNonz holds the sparsity pattern Lagrangian of the Hessian
04737 #ifdef COIN_HAS_CPPAD
04738                 m_vbLagHessNonz = (*Fad).RevSparseHes(m_iNumberOfNonlinearVariables, e);
04739 #else
04740                 throw ErrorClass( "Error: An Algorithmic Differentiation Package Not Available");
04741 #endif
04742                 
04743                 for(i = 0; i < m_iNumberOfNonlinearVariables; i++){
04744                         //std::cout << "Row " << i << "  of Hessian " << std::endl;
04745                         for(j = i; j < m_iNumberOfNonlinearVariables; j++){
04746                                 if(m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j]  == true) numNonz++;
04747                                 //std::cout << m_vbLagHessNonz[ i*m_iNumberOfNonlinearVariables + j] <<  "  " ;
04748                         }
04749                         //std::cout << std::endl;
04750                 }       
04751                 return numNonz;
04752         }
04753         catch(const ErrorClass& eclass){
04754                 throw ErrorClass( eclass.errormsg);
04755         }
04756 }//end getADSparsityHessian()
04757 
04758 

Generated on Mon May 3 03:05:23 2010 by  doxygen 1.4.7