FFSM++  1.1.0
French Forest Sector Model ++
Sandbox.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2015 by Laboratoire d'Economie Forestière *
3  * http://ffsm-project.org *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 3 of the License, or *
8  * (at your option) any later version, given the compliance with the *
9  * exceptions listed in the file COPYING that is distribued together *
10  * with this file. *
11  * *
12  * This program is distributed in the hope that it will be useful, *
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15  * GNU General Public License for more details. *
16  * *
17  * You should have received a copy of the GNU General Public License *
18  * along with this program; if not, write to the *
19  * Free Software Foundation, Inc., *
20  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
21  ***************************************************************************/
22 #include <algorithm>
23 
24 #include <cmath>
25 #include <algorithm>
26 #include <map>
27 #include <tr1/array>
28 
29 #include <Eigen/Dense>
30 
31 #include "Sandbox.h"
32 #include "ThreadManager.h"
33 #include "ModelData.h"
34 #include "Gis.h"
35 #include "ModelRegion.h"
36 #include "Carbon.h"
37 
38 
39 //Testing random distribution, using some new in C++ random generator seeds..
40 #include <iostream>
41 #include <iomanip>
42 #include <string>
43 #include <map>
44 #include <random>
45 #include <cmath>
46 #include <float.h>
47 #include <limits>
48 #include <cstddef>
49 
50 
51 // Testing zip library...
52 //#include "zip.h"
53 //#include "unzip.h"
54 //#include <QFile>
55 //#include <QFileInfo>
56 //#include <QString>
57 //#include <QStringList>
58 //#include <QList>
59 //#include <iostream>
60 //#include <iomanip>
61 
62 
63 //Testing FlopC++ (requires modified src.pro qmake file)
64 //#include "flopc.hpp"
65 //using namespace flopc;
66 //#include <OsiClpSolverInterface.hpp>
67 //#include <OsiCbcSolverInterface.hpp>
68 
69 #include "IpIpoptApplication.hpp"
70 #include "IpSolveStatistics.hpp"
71 
73 #include "Adolc_debugtest.h"
74 
75 
76 typedef map<string, string> TStrStrMap;
77 typedef pair<string, string> TStrStrPair;
78 
79 using namespace std;
80 
82  MTHREAD=MTHREAD_h;
83 }
84 
86 
87 }
88 
89 
91 
92 }
93 
94 // ---------------------------------------------
95 struct GccTest
96 {
97 
98  GccTest(string name_h){
99  nameMember = name_h;
100  };
101 
102  string nameMember;
103 
104  operator string ()
105  {
106 
107  cout << "the first function\n";
108  cout << nameMember << endl;
109  return "42";
110  }
111 
112  operator int ()
113  {
114  cout << "its \"underload\"\n";
115  return 42;
116  }
117 
118  operator vector<int> ()
119  {
120  cout << "within vector <int>" << endl;
121  vector <int> toReturn;
122  toReturn.push_back(3);
123  toReturn.push_back(4);
124  toReturn.push_back(5);
125  return toReturn;
126  }
127 
128 };
129 
130 // --------------------------------------
131 void
133 
134  /*
135  // Checking integer division
136 
137  int a = 19;
138  int b = 5;
139  int c = a/b;
140  int d = a%b;
141  cout << a << " - " << b << " - " << c << " - " << d << endl;
142  exit(0);
143  */
144 
145  /*
146  // Testing initializating a matrix with fixed values in C++11
147  //vector< vector<double> > deltaAreas(fTypes.size()+1, vector<double>(fTypes.size()+1,5));
148  vector< vector<double> > deltaAreas(3, vector<double>(5,4));
149  for (uint i=0;i<3;i++){
150  for (uint j=0;j<5;j++){
151  cout << deltaAreas.at(i).at(j) << "\t";
152  }
153  cout << endl;
154  }
155  exit(1);
156  */
157 
158  /*
159  // Testing map of generic vector of strings
160  //map<vector<string>,double> testMap;
161  map<tr1::array<string, 3>,double> testMap;
162 
163  //vector<string> k1 = {"aa","aa","aa"};
164  tr1::array<string, 3> k1 = {"aa","aa","aa"};
165  double v1 = 1;
166  double v1b = 3;
167  //vector<string> k2 = {"aa","bb","aa"};
168  tr1::array<string, 3> k2 = {"aa","bb","aa"};
169  double v2 = 2;
170  incrOrAddMapValue(testMap, k1, v1);
171  incrOrAddMapValue(testMap, k2, v2);
172  incrOrAddMapValue(testMap, k1, v1b);
173  double debug = findMap(testMap, k1);
174  cout << debug << endl;
175  double debug2 = findMap(testMap, k2);
176  cout << debug2 << endl;
177  exit(1);
178  */
179 
180 
181  /*
182  // Testing debugging a map
183  iisskey k1(2007,11021,"broadL_HighF","15");
184  iisskey k2(2007,11021,"broadL_HighF","30");
185  iisskey k3(2007,11021,"con_HighF","15");
186  iisskey k4(2007,11022,"broadL_HighF","15");
187  iisskey k5(2008,11021,"broadL_HighF","15");
188 
189  // Testing the new changeMapValue(), incrMapValue(), resetMapValues(), incrOrAddMapValue(map, key, value) and vectorToMap() funcions
190  map<iisskey,double> testMap;
191  pair<iisskey,double> pair1(k1,1.1);
192  pair<iisskey,double> pair2(k2,1.2);
193  pair<iisskey,double> pair3(k3,1.3);
194  pair<iisskey,double> pair4(k4,1.4);
195  pair<iisskey,double> pair5(k5,1.5);
196  testMap.insert(pair1);
197  testMap.insert(pair2);
198  testMap.insert(pair3);
199  testMap.insert(pair4);
200  testMap.insert(pair5);
201  debugMap(testMap,iisskey(NULL,NULL,"",""));
202  debugMap(testMap,iisskey(2007,NULL,"con_HighF",""));
203  exit(0);
204  */
205 
206 
207 
208 
209  /*
210  // Testing standard deviation algorithm, as from http://stackoverflow.com/questions/7616511/calculate-mean-and-standard-deviation-from-a-vector-of-samples-in-c-using-boos
211  vector<double> v;
212  v.push_back(3.0);
213  v.push_back(2.0);
214  v.push_back(5.0);
215  v.push_back(4.0);
216  double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
217  double m = sum / v.size();
218  double accum = 0.0;
219  std::for_each (std::begin(v), std::end(v), [&](const double d) {
220  accum += (d - m) * (d - m);
221  });
222  double stdev = sqrt(accum / (v.size()-1));
223  cout << stdev << endl;
224  double sd2 = getSd(v);
225  double sd3 = getSd(v,false);
226  cout << sd2 << endl;
227  cout << sd3 << endl;
228  exit(0);
229  */
230 
231  /*
232  // Testing tokenize, untokenize functions
233  vector<string> istrings;
234  istrings.push_back("Questo");
235  istrings.push_back("cielo");
236  istrings.push_back("è");
237  istrings.push_back("sempre");
238  istrings.push_back("più");
239  istrings.push_back("blu.");
240  string delimiter = " . ";
241 
242  string fullstring="";
243  vector<string> ostrings;
244  untokenize(fullstring, istrings, delimiter);
245  cout << fullstring << endl;
246 
247  fullstring += delimiter;
248  cout << fullstring << endl;
249 
250  tokenize(fullstring, ostrings, delimiter);
251  for (uint i=0;i<ostrings.size();i++){
252  cout << ostrings[i] << endl;
253  }
254  exit(0);
255  */
256 
257 
258  /*
259  // Testing FlopC++
260  // For a single file compile as:
261  // -- two passages:
262  // g++ -O3 -I /usr/include/coin -DFLOPCPP_BUILD `PKG_CONFIG_PATH=/usr/lib64/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig: pkg-config --libs flopcpp osi-cbc osi-clp` transport.cpp -c -o transport.o
263  // g++ -o transport2 transport.o -Wl,-rpath,'$ORIGIN' -L . -DFLOPCPP_BUILD `PKG_CONFIG_PATH=/usr/lib64/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig: pkg-config --libs flopcpp osi-cbc osi-clp`
264  // -- single passage:
265  // g++ -O3 -I /usr/include/coin transport.cpp -DFLOPCPP_BUILD `PKG_CONFIG_PATH=/usr/lib64/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig: pkg-config --libs flopcpp osi-cbc osi-clp` -o transport3
266 
267  MP_model::getDefaultModel().setSolver(new OsiClpSolverInterface);
268  //MP_model::getDefaultModel().setSolver(new OsiCbcSolverInterface);
269  enum {seattle, sandiego, numS};
270  enum {newyork, chicago, topeka,numD};
271 
272  MP_set S(numS); // Sources
273  MP_set D(numD); // Destinations
274  MP_subset<2> Link(S,D); // Transportation links (sparse subset of S*D)
275 
276  Link.insert(seattle,newyork);
277  Link.insert(seattle,chicago);
278  Link.insert(sandiego,chicago);
279  Link.insert(sandiego,topeka);
280 
281  MP_data SUPPLY(S);
282  MP_data DEMAND(D);
283 
284  SUPPLY(seattle)=350; SUPPLY(sandiego)=600;
285  DEMAND(newyork)=325; DEMAND(chicago)=300; DEMAND(topeka)=275;
286 
287  MP_data COST(Link);
288 
289  COST(Link(seattle,newyork)) = 2.5;
290  COST(Link(seattle,chicago)) = 1.7;
291  COST(Link(sandiego,chicago))= 1.8;
292  COST(Link(sandiego,topeka)) = 1.4;
293 
294  COST(Link) = 90 * COST(Link) / 1000.0;
295 
296  MP_variable x(Link);
297  x.display("...");
298 
299  MP_constraint supply(S);
300  MP_constraint demand(D);
301 
302  supply.display("...");
303 
304  supply(S) = sum( Link(S,D), x(Link) ) <= SUPPLY(S);
305  demand(D) = sum( Link(S,D), x(Link) ) >= DEMAND(D);
306 
307  cout<<"Here"<<endl;
308 
309  minimize( sum(Link, COST(Link)*x(Link)) );
310  assert(MP_model::getDefaultModel()->getNumRows()==5);
311  assert(MP_model::getDefaultModel()->getNumCols()==4);
312  assert(MP_model::getDefaultModel()->getNumElements()==8);
313  assert(MP_model::getDefaultModel()->getObjValue()>=156.14 && MP_model::getDefaultModel()->getObjValue()<=156.16);
314 
315  x.display("Optimal solution:");
316  supply.display("Supply dual solution");
317  cout<<"Test transport passed."<<endl;
318  */
319 
320 
321 
322  /*
323  // Testing limits for 0
324  double test = DBL_MIN;
325  cout << test << endl;
326  test = numeric_limits<double>::min();
327  cout << test << endl;
328  exit(0);
329  */
330 
331 
332  /*
333  // Testing getMaxPos()
334  vector<double> test {7,2,6,4,7,2,5,7,2};
335  double maxpos = getMaxPos(test);
336  double maxvalue = getMax(test);
337  double minpos = getMinPos(test);
338  double minvalue = getMin(test);
339  //double maxpos = testB();
340  cout << "maxpos: " << maxpos << endl;
341  cout << "maxvalue: " << maxvalue << endl;
342  cout << "minpos: " << minpos << endl;
343  cout << "minvalue: " << minvalue << endl;
344  exit(0);
345  */
346 
347 
348  /*
349  //This was in ModelData::debug():
350  // ********** START DEBUG CODE....... ************
351  double ddebuga=0; //20080209
352  uint idebuga=0;
353  double ddebugb=0; //20080209
354  uint idebugb=0;
355  double ddebugc=0; //20080209
356  uint idebugc=0;
357  double debugmin = 0;
358  double debugmax = 1000;
359  for (uint q=0;q<10000;q++){
360  ddebuga += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
361  ddebugb += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
362  ddebugc += debugmin + ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(debugmax-debugmin+1);
363  }
364  idebuga = ddebuga;
365  idebugb = ddebugb;
366  idebugc = ddebugc;
367  cout << "idebuga: "<<idebuga<<endl;
368  cout << "idebugb: "<<idebugb<<endl;
369  cout << "idebugc: "<<idebugc<<endl;
370  throw 2;
371  // ******** .....END DEBUG CODE *******************
372  */
373 
374  /*
375  // Testing the new iskey class
376  iskey op1(2100,"test");
377  iskey op2(2100,"test");
378  iskey op3(2101,"test");
379  iskey op4(2101,"tgst");
380  iskey op5(2101,"tb");
381  iskey op6(2101,"testa");
382  if(op1 == op2){
383  cout << "op1 and op2 are equal" << endl;
384  }
385  if(op1 == op3){
386  cout << "op1 and op3 are equal" << endl;
387  }
388  if(op6 > op3) cout << "test3 passed" << endl;
389  if(op5 < op3) cout << "test4 passed" << endl;
390  if(op6 >= op3) cout << "test5 passed" << endl;
391  if(op6 != op3) cout << "test6 passed" << endl;
392  if(op4 <= op3) cout << "test7 passed that it shoudn't" << endl;
393  exit(0);
394  */
395 
396  /*
397  // Testing the new changeMapValue(), incrMapValue(), resetMapValues(), incrOrAddMapValue(map, key, value) and vectorToMap() funcions
398  map<int,double> testMap;
399  for (uint i=0;i<5;i++){
400  pair<int,double> mypair(i,i*2.5);
401  testMap.insert(mypair);
402  }
403  double result = findMap(testMap,3,MSG_NO_MSG);
404  double result2 = findMap(testMap,1,MSG_ERROR);
405  double result3 = findMap(testMap,7,MSG_DEBUG);
406  cout << findMap(testMap,3,MSG_NO_MSG)<< endl;
407  changeMapValue(testMap,3,200.0,MSG_ERROR);
408  cout << findMap(testMap,3,MSG_NO_MSG)<< endl;
409  incrMapValue(testMap,3,5.0,MSG_ERROR);
410  cout << findMap(testMap,3,MSG_NO_MSG)<< endl;
411  incrOrAddMapValue(testMap, 3, 200.0);
412  cout << findMap(testMap,3,MSG_NO_MSG)<< endl;
413  incrOrAddMapValue(testMap, 10, 100.0);
414  cout << findMap(testMap,10,MSG_NO_MSG)<< endl;
415  cout << "done" << endl;
416 
417  vector<string> mykeys;
418  mykeys.push_back("andrea");
419  mykeys.push_back("antonello");
420  mykeys.push_back("paolo");
421  map<string,double> mymap = vectorToMap(mykeys,15.0);
422  string searchkey;
423  searchkey = "andrea";
424  cout << findMap(mymap,searchkey,MSG_DEBUG)<< endl;
425  resetMapValues(mymap,32.0);
426  cout << findMap(mymap,searchkey,MSG_DEBUG)<< endl;
427  exit(0);
428  */
429 
430 
431 
432  /*
433  // -------------------------------------------------------------------
434  // Sampling from uniform distribution with local random seed
435  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
436 
437  //this code sample from a uniform distribution. In this case also the seed is reinitialisated, but it it valid only locally: the rest of the program run with the same seed
438 
439  std::random_device rd;
440  std::mt19937 gen(rd());
441  std::uniform_int_distribution<> dis(1, 6);
442 
443  for (int n=0; n<10; ++n)
444  std::cout << dis(gen) << ' ';
445  std::cout << '\n';
446  exit(0);
447  */
448 
449 
450 
451  /*
452  // -------------------------------------------------------------------
453  // Testing how to get all elements in a map by substrings
454  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
455  map <string,double> values;
456  pair <string,double> val1("AAAAAA",1);
457  pair <string,double> val2("AAABBB",2);
458  pair <string,double> val3("BBBAAA",3);
459  pair <string,double> val4("BBBBBB",4);
460  pair <string,double> val5("CCCAAA",5);
461  pair <string,double> val6("C",6);
462  pair <string,double> val7("BBB",7);
463 
464  values.insert(val1);
465  values.insert(val2);
466  values.insert(val3);
467  values.insert(val4);
468  values.insert(val5);
469  values.insert(val6);
470  values.insert(val7);
471 
472  cout << "Printing whole map" << endl;
473  for (std::map<string,double>::iterator it=values.begin(); it!=values.end(); ++it)
474  std::cout << it->first << " => " << it->second << '\n';
475 
476  string search_for = "BBB";
477 
478  cout << "Using lower bound " << endl;
479  for (std::map<string,double>::iterator it=values.lower_bound(search_for); it!=values.end(); ++it)
480  std::cout << it->first << " => " << it->second << '\n';
481  cout << "Using upper bound " << endl;
482  for (std::map<string,double>::iterator it=values.upper_bound(search_for); it!=values.end(); ++it)
483  std::cout << it->first << " => " << it->second << '\n';
484 
485  cout << "Printing only substrings " << endl;
486  for (std::map<string,double>::iterator it=values.lower_bound(search_for); it!=values.end(); ++it){
487  string key = it->first;
488  if (key.compare(0, search_for.size(), search_for) == 0){
489  std::cout << it->first << " => " << it->second << '\n';
490  }
491  }
492 
493 
494  exit(0);
495  */
496 
497  /*
498  // testing findMap
499  map<int,double> testMap;
500  for (uint i=0;i<5;i++){
501  pair<int,double> mypair(i,i*2.5);
502  testMap.insert(mypair);
503  }
504  double result = findMap(testMap,3,MSG_NO_MSG);
505  double result2 = findMap(testMap,1,MSG_ERROR);
506  double result3 = findMap(testMap,7,MSG_DEBUG);
507  cout << "Done" << endl;
508  map<int, vector <double> > testMap2;
509  for (uint i=0;i<5;i++){
510  vector <double> myvector;
511  for(uint j=0;j<10;j++) {
512  myvector.push_back(i*100+j);
513  }
514  pair<int,vector <double> > mypair2(i,myvector);
515  testMap2.insert(mypair2);
516  }
517  vector <double> resultb = findMap(testMap2,3,MSG_NO_MSG);
518  vector <double> resultb2 = findMap(testMap2,1,MSG_ERROR);
519  vector <double> resultb3 = findMap(testMap2,7);
520  cout << "Done2" << endl;
521  exit(1);
522  */
523 
524 
525 
526  /*
527  // Testing vSum
528  vector <int> ivector(5,5);
529  vector <double> dvector(5,1.5);
530  vector < vector <int> > ivector2;
531  vector <vector <double > > dvector2;
532 
533 
534  for(uint i=0;i<5;i++){
535  ivector2.push_back(ivector);
536  dvector2.push_back(dvector);
537  }
538 
539  int iSum = vSum(ivector);
540  int iSum2 = vSum(ivector2[2]);
541  double dSum = vSum(dvector);
542  double dSum2 = vSum(dvector2[1]);
543  int iSum3 = vSum(ivector2);
544  double dSum3 = vSum(dvector2);
545 
546  cout << "hi there" << endl;
547  */
548 
549  /*
550  // Testing Eigen
551  using Eigen::MatrixXd;
552  MatrixXd m(2,2);
553  m(0,0) = 4;
554  m(1,0) = 2.5;
555  m(0,1) = -1;
556  m(1,1) = m(1,0) + m(0,1);
557  std::cout << m << std::endl;
558  exit(0);
559  */
560 
561  /*
562  // Test on two different type of partial matching over map values
563  testPartMatching2();
564  testPartMatching();
565  */
566 
567  /*
568  // -------------------------------------------------------------------
569  // Testing how to erase elements from a vector according to conditions
570  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
571 
572  vector<string> myvector;
573  myvector.push_back("a");
574  myvector.push_back("b");
575  myvector.push_back("c");
576  myvector.push_back("d");
577  myvector.push_back("e");
578 
579  for (uint i=0; i<myvector.size();i++){
580  cout << "i:" << i << " myvector[i]: " << myvector[i] << endl;
581  if(myvector[i]== "c" || myvector[i]=="d"){
582  cout << " -- TBR: " << "i:" << i << " myvector[i]: " << myvector[i] << endl;
583  myvector.erase (myvector.begin()+i);
584  i--;
585  }
586  }
587 
588  cout << "Myvector now contains:" << endl;
589  for (int i=0; i<myvector.size(); i++) {
590  cout << "i: " << i << " myvector[i]: " << myvector[i] << endl;
591  }
592  exit (0);
593  */
594 
595 
596 }
597 
598 void
600 
601  /*
602  // checking that the overriding works also for secondary dimension
603  // yep, it works!! ;-)
604  //ct 11003 beechRoundW 11001 69.71 100
605  double ct_11003_11002_beech = MTHREAD->MD->getProdData("ct",11003,"beechRoundW",2013,"11002");
606  double ct_11003_11001_beech = MTHREAD->MD->getProdData("ct",11003,"beechRoundW",2013,"11001");
607  double ct_11003_11002_hardW = MTHREAD->MD->getProdData("ct",11003,"hardWRoundW",2013,"11002");
608  double ct_11003_11001_hardW = MTHREAD->MD->getProdData("ct",11003,"hardWRoundW",2013,"11001");
609  exit(1);
610  */
611 
612  /*
613  // getting x,y of the pixel with sawmill in the TIGA project
614  Pixel* px = MTHREAD->GIS->getPixel(8967);
615  int x = px->getX();
616  int y = px->getY();
617  cout << "(X,Y) of pixel 8967: " << x << "\t" << y << endl;
618  px = MTHREAD->GIS->getPixel(0);
619  x = px->getX();
620  y = px->getY();
621  cout << "(X,Y) of pixel 0: " << x << "\t" << y <<endl;
622  exit(1);
623  */
624 
625  /*
626  // Testing overriding of just a product/region if it works
627  // Perfect.. the override works even just setting one specific ft/region value !! :-)
628  double ad = MTHREAD->MD->getProdData("additionalDemand",11001,"beechSawnW",2020); // this should be 0.004
629  double adt = MTHREAD->MD->getProdData("additionalDemand",11001,"beechSawnW",2022);
630  double adr = MTHREAD->MD->getProdData("additionalDemand",11002,"beechSawnW",2020);
631  double adp = MTHREAD->MD->getProdData("additionalDemand",11001,"hardWSawnW",2020);
632  cout << "additional demand test:" << endl;
633  cout << ad << "\t" << adt << "\t" << adr << "\t" << adp << endl;
634 
635  // Testing (again, for the TIGA project) the availalibily coefficient of Hetre
636  Pixel* px = MTHREAD->GIS->getPixel(32,30);
637  double ac = px->getSTData("avalCoef","Fut_Hetre",2013);
638  double act1 = px->getSTData("avalCoef","Fut_Hetre",2010);
639  double act2 = px->getSTData("avalCoef","Fut_Hetre",2014);
640  double act3 = px->getSTData("avalCoef","Fut_Hetre",2020);
641  double acft = px->getSTData("avalCoef","Fut_Feu",2013);
642  cout << "availability coefficient test:" << endl;
643  cout << ac << "\t" << act1 << "\t" << act2 << "\t" << act3 << "\t" << acft << endl;
644  exit(1);
645  */
646 
647  /*
648  // Testing picking up a national level variable defined only at national level. This may raise a segfault ?
649  //double debug = MTHREAD->MD->getProdData("carbonPrice",11000,"",2007);
650  cout << debug << endl;
651  exit(1);
652  */
653 
654  /*
655  // Testing getTableFromFile() function
656  LLData debug = MTHREAD->MD->getTableFromFile("debug", "scenarios/debug.csv");
657  exit(1);
658  */
659 
660 
661  /*
662  // Testing regional overriding in the new getBaseData() function
663  double mr11061 = MTHREAD->MD->getDoubleSetting("mr",DATA_NOW,11061);
664  double mr11042 = MTHREAD->MD->getDoubleSetting("mr",DATA_NOW,11042);
665  double mr = MTHREAD->MD->getDoubleSetting("mr",DATA_NOW);
666  // this should give critical error:
667  double mr5 = MTHREAD->MD->getDoubleSetting("mr",DATA_NOW,5);
668  exit(1);
669  */
670 
671  /*
672  // Testing the new getSTData() function
673  cout << "Starting test" << endl;
674  Pixel* px = MTHREAD->GIS->getPixel(32,30);
675  cout << "got pixel" << endl;
676  //double avalCoef = px->getMultiplier("avalCoefTest", "con_highF", 2007);
677  double avalCoef = px->getSTData("avalCoef","broadL_highF",2008);
678  cout << avalCoef << endl;
679  exit(1);
680  */
681 
682 
683  /*
684  // Testing shareMortalityUsableTimber call for a specific forest type and at the opposite with a null forest type
685  // to see if gfd() expands as expected
686 
687  double test1 = MTHREAD->MD->getForData("shareMortalityUsableTimber",11041,"","",2016);
688  cout << "test1: " << test1 << endl;
689  exit(1);
690  */
691 
692  /*
693  //testing supply_fromForestShare
694  double test = MTHREAD->MD->getProdData("supply_fromForestShare",11042,"hardWRoundW",2006);
695  cout << test << endl;
696  exit(1);
697  */
698 
699  /*
700  // Testing getSiblings() ok
701  ModelRegion* reg1 = MTHREAD->MD->getRegion(11042);
702  vector <ModelRegion*> siblings = reg1->getSiblings();
703  for(uint i=0;i<siblings.size();i++){
704  cout << siblings[i]->getRegId() << endl;
705  }
706  exit(1);
707  */
708 
709  /*
710  // Testing if after not found gpd(.) or gfd(.) we always have a negative tempBool.. yes
711  bool debug = true;
712  MTHREAD->MD->setTempBool(true);
713  double test1 = MTHREAD->MD->getForData("vol",11042,"broadL_highF","15");
714  debug = MTHREAD->MD->getTempBool();
715  double test2 = MTHREAD->MD->getForData("fgdfgdfhdfhdfhuk",11042,"broadL_highF","");
716  debug = MTHREAD->MD->getTempBool();
717  debug = true;
718  exit(1);
719  */
720 
721  /*
722  // Testing if asking a value from freeDim when this is not efined what returns
723  // no, if the freeDim is either null or 11000 I can't ask for e.g. 11042, I didn't developed expansion in the freeDim
724  double debug = MTHREAD->MD->getProdData("pol_ctSub",11042,"fuelW",DATA_NOW);
725  cout << debug << endl;
726  exit(1);
727  */
728 
729  /*
730  // Getting forest area by each forest type
731  vector<int> regIds2 = MTHREAD->MD->getRegionIds(2);
732  for(uint r=0;r<regIds2.size();r++){
733  int rId = regIds2[r];
734  ModelRegion* reg = MTHREAD->MD->getRegion(regIds2[r]);
735  vector <string> fTypes= MTHREAD->MD->getForTypeIds();
736  for(uint f=0;f<fTypes.size();f++){
737  string ft = fTypes[f];
738  forType* FT = MTHREAD->MD->getForType(ft);
739  double totalArea = 0.0;
740  vector <Pixel*> rpx = MTHREAD->GIS->getAllPlotsByRegion(regIds2[r]);
741  for (uint p=0;p<rpx.size();p++){
742  Pixel* px = rpx[p];
743  totalArea += px->getDoubleValue (FT->forLayer, true);
744  }
745  cout << rId << "\t" << ft << "\t" << totalArea << endl;
746  }
747  }
748  exit(1);
749  */
750 
751  /*
752  // Testing the new getForTypeParents()function
753  vector<string> parents = MTHREAD->MD->getForTypeParents();
754  for(uint i=0;i<parents.size();i++){
755  vector <string> childIds = MTHREAD->MD->getForTypeChilds(parents[i]);
756  vector <int> childPos = MTHREAD->MD->getForTypeChilds_pos(parents[i]);
757  double debug = 0.0;
758  }
759  */
760 
761  /*
762  // Testing the reg->getArea() functions
763  // Actually this need to be run further later, as pixels doesn't yet have area information
764  vector <string> dClasses = MTHREAD->MD->getStringVectorSetting("dClasses");
765  vector <string> fTypes= MTHREAD->MD->getForTypeIds();
766  ModelRegion* REG = MTHREAD->MD->getRegion(11041);
767  cout << "Total ft area: "<< REG->getArea()<< endl;
768 
769  for(uint j=0;j<fTypes.size();j++){
770  cout << fTypes[j] << "\t" << REG->getArea(fTypes[j]) << "\t" << REG->getArea(j) << endl;
771  }
772  for(uint j=0;j<fTypes.size();j++){
773  cout << fTypes[j] << "\t" << REG->getArea(fTypes[j]) << "\t";
774  for(uint u=0;u<dClasses.size();u++){
775  cout << REG->getArea(j,u) << " ";
776  }
777  cout << endl;
778  }
779  */
780 
781  /*
782  // Testing getForData() function with no forest id specified
783  double vartest= MTHREAD->MD->getForData("forestChangeAreaIncrementsRel",11061,"","",2009);
784  cout << vartest << endl;
785  exit(0);
786  */
787 
788 
789  /*
790  // Testing the decay model - ok, passed
791  double initialValue = 100;
792  double halfLife = 2;
793  double years = 0;
794  double remStock = MTHREAD->CBAL->getRemainingStock(initialValue, halfLife, years); ///< Apply a single exponential decay model to retrieve the remining stock given the initial stock, the half life and the time passed from stock formation.
795  cout << "Remaining stock: " << remStock << endl;
796  years = 1;
797  remStock = MTHREAD->CBAL->getRemainingStock(initialValue, halfLife, years);
798  cout << "Remaining stock: " << remStock << endl;
799  years = 5;
800  remStock = MTHREAD->CBAL->getRemainingStock(initialValue, halfLife, years);
801  cout << "Remaining stock: " << remStock << endl;
802  years =10;
803  remStock = MTHREAD->CBAL->getRemainingStock(initialValue, halfLife, years);
804  cout << "Remaining stock: " << remStock << endl;
805  years = 200;
806  remStock = MTHREAD->CBAL->getRemainingStock(initialValue, halfLife, years);
807  cout << "Remaining stock: " << remStock << endl;
808  */
809 
810  /*
811  // Testing normSample
812  // template <typename K> K normSample (const K& avg, const K& stdev, const K& minval=NULL, const K& maxval=NULL)
813  // template <typename K> K normSample (const normal_distribution<K>& d, const std::mt19937& gen, const K& minval=NULL, const K& maxval=NULL)
814  double avg = 0.8;
815  double stdev = 0.2;
816  double minval = 0.0;
817  double maxval = 1.0;
818  double result;
819 
820  cout << "Starting first method.." << endl;
821  normal_distribution<double> d(avg,stdev);
822  std::mt19937 gen = *MTHREAD->gen;
823  for (uint i=0;i<1000;i++){
824  result = normSample(d, gen, minval, maxval);
825  cout << "Result1: " << result << endl;
826  }
827  cout << "Finished first method and starting second one.." << endl;
828  for (uint i=0;i<1000;i++){
829  result = normSample(avg, stdev, minval, maxval);
830  cout << "Result2: " << result << endl;
831  }
832  cout << "Finished second method."<< endl;
833 
834  exit(0);
835  */
836 
837 
838  //double disttest = MTHREAD->MD->getProdData("dist",11042,"",DATA_NOW,i2s(11061));
839  //cout << disttest << endl;
840  //exit(0);
841 
842 
843  /*double test = MTHREAD->CBAL->getStock(11061, STOCK_INV);
844  //STOCK_INV -> from inventary source and death trees
845  //STOCK_EXTRA -> from inventary source and death trees
846  //STOCK_PRODUCTS -> from products
847  cout << "DONE" << endl;
848  exit(0);
849  */
850 
851  /*
852  // Testing if forestData can uses other arbitrary elements in the diameter field in order to generalise it
853  double test = MTHREAD->MD->getForData("covar",11082,"con_highF","con_highF");
854  MTHREAD->MD->setForData(0.1,"covar",11082,"con_highF","con_highF");
855  MTHREAD->MD->setForData(0.1,"covar",11061,"con_highF","con_highF",DATA_NOW,true);
856  test = MTHREAD->MD->getForData("covar",11082,"con_highF","con_highF");
857  test = MTHREAD->MD->getForData("covar",11061,"con_highF","con_highF");
858  test = MTHREAD->MD->getForData("covar",11082,"con_highF","");
859  cout << test << endl;
860  exit(0);
861  */
862 
863  /*
864  // Testing getProdData for the freeDimension
865  MTHREAD->MD->setProdData(0.4,"rt",11041,"hardWSawnW",DATA_NOW,true,"11061");
866  MTHREAD->MD->setProdData(0.3,"rt",11041,"hardWSawnW",DATA_NOW,true,"11030");
867  MTHREAD->MD->setProdData(0.2,"rt",11041,"hardWSawnX",DATA_NOW,true,"11030");
868  double debug = MTHREAD->MD->getProdData("rt",11041,"hardWSawnW",DATA_NOW,"11061");
869  double debug2 = MTHREAD->MD->getProdData("rt",11041,"hardWSawnW",DATA_NOW);
870  cout << debug << " " << debug2 << endl;
871  exit(0);
872  */
873 
874  /*
875  // Testing api to call generic forest type data, parent/child
876  cout << "Hello world " << endl;
877  cout << MTHREAD->MD->getForData("freq_norm",11041,"broadL","",2040) << endl;
878  MTHREAD->MD->setForData(100,"freq_norm",11041,"broadL","",2040);
879  cout << MTHREAD->MD->getForData("freq_norm",11041,"broadL","",2040) << endl;
880  cout << MTHREAD->MD->getForTypeParentId("broadL_highF")<< endl;
881  cout << MTHREAD->MD->getForTypeParentId("con_highF")<< endl;
882  exit(0);
883  */
884 
885  /*
886  // Testing for each region how far is the average of the multipliers from 1
887  vector<int> regIds = MTHREAD->MD->getRegionIds(2);
888  vector <string> ftypes = MTHREAD->MD->getForTypeIds();
889 
890  cout << "*** Checking how far is the tpMultiplier far from 1 in each region:" << endl;
891  for (int i=0;i< regIds.size();i++){
892  ModelRegion* region = MTHREAD->MD->getRegion(regIds[i]);
893  vector <Pixel*> regpixels = MTHREAD->GIS->getAllPlotsByRegion(regIds[i]);
894  if(regpixels.size()==0) continue;
895  cout << "*** " << region->getRegLName() << ": "<< endl;
896  for(int ft = 0;ft<ftypes.size();ft++){
897  double tot = 0;
898  double avg = 0;
899  for(int j=0;j<regpixels.size();j++){
900  tot += regpixels[j]->getSpModifier(ftypes[ft]);
901  }
902  avg = tot/regpixels.size();
903  cout << ftypes[ft] << ": " << avg << endl;
904  }
905  }
906  exit(0);
907  */
908 
909  /*
910  // Testing the number of plots in the model
911  vector <ModelRegion*> regions = MTHREAD->MD->getAllRegions();
912  int total = 0;
913  cout << "*** Pixels by region:" << endl;
914  for (int i=0;i< regions.size();i++){
915  vector <Pixel*> regpixels = MTHREAD->GIS->getAllPlotsByRegion(*regions[i]);
916  cout << regions[i]->getRegLName() << ": " << regpixels.size() << endl;
917  total += regpixels.size() ;
918  }
919  cout << "** Total: " << total << endl;
920  exit(0);
921  */
922 
923  /*
924  // Testing the new random distributions. Requires the pointer MTHREAD->gen to be initialised,
925  // so this test can't run in basic test.
926  std::normal_distribution<double> d(100000,3); // default any how to double
927  for(int n=0; n<20; ++n) {
928  double x = d(*MTHREAD->gen);
929  int i = round(d(*MTHREAD->gen));
930  cout << i << ';' << 1 << endl;
931  }
932  exit (0);
933  */
934 
935  /*
936  // Testing I have correctly the info about world price !!!
937  // yes, it seems ok here !!!
938  int firstYear = MTHREAD->MD->getIntSetting("initialYear");
939  int initialOptYear= MTHREAD->MD->getIntSetting("initialOptYear");
940  int simulationYears = MTHREAD->MD->getIntSetting("simulationYears");
941  int WL2 = MTHREAD->MD->getIntSetting("worldCodeLev2");
942  vector <string> priProducts = MTHREAD->MD->getStringVectorSetting("priProducts");
943  vector <string> secProducts = MTHREAD->MD->getStringVectorSetting("secProducts");
944  vector <string> allProducts = priProducts;
945  allProducts.insert( allProducts.end(), secProducts.begin(), secProducts.end() );
946 
947  for(uint i=0;i<allProducts.size();i++){
948  for(int y=firstYear; y<initialOptYear+simulationYears; y++){
949  double pw = MTHREAD->MD->getProdData("pl",WL2,allProducts[i],y);
950  cout << allProducts[i] << " " << y << " " << pw << endl;
951  }
952  }
953  exit (0);
954  */
955 
956  /*
957  // testing Pixel::getMultiplier (const string& multiplierName, const string& forName, int year)
958  Pixel* px = MTHREAD->GIS->getPixel(0);
959  double debug1 = px->getMultiplier("tp_multiplier","broadL_highF",2012);
960  double debug2 = px->getMultiplier("tp_multiplier","broadL_highF",2008);
961  double debug3 = px->getMultiplier("tp_multiplier","broadL_highF",2009);
962  double debug4 = px->getMultiplier("tp_multiplier","broadL_highF",2010);
963  double debug5 = px->getMultiplier("mortCoeff_multiplier","broadL_highF",2012);
964  double debug6 = px->getMultiplier("mortCoeff_multiplier","con_copp",2012);
965  double debug7 = px->getMultiplier("blaaaa","broadL_highF",2012);
966 
967  double debug10 = debug1;
968 */
969 
970  /*
971  // testing reading a directory
972  string dir = MTHREAD->MD->getBaseDirectory()+MTHREAD->MD->getStringSetting("spatialDataSubfolder");
973  vector<string> files = vector<string>();
974 
975  MTHREAD->MD->getFilenamesByDir (dir,files, ".grd");
976 
977  for (unsigned int i = 0;i < files.size();i++) {
978  cout << files[i] << endl;
979  }
980  */
981 
982  /*
983  // testing ModelData:: ModelData::calculateAnnualisedEquivalent(double amount_h, int years_h)
984  cout << "Value:" << MTHREAD->MD->calculateAnnualisedEquivalent(500.,4) << endl;
985  cout << "Value:" << MTHREAD->MD->calculateAnnualisedEquivalent(500.,30) << endl;
986  cout << "Value:" << MTHREAD->MD->calculateAnnualisedEquivalent(107.035040105,10) << endl;
987  cout << "Value:" << MTHREAD->MD->calculateAnnualisedEquivalent(8.91507,1) << endl;
988  cout << "Done" << endl;
989  exit(0);
990  */
991 
992  /*
993  // testing snprintf
994  vector <int> myintegers;
995  vector <double> mydoubles;
996  char szResult[24];
997 
998  myintegers.push_back(1);
999  myintegers.push_back(202);
1000  myintegers.push_back(3003);
1001  myintegers.push_back(400004);
1002  myintegers.push_back(50000005);
1003  myintegers.push_back(6000000006);
1004  mydoubles.push_back(1.1234567890);
1005  mydoubles.push_back(12345678.9);
1006  mydoubles.push_back(12345678.90123456);
1007  mydoubles.push_back(6000000006.123456789012);
1008  for(uint i=0;i<myintegers.size();i++){
1009  snprintf ( szResult, sizeof(szResult), "%d", myintegers[i] ); // "safe" version
1010  cout << "int/string: " << myintegers[i] << " / " << szResult << endl;
1011  }
1012  for(uint i=0;i<mydoubles.size();i++){
1013  snprintf ( szResult, sizeof(szResult), "%f", mydoubles[i] ); // "safe" version
1014  cout << "double/string: " << mydoubles[i] << " / " << szResult << endl;
1015  }
1016  exit(0);
1017  */
1018 
1019  /*
1020  // testing stod() ..
1021  // this is giving different results if gui or console mode !!
1022  vector<string> numbers;
1023  numbers.push_back("123.1234567890");
1024  numbers.push_back("123.1234");
1025  numbers.push_back("123,1234567890");
1026  numbers.push_back("123,1234");
1027  double outd;
1028  for(uint i=0;i<numbers.size();i++){
1029  try {
1030  outd = stod(numbers[i]);
1031  cout << "Conversion passed: " << numbers[i] << " - " << outd << endl;
1032  } catch (...) {
1033  cout << "Conversion DID NOT passed: " << numbers[i] << " - " <<endl;
1034  }
1035  }
1036  exit(0);
1037  */
1038 
1039 /*
1040 // ------------------------------------
1041 // Testing makeKeyProdData() and unpackKeyProdData()
1042  string parName = "za";
1043  int regId = 20000;
1044  string prod = "wood";
1045  string freeDim = "";
1046  string key = MTHREAD->MD->makeKeyProdData(parName,i2s(regId),prod,freeDim);
1047  cout << "key: " << key << endl;
1048  MTHREAD->MD->unpackKeyProdData(key,parName,regId,prod,freeDim);
1049  cout << "parName: " << parName << endl;
1050  cout << "regId: " << regId << endl;
1051  cout << "prod: " << prod << endl;
1052  cout << "freeDim: " << freeDim << endl;
1053  exit(0);
1054 */
1055 
1056 /*
1057 // ---------------------------------------------
1058 // checking the functions dataMapCheckExist() and dataMapGetValue() works well
1059 typedef map<string, vector <double> > DataMap;
1060 typedef pair<string, vector <double> > DataPair;
1061 
1062 vector <double> abaa (5, 1.);
1063 vector <double> abcc (5,10);
1064 vector <double> anbb (5,100);
1065 vector <double> andd (5,5);
1066 vector <double> anff (5,3);
1067 vector <double> ag (5,2);
1068 vector <double> agii (5,7);
1069 
1070 
1071 
1072 DataMap dM;
1073 dM.insert(DataPair("abaa", abaa));
1074 dM.insert(DataPair("abcc", abcc));
1075 dM.insert(DataPair("anbb", anbb));
1076 dM.insert(DataPair("andd", andd));
1077 dM.insert(DataPair("anff", anff));
1078 dM.insert(DataPair("ag", ag));
1079 dM.insert(DataPair("agii", agii));
1080 
1081 vector<string> tests;
1082 tests.push_back("ab");
1083 tests.push_back("anbb");
1084 tests.push_back("ane");
1085 tests.push_back("an");
1086 tests.push_back("ac");
1087 tests.push_back("ag");
1088 tests.push_back("agii");
1089 tests.push_back("al");
1090 
1091 
1092 bool found;
1093 double value;
1094 
1095 for(uint i=0;i<tests.size();i++){
1096  found = MTHREAD->MD->dataMapCheckExist(dM, tests[i]);
1097  value = MTHREAD->MD->dataMapGetValue(dM, tests[i],2010);
1098  cout << tests[i] << ": " << b2s(found) << " value: "<< value << endl;
1099 }
1100 
1101 exit(0);
1102 */
1103 
1104 
1105  /*
1106  // testing how to search on a vector using the find algorithm
1107 
1108  vector<string> names;
1109  names.push_back("pippo");
1110  names.push_back("topolino");
1111  names.push_back("minni");
1112  names.push_back("paperino");
1113 
1114  string toSearch1 = "minni";
1115  string toSearch2 = "zio paperone";
1116 
1117  if( find(names.begin(), names.end(), toSearch1)!= names.end() ){
1118  cout << "minni trovata" << endl;
1119  }
1120  if( find(names.begin(), names.end(), toSearch2)!= names.end() ){
1121  cout << "zio paperone trovato" << endl;
1122  }
1123  cout << "test on find ended." << endl;
1124  exit(0);
1125  */
1126 
1127 // ------------------------------------------------------------------
1128 
1129 
1130  /*
1131  int a;
1132  a = getSetting<int>("myIntData", TYPE_INT);
1133 
1134  string b;
1135  b = getSetting<string>("myStringData", TYPE_STRING);
1136 
1137  bool c;
1138  c = getSetting<bool>("myBoolData", TYPE_BOOL);
1139 
1140 
1141  cout << "A is: " << a << endl;
1142 
1143  cout << "B is: " << b << endl;
1144 
1145  cout << "C is: " << c << endl;
1146 
1147  //vector<string> getVectorSetting <string> ("test", TYPE_STRING);
1148  //template <class T> vector <T> getVectorSetting(string name_h, int type);
1149 
1150  //vector <string> myStrings = getVectorSetting <vector<string> > ("test", TYPE_STRING);
1151 
1152  string s = GccTest("test");
1153  int i = GccTest("test");
1154  vector <int> iVector = GccTest("test");
1155 
1156  for (int i=0; i< iVector.size(); i++){
1157  cout << "iVector: " << iVector.at(i) << endl;
1158  }
1159  */
1160 
1161  // ------------------------------------------------------------------
1162 
1163  /* // I learned: how to access elements - both objects and pointers - of a vector using pointers
1164  // testing how to operate with iterators over a pointer element in an array:
1165 
1166  cout << "Starting iterator test..." << endl;
1167 
1168  TestStructure a,b,c,d;
1169  a.i=0; b.i=1; c.i=2; d.i=3;
1170  TestStructure* ap;
1171  TestStructure* bp;
1172  TestStructure* cp;
1173  TestStructure* dp;
1174 
1175  ap = &a;
1176  bp = &b;
1177  cp = &c;
1178  dp = &d;
1179 
1180  vector <TestStructure> objects;
1181  vector <TestStructure*> pointers;
1182 
1183  objects.push_back(a);
1184  objects.push_back(b);
1185  objects.push_back(c);
1186  objects.push_back(d);
1187 
1188  pointers.push_back(ap);
1189  pointers.push_back(bp);
1190  pointers.push_back(cp);
1191  pointers.push_back(dp);
1192 
1193  vector<TestStructure>::iterator pi;
1194  vector<TestStructure*>::iterator pp;
1195 
1196  //ok it works
1197  //for ( pi = objects.begin() ; pi != objects.end();){
1198  // if(pi->i==2){
1199  // objects.erase(pi);
1200  // }
1201  // else {
1202  // ++pi;
1203  // }
1204  //}
1205 
1206  //for (int j=0;j<objects.size();j++){
1207  // cout << j << " object is: " << objects[j].i << endl;
1208  //}
1209 
1210 
1211  // works as well ;-))
1212  for ( pp = pointers.begin() ; pp != pointers.end();){
1213  if( (*pp)->i==2){
1214  //delete (*pp);
1215  pointers.erase(pp);
1216  }
1217  else {
1218  ++pp;
1219  }
1220  }
1221 
1222  for (int j=0;j<pointers.size();j++){
1223  cout << j << " pointers is: " << pointers[j]->i << endl;
1224  }
1225 
1226  // c is not destructed if we don't explicitelly call delete over the pointer...
1227  cout << c.i << endl; // this go in seg-frag if we call delete (*pp)..
1228  */
1229 
1230  // ------------------------------------------------------------------
1231  /* test on how to remove from a map.. deletable
1232  map <int, string> test;
1233  test.insert(pair<int, string>(2, "pippo"));
1234  test.insert(pair<int, string>(1, "pluto"));
1235  test.insert(pair<int, string>(5, "minni"));
1236  test.insert(pair<int, string>(3, "topolino"));
1237 
1238 
1239  map <int, string>::iterator p;
1240  p=test.find(3);
1241  if(p != test.end()){
1242  cout << p->second <<endl;
1243  test.erase(p);
1244  }
1245  else {
1246  cout << "not found " << endl;
1247  }
1248 
1249  map <int, string>::iterator p2;
1250  p2=test.find(3);
1251  if(p2 != test.end()){
1252  cout << p2->second <<endl;
1253  test.erase(p2);
1254  }
1255  else {
1256  cout << "not found " << endl;
1257  }
1258  */
1259 
1260  /*vector<int> test;
1261  for (int i=0;i<5;i++) test.push_back(i);
1262  cout << "test.." << endl;
1263  for (uint i=0;i<test.size();i++){
1264  cout << "Test "<<i<<": "<<test.at(i) << endl;
1265  }
1266  //test.erase(2);
1267 
1268  vector<int>::iterator p;
1269  for ( p = test.begin() ; p != test.end();){
1270  if(*p == 1 || *p == 2 || *p==4){
1271  test.erase(p);
1272  }
1273  else {
1274  ++p;
1275  }
1276  }
1277 
1278 
1279  for (uint i=0;i<test.size();i++){
1280  cout << "Test "<<i<<": "<<test.at(i) << endl;
1281  }
1282 
1283 // test.erase(remove_if(test.begin(), test.end(), FindMatchingString(&fs))
1284 
1285 // for (int i=0;i<test.size();i++) cout << "TEST: "<<i<< " " << test.at(i) << endl;
1286  */
1287 
1288  /*
1289  // On this test I am showing how to "move" one pointer from a vector of pointers to an other one. The real case is used to move Agent_farmer* pointers from the managedAgents vector to the removedVector.
1290 
1291  double* myDouble1 = new double(1);
1292  double* myDouble2 = new double(2);
1293  double* myDouble3 = new double(3);
1294 
1295  vector <double*> origin;
1296  vector <double*> destination;
1297 
1298  origin.push_back(myDouble1);
1299  origin.push_back(myDouble2);
1300  origin.push_back(myDouble3);
1301 
1302  cout << "MyDouble2: "<< *myDouble2 << endl;
1303  vector<double*>::iterator doublePIterator;
1304 
1305  for (int i=0;i<origin.size();i++){
1306  cout << i << " origin is: " << *origin[i] << endl;
1307  }
1308 
1309  for ( doublePIterator = origin.begin() ; doublePIterator !=origin.end();){
1310  if(*doublePIterator == myDouble2){
1311  destination.push_back(myDouble2);
1312  origin.erase(doublePIterator);
1313  }
1314  else {
1315  ++doublePIterator;
1316  }
1317  }
1318 
1319  for (int i=0;i<origin.size();i++){
1320  cout << i << " origin is now: " << *origin[i] << endl;
1321  }
1322 
1323  for (int i=0;i<destination.size();i++){
1324  cout << i << " destination is: " << *destination[i] << endl;
1325  } */
1326 
1327  // ------------------------------------------------------------------
1328  /*
1329  // Test on how to return a vector of pointers from a member vector of data
1330  TestStructure a,b,c,d;
1331  a.i=0; b.i=1; c.i=2; d.i=3;
1332  testVector.push_back(a);
1333  testVector.push_back(b);
1334  testVector.push_back(c);
1335  testVector.push_back(d);
1336 
1337  vector<TestStructure*> myVector=getTestStructure();
1338 
1339  for(uint i=0;i<myVector.size();i++){
1340  msgOut(MSG_DEBUG, i2s(myVector[i]->i));
1341  }
1342  */
1343 
1344  /*
1345  // Deleting an object and inserting a new one on a vector of objects.. it doesn't works.. problems with the last element..
1346  vector<BasicData>::iterator p;
1347  for(p=programSettingsVector.begin();p!=programSettingsVector.end();p++){
1348  if(p->name == SETT.name){
1349  programSettingsVector.erase(p);
1350  programSettingsVector.insert(p,1,SETT);
1351  cout << SETT.name <<endl;
1352  break;
1353  }
1354  }
1355  */
1356 
1357  /*double test = -987654321.987654321;
1358  double result;
1359  result = fabs(test);
1360  cout << "Test: "<< result << endl;*/
1361 
1362 
1363  /*
1364  // Testing the zip library:
1365 
1366  cout <<"Hello world Zip!" << endl;
1367 
1368  QString file = "data/testInput.ods";
1369  QString out = "data/tempInput";
1370  QString pwd = "";
1371  if (!QFile::exists(file))
1372  {
1373  cout << "File does not exist." << endl << endl;
1374  //return false;
1375  }
1376 
1377  UnZip::ErrorCode ec;
1378  UnZip uz;
1379 
1380  if (!pwd.isEmpty())
1381  uz.setPassword(pwd);
1382 
1383  ec = uz.openArchive(file);
1384  if (ec != UnZip::Ok)
1385  {
1386  //cout << "Failed to open archive: " << uz.formatError(ec).toAscii().data() << endl << endl; // Qt4
1387  cout << "Failed to open archive: " << uz.formatError(ec).toLatin1().data() << endl << endl; // Qt5
1388  //return false;
1389  }
1390 
1391  ec = uz.extractAll(out);
1392  if (ec != UnZip::Ok)
1393  {
1394  //cout << "Extraction failed: " << uz.formatError(ec).toAscii().data() << endl << endl; // Qt4
1395  cout << "Extraction failed: " << uz.formatError(ec).toLatin1().data() << endl << endl; // Qt5
1396  uz.closeArchive();
1397  //return false;
1398  }
1399  */
1400 
1401  /*
1402  // How to : delete an element from an array from its position
1403  cout << "How to : delete an element from an array from its position" << endl;
1404 
1405  vector <string> headers;
1406  vector < vector <string> > records;
1407  vector <string> firstrecord;
1408  vector <string> secondrecord;
1409  records.push_back(firstrecord);
1410  records.push_back(secondrecord);
1411 
1412  headers.push_back("a");
1413  headers.push_back("b");
1414  headers.push_back("");
1415  headers.push_back("d");
1416  headers.push_back("e");
1417  headers.push_back("");
1418 
1419  records[0].push_back("0");
1420  records[0].push_back("1");
1421  records[0].push_back("2");
1422  records[0].push_back("3");
1423  records[0].push_back("4");
1424  records[0].push_back("5");
1425  records[1].push_back("00");
1426  records[1].push_back("11");
1427  records[1].push_back("22");
1428  records[1].push_back("33");
1429  records[1].push_back("44");
1430  records[1].push_back("55");
1431 
1432  for (int i=headers.size()-1;i>=0;i--){
1433  if(headers[i] == ""){
1434  headers.erase(headers.begin()+i);
1435  for (int j=0;j<records.size();j++){
1436  records[j].erase(records[j].begin()+i);
1437  }
1438  }
1439  }
1440  for(uint i=0;i<headers.size();i++){
1441  cout << headers.at(i) << " - " << records[0].at(i) << " - " << records[1].at(i) << endl;
1442  }
1443  cout << "done!" << endl;
1444  */
1445 
1446  //testThreads();
1447  /*vector<double> numbers;
1448  double cumNumbers = 0.00;
1449  numbers.push_back(0.40);
1450  numbers.push_back(0.10);
1451  numbers.push_back(0.20);
1452  numbers.push_back(0.08);
1453  numbers.push_back(0.22);
1454 
1455  for (uint i=0;i<numbers.size();i++){
1456  cumNumbers += numbers[i];
1457  }
1458 
1459  if (cumNumbers <= 0.99999999 || cumNumbers >= 1.00000001) {
1460  cout <<"Bastardo!"<<endl;
1461  } else {
1462  cout <<"qui funzia!"<<endl;
1463  }*/
1464 
1465 }
1466 
1467 template <class T> vector <T> getVectorSetting(string name_h, int type) {
1468 
1469  vector <string> myStringDatas;
1470  myStringDatas.push_back("aaaaa");
1471  myStringDatas.push_back("bbbbb");
1472  myStringDatas.push_back("ccccc");
1473  vector <T> xVector;
1474 
1475  for (int i=0;i<myStringDatas.size();i++){
1476  istringstream iss(myStringDatas[i]);
1477  T x;
1478  iss >> x;
1479  xVector.push_back(x);
1480  }
1481 
1482  return xVector;
1483 }
1484 
1485 
1486 
1487 
1488 template <class T> T
1489 Sandbox::getSetting(string name_h, int type){
1490 
1491  string myIntData;
1492  myIntData = "34";
1493  string myStringData;
1494  myStringData = "abcdefg";
1495 
1496  string myBoolData;
1497  myBoolData = "false";
1498 
1499  if(type==TYPE_INT){
1500  istringstream iss(myIntData);
1501  T x;
1502  iss >> x;
1503  return x;
1504  }
1505 
1506  if(type==TYPE_STRING){
1507  istringstream iss(myStringData);
1508  T x;
1509  iss >> x;
1510  return x;
1511  }
1512 
1513  if(type==TYPE_BOOL){
1514  string tempBoolString;
1515  if (myBoolData == "1" || myBoolData == "true" || myBoolData == "True" || myBoolData == "TRUE" || myBoolData == "vero" || myBoolData == "Vero"|| myBoolData == "VERO"){
1516  tempBoolString = "1";
1517  }
1518  else if (myBoolData == "0" || myBoolData == "false" || myBoolData == "False" || myBoolData == "FALSE" || myBoolData == "falso" || myBoolData == "falso"|| myBoolData == "FALSO"){
1519  tempBoolString = "0";
1520  }
1521  else {
1522  msgOut(MSG_CRITICAL_ERROR, "Impossible conversion of "+myBoolData+" to bool!. Aborted.");
1523  }
1524  istringstream iss(tempBoolString);
1525  T x;
1526  iss >> x;
1527  return x;
1528  }
1529 
1530 
1531 }
1532 
1533 template<typename T> T
1534 Sandbox::test2(const std::string& s) {
1535  std::istringstream iss(s);
1536  T x;
1537  iss >> x;
1538  return x;
1539 }
1540 
1541 
1542 vector <TestStructure*>
1544  vector <TestStructure*> toReturn;
1545  for (uint i=0;i<testVector.size();i++){
1546  //TestStructure* tempTest = new TestStructure;
1547  toReturn.push_back(&testVector[i]);
1548  }
1549  return toReturn;
1550 
1551 }
1552 
1553 
1554 
1555 void
1557 
1558  /*
1559  PSEUDOCODE
1560  - attivo i vari thread
1561  - per ogni closestAgent itero fra i vari thread e se "è libero" gli assegno il closestAgent
1562  - quando ho finito i closestAgent aspetto che tutti i threads abbiano finito il lavoro
1563  - chiudo i threads
1564  - vado avanti
1565  */
1566  int nAgents= 50;
1567  vector<TestStructure*> myAgents;
1568  vector<double> myResults (nAgents, (double) 0);
1569  //int nThreads = MTHREAD->MD->getIntSetting("nThreads");
1570  int nThreads= 5;
1571 
1572  for (int i=0; i < nAgents; i++){
1573  TestStructure* myAgent = new TestStructure;
1574  myAgent->i = i;
1575  myAgent->random = (0+( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(10-0+1))/ (double)100;
1576  myAgents.push_back(myAgent);
1577  }
1578 
1579  vector <testThread*> myThreads ;
1580 
1581  for (int i=0; i < nThreads; i++){
1582  testThread* myThread = new testThread;
1583  myThreads.push_back(myThread);
1584  }
1585 
1586  for (uint i=0;i<myAgents.size();i++){
1587  bool assigned = false;
1588  while(!assigned) {
1589  for (uint j=0;j<myThreads.size();j++){
1590  if (!myThreads[j]->isRunning()){
1591  cout << "Assigning agent " << i << " to thread " << j << endl;
1592  myThreads[j]->assignJob(myAgents[i]);
1593  myThreads[j]->start();
1594  assigned = true;
1595  break;
1596  }
1597  else {
1598  cout << "Thread " << j << " is busy" << endl;
1599  }
1600  }
1601  }
1602  }
1603  /*
1604  volatile bool somethingStopping = true;
1605  while (somethingStopping){
1606  somethingStopping = false;
1607  for (uint i=0;i<myThreads.size();i++){
1608  if(myThreads[i]->isRunning()){
1609  somethingStopping = true;
1610  //cout << "somethingStopping is true" << endl;
1611  }
1612  }
1613  }
1614 
1615  if (somethingStopping) {
1616  cout << "somethingStopping is true" << endl;
1617  }
1618  else {
1619  cout << "somethingStopping is false" << endl;
1620  }
1621  cout << "pinco pallo sono nel mezzo dei threads..."<<endl;
1622  */
1623  for (int i=0; i < nThreads; i++){
1624  myThreads[i]->wait();
1625  }
1626 
1627 
1628  for (int i=0; i < nThreads; i++){
1629  delete myThreads[i];
1630  }
1631 
1632  for (uint i=0;i<myAgents.size();i++){
1633  //cout <<myAgents[i]->cachedOffer<<endl;
1634 
1635  double random = (0+( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(10-0+1))/ (double)100;
1636 
1637  // important !
1638  // for random integer see also std::uniform_int_distribution :
1639  // http://stackoverflow.com/questions/7780918/stduniform-int-distributionint-range-in-g-and-msvc
1640  // in regmas:
1641  // int randomRed = int (50+( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(255-50+1)); // randomRed is [50,255] Don't use "randomNumber % range" !!
1642 
1643  //cout <<random<<endl;
1644  }
1645 
1646  //thread1.stop();
1647  cout << "FINITO"<<endl;
1648 
1649 
1650 }
1651 
1653 
1654 }
1655 
1656 void
1658 
1659  cout << agent->i << endl;
1660 
1661  double randChange = (0+( (double)rand() / ((double)(RAND_MAX)+(double)(1)) )*(10-0+1))/ (double)100; //rand() must be not thread safe !!!!
1662 
1663  int justn = 10000;
1664  vector <double> takeTimeVector (justn, 0);
1665  for (int i =0; i< justn;i++){
1666  takeTimeVector.at(i)=i*2;
1667  }
1668  agent->cachedOffer = agent->random;
1669 }
1670 
1671 void
1673  agent = agent_h;
1674  agent->cachedOffer = 0;
1675 }
1676 
1677 void
1679 
1680 
1681  using namespace Ipopt;
1682 
1683  // Create a new instance of your nlp
1684  // (use a SmartPtr, not raw)
1685  SmartPtr<TNLP> mynlp = new Ipopt_nlp_problem_debugtest();
1686 
1687  // Create a new instance of IpoptApplication
1688  // (use a SmartPtr, not raw)
1689  // We are using the factory, since this allows us to compile this
1690  // example with an Ipopt Windows DLL
1691  SmartPtr<IpoptApplication> app = IpoptApplicationFactory();
1692 
1693  // Change some options
1694  // Note: The following choices are only examples, they might not be
1695  // suitable for your optimization problem.
1696  app->Options()->SetNumericValue("tol", 1e-7);
1697  app->Options()->SetStringValue("mu_strategy", "adaptive");
1698  app->Options()->SetStringValue("output_file", "ipopt.out");
1699  //app->Options()->SetStringValue("hessian_approximation", "limited-memory");
1700  //app->Options()->SetStringValue("derivative_test", "second-order");
1701  //app->Options()->SetStringValue("derivative_test_print_all", "yes");
1702 
1703 
1704  // The following overwrites the default name (ipopt.opt) of the
1705  // options file
1706  // app->Options()->SetStringValue("option_file_name", "hs071.opt");
1707 
1708  // Intialize the IpoptApplication and process the options
1709  ApplicationReturnStatus status;
1710  status = app->Initialize();
1711  if (status != Solve_Succeeded) {
1712  std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
1713  //return (int) status; // here the abort
1714  }
1715 
1716  // Ask Ipopt to solve the problem
1717  status = app->OptimizeTNLP(mynlp);
1718 
1719  if (status == Solve_Succeeded) {
1720  std::cout << std::endl << std::endl << "*** The problem solved!" << std::endl;
1721  }
1722  else {
1723  std::cout << std::endl << std::endl << "*** The problem FAILED!" << std::endl;
1724  }
1725 
1726 }
1727 
1728 int
1730 
1731  using namespace Ipopt;
1732  // Create an instance of your nlp...
1733  SmartPtr<TNLP> myadolc_nlp = new MyADOLC_NLP();
1734  //SmartPtr<TNLP> myadolc_nlp = new MyADOLC_sparseNLP();
1735 
1736  // Create an instance of the IpoptApplication
1737  SmartPtr<IpoptApplication> app = new IpoptApplication();
1738 
1739  // Initialize the IpoptApplication and process the options
1740  ApplicationReturnStatus status;
1741  status = app->Initialize();
1742  if (status != Solve_Succeeded) {
1743  printf("\n\n*** Error during initialization!\n");
1744  return (int) status;
1745  }
1746 
1747  status = app->OptimizeTNLP(myadolc_nlp);
1748 
1749  if (status == Solve_Succeeded) {
1750  // Retrieve some statistics about the solve
1751  Index iter_count = app->Statistics()->IterationCount();
1752  printf("\n\n*** The problem solved in %d iterations!\n", iter_count);
1753 
1754  Number final_obj = app->Statistics()->FinalObjective();
1755  printf("\n\n*** The final value of the objective function is %e.\n", final_obj);
1756  }
1757 
1758  return (int) status;
1759 }
1760 
1761 // ------------------------------------------------------------------
1762 // How to partial matching the key of a map
1763 
1764 /*TStrStrMap::iterator
1765 Sandbox::FindPrefix(const TStrStrMap& map, const string& search_for) {
1766  TStrStrMap::iterator i = map.lower_bound(search_for);
1767  if (i != map.end()) {
1768  const string& key = i->first;
1769  if (key.compare(0, search_for.size(), search_for) == 0) // Really a prefix?
1770  return i;
1771  }
1772  return map.end();
1773 }
1774 */
1775 
1776 /*
1777 void
1778 Sandbox::testSearchMap(const TStrStrMap& map, const string& search_for) {
1779  cout << search_for;
1780  TStrStrMap::iterator i = FindPrefix(map, search_for);
1781  if (i != map.end())
1782  cout << '\t' << i->first << ", " << i->second;
1783  cout << endl;
1784 
1785 }
1786 */
1787 
1788 void
1789 Sandbox::testSearchMap(const TStrStrMap& map, const string& search_for) {
1790  TStrStrMap::const_iterator i = map.lower_bound(search_for);
1791  for(;i != map.end();i++){
1792  const string& key = i->first;
1793  if (key.compare(0, search_for.size(), search_for) == 0) {// Really a prefix?
1794  cout << i->first << ", " << i->second << endl;
1795  } else {
1796  break;
1797  }
1798  }
1799 
1800 }
1801 
1802 
1803 void
1805 
1806  TStrStrMap tMap;
1807 
1808  tMap.insert(TStrStrPair("John", "AA"));
1809  tMap.insert(TStrStrPair("Mary", "BBB"));
1810  tMap.insert(TStrStrPair("Mother", "A"));
1811  tMap.insert(TStrStrPair("Moliere", "D"));
1812  tMap.insert(TStrStrPair("Marlon", "C"));
1813 
1814  testSearchMap(tMap, "Marl");
1815  testSearchMap(tMap, "Mo");
1816  testSearchMap(tMap, "ther");
1817  testSearchMap(tMap, "Mad");
1818  testSearchMap(tMap, "Mom");
1819  testSearchMap(tMap, "Perr");
1820  testSearchMap(tMap, "Jo");
1821 
1822  exit(0);
1823  return;
1824 }
1825 
1826 void
1827 Sandbox::testSearchMap2(const TStrStrMap& map_h, const string& search_for) {
1828  TStrStrMap::const_iterator i = map_h.upper_bound(search_for);
1829  if(i!= map_h.begin()) i--;
1830  const string& key = i->first;
1831  string search_base = search_for.substr(0,search_for.size()-4);
1832  if (key.compare(0, search_base.size(), search_base) == 0){
1833  cout << "MATCH: " << search_for <<", "<< i->first << ", " << i->second << endl;
1834  } else {
1835  cout << "NOTM: " << search_for <<", "<< i->first << endl;
1836  }
1837 
1838 }
1839 
1840 void
1842 
1843  TStrStrMap tMap;
1844 
1845 
1846  tMap.insert(TStrStrPair("mortCoeff_multiplier#broadL_highF##2005", "2005"));
1847  tMap.insert(TStrStrPair("regLev_1", "-9999"));
1848  tMap.insert(TStrStrPair("regLev_2", "-9999"));
1849  tMap.insert(TStrStrPair("tp_multiplier#broadL_copp##2005", "-9999"));
1850  tMap.insert(TStrStrPair("tp_multiplier#broadL_highF##2005", "50"));
1851  tMap.insert(TStrStrPair("tp_multiplier#broadL_highF##2010", "2010"));
1852  tMap.insert(TStrStrPair("tp_multiplier#broadL_mixedF##2005", "-9999"));
1853  tMap.insert(TStrStrPair("tp_multiplier#con_copp##2005", "-9999"));
1854  tMap.insert(TStrStrPair("tp_multiplier#con_highF##2005", "-9999"));
1855  tMap.insert(TStrStrPair("tp_multiplier#con_mixedF##2005", "aa"));
1856 
1857  TStrStrMap::const_iterator i;
1858 
1859  for(i=tMap.begin();i!=tMap.end();i++){
1860  cout << i->first << ", " << i->second << endl;
1861  }
1862  cout << endl;
1863 
1864  testSearchMap2(tMap, "mortCoeff_multiplier#broadL_highF##2006");
1865  testSearchMap2(tMap, "tp_multiplier#broadL_highF##2008");
1866  testSearchMap2(tMap, "aaaaaa");
1867  testSearchMap2(tMap, "zzzzzz");
1868 
1869  exit(0);
1870  return;
1871 }
1872 
1873 
void testPartMatching()
How to partial matching the key of a map.
Definition: Sandbox.cpp:1804
int testAdolc()
Definition: Sandbox.cpp:1729
void testPartMatching2()
How to partial matching the key of a map.
Definition: Sandbox.cpp:1841
void testIpopt()
Definition: Sandbox.cpp:1678
vector< TestStructure * > getTestStructure()
Definition: Sandbox.cpp:1543
The required data is a string.
Definition: BaseClass.h:68
The required data is a bool.
Definition: BaseClass.h:69
pair< string, string > TStrStrPair
Definition: Sandbox.cpp:77
STL namespace.
Thread manager. Responsable to manage the main thread and "speak" with the GUI.
Definition: ThreadManager.h:65
void run()
Definition: Sandbox.cpp:1657
void testSearchMap2(const map< string, string > &map_h, const string &search_for)
Definition: Sandbox.cpp:1827
Sandbox()
Definition: Sandbox.cpp:85
Print an error message and stop the model.
Definition: BaseClass.h:62
void fullTest()
Tests that require a full sandbox object including MTHREAD. Normally empty.
Definition: Sandbox.cpp:599
~Sandbox()
Definition: Sandbox.cpp:90
double random
Definition: Sandbox.h:73
string nameMember
Definition: Sandbox.cpp:100
map< string, string > TStrStrMap
Definition: Sandbox.cpp:76
GccTest(string name_h)
Definition: Sandbox.cpp:98
T test2(const std::string &s)
Definition: Sandbox.cpp:1534
vector< T > getVectorSetting(string name_h, int type)
Definition: Sandbox.cpp:1467
The required data is an integer.
Definition: BaseClass.h:66
T getSetting(string name_h, int type)
Definition: Sandbox.cpp:1489
double cachedOffer
Definition: Sandbox.h:72
void testSearchMap(const map< string, string > &map, const string &search_for)
Definition: Sandbox.cpp:1789
void assignJob(TestStructure *agent_h)
Definition: Sandbox.cpp:1672
void testThreads()
Definition: Sandbox.cpp:1556
void basicTest()
Simple tests that doesn&#39;t require anything else (are encapsulated) and so they can be run at the begi...
Definition: Sandbox.cpp:132