optimizer.cpp
Go to the documentation of this file.
1 
18 #include <cstdio>
19 #include <iostream>
20 #include <cstring>
21 #include <fstream>
22 
23 #include <boost/program_options.hpp>
24 namespace po = boost::program_options;
25 
26 #include <log.h>
27 #include <frame.h>
28 #include <datapairs.h>
29 #include <value_setter.h>
30 #include <optimizer_goal.h>
35 #include <optimizer_container.h>
36 #include <optimizer.h>
37 
38 using namespace robotLibPbD;
39 
40 void COptimizer::setValue(double *x)
41 {
42  unsigned int counter = 0;
43  for (unsigned int i=0; i<data.size(); i++)
44  {
45  data[i].setValue(x, counter);
46  counter += data[i].dofs.size();
47  }
48 }
49 
50 std::string COptimizer::readFromFile(std::string filename)
51 {
52  std::vector<std::string> text;
53  std::string line;
54  std::ifstream textstream;
55 
56  textstream.open(filename.c_str());
57 
58 
59  while (textstream.good() && std::getline(textstream, line)) {
60  text.push_back(line + "\n");
61  }
62  textstream.close();
63  std::string alltext;
64  for (unsigned int i=0; i < text.size(); i++)
65  alltext += text[i];
66 
67  return alltext;
68 }
69 
70 
71 void COptimizer::setData(std::vector<double> &values)
72 {
73  for (unsigned int i=0; i<valueSetters.size(); i++)
74  {
75  valueSetters[i].set(values);
76  }
77  /*
78  for (unsigned int i=0; i<values.size(); i++)
79  {
80  LOG_MSG(10, "Setting: %s = %s\n", printToString("%d", i+1).c_str(), printToString("%f", values[i]).c_str());
81  information.add(printToString("%d", i+1), printToString("%f", values[i]), true);
82  }
83  frames.loadFromFile(cfg.c_str(), information, config, false);
84  frames.invalidate();
85  */
86 }
87 
88 void COptimizer::rosenbrockCallback(int nparam, double *x, double *fj, void *extraparams)
89 {
90  if (extraparams != NULL)
91  ((COptimizer*) extraparams)->callback(nparam, x, fj);
92 }
93 
94 void COptimizer::callback(int nparam, double *x, double *fj)
95 {
96  LOG_MSG(10, "X: ");
97  for (int i=0; i<nparam; i++)
98  LOG_MSG(10, "%f ", x[i]);
99  LOG_MSG(10, "\n");
100 
101  fj[0] = 0.0;
102 
103 
104  for (unsigned int i=0; i<globalFunctions.size(); i++)
105  globalFunctions[i]->reset();
106 
107  setValue(x);
108 
109  for (unsigned int j=0; j<examples.size(); j++)
110  {
111  setData(examples[j]);
112 
113  if (LOG_MSG_LEVEL(10))
114  {
115  CFrameInterface interface;
116  for (unsigned int i=0; i<frames.getFrames().size(); i++)
117  {
118  interface.setFrame(frames.getFrame(i));
119  LOG_MSG(10, "%s", interface.getFrameAsXml().c_str());
120  LOG_MSG(10, "%s", frames.getFrame(i)->getRelativeToBase().toString().c_str());
121  }
122  }
123 
124  distances[j] = 0.0;
125  for (unsigned int i=0; i<functions.size(); i++)
126  {
127  double tmpf = functions[i]->getDistance();
128  LOG_MSG(6, "%d %d: %f\n", j, i, tmpf);
129 
130  distances[j] += tmpf;
131 
132  //fj[0] += tmpf / (double) examples.size();
133  }
134 
135 
136  for (unsigned int i=0; i<globalFunctions.size(); i++)
137  globalFunctions[i]->add();
138  }
139 
140 
141  for (unsigned int i=0; i<globalFunctions.size(); i++)
142  fj[0] += globalFunctions[i]->getDistance();
143 
144  if (functions.size() > 0)
145  {
146  if (distances.size() == 1)
147  {
148  fj[0] += distances[0];
149  } else
150  {
151  std::sort(distances.begin(), distances.end());
152  for (unsigned int i=trimming; i<distances.size() - trimming; i++)
153  fj[0] += distances[i] / (double) (distances.size() - 2*trimming);
154  }
155  }
156 
157  if (LOG_MSG_LEVEL(5))
158  {
159  LOG_MSG(2,"Value: %f X: ", fj[0]);
160  for (int i=0; i<nparam; i++)
161  LOG_MSG(2,"%f ", x[i]);
162  LOG_MSG(2,"\n");
163  }
164 
165  counter++;
166  if (useShowResult || counter % counterMod == 0 )
167  {
168  LOG_MSG(2,"Goal-Value: %f State-Values: ", fj[0]);
169  for (int i=0; i<nparam; i++)
170  LOG_MSG(2,"%f ", x[i]);
171  LOG_MSG(2,"\n");
172  std::string tmp = generateOutput();
173  LOG_MSG(2,"%s\n", tmp.c_str());
174  }
175 }
176 
177 bool COptimizer::isEqual(std::vector<double> &first, std::vector<double> &second, double eps)
178 {
179  for (unsigned int i=0; i<first.size() && i<second.size(); i++)
180  if (fabsf(first[i] - second[i]) > eps)
181  return false;
182 
183  return true;
184 }
185 
186 void COptimizer::loadData(std::string filename, unsigned int startId)
187 {
188  std::string line, prev;
189  std::ifstream textstream;
190  std::vector<double> input;
191  std::vector<std::vector<double> > examples2;
192  LOG_VERBOSE("Reading data from %s.\n", filename.c_str());
193 
194  textstream.open(filename.c_str());
195 
196  unsigned int lines = 0;
197  while (textstream.good() && std::getline(textstream, line))
198  {
199  lines++;
200  if (lines <= startId)
201  continue;
202 
203  input.clear();
204 
205  if (line.find(":") != std::string::npos)
206  line = line.substr(line.find(":")+1, line.length());
207 
208 
209 
210  if (line.size() <= 0)
211  continue;
212 
213  LOG_VERBOSE("%s\n", line.c_str());
214  strToArray(line, input, ";");
215 
216  //ToDo: Debug isEqual
217  //if (examples2.size() > 0 && isEqual(examples2.back(), input))
218  //continue;
219 
220  examples2.push_back(input);
221  prev = line;
222  }
223  textstream.close();
224 
225  int exampleCount = examples2.size();
226  LOG_VERBOSE("Loaded %d ( %d ) examples\n", exampleCount, lines);
227  unsigned int offset = examples2.size() / examplesMax;
228  if (offset < 1)
229  offset = 1;
230  for (unsigned int i=0; i<examples2.size(); i+=offset)
231  examples.push_back(examples2[i]);
232 
233  distances.resize(examples.size());
234 }
235 
236 
238 {
239  std::string tmp;
240  CFrameInterface interface;
241  for (unsigned int i=0; i<data.size(); i++)
242  {
243  CVec position, quater;
244  CMatrix matrix = data[i].frame->getPose();
245  position = matrix[3];
246  CMathLib::quaternionFromMatrix(matrix, quater);
247  interface.setFrame(data[i].frame);
248  CVec eulerAngles;
249  CMathLib::getEulerZXZ(matrix, eulerAngles);
250  tmp += printToString("Result: %s", interface.getFrameAsXml().c_str());
251  tmp += printToString("Position (xyz): %f %f %f Quaternion (wxyz): %f %f %f %f EulerAngles(ZXZ): %f %f %f \n\n", position.x, position.y, position.z,
252  quater.w, quater.x, quater.y, quater.z, eulerAngles.x*180.0/M_PI, eulerAngles.y*180.0/M_PI, eulerAngles.z*180.0/M_PI);
253  }
254  tmp += printToString("<-- result -->\n\n");
255  return tmp;
256 }
257 
258 bool COptimizer::writeToFile(std::string filename, std::string buffer)
259 {
260  std::ofstream textstream(filename.c_str());
261  if (textstream.fail())
262  return false;
263 
264  textstream << buffer;
265  textstream.close();
266  return true;
267 }
268 
269 int COptimizer::getValue(TiXmlElement *node, std::string item)
270 {
271  std::string tmp, tmp2;
272  tmp = CConfiguration::getAttributeString(node, item.c_str(), "");
273  size_t found = tmp.find("([");
274  size_t found2 = tmp.find("])");
275 
276  if (found != std::string::npos && found2 !=std::string::npos)
277  {
278  tmp2 = tmp.substr(found+2, found2-found-2);
279  LOG_MSG(2, "Value: %s\n", tmp2.c_str());
280  return (int) atof(tmp2.c_str()) - 1;
281  }
282 
283  return -1;
284 }
285 
286 void COptimizer::loadDofs(std::string filename)
287  {
288  // load frame structure from xml
289  frames.loadFromFile(filename.c_str());
291 
292  CFrameInterface interface;
293  std::vector<double> dofs_max, dofs_min;
294  std::vector<unsigned int> dofs;
295 
296  unsigned int n = 0;
297  for (unsigned int i=0; i<frames.getFrames().size(); i++)
298  {
299  interface.setFrame(frames.getFrame(i));
300  LOG_VERBOSE("Frame: %s\n", interface.getFrameAsXml().c_str());
301 
302  frames.getFrame(i)->getDofs(dofs);
303  if (dofs.size() > 0)
304  {
305  frames.getFrame(i)->getDofs(dofs_min, dofs_max);
306  for (unsigned int j=0; j<dofs.size(); j++)
307  LOG_VERBOSE("Loaded dof %d: %g %g\n", dofs[j], dofs_min[dofs[j]], dofs_max[dofs[j]]);
308 
309  n += dofs.size();
310 
311  OptimizerContainer item;
312  item.frame = frames.getFrame(i);
313  item.dofs_max = dofs_max;
314  item.dofs_min = dofs_min;
315  item.dofs = dofs;
316  data.push_back(item);
317  }
318  }
319 
320  LOG_VERBOSE("Total number of dofs: %d\n", n);
321  this->dofs = n;
322  }
323 
324 
325 void COptimizer::loadValueSetters(std::string filename)
326  {
327  // load frame structure from xml
328  CConfiguration config("Data");
329  //bool okay = config.load(filename.c_str());
330  config.load(filename.c_str());
331 
332  // Load goal
333  std::vector<TiXmlElement*> result;
334  config.findNodes("Frames.Frame", result);
335  for (unsigned int i=0; i<result.size(); i++)
336  {
337  LOG_MSG(2,"Frame: %s\n", CConfiguration::getAttributeString(result[i], "name", ""));
338  ValueSetter valueSetter;
339 
340  valueSetter.x = getValue(result[i], "x");
341  valueSetter.y = getValue(result[i], "y");
342  valueSetter.z = getValue(result[i], "z");
343  valueSetter.qw = getValue(result[i], "qw");
344  valueSetter.qx = getValue(result[i], "qx");
345  valueSetter.qy = getValue(result[i], "qy");
346  valueSetter.qz = getValue(result[i], "qz");
347  valueSetter.a = getValue(result[i], "a");
348  valueSetter.b = getValue(result[i], "b");
349  valueSetter.g = getValue(result[i], "g");
350 
351  if (valueSetter.x < 0 &&
352  valueSetter.y < 0 &&
353  valueSetter.z < 0 &&
354  valueSetter.qw < 0 &&
355  valueSetter.qx < 0 &&
356  valueSetter.qy < 0 &&
357  valueSetter.qz < 0 &&
358  valueSetter.a < 0 &&
359  valueSetter.b < 0 &&
360  valueSetter.g < 0)
361  continue;
362 
363  int frameId = frames.getFrameByName(CConfiguration::getAttributeString(result[i], "name", ""));
364  if (frameId < 0)
365  continue;
366 
367  valueSetter.frame = frames.getFrame(frameId);
368 
369  valueSetters.push_back(valueSetter);
370  }
371  }
372 
373 
374 void COptimizer::loadGoals(std::string filename)
375  {
376  // load frame structure from xml
377  CConfiguration config("Data");
378  //bool okay = config.load(filename.c_str());
379  config.load(filename.c_str());
380 
381  // Load goal
382  std::vector<TiXmlElement*> result;
383  config.findNodes("Goal.Function", result);
384  for (unsigned int i=0; i<result.size(); i++)
385  {
386  OptimizerGoal* goal = new OptimizerGoal();
387  goal->loadFromXml(frames, result[i]);
388  functions.push_back(goal);
389  }
390 
391  result.clear();
392  config.findNodes("Goal.GlobalPosition", result);
393  for (unsigned int i=0; i<result.size(); i++)
394  {
396  goal->loadFromXml(frames, result[i]);
397  goal->setTrimming(trimming);
398  globalFunctions.push_back(goal);
399  }
400 
401 
402  result.clear();
403  config.findNodes("Goal.GlobalOrientation", result);
404  for (unsigned int i=0; i<result.size(); i++)
405  {
407  goal->loadFromXml(frames, result[i]);
408  goal->setTrimming(trimming);
409  globalFunctions.push_back(goal);
410  }
411 
412  result.clear();
413  config.findNodes("Goal.Position", result);
414  for (unsigned int i=0; i<result.size(); i++)
415  {
417  goal->loadFromXml(frames, result[i]);
418  functions.push_back(goal);
419  }
420 
421  result.clear();
422  config.findNodes("Goal.Orientation", result);
423  for (unsigned int i=0; i<result.size(); i++)
424  {
426  goal->loadFromXml(frames, result[i]);
427  functions.push_back(goal);
428  }
429  }
430 
431 
433 {
434  result.clear();
435  valueSetters.clear();
436  data.clear();
437 
438 
439  globalFunctions.clear();
440 
441 
442  functions.clear();
443 
444  information.clear();
445  frames.clear();
446 
447  examples.clear();
448  distances.clear();
449 }
450 
451 void COptimizer::load(std::string cfg, std::string data, unsigned int start)
452 {
453  reset();
454 
455  loadData(data, start);
456 
457  loadDofs(cfg);
458 
459  loadGoals(cfg);
460 
461  loadValueSetters(cfg);
462 
463 }
464 
465 void COptimizer::run(const std::vector<double> &initialValues)
466 {
467  // reset
468  counter = 0;
469 
470  // set trimming
471  trimming = 0;
472  if (trim > 0.0 && trim < 1.0)
473  {
474  trimming = (unsigned int) (trim / 2.0 * (double) examples.size());
475  if (trimming == 0)
476  trimming = 0;
477 
478  LOG_VERBOSE("Trimming best %d and worst %d items\n", trimming, trimming);
479  }
480  for (unsigned int i=0; i<globalFunctions.size(); i++)
482 
483  int nparam,maxIter,verbosity;
484  double *st,*bl,*bu,bigbnd,eps;
485  nparam=dofs;
486  st=(double*)calloc(nparam,sizeof(double));
487  bl=(double *)calloc(nparam,sizeof(double));
488  bu=(double *)calloc(nparam,sizeof(double));
489  bigbnd=1.e10;
490  maxIter=iterations;
491  eps=epsilon;//CHANGED 1.e-8;
492  verbosity=0;
493 
494  for (int i=0; i<nparam; i++)
495  {
496  st[i] = 0.5;
497  bl[i] = 0.0;
498  bu[i] = 1.0;
499  }
500 
501  if ((int)initialValues.size() >= nparam)
502  for (int i=0; i<nparam; i++)
503  {
504  st[i] = initialValues[i];
505  if (st[i] < 0.0 || st[i] > 1.0)
506  LOG_MSG(2,"Error: %d'th value %f has to be in [0,1].\n", i, st[i]);
507  }
508 
509  if (useRandom)
510  for (int i=0; i<nparam; i++)
511  {
512  st[i] = getUniform();
513  }
514  double y[1];
515 
516 
517  LOG_MSG(2, "Initial:\n");
518  for (int i=0; i<nparam; i++)
519  LOG_MSG(2, "%f\n", st[i]);
520 
521  if (doQuit)
522  {
523  rosenbrockCallback(nparam, st, y, this);
524  exit(0);
525  }
526 
527 
528  rosenbrock(nparam,st,bl,bu,bigbnd,maxIter,eps,verbosity,rosenbrockCallback, this);
529 
530  rosenbrockCallback(nparam, st, y, this);
531 
532  LOG_MSG(2, "Best: %f\n", y[0]);
533 
534  LOG_MSG(2, "Result:\n");
535  for (int i=0; i<nparam; i++)
536  LOG_MSG(2, "%f\n", st[i]);
537 
538  LOG_MSG(1, "%f ", y[0]);
539 
540  for (int i=0; i<nparam; i++)
541  LOG_MSG(1, "%f ", st[i]);
542  LOG_MSG(1, "%f\n", y[0]);
543 
544  setValue(st);
545  std::string output = generateOutput();
546  LOG_MSG(2, "Final result:\n");
547  LOG_MSG(2, "%s\n", output.c_str());
548 
549  this->resultValue = y[0];
550 
551  this->result.resize(nparam);
552  for (int i=0; i<nparam; i++)
553  this->result[i] = st[i];
554 
555  free(st);
556  free(bl);
557  free(bu);
558 }
559 
560 
562 {
563  allPoses.clear();
564  optimizedPoses.clear();
565  values.clear();
566  timelineOfPoses.clear();
567 }
568 
570 {
571  if (result.size() == 0)
572  return false;
573 
574  double *st = (double*)calloc(result.size(),sizeof(double));
575  for (unsigned int i=0; i<result.size(); i++)
576  st[i] = result[i];
577 
578  setValue(st);
579 
580  // reset
581  out.clear();
582 
583  // set result
584  out.result = resultValue;
585  out.values = result;
586  for (unsigned int i=0; i<data.size(); i++)
587  {
588  out.optimizedPoses.push_back(make_pair((std::string)data[i].frame->getName(), data[i].frame->getPose()));
589  }
590 
591  for (unsigned int i=0; i<frames.getFrames().size(); i++)
592  out.allPoses.push_back(make_pair((std::string)frames.getFrame(i)->getName(), frames.getFrame(i)->getPose()));
593 
594  // generate timeline
595  out.timelineOfPoses.resize(examples.size());
596  for (unsigned int j=0; j<examples.size(); j++)
597  {
598  setData(examples[j]);
599  setValue(st);
600 
601  for (unsigned int i=0; i<frames.getFrames().size(); i++)
602  out.timelineOfPoses[j].push_back(make_pair((std::string)frames.getFrame(i)->getName(), frames.getFrame(i)->getPose()));
603  }
604 
605  free(st);
606  return true;
607 }
std::vector< std::vector< double > > examples
Definition: optimizer.h:61
CFrameContainer frames
Definition: optimizer.h:58
bool isEqual(std::vector< double > &first, std::vector< double > &second, double eps=0.1)
Definition: optimizer.cpp:177
PRECISION z
Definition: vecmath.h:60
std::vector< std::pair< std::string, CMatrix > > optimizedPoses
Definition: optimizer.h:42
void run(const std::vector< double > &initialValues)
Definition: optimizer.cpp:465
bool writeToFile(std::string filename, std::string buffer)
Definition: optimizer.cpp:258
std::string printToString(const char *format,...)
Definition: utils.cpp:149
void loadFromXml(CFrameContainer &frames, TiXmlElement *frameNode)
void callback(int nparam, double *x, double *fj)
Definition: optimizer.cpp:94
bool getFrameByName(const char *name, CFrame *&frame)
Definition: frame.cpp:945
std::vector< std::vector< std::pair< std::string, CMatrix > > > timelineOfPoses
Definition: optimizer.h:39
bool getResult(COptimizerResult &out)
Definition: optimizer.cpp:569
virtual std::string getFrameAsXml()
Definition: frame.cpp:1186
void getDofs(std::vector< unsigned int > &dofs)
Definition: frame.cpp:501
static const char * getAttributeString(TiXmlElement *node, const char *str, const char *def="")
virtual CMatrix getRelativeToBase()
Returns pose in the base (frame with no predecessor) frame.
Definition: frame.h:508
std::vector< double > values
Definition: optimizer.h:43
int getValue(TiXmlElement *node, std::string item)
Definition: optimizer.cpp:269
unsigned int examplesMax
Definition: optimizer.h:65
void setTrimming(unsigned int value)
#define LOG_MSG_LEVEL(index)
Definition: log.h:41
unsigned int trimming
Definition: optimizer.h:67
PRECISION w
Definition: vecmath.h:60
std::vector< CFrame * > getFrames()
Definition: frame.h:227
unsigned int iterations
Definition: optimizer.h:65
std::vector< double > result
Definition: optimizer.h:53
static void quaternionFromMatrix(const CMatrix &mat, CVec &quaternion)
Transforms a homogenous matrix into quaternion representation.
Definition: vecmath.cpp:525
static void getEulerZXZ(CMatrix &mat, CVec &first)
Transforms homogenous matrix into Euler angle (YZX) representation (two solutions) ...
Definition: vecmath.cpp:618
void setData(std::vector< double > &values)
Definition: optimizer.cpp:71
virtual std::string generateOutput()
Definition: optimizer.cpp:237
Homogenous vector.
Definition: vecmath.h:57
virtual void setFrame(CFrame *frame)
Definition: frame.h:144
void clear()
Clears storage buffer.
Definition: datapairs.cpp:126
Homogenous matrix.
Definition: vecmath.h:187
std::string toString(bool round=false)
Definition: vecmath.cpp:221
#define LOG_MSG(index, format,...)
Definition: log.h:32
bool load(const char *cfgFile)
void loadGoals(std::string filename)
Definition: optimizer.cpp:374
void loadFromFile(const char *filename)
Definition: frame.cpp:1112
virtual char * getName()
Definition: frame.h:103
#define LOG_VERBOSE(format,...)
Definition: log.h:34
unsigned int counter
Definition: optimizer.h:63
unsigned int dofs
Definition: optimizer.h:66
std::vector< unsigned int > dofs
unsigned int counterMod
Definition: optimizer.h:67
double getUniform()
Definition: vecmath.h:429
virtual CMatrix getPose()
Definition: frame.h:118
void setTrimming(double trim)
Definition: optimizer.h:99
void loadData(std::string filename, unsigned int startId=0)
Definition: optimizer.cpp:186
std::vector< ValueSetter > valueSetters
Definition: optimizer.h:52
void setValue(double *x)
Definition: optimizer.cpp:40
void strToArray(std::string text, std::vector< double > &result, std::string delimiter=" ")
Definition: utils.cpp:161
CFrame * getFrame(unsigned int id)
Definition: frame.h:224
void loadDofs(std::string filename)
Definition: optimizer.cpp:286
void loadValueSetters(std::string filename)
Definition: optimizer.cpp:325
std::vector< double > distances
Definition: optimizer.h:62
static void rosenbrockCallback(int nparam, double *x, double *fj, void *extraparams)
Definition: optimizer.cpp:88
void rosenbrock(int n, double *x, double *bl, double *bu, double bigbnd, int maxiter, double eps, int verbose, void obj(int, double *, double *, void *), void *extraparams)
Definition: vecmath.cpp:871
std::vector< std::pair< std::string, CMatrix > > allPoses
Definition: optimizer.h:41
void load(std::string cfg, std::string data, unsigned int start=0)
Definition: optimizer.cpp:451
void findNodes(const char *name, std::vector< TiXmlElement * > &result, TiXmlElement *start, unsigned int level)
std::vector< OptimizerGoalGlobal * > globalFunctions
Definition: optimizer.h:56
PRECISION y
Definition: vecmath.h:60
Configuration file wrapper.
Definition: configuration.h:34
std::vector< OptimizerContainer > data
Definition: optimizer.h:55
PRECISION x
Definition: vecmath.h:60
std::vector< OptimizerGoal * > functions
Definition: optimizer.h:57
std::string readFromFile(std::string filename)
Definition: optimizer.cpp:50


asr_kinematic_chain_optimizer
Author(s): Aumann Florian, Heller Florian, Jäkel Rainer, Wittenbeck Valerij
autogenerated on Mon Jun 10 2019 12:35:36