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

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

Generated on Thu Aug 5 03:02:58 2010 by  doxygen 1.4.7