CommonPlacesTester.cpp
Go to the documentation of this file.
1/*
2 * This file is part of ArmarX.
3 *
4 * Copyright (C) 2011-2016, High Performance Humanoid Technologies (H2T), Karlsruhe Institute of Technology (KIT), all rights reserved.
5 *
6 * ArmarX is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
9 *
10 * ArmarX is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * @package
19 * @author
20 * @date
21 * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
22 * GNU General Public License
23 */
24
25
26#include "CommonPlacesTester.h"
27
29
30#include <MemoryX/interface/memorytypes/MemoryEntities.h>
35
36// Object Factories
37#include <fstream>
38#include <iostream>
39#include <thread>
40
41#include <Eigen/Core>
42
44
47
48namespace memoryx
49{
50 void
52 {
53 usingProxy("WorkingMemory");
54 usingProxy("LongtermMemory");
55 usingProxy("CommonPlacesLearner");
56
57 testToRun = getProperty<std::string>("TestToRun").getValue();
58 }
59
60 void
62 {
63 std::cout << "Starting CommonPlacesTester" << std::endl;
64
65 const Ice::CommunicatorPtr ic = getIceManager()->getCommunicator();
66
67
68 memoryPrx = getProxy<WorkingMemoryInterfacePrx>("WorkingMemory");
69 longtermMemoryPrx = getProxy<LongtermMemoryInterfacePrx>("LongtermMemory");
70 cpLearnerPrx = getProxy<CommonPlacesLearnerInterfacePrx>("CommonPlacesLearner");
71
72 ltmSegmentName = getProperty<std::string>("LTMSegment").getValue();
73 cpLearnerPrx->setLTMSegmentName(ltmSegmentName);
74
75 objectToLoad = getProperty<std::string>("ObjectToLoad").getValue();
76
77 // load snapshot, if specified
78 const std::string snapshotName = getProperty<std::string>("SnapshotToLoad").getValue();
79
80 if (!snapshotName.empty())
81 {
82 longtermMemoryPrx->loadWorkingMemorySnapshot(snapshotName, memoryPrx);
83 ARMARX_INFO << "Snapshot succcessfully loaded: " << snapshotName;
84 }
85
86 if (testToRun == "LearnFromSnapshot")
87 {
88 testLearnFromSnapshot();
89 }
90 else if (testToRun == "LearnFromSingleSnapshot")
91 {
92 testLearnFromSingleSnapshot();
93 }
94 else if (testToRun == "LoadLTM")
95 {
96 testLoadLTM();
97 }
98 else if (testToRun == "Clustering")
99 {
100 testClustering();
101 }
102 else if (testToRun == "Merging")
103 {
104 testMerging();
105 }
106 else if (testToRun == "Aging")
107 {
108 testAging();
109 }
110 else if (testToRun == "Aging2")
111 {
112 testAging2();
113 }
114 else if (testToRun == "ClusteringBatch")
115 {
116 testClusteringBatch();
117 }
118 else if (testToRun == "GetClusterLocations")
119 {
120 testGetClusterLocations();
121 }
122
123 else
124 {
125 std::cout << "Unknown test name: " << testToRun << std::endl;
126 }
127 }
128
129 void
130 CommonPlacesTester::testLearnFromSnapshot()
131 {
132 const std::string snapshotName =
133 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
134 const bool loadToWM = getProperty<bool>("LoadToWM").getValue();
135 const int initDelay = getProperty<int>("InitialDelay").getValue();
136 const int delay = getProperty<int>("DelayBetweenSnapshots").getValue();
137
138 if (!snapshotName.empty())
139 {
140 std::this_thread::sleep_for(std::chrono::milliseconds(initDelay));
141
142 NameList snapNameList = armarx::Split(snapshotName, ",");
143
144 for (NameList::const_iterator it = snapNameList.begin(); it != snapNameList.end(); ++it)
145 {
146 cpLearnerPrx->learnFromSnapshot(*it);
147 ARMARX_INFO << "Snapshot succcessfully processed by CommonPlacesLearner: " << *it;
148
149 if (loadToWM)
150 {
151 testLoadLTM();
152 }
153
154 std::this_thread::sleep_for(std::chrono::milliseconds(delay));
155 }
156 }
157 else
158 {
159 ARMARX_ERROR << "SnapshotsToLearnFrom parameter must be specified! ";
160 }
161 }
162
163 void
164 CommonPlacesTester::testLearnFromSingleSnapshot()
165 {
166 const std::string snapshotName =
167 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
168 const bool loadToWM = getProperty<bool>("LoadToWM").getValue();
169 const int initDelay = getProperty<int>("InitialDelay").getValue();
170 const int delay = getProperty<int>("DelayBetweenSnapshots").getValue();
171
172 std::this_thread::sleep_for(std::chrono::milliseconds(initDelay));
173
174 WorkingMemorySnapshotInterfacePrx snapshot =
175 longtermMemoryPrx->openWorkingMemorySnapshot(snapshotName);
176
177 if (!snapshot)
178 {
179 ARMARX_ERROR << "Snapshot not found in LTM: " << snapshotName;
180 return;
181 }
182
183 const std::string segmentName = "objectInstances";
184 PersistentEntitySegmentBasePrx segInstances = snapshot->getSegment(segmentName);
185
186 if (!segInstances)
187 {
188 ARMARX_ERROR << "Segment not found in snapshot: " << segmentName;
189 return;
190 }
191
192 EntityIdList ids = segInstances->getAllEntityIds();
193
194 // sort ids
195 struct EntityIdComparator
196 {
197 static bool
198 compare(const std::string& i, const std::string& j)
199 {
200 return (std::stoi(i) < std::stoi(j));
201 }
202 };
203
204 std::sort(ids.begin(), ids.end(), EntityIdComparator::compare);
205
206 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
207 {
208 EntityBasePtr snapEntity = segInstances->getEntityById(*it);
209 ObjectInstancePtr snapInstance = ObjectInstancePtr::dynamicCast(snapEntity);
210 cpLearnerPrx->learnFromObject(snapInstance);
211 ARMARX_INFO << "Object processed by CommonPlacesLearner: " << *it;
212
213 if (loadToWM)
214 // testLoadLTM();
215 {
216 testClustering();
217 }
218
219
220 std::this_thread::sleep_for(std::chrono::milliseconds(delay));
221 }
222 }
223
224 void
225 CommonPlacesTester::testLoadLTM()
226 {
227 ObjectInstanceMemorySegmentBasePrx wmObjectsSeg = memoryPrx->getObjectInstancesSegment();
228 PersistentEntitySegmentBasePrx ltmObjectsSeg =
229 longtermMemoryPrx->getCustomInstancesSegment(ltmSegmentName, false);
230
231 if (ltmObjectsSeg)
232 {
233 if (!objectToLoad.empty())
234 {
235 EntityBasePtr obj = ltmObjectsSeg->getEntityByName(objectToLoad);
236 EntityBasePtr oldWMObj = wmObjectsSeg->getEntityByName(objectToLoad);
237
238 if (obj)
239 {
240 if (oldWMObj)
241 {
242 wmObjectsSeg->updateEntity(oldWMObj->getId(), obj);
243 }
244 else
245 {
246 wmObjectsSeg->addEntity(obj);
247 }
248
249 std::cout << "Loaded from LTM: " << ObjectInstancePtr::dynamicCast(obj)
250 << std::endl;
251 }
252 else
253 {
254 ARMARX_ERROR << "Entity not found in LTM: " << objectToLoad;
255 }
256 }
257 else
258 {
259 EntityIdList ids = ltmObjectsSeg->getAllEntityIds();
260
261 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
262 {
263 wmObjectsSeg->addEntity(ltmObjectsSeg->getEntityById(*it));
264 }
265 }
266 }
267 else
268 {
269 ARMARX_ERROR << "LTM segment not found: " << ltmSegmentName;
270 }
271 }
272
273 void
274 CommonPlacesTester::testClustering()
275 {
276 const bool loadToWM = getProperty<bool>("LoadToWM").getValue();
277
278 if (loadToWM)
279 {
280 testLoadLTM();
281 }
282
283 float maxDeviation = getProperty<float>("ClusterMaxDeviation").getValue();
284 std::string deviationTypeStr = getProperty<std::string>("ClusterDeviationType").getValue();
285 DeviationType devType = getDeviationTypeFromString(deviationTypeStr);
286
287 // Cluster3DList posClusters = cpLearnerPrx->getPositionClustersByMaxDeviation(objectToLoad, maxDeviation, devType);
288 // std::cout << "Reduced to clusters: " << std::endl;
289 // int i = 1;
290 // for (Cluster3DList::const_iterator it = posClusters.begin(); it != posClusters.end(); ++it)
291 // {
292 // std::cout << "Cluster " << i <<
293 // ": center = (" << it->center.x << ", " << it->center.y << ", " << it->center.z <<
294 // ") weight = " << it->weight << std::endl;
295 // ++i;
296 // }
297
298 ObjectInstanceMemorySegmentBasePrx wmObjectsSeg = memoryPrx->getObjectInstancesSegment();
299
300 mstimer.time_start();
301 GaussianMixtureDistributionPtr posDistr = GaussianMixtureDistributionPtr::dynamicCast(
302 cpLearnerPrx->getPositionReducedByMaxDeviation(objectToLoad, maxDeviation, devType));
303 ARMARX_INFO << "Elapsed time for reduction: " << mstimer.time_stop() << " ms" << std::endl;
304
305 if (posDistr)
306 {
307 ARMARX_INFO << "Reduced to: " << posDistr->output() << std::endl;
308
309 EntityBasePtr oldWMObj = wmObjectsSeg->getEntityByName(objectToLoad + "GaussPos");
310
311 if (oldWMObj)
312 {
313 wmObjectsSeg->removeEntity(oldWMObj->getId());
314 }
315
316 ObjectInstancePtr obj = new ObjectInstance(objectToLoad + "GaussPos");
317 obj->setClass(objectToLoad, 1.f);
319 NormalDistributionPtr::dynamicCast(posDistr->getModalComponent().gaussian);
320 armarx::FramedPositionPtr curPos = new armarx::FramedPosition(
321 (Eigen::Vector3f)mode->toEigenMean(), armarx::GlobalFrame, "");
322 obj->setPosition(curPos);
323 obj->getPositionAttribute()->setValueWithUncertainty(
324 obj->getPositionAttribute()->getValue(), posDistr);
325
326 Eigen::Quaternionf quat(0., 0., 0., 1.);
327 armarx::FramedOrientationBasePtr orient =
328 new armarx::FramedOrientation(quat.toRotationMatrix(), armarx::GlobalFrame, "");
329 obj->setOrientation(orient);
330
331 obj->putAttribute("UncertaintyColorMap", "eHot");
332 obj->putAttribute("UncertaintyTransparency", 0.7f);
333
334 wmObjectsSeg->addEntity(obj);
335 }
336 else
337 {
338 ARMARX_INFO << "Unable to get object pos gaussian! " << std::endl;
339 }
340 }
341
342 void
343 CommonPlacesTester::testMerging()
344 {
345 const std::string snapshotName =
346 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
347
348 //const int sampleSize = getProperty<int>("SampleSize").getValue();
349 const int itCount = getProperty<int>("IterationCount").getValue();
350
351 const int THRESHOLD_COUNT = 11;
352 const float thresholds[THRESHOLD_COUNT] = {0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
353 float grandTotalDensity[THRESHOLD_COUNT];
354 float grandTotalKL[THRESHOLD_COUNT];
355 float grandTotalISD[THRESHOLD_COUNT];
356 float grandReductionRate[THRESHOLD_COUNT];
357
358 for (int i = 0; i < THRESHOLD_COUNT; ++i)
359 {
360 grandTotalDensity[i] = 0;
361 grandTotalKL[i] = 0;
362 grandTotalISD[i] = 0;
363 grandReductionRate[i] = 0;
364 }
365
366 // RunnallsKLDistance klDistance;
367 ISDDistance isdDistance;
368
369 NameList snapNameList = armarx::Split(snapshotName, ",");
370
371 for (NameList::const_iterator it = snapNameList.begin(); it != snapNameList.end(); ++it)
372 {
373 WorkingMemorySnapshotInterfacePrx snapshot =
374 longtermMemoryPrx->openWorkingMemorySnapshot(*it);
375
376 if (!snapshot)
377 {
378 ARMARX_ERROR << "Snapshot not found in LTM: " << snapshotName;
379 return;
380 }
381
382 const std::string segmentName = "objectInstances";
383 PersistentEntitySegmentBasePrx segInstances = snapshot->getSegment(segmentName);
384
385 if (!segInstances)
386 {
387 ARMARX_ERROR << "Segment not found in snapshot: " << segmentName;
388 return;
389 }
390
391 EntityIdList ids = segInstances->getAllEntityIds();
392
393 std::ofstream snfile;
394 const std::string fname = "m_" + (*it) + ".csv";
395 snfile.open(fname.c_str());
396
397 for (int t = 0; t < THRESHOLD_COUNT; ++t)
398 {
399 cpLearnerPrx->setMergingThreshold(thresholds[t]);
400
401 float totalDensity = 0., totalKL = 0., totalISD = 0.;
402 int origComp = 0, mergedComp = 0;
403
404 for (int i = 0; i < itCount; ++i)
405 {
406 // EntityIdList ids;
407 // getRandomIds(allIds, ids, sampleSize);
408
409 std::random_shuffle(ids.begin(), ids.end());
410
411 longtermMemoryPrx->getCustomInstancesSegment(ltmSegmentName, false)->clear();
412
413 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
414 {
415 EntityBasePtr snapEntity = segInstances->getEntityById(*it);
416 ObjectInstancePtr snapInstance = ObjectInstancePtr::dynamicCast(snapEntity);
418 GaussianMixtureDistributionPtr::dynamicCast(
419 cpLearnerPrx->getPositionFull(
420 snapInstance->getMostProbableClass()));
421
422 if (gmm)
423 {
424 totalDensity += gmm->getDensity(snapInstance->getPosition()->toEigen());
425 // totalKL += klDistance.getDistance(gmm, GaussianMixtureDistribution::FromProbabilityMeasure(snapInstance->getPositionUncertainty()));
426 // totalISD += isdDistance.getDistance(gmm, GaussianMixtureDistribution::FromProbabilityMeasure(snapInstance->getPositionUncertainty()), true);
427 }
428
429 cpLearnerPrx->learnFromObject(snapInstance);
430 // ARMARX_INFO << "Object processed by CommonPlacesLearner: " << *it;
431 }
432
434 GaussianMixtureDistributionPtr::dynamicCast(
435 cpLearnerPrx->getPositionFull(objectToLoad));
436
437 // learn w/o merging
438 cpLearnerPrx->setLTMSegmentName(ltmSegmentName + "2");
439 longtermMemoryPrx->getCustomInstancesSegment(ltmSegmentName + "2", false)
440 ->clear();
441 cpLearnerPrx->setMergingThreshold(0.);
442
443 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
444 {
445 EntityBasePtr snapEntity = segInstances->getEntityById(*it);
446 ObjectInstancePtr snapInstance = ObjectInstancePtr::dynamicCast(snapEntity);
447 cpLearnerPrx->learnFromObject(snapInstance);
448 }
449
451 GaussianMixtureDistributionPtr::dynamicCast(
452 cpLearnerPrx->getPositionFull(objectToLoad));
453 origComp += origGMM->size();
454 mergedComp += mergedGMM->size();
455 totalISD += isdDistance.getDistance(mergedGMM, origGMM, true);
456 cpLearnerPrx->setLTMSegmentName(ltmSegmentName);
457 }
458
459 totalISD /= itCount;
460 const float redRate = float(mergedComp) / float(origComp);
461
462 // write snap file
463 snfile << thresholds[t] << "," << totalDensity << "," << totalISD << ","
464 << float(origComp) / itCount << "," << float(mergedComp) / itCount << ","
465 << float(mergedComp) / float(origComp) << std::endl;
466
467 grandTotalDensity[t] += totalDensity;
468 grandTotalISD[t] += totalISD;
469 grandTotalKL[t] += totalKL;
470 grandReductionRate[t] += redRate;
471 // ARMARX_INFO << "Total density: " << totalDensity / itCount;
472 }
473
474 snfile.close();
475 } // end snapshots
476
477 // write total file
478 std::ofstream totfile;
479 totfile.open("m_totals.csv");
480
481 for (int t = 0; t < THRESHOLD_COUNT; ++t)
482 totfile << thresholds[t] << "," << (grandTotalDensity[t] / snapNameList.size()) << ","
483 << (grandTotalISD[t] / snapNameList.size()) << ","
484 << (grandReductionRate[t] / snapNameList.size()) << std::endl;
485
486 totfile.close();
487 }
488
489 void
490 CommonPlacesTester::testAging()
491 {
492 const std::string snapshotName =
493 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
494
495 const int itCount = getProperty<int>("IterationCount").getValue();
496
497 const int COEFF_COUNT = 10;
498 const float thresholds[COEFF_COUNT] = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1};
499 float grandTotalMah[COEFF_COUNT];
500 int grandTotalCorrect[COEFF_COUNT];
501 int totalObjects = 0;
502
503 for (int i = 0; i < COEFF_COUNT; ++i)
504 {
505 grandTotalMah[i] = 0;
506 grandTotalCorrect[i] = 0;
507 }
508
509 // RunnallsKLDistance klDistance;
510 ISDDistance isdDistance;
511 MahalanobisDistance mahDistance;
512
513 NameList snapNameList = armarx::Split(snapshotName, ",");
514
515 for (NameList::const_iterator it = snapNameList.begin(); it != snapNameList.end(); ++it)
516 {
517 WorkingMemorySnapshotInterfacePrx snapshot =
518 longtermMemoryPrx->openWorkingMemorySnapshot(*it);
519
520 if (!snapshot)
521 {
522 ARMARX_ERROR << "Snapshot not found in LTM: " << *it;
523 return;
524 }
525
526 const std::string segmentName = "objectInstances";
527 PersistentEntitySegmentBasePrx segInstances = snapshot->getSegment(segmentName);
528
529 if (!segInstances)
530 {
531 ARMARX_ERROR << "Segment not found in snapshot: " << segmentName;
532 return;
533 }
534
535 ARMARX_INFO << "Processing snapshot: " << *it;
536
537 EntityIdList ids = segInstances->getAllEntityIds();
538
539 totalObjects += ids.size();
540
541 for (int t = 0; t < COEFF_COUNT; ++t)
542 {
543 cpLearnerPrx->setAgingFactor(thresholds[t]);
544
545 float totalMah = 0.; //, totalKL = 0., totalISD = 0.;
546 int corrClusters = 0;
547
548 for (int i = 0; i < itCount; ++i)
549 {
550 // EntityIdList ids;
551 // getRandomIds(allIds, ids, sampleSize);
552
553 std::random_shuffle(ids.begin(), ids.end());
554
555 longtermMemoryPrx->getCustomInstancesSegment(ltmSegmentName, false)->clear();
556
557 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
558 {
559 EntityBasePtr snapEntity = segInstances->getEntityById(*it);
560 ObjectInstancePtr snapInstance = ObjectInstancePtr::dynamicCast(snapEntity);
562 GaussianMixtureDistributionPtr::dynamicCast(
563 cpLearnerPrx->getPositionReducedByMaxDeviation(
564 objectToLoad, 150, eDevAABB));
565
566 if (gmm)
567 {
568 totalMah += mahDistance.getWeigtedDistance(
569 gmm, snapInstance->getPositionUncertainty());
570
571 // discrete criterion: cluster is "correct", if observation mean within 3 sigma from cluster mean
572 GaussianMixtureComponent c = gmm->getComponent(0);
574 NormalDistributionPtr::dynamicCast(c.gaussian);
575 const Eigen::VectorXf obsMean = snapInstance->getPosition()->toEigen();
576 Eigen::Vector3f sigma;
577 sigma << sqrtf(g->getCovariance(0, 0)), sqrtf(g->getCovariance(1, 1)),
578 sqrtf(g->getCovariance(2, 2));
579 const Eigen::VectorXf triSigmaPoint = g->toEigenMean() + 3 * sigma;
580
581 if (g->getDensity(obsMean) > g->getDensity(triSigmaPoint))
582 {
583 corrClusters++;
584 }
585 }
586
587 cpLearnerPrx->learnFromObject(snapInstance);
588 // ARMARX_INFO << "Object processed by CommonPlacesLearner: " << *it;
589 }
590 }
591
592 totalMah /= itCount;
593 const float avgCorrect = float(corrClusters) / itCount;
594
595 grandTotalMah[t] += totalMah;
596 grandTotalCorrect[t] += avgCorrect;
597 // ARMARX_INFO << "Total density: " << totalDensity / itCount;
598 }
599
600 } // end snapshots
601
602 // write total file
603 std::ofstream totfile;
604 totfile.open("a_totals.csv");
605
606 for (int t = 0; t < COEFF_COUNT; ++t)
607 totfile << thresholds[t] << "," << grandTotalMah[t] << // total mah dist
608 "," << grandTotalMah[t] / totalObjects << // avg mah dist/obj
609 "," << grandTotalCorrect[t] << // total correct clusters
610 "," << float(grandTotalCorrect[t]) / totalObjects << // correct cluster rate
611 std::endl;
612
613 totfile.close();
614 }
615
616 void
617 CommonPlacesTester::testAging2()
618 {
619 const std::string snapshotName =
620 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
621
622 const int itCount = getProperty<int>("IterationCount").getValue();
623
624 const int COEFF_COUNT = 10;
625 const float thresholds[COEFF_COUNT] = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1};
626 float grandTotalMah[COEFF_COUNT];
627 int grandTotalCorrect[COEFF_COUNT];
628 int totalObjects = 0;
629
630 for (int i = 0; i < COEFF_COUNT; ++i)
631 {
632 grandTotalMah[i] = 0;
633 grandTotalCorrect[i] = 0;
634 }
635
636 MahalanobisDistance mahDistance;
637
638 NameList snapNameList = armarx::Split(snapshotName, ",");
639
640 for (int t = 0; t < COEFF_COUNT; ++t)
641 {
642 cpLearnerPrx->setAgingFactor(thresholds[t]);
643
644 float totalMah = 0.;
645 int corrClusters = 0;
646
647 for (int i = 0; i < itCount; ++i)
648 {
649 longtermMemoryPrx->getCustomInstancesSegment(ltmSegmentName, false)->clear();
650
651 for (NameList::const_iterator it = snapNameList.begin(); it != snapNameList.end();
652 ++it)
653 {
654 WorkingMemorySnapshotInterfacePrx snapshot =
655 longtermMemoryPrx->openWorkingMemorySnapshot(*it);
656
657 if (!snapshot)
658 {
659 ARMARX_ERROR << "Snapshot not found in LTM: " << *it;
660 return;
661 }
662
663 const std::string segmentName = "objectInstances";
664 PersistentEntitySegmentBasePrx segInstances = snapshot->getSegment(segmentName);
665
666 if (!segInstances)
667 {
668 ARMARX_ERROR << "Segment not found in snapshot: " << segmentName;
669 return;
670 }
671
672 ARMARX_INFO << "Processing snapshot: " << *it;
673
674 EntityIdList ids = segInstances->getAllEntityIds();
675
676 if (t == 0 && i == 0)
677 {
678 totalObjects += ids.size();
679 }
680
681 std::random_shuffle(ids.begin(), ids.end());
682
683 for (EntityIdList::const_iterator it = ids.begin(); it != ids.end(); ++it)
684 {
685 EntityBasePtr snapEntity = segInstances->getEntityById(*it);
686 ObjectInstancePtr snapInstance = ObjectInstancePtr::dynamicCast(snapEntity);
688 GaussianMixtureDistributionPtr::dynamicCast(
689 cpLearnerPrx->getPositionReducedByMaxDeviation(
690 objectToLoad, 150, eDevAABB));
691
692 if (gmm)
693 {
694 totalMah += mahDistance.getWeigtedDistance(
695 gmm, snapInstance->getPositionUncertainty());
696
697 // discrete criterion: cluster is "correct", if observation mean within 3 sigma from cluster mean
698 GaussianMixtureComponent c = gmm->getModalComponent();
700 NormalDistributionPtr::dynamicCast(c.gaussian);
701 const Eigen::VectorXf obsMean = snapInstance->getPosition()->toEigen();
702 Eigen::Vector3f sigma;
703 sigma << sqrtf(g->getCovariance(0, 0)), sqrtf(g->getCovariance(1, 1)),
704 sqrtf(g->getCovariance(2, 2));
705 const Eigen::VectorXf triSigmaPoint = g->toEigenMean() + 3 * sigma;
706
707 if (g->getDensity(obsMean) > g->getDensity(triSigmaPoint))
708 {
709 corrClusters++;
710 }
711 }
712
713 cpLearnerPrx->learnFromObject(snapInstance);
714 // ARMARX_INFO << "Object processed by CommonPlacesLearner: " << *it;
715 }
716 } // end snapshots
717
718 // ARMARX_INFO << "Total density: " << totalDensity / itCount;
719
720 } // end iterations
721
722 totalMah /= itCount;
723 const float avgCorrect = float(corrClusters) / itCount;
724
725 grandTotalMah[t] += totalMah;
726 grandTotalCorrect[t] += avgCorrect;
727
728 } // end coefficients
729
730 // write total file
731 std::ofstream totfile;
732 totfile.open("a_totals.csv");
733
734 for (int t = 0; t < COEFF_COUNT; ++t)
735 totfile << thresholds[t] << "," << grandTotalMah[t] << // total mah dist
736 "," << grandTotalMah[t] / totalObjects << // avg mah dist/obj
737 "," << grandTotalCorrect[t] << // total correct clusters
738 "," << float(grandTotalCorrect[t]) / totalObjects << // correct cluster rate
739 std::endl;
740
741 totfile.close();
742 }
743
744 void
745 CommonPlacesTester::testGetClusterLocations()
746 {
747 Cluster3DList clusterList =
748 cpLearnerPrx->getPositionClustersByComponentCount(objectToLoad, 3);
749
750 if (clusterList.size() > 0)
751 {
752 for (Cluster3DList::iterator it = clusterList.begin(); it != clusterList.end(); it++)
753 {
754 Cluster3D& entry = *it;
755 ARMARX_IMPORTANT << "object center: x:" << entry.center.x
756 << " y: " << entry.center.y << " with weight: " << entry.weight;
757 }
758 }
759 else
760 {
761 ARMARX_WARNING << "no cluster found for object " << objectToLoad;
762 }
763 }
764
765 void
766 CommonPlacesTester::testClusteringBatch()
767 {
768 const std::string snapshotName =
769 getProperty<std::string>("SnapshotsToLearnFrom").getValue();
770
771 const int DEV_COUNT = 11;
772 const float thresholds[DEV_COUNT] = {
773 10., 30., 50., 75., 100., 150., 200., 400., 800., 1000., 2000.};
774
775 // const int DEV_COUNT = 1;
776 // const float thresholds[DEV_COUNT] = {150.};
777
778 std::ofstream snfile;
779 const std::string fname = "c_" + ltmSegmentName + "_" + objectToLoad + ".csv";
780 snfile.open(fname.c_str());
781
782 for (int t = 0; t < DEV_COUNT; ++t)
783 {
784 ARMARX_INFO << "Processing dev: " << thresholds[t];
785
786 GaussianMixtureDistributionBasePtr gmmAABB =
787 cpLearnerPrx->getPositionReducedByMaxDeviation(
788 objectToLoad, thresholds[t], eDevAABB);
789 GaussianMixtureDistributionBasePtr gmmOBB =
790 cpLearnerPrx->getPositionReducedByMaxDeviation(
791 objectToLoad, thresholds[t], eDevOrientedBBox);
792 GaussianMixtureDistributionBasePtr gmmSphere =
793 cpLearnerPrx->getPositionReducedByMaxDeviation(
794 objectToLoad, thresholds[t], eDevEqualSphere);
795
796 // write snap file
797 snfile << thresholds[t] << "," << gmmAABB->size() << "," << gmmOBB->size() << ","
798 << gmmSphere->size() << "," << std::endl;
799
800 // ARMARX_INFO << "Total density: " << totalDensity / itCount;
801 }
802
803 snfile.close();
804 ARMARX_INFO << "Finished: ";
805 }
806
807 void
808 CommonPlacesTester::getRandomIds(std::vector<std::string>& allIds,
809 std::vector<std::string>& ids,
810 int sampleSize)
811 {
812 if (sampleSize > (int)(allIds.size()))
813 {
814 ids.assign(allIds.begin(), allIds.end());
815 return;
816 }
817
818 std::set<std::string> idset;
819
820 while (idset.size() < (size_t)sampleSize)
821 {
822 const size_t ind =
823 (size_t)truncf(((float)rand()) / float(RAND_MAX) * float(allIds.size()));
824 std::cout << "index to add" << ind << std::flush;
825 idset.insert(allIds[ind]);
826 }
827
828 ids.assign(idset.begin(), idset.end());
829 }
830
831 DeviationType
832 CommonPlacesTester::getDeviationTypeFromString(const std::string& devTypeStr)
833 {
834
835 if (devTypeStr == "AABB")
836 {
837 return eDevAABB;
838 }
839 else if (devTypeStr == "OrientedBBox")
840 {
841 return eDevOrientedBBox;
842 }
843 else if (devTypeStr == "EqualSphere")
844 {
845 return eDevEqualSphere;
846 }
847 else
848 {
849 return eDevAABB;
850 }
851 }
852} // namespace memoryx
#define float
Definition 16_Level.h:22
constexpr T c
Property< PropertyType > getProperty(const std::string &name)
bool usingProxy(const std::string &name, const std::string &endpoints="")
Registers a proxy for retrieval after initialization and adds it to the dependency list.
IceManagerPtr getIceManager() const
Returns the IceManager.
Ice::ObjectPrx getProxy(long timeoutMs=0, bool waitForScheduler=true) const
Returns the proxy of this object (optionally it waits for the proxy)
void onInitComponent() override
Pure virtual hook for the subclass.
void onConnectComponent() override
Pure virtual hook for the subclass.
#define ARMARX_INFO
The normal logging level.
Definition Logging.h:181
#define ARMARX_IMPORTANT
The logging level for always important information, but expected behaviour (in contrast to ARMARX_WAR...
Definition Logging.h:190
#define ARMARX_ERROR
The logging level for unexpected behaviour, that must be fixed.
Definition Logging.h:196
#define ARMARX_WARNING
The logging level for unexpected behaviour, but not a serious problem.
Definition Logging.h:193
std::string const GlobalFrame
Variable of the global coordinate system.
Definition FramedPose.h:65
Quaternion< float, 0 > Quaternionf
::IceInternal::Handle<::Ice::Communicator > CommunicatorPtr
Definition IceManager.h:49
int compare(const T &lhs, const T &rhs)
std::vector< std::string > Split(const std::string &source, const std::string &splitBy, bool trimElements=false, bool removeEmptyElements=false)
IceInternal::Handle< FramedPosition > FramedPositionPtr
Definition FramedPose.h:149
VirtualRobot headers.
IceInternal::Handle< NormalDistribution > NormalDistributionPtr
IceInternal::Handle< GaussianMixtureDistribution > GaussianMixtureDistributionPtr
IceInternal::Handle< ObjectInstance > ObjectInstancePtr