RegData.cpp

Go to the documentation of this file.
00001 /***************************************************************************
00002  *   Copyright (C) 2006-2008 by Antonello Lobianco                         *
00003  *   http://regmas.org                                                     *
00004  *                                                                         *
00005  *   This program is free software; you can redistribute it and/or modify  *
00006  *   it under the terms of the GNU General Public License as published by  *
00007  *   the Free Software Foundation; either version 3 of the License, or     *
00008  *   (at your option) any later version.                                   *
00009  *                                                                         *
00010  *   This program is distributed in the hope that it will be useful,       *
00011  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
00012  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
00013  *   GNU General Public License for more details.                          *
00014  *                                                                         *
00015  *   You should have received a copy of the GNU General Public License     *
00016  *   along with this program; if not, write to the                         *
00017  *   Free Software Foundation, Inc.,                                       *
00018  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
00019  ***************************************************************************/
00020 #include <sstream>
00021 #include <stdexcept>
00022 #include <algorithm> //alghoritm used to reverse an array ( reverse(v.begin(), v.end()); )
00023 #include <iomanip> // for unzip
00024 
00025 // Qt headers..
00026 #include <QFile>
00027 #include <QFileInfo>
00028 #include <QString>
00029 #include <QStringList>
00030 #include <QList>
00031 
00032 // Unzip headers..
00033 #include "unzip.h"
00034 
00035 // RegMAS headers..
00036 #include "RegData.h"
00037 //#include "InputDocument.h"
00038 //#include "InputNode.h"
00039 #include "ModelObject.h"
00040 #include "MainWindow.h"
00041 #include "Scheduler.h"
00042 
00043 
00044 
00045 RegData::RegData(ThreadManager* MTHREAD_h){
00046     MTHREAD = MTHREAD_h;
00047 }
00048 
00049 RegData::~RegData(){
00050 
00051 }
00052 
00053 vector<string>
00054 RegData::getScenarios(){
00055     vector<string> toReturn;
00056     LLData table = getTable("scenarios");
00057     for(int i=0;i<table.nrecords();i++){
00058         string scenarioName = table.getData(i,"id");
00059         toReturn.push_back(scenarioName);
00060     }
00061     return toReturn;
00062 }
00063 
00064 int
00065 RegData::getScenarioIndex(){
00066     vector<string> scenarios = getScenarios(); // TODO Check that I can call this function all around the model and not only at the beginning
00067     string currentScenario = MTHREAD->getScenarioName();
00068     for(int i=0;i<scenarios.size();i++){
00069         if (currentScenario == scenarios[i]){
00070             return i;
00071         }
00072     }
00073     msgOut(MSG_CRITICAL_ERROR, "function getScenarioIndex() didn't found the current scenarioName within those returned by getScenarios().");
00074     return 0;
00075 }
00076 
00077 
00078 void 
00079 RegData::setDefaultSettings(){
00080 
00081     LLData table = getTable("settings");
00082     for (int i=0; i< table.nrecords();i++){
00083         BasicData SETT;
00084         SETT.name = table.getData(i,"name");
00085         string type = table.getData(i,"type");
00086         SETT.type = getType(type);
00087         SETT.comment = table.getData(i,"comment");
00088         vector <string> values;
00089         for (int z=0;z<100;z++){
00090             string toSearch = "value_"+i2s(z);
00091             string value = table.getData(i,toSearch);
00092             if (value != ""){
00093                 values.push_back(value);
00094             }
00095         }
00096         SETT.values = values;
00097         programSettingsVector.push_back(SETT);
00098     }   
00099 
00100     // rescaling if we are in the region mode...
00101     if(MTHREAD->RD->getBoolSetting("subRegionMode")){   
00102         int XL  = MTHREAD->RD->getIntSetting("subRegionXLeft");
00103         int XR   = MTHREAD->RD->getIntSetting("subRegionXRight");
00104         int YT = MTHREAD->RD->getIntSetting("subRegionYTop");
00105         int YB = MTHREAD->RD->getIntSetting("subRegionYBottom"); 
00106         double scaleCoeff =
00107             ( (double)  ((XR-XL)*(YB-YT)) )
00108                       /
00109             ( MTHREAD->RD->getIntSetting("nCols") * MTHREAD->RD->getIntSetting("nRows")) ; // ratio between npixel in the subRegion and npixels in the original region
00110         vector <string> value;
00111         value.push_back(d2s(scaleCoeff));
00112         MTHREAD->RD->addSetting("scaleCoeff",value, TYPE_DOUBLE, "Scale coefficient used as this simulation is ran on a sub-region trial");
00113     }
00114     else {
00115         double scaleCoeff = 1;
00116         vector <string> value;
00117         value.push_back(d2s(scaleCoeff));
00118         MTHREAD->RD->addSetting("scaleCoeff",value, TYPE_DOUBLE, "Scale coefficient equal to 1 as this simulation is ran on the whole region");
00119     }
00120 
00121 
00122     // post settings hacks & messages...
00123     if(getBoolSetting("subRegionMode") ){
00124         msgOut(MSG_INFO, "The model is currently running on a sub-region area (mainly for initial model debugging).\nThe Scale coefficient is "+d2s(getDoubleSetting("scaleCoeff"))+".\nYou can enable full-region mode with the setting \"subRegionMode\"");
00125     }
00126     else {
00127         msgOut(MSG_INFO, "The model is currently running on a the whole area (normal mode).\nYou can enable sub-region mode with the setting \"subRegionMode\"\n(useful for initial model debugging/calibration)");
00128     }
00129     // defining if individual agent data has to be show in the model tree Viewer (that is, if we are in the sub-mode region or if we forced to view it)
00130     if ( (getBoolSetting("subRegionMode") || getBoolSetting("forceAgentsView")) &&   ! getBoolSetting("forceAgentsHide") ){
00131         addSetting("agentsView", "true", TYPE_BOOL, "Define if agent data need to be view on the tree viewer");
00132         if (getBoolSetting("forceAgentsView")){
00133             msgOut(MSG_WARNING, "View of individual agent data on the Model Tree Viewer has been forced on.\nThis will considerably slow down the simulation.");
00134         }
00135     }
00136     else {
00137         addSetting("agentsView", "false", TYPE_BOOL, "Define if agent data need to be view on the tree viewer");
00138             msgOut(MSG_INFO, "View of individual agent data on the Model Tree Viewer has been disabled for performance reasons. \nYou can force it on with the setting \"forceAgensView\".");
00139     }
00140     msgOut(MSG_INFO,"### USING SCENARIO: "+MTHREAD->getScenarioName()+" ###");
00141     
00142     setOutputDirectory(getStringSetting("outputDirname").c_str());
00143 };
00144 
00145 void
00146 RegData::setScenarioSettings(){
00147 
00148     string scenarioName = MTHREAD->getScenarioName();
00149     LLData table = getTable(scenarioName+"_settings", MSG_WARNING); //this scenario could not have an associated setting sheet
00150     if(table.getTableName() == "") return;
00151 
00152     for(int i=0; i< table.nrecords(); i++){
00153         BasicData SETT;
00154         string name = table.getData(i,"name");
00155         string stype = table.getData(i,"type");
00156         int type = getType(stype);
00157         string comment = table.getData(i,"comment");
00158         vector <string> values;
00159         for (int z=0;z<100;z++){
00160             string toSearch = "value_"+i2s(z);
00161             string value = table.getData(i,toSearch);
00162             if (value != ""){
00163                 values.push_back(value);
00164             }
00165         }
00166 
00167         for(uint i=0;i<programSettingsVector.size();i++){
00168             if(programSettingsVector[i].name == name){
00169                 programSettingsVector[i].values = values;
00170                 programSettingsVector[i].type = type;
00171                 programSettingsVector[i].comment = comment;
00172                 break;
00173             }
00174         }
00175 
00176     }
00177 
00178     // scaling to subregionmode again as some parameters may have been changed..
00179     if(MTHREAD->RD->getBoolSetting("subRegionMode")){   
00180         int XL  = MTHREAD->RD->getIntSetting("subRegionXLeft");
00181         int XR   = MTHREAD->RD->getIntSetting("subRegionXRight");
00182         int YT = MTHREAD->RD->getIntSetting("subRegionYTop");
00183         int YB = MTHREAD->RD->getIntSetting("subRegionYBottom"); 
00184         double scaleCoeff =
00185             ( (double)  ((XR-XL)*(YB-YT)) )
00186                       /
00187             ( MTHREAD->RD->getIntSetting("nCols") * MTHREAD->RD->getIntSetting("nRows")) ; // ratio between npixel in the subRegion and npixels in the original region
00188         setBasicData("scaleCoeff",scaleCoeff);
00189     }
00190     else {
00191         setBasicData("scaleCoeff",((double)1));
00192     }
00193 
00194     // post settings hacks & messages...
00195     if(getBoolSetting("subRegionMode") ){
00196         msgOut(MSG_INFO, "The model is currently running on a sub-region area (mainly for initial model debugging).\nThe Scale coefficient is "+d2s(getDoubleSetting("scaleCoeff"))+".\nYou can enable full-region mode with the setting \"subRegionMode\"");
00197     }
00198     else {
00199         msgOut(MSG_INFO, "The model is currently running on a the whole area (normal mode).\nYou can enable sub-region mode with the setting \"subRegionMode\"\n(useful for initial model debugging/calibration)");
00200     }
00201     // defining if individual agent data has to be show in the model tree Viewer (that is, if we are in the sub-mode region or if we forced to view it)
00202     if ( (getBoolSetting("subRegionMode") || getBoolSetting("forceAgentsView")) &&   ! getBoolSetting("forceAgentsHide") ){
00203         setBasicData("agentsView", true);
00204         if (getBoolSetting("forceAgentsView")){
00205             msgOut(MSG_WARNING, "View of individual agent data on the Model Tree Viewer has been forced on.\nThis will considerably slow down the simulation.");
00206         }
00207     }
00208     else {
00209         setBasicData("agentsView", false);
00210             msgOut(MSG_INFO, "View of individual agent data on the Model Tree Viewer has been disabled for performance reasons. \nYou can force it on with the setting \"forceAgensView\".");
00211     }
00212     setOutputDirectory(getStringSetting("outputDirname").c_str());
00213 }
00214 
00215 void
00216 RegData::addSetting(string name_h, vector <string> values_h, int type_h, string comment_h){
00217 
00218     for (uint i=0;i<programSettingsVector.size();i++){
00219         if (programSettingsVector.at(i).name == name_h){
00220             msgOut(MSG_ERROR, "I already have setting "+name_h+".. Nothing is added..");
00221             return;
00222         }
00223     }
00224     BasicData SETT;
00225     SETT.name = name_h;
00226     SETT.values = values_h;
00227     SETT.type= type_h;
00228     SETT.comment = comment_h;
00229     programSettingsVector.push_back(SETT);
00230 }
00231 
00232 void
00233 RegData::addSetting(string name_h, string value_h, int type_h, string comment_h){
00234     vector <string> values;
00235     values.push_back(value_h);
00236     addSetting(name_h, values, type_h, comment_h);
00237 }
00238 
00239 void 
00240 RegData::setResources(){
00241 
00242     LLData table = getTable("resources");
00243     for(int i=0; i< table.nrecords(); i++){
00244         RegResources RES;
00245         RES.name =  table.getData(i,"resourceName");
00246         RES.unit =  table.getData(i,"resourceUnit");
00247         RES.comment =  table.getData(i,"resourceComment");
00248         string resSource = table.getData(i,"source");
00249         if      (resSource == "zero")      { RES.source= RESSOURCE_ZERO;}
00250         else if (resSource == "fixed")     { RES.source= RESSOURCE_FIXED;}
00251         else if (resSource == "calculated"){ RES.source= RESSOURCE_CALCULATED;}
00252         else if (resSource == "objects")   { RES.source= RESSOURCE_OBJECTS;}
00253         else {
00254             msgOut(MSG_ERROR,"Resource "+RES.name+" has an unexpected source ("+resSource+"), I don't know how to handle that! I left 0, please check that it has a sence!");
00255             RES.source= RESSOURCE_ZERO;
00256         }
00257         string resType = table.getData(i,"resourceTypology");
00258         if      (resType == "generic")        { RES.type= RESTYPE_GENERIC;}
00259         else if (resType == "financial")      { RES.type= RESTYPE_FINANCIAL;}
00260         else if (resType == "policyPremium")  { RES.type= RESTYPE_POLICYPREMIUM;}
00261         else if (resType == "labour")         { RES.type= RESTYPE_LABOUR;}
00262         else if (resType == "stables")        { RES.type= RESTYPE_STABLES;}
00263         else if (resType == "machinary")      { RES.type= RESTYPE_MACHINARY;}
00264         else if (resType == "feed")           { RES.type= RESTYPE_FEED;}
00265         else {
00266             msgOut(MSG_ERROR,"Resource "+RES.name+" has an unexpected type ("+resType+"), I don't know how to handle that! I left \"generic\", please check that it has a sence!");
00267             RES.type= RESTYPE_GENERIC;
00268         }
00269         RES.subType =  table.getData(i,"resourceSubTypology");
00270         resourcesDefinitionVector.push_back(RES);
00271     }
00272 };
00273 
00274 void 
00275 RegData::setDefaultActivities(){
00276 
00277     int simulationYears=this->getIntSetting("simulationYears");
00278     LLData table = getTable("activities");
00279     for(int i=0; i< table.nrecords(); i++){
00280         RegActivities ACT(MTHREAD);
00281         ACT.setName(table.getData(i,"activityName"));
00282         ACT.setComment(table.getData(i,"activityComment"));
00283         for(int j=0;j<simulationYears;j++){
00284             ACT.matrixGrossMarginByYear.push_back(s2d(table.getData(i,"matrixGrossMargin")));
00285         }
00286 
00287         string LUCToken = "RequiredLandUseCode_";
00288         for (int z=0; z<5; z++){
00289             string fullToken = LUCToken+i2s(z);
00290             int LUC = s2i(table.getData(i,fullToken));
00291             if (LUC>0){ACT.requiredLandUseCodes.push_back(LUC);}
00292         }
00293         if (ACT.requiredLandUseCodes.size()>0){
00294             ACT.spatiallyExplicit=true;
00295         }
00296         else {ACT.spatiallyExplicit=false;}
00297 
00298         // The requiredobject on plot now is only one... don't delete as this is still an open point..
00299         //string ReqObjToken = "RequiredObjectOnPlot_";
00300         //for (int z=0; z<3; z++){
00301         //  string fullToken = ReqObjToken+i2s(z);
00302         //  string OBJ = nodes.at(i).getNodeByName(fullToken).getStringContent();
00303         //  if (OBJ != ""){
00304         //      ACT.requiredObjectsOnPlot.push_back(OBJ);
00305         //  }
00306         //}
00307         ACT.requiredObjectOnPlot = table.getData(i,"RequiredObjectOnPlot");
00308 
00309         // map display settings..
00310         if ( ACT.spatiallyExplicit){
00311             ACT.mapCode   = s2i(table.getData(i,"mapCode"));
00312             ACT.mapRColor = s2i(table.getData(i,"mapRColor"));
00313             ACT.mapGColor = s2i(table.getData(i,"mapGColor"));
00314             ACT.mapBColor = s2i(table.getData(i,"mapBColor"));
00315         }
00316 
00317         map<string, double> tempMap;
00318         for(uint z=0;z<resourcesDefinitionVector.size();z++){
00319             string resourceName = resourcesDefinitionVector.at(z).name;
00320             double resourceValue = s2d(table.getData(i,resourceName));
00321             tempMap.insert(pair<string, double>(resourceName, resourceValue));
00322         }
00323 
00324         for(int i=0;i<simulationYears;i++){
00325             ACT.matrixActResByYear.push_back(tempMap);
00326         }
00327 
00328         // setting the decoupling rights...
00329         for(int i=0;i<simulationYears;i++){
00330             vector <double> tempVector (simulationYears,0);
00331             for(uint j=0; j<getResourceSize(RESTYPE_POLICYPREMIUM); j++){
00332                 ACT.decouplingOptions.push_back(tempVector);
00333             }
00334         }
00335 
00336         activitiesDefinitionVector.push_back(ACT);
00337     }
00338 
00339 };
00340 
00341 // ###############################
00342 void 
00343 RegData::setScenarioActivities(){
00344 
00345     string scenarioName = MTHREAD->getScenarioName();
00346     int initialYear     = this->getIntSetting("initialYear");
00347     int simulationYears = this->getIntSetting("simulationYears");
00348     unsigned int z; // index to find the name of the actifity
00349 
00350     LLData table = getTable(scenarioName+"_activities", MSG_WARNING); //this scenario could not have an activity sheet associated
00351     if(table.getTableName() == "") return;
00352 
00353     for(int i=0; i< table.nrecords(); i++){
00354 
00355         // reading the content into memory...
00356         vector<double> values;
00357         string name = table.getData(i,"actName");
00358         string type = table.getData(i,"type");
00359         for(int j=initialYear;j<initialYear+simulationYears;j++){
00360             values.push_back( s2d( table.getData(i,"y"+i2s(j)) ) ); // xml names can not be only numbers
00361         }
00362         
00363         // changing the values of the activities according with the new scenario just loaded..
00364         for (uint j=0;j<activitiesDefinitionVector.size();j++){
00365             if ( activitiesDefinitionVector[j].activityName == name){
00366                 z = type.find("decouplingRights"); // search for "decouplingRights" in type...
00367                 if (type == "matrixGrossMargin") {
00368                     activitiesDefinitionVector[j].matrixGrossMarginByYear = values;
00369                 } else if (z!=string::npos) { // z in not at the end of the string, means "decouplingRights" founded!
00370                     vector <string> tokens;
00371                     tokenize(type, tokens);
00372                     if(tokens.size() != 2) msgOut(MSG_CRITICAL_ERROR,"There is an error reading the decoupling rights for this scenario. Sure you didn't use spaces in the resources definition??");
00373                     vector <string> policyResources = getResourceNames(RESTYPE_POLICYPREMIUM);
00374                     for(uint y=0;policyResources.size();y++){
00375                         if(tokens[1] == policyResources[y]){
00376                             activitiesDefinitionVector[j].decouplingOptions[y] = values;
00377                             break;
00378                         }
00379                     }
00380                 } else {
00381                     for(int z=0;z<simulationYears;z++){
00382                         map<string,double>::iterator p;
00383                         p=activitiesDefinitionVector[j].matrixActResByYear.at(z).find(type);
00384                         if(p != activitiesDefinitionVector[j].matrixActResByYear.at(z).end() ){
00385                             p->second = values.at(z);
00386                         }
00387                         else {
00388                             msgOut(MSG_ERROR,"In the scenario activities file, I can't change the resource coefficient "+type+" for the activity "+name+". Sure you spelt it correctly?");
00389                             break;
00390                         }
00391                     }
00392                 }
00393                 break;
00394             }
00395         }
00396     }
00397 
00398 }
00399 // ################################
00400 
00401 void 
00402 RegData::setObjectsDefinitions(){
00403 
00404     LLData table = getTable("objects");
00405     for(int i=0; i< table.nrecords(); i++){
00406         ModelObject OBJ(MTHREAD);
00407         OBJ.setName(table.getData(i,"objectName"));
00408         OBJ.setType(table.getData(i,"objectTypology"));
00409         OBJ.setSubType(table.getData(i,"objectSubTypology"));
00410         OBJ.setComment(table.getData(i,"objectComment"));
00411         OBJ.setLifeTerm(s2i(table.getData(i,"object MaxLife")));
00412         OBJ.setInitialCost(s2d(table.getData(i,"initial Cost")));
00413         OBJ.setMatrixGrossMargin(s2d(table.getData(i,"matrix GrossMargin")));
00414 
00415         string LUCToken = "RequiredLandUseCode_";
00416         for (int z=0; z<5; z++){
00417             string fullToken = LUCToken+i2s(z);
00418             int LUC = s2i(table.getData(i,fullToken));
00419             if (LUC>0){
00420                 OBJ.requiredLandUseCodes.push_back(LUC);
00421             }
00422         }
00423         if (OBJ.requiredLandUseCodes.size()>0){
00424             OBJ.spatiallyExplicit=true;
00425         }
00426         else {OBJ.spatiallyExplicit=false;}
00427 
00428         map<string, double> resourceMap;
00429         for(uint z=0;z<resourcesDefinitionVector.size();z++){
00430             string resourceName = resourcesDefinitionVector.at(z).name;
00431             double resourceValue = s2d(table.getData(i,resourceName));
00432             resourceMap.insert(pair<string, double>(resourceName, resourceValue));
00433         }
00434 
00435         for(uint z=0;z<activitiesDefinitionVector.size();z++){
00436             if(activitiesDefinitionVector[z].getRequiredObjectOnPlot() == table.getData(i,"objectName")) {
00437                 OBJ.setRequiredFor(activitiesDefinitionVector[z].getName());
00438                 break;
00439             }
00440         }
00441         OBJ.setMatrixObjRes(resourceMap);
00442         objectsDefinitionVector.push_back(OBJ);
00443     }
00444 
00445     /*
00446     string directory;
00447     string filename;
00448     string filename_complete;
00449     
00450     for (uint i=0; i<iFilesVector.size(); i++){
00451         if (iFilesVector.at(i).type == "modelObjectDefinitions"){
00452             directory=iFilesVector.at(i).directory;
00453             filename=iFilesVector.at(i).name;
00454             break;
00455         }
00456     }
00457     filename_complete = baseDirectory+directory+filename;
00458     InputNode objectDocument;
00459     bool test=objectDocument.setWorkingFile(filename_complete);
00460     if (!test){msgOut(MSG_CRITICAL_ERROR, "Error opening the objects definition file "+filename_complete);}
00461     vector<InputNode> nodes = objectDocument.getNodesByName("record");
00462     for (uint i=0; i<nodes.size();i++){
00463         ModelObject OBJ(MTHREAD);
00464         OBJ.setName(nodes.at(i).getNodeByName("objectName").getStringContent());
00465         OBJ.setType(nodes.at(i).getNodeByName("objectTypology").getStringContent());
00466         OBJ.setSubType(nodes.at(i).getNodeByName("objectSubTypology").getStringContent());
00467         OBJ.setComment(nodes.at(i).getNodeByName("objectComment").getStringContent());
00468         OBJ.setLifeTerm(nodes.at(i).getNodeByName("object_MaxLife").getIntContent());
00469         OBJ.setInitialCost(nodes.at(i).getNodeByName("initial_Cost").getDoubleContent());
00470         OBJ.setMatrixGrossMargin(nodes.at(i).getNodeByName("matrix_GrossMargin").getDoubleContent());
00471 
00472         string LUCToken = "RequiredLandUseCode_";
00473         for (int z=0; z<5; z++){
00474             string fullToken = LUCToken+i2s(z);
00475             int LUC = nodes.at(i).getNodeByName(fullToken).getIntContent();
00476             if (LUC>0){
00477                 OBJ.requiredLandUseCodes.push_back(LUC);
00478             }
00479         }
00480         if (OBJ.requiredLandUseCodes.size()>0){
00481             OBJ.spatiallyExplicit=true;
00482         }
00483         else {OBJ.spatiallyExplicit=false;}
00484 
00485         map<string, double> resourceMap;
00486         for(uint z=0;z<resourcesDefinitionVector.size();z++){
00487             string resourceName = resourcesDefinitionVector.at(z).name;
00488             double resourceValue = nodes.at(i).getNodeByName(resourceName).getDoubleContent();
00489             resourceMap.insert(pair<string, double>(resourceName, resourceValue));
00490         }
00491 
00492         for(uint z=0;z<activitiesDefinitionVector.size();z++){
00493             if(activitiesDefinitionVector[z].getRequiredObjectOnPlot() == nodes.at(i).getNodeByName("objectName").getStringContent()){
00494                 OBJ.setRequiredFor(activitiesDefinitionVector[z].getName());
00495                 break;
00496             }
00497         }
00498         OBJ.setMatrixObjRes(resourceMap);
00499         objectsDefinitionVector.push_back(OBJ);
00500     }   
00501     */
00502 }
00503 
00504 // ###############################################################################
00505 void
00506 RegData::setOutputDirectory(const char* output_dirname_h){
00507 
00508     if (strlen(output_dirname_h)==0){
00509         outputDirname=baseDirectory+"output/";
00510     }
00511     else {
00512         outputDirname=output_dirname_h;
00513     }   
00514     MTHREAD->setOutputDirName(outputDirname); //for the GUI
00515 }   
00516 
00517 string
00518 RegData::getBaseData (const string &name_h, int type_h, int position){
00519     // If the data is called with DATA_NOW we interpret the array of values as a temporal array and we return the value at the current time.
00520     if(position == DATA_NOW) {
00521         position = MTHREAD->SCD->getIteration();
00522     }
00523     for (uint i=0; i<programSettingsVector.size();i++){
00524         if (programSettingsVector.at(i).name == name_h){
00525             int type = programSettingsVector.at(i).type;
00526             if(type != type_h){msgOut(MSG_CRITICAL_ERROR, "mismatching type in calling getBaseData() for "+name_h);}
00527             if(programSettingsVector.at(i).values.size() > ((uint)position)) {
00528                 return programSettingsVector.at(i).values.at(position);
00529             } else if (programSettingsVector.at(i).values.size() > 0 ){
00530                 // returning the last available value...
00531                 return programSettingsVector.at(i).values.at( programSettingsVector.at(i).values.size()-1 );
00532             }
00533             else {msgOut(MSG_CRITICAL_ERROR, "Error: "+name_h+" doesn't have any value, even on the first position(year)!"); }
00534         }
00535     }
00536     if(type_h==TYPE_BOOL){
00537         msgOut(MSG_DEBUG, "Possible error calling getBaseData(TYPE_BOOL) for "+ name_h +". No setting option or macro data found with this name. Returning false.");
00538         return "0";
00539     } else {
00540         msgOut(MSG_CRITICAL_ERROR, "Error calling getBaseData() for "+ name_h +". No setting option or macro data found with this name.");
00541     }
00542     return "";
00543 };
00544 
00545 vector <string>
00546 RegData::getVectorBaseData (const string &name_h, int type_h){
00547     for (uint i=0; i<programSettingsVector.size();i++){
00548         if (programSettingsVector.at(i).name == name_h){
00549             int type = programSettingsVector.at(i).type;
00550             if(type != type_h){msgOut(MSG_CRITICAL_ERROR, "mismatching type in calling getVectorBaseData() for "+name_h);}
00551             return programSettingsVector.at(i).values;
00552         }
00553     }
00554     msgOut(MSG_CRITICAL_ERROR, "Error calling getVectorBaseData() for "+ name_h +". No setting option or macro data found with this name.");
00555     vector <string> toReturn;
00556     return toReturn;
00557 };
00558 
00559 // ------------- start getSetting() amd getMacro() functions ....... -----------------
00560 int
00561 RegData::getIntSetting(const string &name_h, int position){
00562     return s2i( MTHREAD->RD->getBaseData(name_h,TYPE_INT,position) );
00563 }
00564 double
00565 RegData::getDoubleSetting(const string &name_h, int position){
00566     return s2d( MTHREAD->RD->getBaseData(name_h,TYPE_DOUBLE,position) );
00567 }
00568 string
00569 RegData::getStringSetting(const string &name_h, int position){
00570     return MTHREAD->RD->getBaseData(name_h,TYPE_STRING,position);
00571 }
00572 bool
00573 RegData::getBoolSetting(const string &name_h, int position){
00574     return s2b( MTHREAD->RD->getBaseData(name_h,TYPE_BOOL,position) );
00575 }
00576 vector<int>
00577 RegData::getIntVectorSetting(const string &name_h){
00578     return s2i(MTHREAD->RD->getVectorBaseData(name_h,TYPE_INT));
00579 }
00580 vector<double>
00581 RegData::getDoubleVectorSetting(const string &name_h){
00582     return s2d(MTHREAD->RD->getVectorBaseData(name_h,TYPE_DOUBLE));
00583 }
00584 vector<string>
00585 RegData::getStringVectorSetting(const string &name_h){
00586     return MTHREAD->RD->getVectorBaseData(name_h,TYPE_STRING);
00587 }
00588 vector<bool>
00589 RegData::getBoolVectorSetting(const string &name_h){
00590     return s2b(MTHREAD->RD->getVectorBaseData(name_h,TYPE_BOOL));
00591 }
00592 
00593 // ------ END of getSetting() functions --------------------- 
00594 
00595 void
00596 RegData::setBasicData(const string &name_h, int value, int position){
00597     setBasicData(name_h, i2s(value), TYPE_INT, position);
00598 }
00599 void
00600 RegData::setBasicData(const string &name_h, double value, int position){
00601     setBasicData(name_h, d2s(value), TYPE_DOUBLE, position);
00602 }
00603 void 
00604 RegData::setBasicData(const string &name_h, string value, int position){
00605     setBasicData(name_h, value, TYPE_STRING, position);
00606 }
00607 void
00608 RegData::setBasicData(const string &name_h, bool value, int position){
00609     setBasicData(name_h, b2s(value), TYPE_BOOL, position);
00610 }
00611 
00612 void
00613 RegData::setBasicData(const string &name_h, string value, int type_h, int position){
00614     for (uint i=0; i<programSettingsVector.size();i++){
00615         if (programSettingsVector.at(i).name == name_h){
00616             int type = programSettingsVector.at(i).type;
00617             if(type != type_h){msgOut(MSG_CRITICAL_ERROR, "mismatching type in calling setBasicData() for "+name_h);}
00618             if(programSettingsVector.at(i).values.size() > ((uint)position)) {
00619                 programSettingsVector.at(i).values.at(position)=value;
00620                 return;
00621             }
00622             else {msgOut(MSG_CRITICAL_ERROR, "out-of-bound error calling setBasicData() for "+name_h); }
00623         }
00624     }
00625     msgOut(MSG_CRITICAL_ERROR, "Error calling setBasicData() for "+ name_h +". No setting option or macro data found with this name.");
00626     return;
00627 }
00628 
00629 std::string
00630 RegData::getFilenameByType(std::string type_h){
00631     std::string directory;
00632     std::string filename;
00633     std::string filename_complete;
00634     for (uint i=0; i<iFilesVector.size(); i++){
00635         if (iFilesVector.at(i).type == type_h){
00636             directory=iFilesVector.at(i).directory;
00637             filename=iFilesVector.at(i).name;
00638             break;
00639         }
00640     }
00641     filename_complete = baseDirectory+directory+filename;
00642     return filename_complete;
00643 };
00644 
00645 vector<RegActivities*>
00646 RegData::getRegActivities(){
00647     vector <RegActivities*> toReturn;
00648     for (uint i=0;i<activitiesDefinitionVector.size();i++){
00649         toReturn.push_back(&activitiesDefinitionVector[i]);
00650     }
00651     return toReturn;
00652 }
00653 
00654 RegActivities*
00655 RegData::getRegActivityByName(string name_h){
00656     RegActivities*  toReturn = 0;
00657     for (uint i=0;i<activitiesDefinitionVector.size();i++){
00658         if (activitiesDefinitionVector[i].getName() == name_h){
00659             return &activitiesDefinitionVector[i];
00660         }
00661     }
00662     msgOut(MSG_CRITICAL_ERROR, "Resource "+name_h+" not found! Aborting.");
00663     return toReturn;
00664 }
00665 
00666 
00667 vector<ModelObject*>
00668 RegData::getObjectsDefinitionVector(){
00669     vector <ModelObject*> toReturn;
00670     for (uint i=0;i<objectsDefinitionVector.size();i++){
00671         toReturn.push_back(&objectsDefinitionVector[i]);
00672     }
00673     return toReturn;
00674 }
00675 
00676 vector <string>
00677 RegData::getResourceNames(int type_h) const {
00678     vector <string> toReturn;
00679     for (uint i=0;i<resourcesDefinitionVector.size();i++){
00680         if(type_h == -1 || resourcesDefinitionVector[i].type == type_h){
00681             toReturn.push_back(resourcesDefinitionVector.at(i).name);
00682         }
00683     }
00684     return toReturn;
00685 }
00686 
00687 int
00688 RegData::getResourceSize(int type_h) const {
00689     int count = 0;
00690     for (uint i=0;i<resourcesDefinitionVector.size();i++){
00691         if(type_h == -1 || resourcesDefinitionVector[i].type == type_h){
00692             count++;
00693         }
00694     }
00695     return count;
00696 }
00697 
00698 vector <string>
00699 RegData::getObjectNames() const {
00700     vector <string> toReturn;
00701     for (uint i=0;i<objectsDefinitionVector.size();i++){
00702         toReturn.push_back(objectsDefinitionVector.at(i).getName());
00703     }
00704     return toReturn;
00705 }
00706 
00707 vector <string>
00708 RegData::getActivityNames() const {
00709     vector <string> toReturn;
00710     for (uint i=0;i<activitiesDefinitionVector.size();i++){
00711         toReturn.push_back(activitiesDefinitionVector.at(i).getName());
00712     }
00713     return toReturn;
00714 }
00715 
00716 int
00717 RegData::getActGisCodeByName(string actName_h) const {
00718     for (uint i=0;i<activitiesDefinitionVector.size();i++){
00719         if(activitiesDefinitionVector[i].getName() == actName_h) {
00720             return activitiesDefinitionVector[i].getMapCode();
00721         }
00722     }
00723     msgOut(MSG_CRITICAL_ERROR, "getActGisCodeByName(string actName_h): Activity named "+actName_h+" not found!");
00724     return 0;
00725 }
00726 
00727 RegResources
00728 RegData::getResourceByName(string name_h){
00729 
00730     for(uint i=0;i<resourcesDefinitionVector.size();i++){
00731         if(resourcesDefinitionVector.at(i).name == name_h){
00732             return resourcesDefinitionVector.at(i);
00733         }
00734     }
00735     msgOut(MSG_ERROR, "Resource "+name_h+" not found!");
00736     RegResources toReturn;
00737     return toReturn;
00738 }
00739 
00747 vector <ModelObject>
00748 RegData::getBestMatchingInitialObjects (string resourceName_h, double resourceQ_h){
00749 
00750     vector <ModelObject> toReturn;
00751     vector <string> objectNames;
00752     vector <double> objectValues;
00753     double remainedResources = resourceQ_h; // remained resources to allocate
00754     bool stop=false; // stop searching for objects when the remaining resources are less than 
00755 
00756     if (resourceQ_h <=0){
00757         return toReturn; // empty vector
00758     }
00759     for(uint i=0;i<resourcesDefinitionVector.size();i++){
00760         if(resourceName_h == resourcesDefinitionVector.at(i).name && resourcesDefinitionVector.at(i).source == RESSOURCE_OBJECTS ){
00761             objectNames = resourcesJoinedObjects.at(i);  // ordered by objectValues
00762             objectValues = resourcesProvidedQuantities.at(i); // ordered
00763             while(!stop){
00764                 for (uint j=0;j<objectNames.size();j++){
00765                     if (objectValues.at(j) >= remainedResources){
00766                         toReturn.push_back(this->getObjectByName(objectNames.at(j)));
00767                         stop = true;
00768                         break;
00769                     }
00770                 }
00771                 if (!stop){ /*  we didn't assign any object, that's because the available resource is higher than the resource provided by the biggest object. We still give the agent the bigger object and we try again */
00772                     toReturn.push_back(this->getObjectByName(objectNames.at(objectNames.size()-1)));
00773                     remainedResources = remainedResources-objectValues.at(objectNames.size()-1);            
00774                 }
00775             }
00776             return toReturn;
00777         }
00778     }
00779     //msgOut(MSG_ERROR, "This agent has a resource that in not in the list ("+resourceName_h+"). No object assigned !");
00780     return toReturn; //empty vector
00781 }
00782 
00783 void
00784 RegData::initializeResourcesObjectsMatch(){
00785     // LESSON: maps can't ever be sorted by their values, as they are always automatically sorted by their keys !
00786     for(uint i=0;i<resourcesDefinitionVector.size();i++){
00787         vector <string> objectNames;
00788         vector <double> objectsAssociatedQuantities;
00789 
00790         map <double, string> tempMap; // used to sort by the associated value..
00791         map <double, string>::iterator p;
00792 
00793         if(resourcesDefinitionVector.at(i).source == RESSOURCE_OBJECTS ){
00794             for (uint j=0;j<objectsDefinitionVector.size();j++){
00795                 double associatedValue=objectsDefinitionVector.at(j).getResourceValue(resourcesDefinitionVector.at(i).name);
00796                 if (associatedValue < 0){
00797                     tempMap.insert(pair<double, string>(-associatedValue, objectsDefinitionVector.at(j).getName()));
00798                 }
00799             }
00800             for(p=tempMap.begin();p!=tempMap.end();p++){
00801                 objectNames.push_back(p->second);
00802                 objectsAssociatedQuantities.push_back(p->first);
00803             } // now both objectNames and objectsAssociatedQuantities are ordered by the associated value
00804 
00805         }
00806         resourcesJoinedObjects.push_back(objectNames);
00807         resourcesProvidedQuantities.push_back(objectsAssociatedQuantities);
00808     }
00809 }
00810 
00811 ModelObject
00812 RegData::getObjectByName(string name_h){
00813     for (uint i=0;i<objectsDefinitionVector.size();i++){
00814         if(objectsDefinitionVector.at(i).getName() == name_h){
00815             return objectsDefinitionVector.at(i);
00816         }
00817     }
00818     ModelObject toReturn(MTHREAD);
00819     msgOut(MSG_ERROR, "Asked for an object name that doesn't exist ("+name_h+") !");
00820     return toReturn;
00821 }
00822 
00826 void
00827 RegData::initializeSpacialObjectsMatch(){
00828     vector <int> landTypes = this->getIntVectorSetting("landTypes");
00829     for (uint i=0;i<landTypes.size();i++){
00830         vector <ModelObject> tempModelObjectVector;
00831         for(uint j=0;j<objectsDefinitionVector.size();j++){
00832             vector <int> requiredLandUseCodes = objectsDefinitionVector.at(j).getRequiredLandUseCodes();
00833             for(uint z=0;z<requiredLandUseCodes.size();z++){
00834                 if(requiredLandUseCodes.at(z) == landTypes.at(i)){
00835                     tempModelObjectVector.push_back(objectsDefinitionVector.at(j));
00836                     break;
00837                 }
00838             }
00839         }
00840         availableObjectsBySoilType.push_back(tempModelObjectVector);
00841     }
00842 }
00843 
00844 vector <ModelObject>
00845 RegData::getModelObjectsBySoilType(int soilType_h){
00846     vector <ModelObject> toReturn;
00847     vector <int> landUses = MTHREAD->RD->getIntVectorSetting("landTypes");
00848     for (uint i=0;i<landUses.size();i++){
00849         if (soilType_h == landUses.at(i)){
00850             return availableObjectsBySoilType.at(i);
00851         }
00852     }
00853     return toReturn;
00854 }
00855 
00856 void
00857 RegData::debug(){
00858     // ********** START DEBUG CODE....... ************
00859     double ddebuga=0; //20080209
00860     uint idebuga=0;
00861     double ddebugb=0; //20080209
00862     uint idebugb=0;
00863     double ddebugc=0; //20080209
00864     uint idebugc=0;
00865     double debugmin = 0;
00866     double debugmax = 1000;
00867     for (uint q=0;q<10000;q++){
00868         ddebuga += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
00869         ddebugb += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
00870         ddebugc += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
00871     }
00872     idebuga = ddebuga;
00873     idebugb = ddebugb;
00874     idebugc = ddebugc;
00875     cout << "idebuga: "<<idebuga<<endl;
00876     cout << "idebugb: "<<idebugb<<endl;
00877     cout << "idebugc: "<<idebugc<<endl;
00878     throw 2;
00879     // ******** .....END DEBUG CODE *******************
00880 }
00881 
00882 void
00883 RegData::loadInput(){
00884     //QString iFile("data/regmasInput.ods");
00885     QString iFile(MTHREAD->getInputFileName().c_str());
00886     //cout << "PIPPO !!!!! " << MTHREAD->getInputFileName().c_str() << endl;
00887     QString oDir((MTHREAD->getBaseDirectory()+"tempInput").c_str());
00888     
00889     // removing output directory if exist..
00890     QDir oQtDir(oDir);
00891 
00892     if(oQtDir.exists()){
00893         bool deleted;
00894         deleted = delDir(oDir);
00895         if(deleted){msgOut(MSG_DEBUG,"Correctly deleted old temporary data");}
00896         else {msgOut(MSG_WARNING, "I could not delete old temporary data dir (hopefully we'll overrite the input files)");}
00897     }
00898 
00899     if (!QFile::exists(iFile))
00900     {
00901         cout << "File does not exist." << endl << endl;
00902         //return false;
00903     }
00904     UnZip::ErrorCode ec;
00905     UnZip uz;
00906     ec = uz.openArchive(iFile);
00907     if (ec != UnZip::Ok)    {
00908         cout << "Failed to open archive: " << uz.formatError(ec).toAscii().data() << endl << endl;
00909         //return false;
00910     }
00911     ec = uz.extractAll(oDir);
00912     if (ec != UnZip::Ok)
00913     {
00914         cout << "Extraction failed: " << uz.formatError(ec).toAscii().data() << endl << endl;
00915         uz.closeArchive();
00916         //return false;
00917     }
00918     
00919     // loading input file into memory...
00920     string inputXMLFileName = MTHREAD->getBaseDirectory()+"tempInput/content.xml";
00921     //string inputXMLFileName = MTHREAD->getBaseDirectory()+"test/content.xml";
00922     //cout << "inputXMLFileName: " << inputXMLFileName << endl;
00923     //mainDocument = new InputDocument();
00924     mainDocument.setWorkingFile(inputXMLFileName);
00925     //InputNode documentContent = mainDocument.getNodeByName("office:document-content");
00926     //InputNode documentBody = mainDocument.getNodeByName("office:body");
00927     //InputNode mainNode = mainDocument.getNodeByName("spreadsheet");
00928     //InputNode pippo = mainDocument.getNodeByName("pippo-pippo");
00929     //InputNode table = mainDocument.getNodeByName("table");
00930     //cout << "Test result: " << table.getStringContent() << endl;
00931 
00932 
00933     vector <InputNode> tables = mainDocument.getNodesByName("table");
00934     for(uint i=0;i<tables.size();i++){
00935         string tableName = tables[i].getStringAttributeByName("name");
00936         //cout <<tableName<<endl;
00937         LLData data(MTHREAD,tables[i].getStringAttributeByName("name"));
00938         vector <InputNode> rows = tables[i].getNodesByName("table-row");
00939         if(rows.size()<2) continue; //empty table or only with headers
00940         // building headers..
00941         vector <InputNode> cells = rows[0].getNodesByName("table-cell");
00942         for (uint y=0; y<cells.size(); y++){
00943             int repeated = 1;
00944             if( cells[y].hasAttributeByName("number-columns-repeated")){
00945                 repeated = cells[y].getIntAttributeByName("number-columns-repeated");
00946             }
00947             for (int q=0;q<repeated;q++){
00948                 if( !cells[y].hasChildNode("p") ){
00949                     data.headers.push_back(""); // empty header
00950                 } else {
00951                     data.headers.push_back(cells[y].getNodeByName("p",MSG_NO_MSG,true).getStringContent());
00952                 }
00953             }
00954         }
00955         // loading data...
00956         for (uint j=1; j<rows.size();j++){
00957             //cout << j << endl;
00958             vector <InputNode> cells = rows[j].getNodesByName("table-cell");
00959             if (cells.size()<1) continue;
00960             vector<string> record;
00961             // checking the first cell is not a comment nor is empty..
00962             int childCount = cells[0].getChildNodesCount();
00963             if (childCount == 0 || !cells[0].hasChildNode("p")) continue; // empty line, first column empty!
00964             string fistCol = cells[0].getNodeByName("p",MSG_NO_MSG,true).getStringContent();
00965             unsigned int z;
00966             z = fistCol.find("#");
00967             if( z!=string::npos && z == 0) continue; // found "#" on fist position, it's a comment!
00968             for (uint y=0; y<cells.size(); y++){
00969                 int repeated = 1;
00970                 if( cells[y].hasAttributeByName("number-columns-repeated")){
00971                     repeated = cells[y].getIntAttributeByName("number-columns-repeated");
00972                 }
00973                 for (int q=0;q<repeated;q++){
00974                     if( !cells[y].hasChildNode("p") ){
00975                         record.push_back(""); // empty header
00976                     } else {
00977                         record.push_back(cells[y].getNodeByName("p",MSG_NO_MSG,true).getStringContent());
00978                     }
00979                 }
00980             }
00981             data.records.push_back(record);
00982         }
00983         data.clean();
00984         LLDataVector.push_back(data);
00985     }
00986 
00987     //debug !!!
00988     /*for (uint i=0; i<LLDataVector.size();i++){
00989         cout << "***************** NEW TABLE: " << LLDataVector[i].tableName << endl;
00990         //cout << "***** Headers: "<< endl;
00991         int headerSize = LLDataVector[i].headers.size();
00992         bool ok = true;
00993         cout << "Header size: " << headerSize << endl;
00994         //for (uint j=0; j<LLDataVector[i].headers.size();j++){
00995         //  cout << "["<<j<<"] " << LLDataVector[i].headers[j] << endl;
00996         //}
00997         //cout << "***** Records: " << endl;
00998         for (uint j=0; j<LLDataVector[i].records.size();j++){
00999             //cout << "** Record "<<j<<":"<<endl; 
01000             if(LLDataVector[i].records[j].size() != headerSize){
01001                 cout << "There is a problem on record " << j <<"!"<< endl;
01002                 cout << "His size is: "<< LLDataVector[i].records[j].size() << endl;
01003                 ok = false;
01004             }
01005             //for (uint y=0; y<LLDataVector[i].records[j].size();y++){
01006             //  cout << "["<<y<<"] " << LLDataVector[i].records[j][y] << endl;
01007             //}
01008         }
01009         if(!ok) {cout <<"Problems with this table :-( !"<<endl;}
01010     }*/
01011 
01012 
01013 
01014     // deleting output directory if exist...
01015     if(oQtDir.exists()){
01016         bool deleted;
01017         deleted = delDir(oDir);
01018         if(deleted){msgOut(MSG_DEBUG,"Correctly deleted old temporary data");}
01019         else {msgOut(MSG_WARNING, "I could not delete old temporary data dir (hopefully we'll overrite the input files)");}
01020     }
01021 }
01022 
01023 bool
01024 RegData::delDir(QString dirname) {
01025         bool deleted = false;
01026         QDir dir(dirname);
01027     //msgOut(MSG_DEBUG, dir.absolutePath().toStdString());
01028     dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
01029     QFileInfoList list = dir.entryInfoList();
01030     deleted = dir.rmdir(dir.absolutePath());
01031     if (deleted) return true;
01032 
01033     for (int i = 0; i < list.size(); ++i) {
01034         QFileInfo fileInfo = list.at(i);
01035         if (fileInfo.isFile()){
01036             //msgOut(MSG_DEBUG, "A file, gonna remove it: "+fileInfo.absoluteFilePath().toStdString());
01037             QFile targetFile(fileInfo.absoluteFilePath());
01038             bool fileDeleted = targetFile.remove();
01039             if (!fileDeleted){
01040                 msgOut(MSG_CRITICAL_ERROR, "We have a problem: can't delete file "+fileInfo.absoluteFilePath().toStdString());
01041             }
01042         }
01043         else if (fileInfo.isDir()){
01044             //msgOut(MSG_DEBUG, "A directory, gonna go inside it: "+fileInfo.absoluteFilePath().toStdString());
01045             delDir(fileInfo.absoluteFilePath());
01046             dir.rmdir(fileInfo.absoluteFilePath());
01047         }   
01048     }
01049 
01050     deleted = dir.rmdir(dir.absolutePath());
01051     if (deleted) return true;
01052     return false;
01053 }
01054 
01055 LLData
01056 RegData::getTable(string tableName_h, int debugLevel){
01057     LLData toReturn(MTHREAD,"");
01058     for(uint i=0;i<LLDataVector.size();i++){
01059         if (LLDataVector[i].getTableName() == tableName_h)return LLDataVector[i];
01060     }
01061     msgOut(debugLevel,"No table found with name "+tableName_h);
01062     return toReturn;
01063 }
01064 
01065 // ========================== RegActivities =======================================
01066 RegActivities::RegActivities(ThreadManager* MTHREAD_h)
01067 {
01068     MTHREAD = MTHREAD_h;
01069 }
01070 
01071 RegActivities::~RegActivities()
01072 {
01073 }
01074 
01075 vector <double>
01076 RegActivities::getMatrixCoefficients(){
01077     vector <string> resourceNames= MTHREAD->RD->getResourceNames();
01078     vector <double> toReturn;
01079     map <string,double> matrixActRes = matrixActResByYear[MTHREAD->SCD->getIteration()];
01080     for (uint i=0;i<resourceNames.size();i++){
01081         map <string,double>::iterator p;
01082         p=matrixActRes.find(resourceNames.at(i));
01083         if(p != matrixActRes.end())
01084             toReturn.push_back(p->second);
01085         else 
01086             toReturn.push_back(0);
01087     }
01088     return toReturn;
01089 }
01090 
01091 double
01092 RegActivities::getMatrixCoefficientByName(string cname_h){
01093     map <string,double>::iterator p;
01094     p=matrixActResByYear[MTHREAD->SCD->getIteration()].find(cname_h);
01095     if( p != matrixActResByYear[MTHREAD->SCD->getIteration()].end() )
01096         return p->second;
01097     else 
01098         msgOut(MSG_ERROR,"I can get the matrix coefficient for resourse "+cname_h+": resource not find with such name!");
01099         return 0;
01100 }
01101 
01102 double
01103 RegActivities::getMatrixGrossMargin() const{
01104     return matrixGrossMarginByYear[MTHREAD->SCD->getIteration()];
01105 }
01106 
01107 map <string, double>
01108 RegActivities::getMatrixActRes() const{
01109     return matrixActResByYear[MTHREAD->SCD->getIteration()];
01110 }
01111 
01112 double
01113 RegActivities::getDecouplingOption(int premiumIndex){
01114     return decouplingOptions[premiumIndex][MTHREAD->SCD->getIteration()];
01115 }
01116 
01117 
01118 // ========================== LLData =======================================
01119 
01120 LLData::LLData(ThreadManager* MTHREAD_h, string tableName_h){
01121     MTHREAD = MTHREAD_h;
01122     tableName = tableName_h;
01123 }
01124 
01125 LLData::~LLData(){
01126 
01127 }
01128 
01129 void
01130 LLData::clean(){
01131     
01132     //checking the size is correct...
01133     int hsize = headers.size();
01134     for (uint i=0;i<records.size();i++){
01135         if(records[i].size() != hsize){
01136             msgOut(MSG_CRITICAL_ERROR,"Error in the input reading table "+tableName+". Record "+i2s(i)+" has "+i2s(records[i].size())+" fields instead of "+i2s(hsize)+".");
01137         }
01138     }
01139     //cleaning empty-header columns...
01140     for (int i=headers.size()-1;i>=0;i--){
01141         if(headers[i] == ""){
01142             headers.erase(headers.begin()+i);
01143             for (uint j=0;j<records.size();j++){
01144                 records[j].erase(records[j].begin()+i);
01145             }
01146         }
01147     }
01148 
01149 }
01150 
01151 string
01152 LLData::getData(int pos_h, string header_h, int debugLevel){
01153     if (records.size()<= pos_h){
01154         msgOut(debugLevel, "Requested position "+i2s(pos_h)+" too high! Not enought records !!");
01155         return "";
01156     }
01157     for (uint i=0;i<headers.size();i++){
01158         if(headers[i] == header_h) return records[pos_h][i];
01159     }
01160     msgOut(debugLevel, "Header string "+header_h+" not found!");
01161     return "";
01162 }