-
Notifications
You must be signed in to change notification settings - Fork 531
/
Mapper.cpp
3261 lines (2717 loc) · 98.7 KB
/
Mapper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 SRI International
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <karto_sdk/Types.h>
#include <math.h>
#include <assert.h>
#include <boost/serialization/vector.hpp>
#include <sstream>
#include <fstream>
#include <stdexcept>
#include <queue>
#include <set>
#include <list>
#include <iterator>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
#include <string>
#include "karto_sdk/Mapper.h"
BOOST_CLASS_EXPORT(karto::MapperGraph);
BOOST_CLASS_EXPORT(karto::Graph<karto::LocalizedRangeScan>);
BOOST_CLASS_EXPORT(karto::EdgeLabel);
BOOST_CLASS_EXPORT(karto::LinkInfo);
BOOST_CLASS_EXPORT(karto::Edge<karto::LocalizedRangeScan>);
BOOST_CLASS_EXPORT(karto::Vertex<karto::LocalizedRangeScan>);
BOOST_CLASS_EXPORT(karto::MapperSensorManager)
BOOST_CLASS_EXPORT(karto::Mapper)
namespace karto
{
// enable this for verbose debug information
// #define KARTO_DEBUG
#define MAX_VARIANCE 500.0
#define DISTANCE_PENALTY_GAIN 0.2
#define ANGLE_PENALTY_GAIN 0.2
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
/**
* Manages the scan data for a device
*/
class ScanManager
{
public:
/**
* Default constructor
*/
ScanManager(kt_int32u runningBufferMaximumSize, kt_double runningBufferMaximumDistance)
: m_pLastScan(NULL),
m_RunningBufferMaximumSize(runningBufferMaximumSize),
m_RunningBufferMaximumDistance(runningBufferMaximumDistance),
m_NextStateId(0)
{
}
ScanManager() {}
/**
* Destructor
*/
virtual ~ScanManager()
{
Clear();
}
public:
/**
* Adds scan to vector of processed scans tagging scan with given unique id
* @param pScan
*/
inline void AddScan(LocalizedRangeScan * pScan, kt_int32s uniqueId)
{
// assign state id to scan
pScan->SetStateId(m_NextStateId);
// assign unique id to scan
pScan->SetUniqueId(uniqueId);
// add it to scan buffer
m_Scans.insert({pScan->GetStateId(), pScan});
m_NextStateId++;
}
/**
* Gets last scan
* @param deviceId
* @return last localized range scan
*/
inline LocalizedRangeScan * GetLastScan()
{
return m_pLastScan;
}
/**
* Clears last scan
* @param deviceId
*/
inline void ClearLastScan()
{
m_pLastScan = NULL;
}
/**
* Sets the last scan
* @param pScan
*/
void SetLastScan(LocalizedRangeScan * pScan)
{
m_pLastScan = pScan;
}
/**
* Gets scans
* @return scans
*/
inline LocalizedRangeScanMap & GetScans()
{
return m_Scans;
}
/**
* Gets running scans
* @return running scans
*/
inline LocalizedRangeScanVector & GetRunningScans()
{
return m_RunningScans;
}
/**
* Gets running scan buffer size
* @return running scan buffer size
*/
inline kt_int32u & GetRunningScanBufferSize()
{
return m_RunningBufferMaximumSize;
}
/**
* Sets running scan buffer size
* @param rScanBufferSize
*/
void SetRunningScanBufferSize(const kt_int32u & rScanBufferSize)
{
m_RunningBufferMaximumSize = rScanBufferSize;
}
/**
* Sets running scan buffer maximum distance
* @param rScanBufferMaxDistance
*/
void SetRunningScanBufferMaximumDistance(const kt_int32u & rScanBufferMaxDistance)
{
m_RunningBufferMaximumDistance = rScanBufferMaxDistance;
}
/**
* Adds scan to vector of running scans
* @param pScan
*/
void AddRunningScan(LocalizedRangeScan * pScan)
{
m_RunningScans.push_back(pScan);
// vector has at least one element (first line of this function), so this is valid
Pose2 frontScanPose = m_RunningScans.front()->GetSensorPose();
Pose2 backScanPose = m_RunningScans.back()->GetSensorPose();
// cap vector size and remove all scans from front of vector that are too far from end of vector
kt_double squaredDistance = frontScanPose.GetPosition().SquaredDistance(
backScanPose.GetPosition());
while (m_RunningScans.size() > m_RunningBufferMaximumSize ||
squaredDistance > math::Square(m_RunningBufferMaximumDistance) - KT_TOLERANCE)
{
// remove front of running scans
m_RunningScans.erase(m_RunningScans.begin());
// recompute stats of running scans
frontScanPose = m_RunningScans.front()->GetSensorPose();
backScanPose = m_RunningScans.back()->GetSensorPose();
squaredDistance = frontScanPose.GetPosition().SquaredDistance(backScanPose.GetPosition());
}
}
/**
* Finds and replaces a scan from m_scans with NULL
* @param pScan
*/
void RemoveScan(LocalizedRangeScan * pScan)
{
LocalizedRangeScanMap::iterator it = m_Scans.find(pScan->GetStateId());
if (it != m_Scans.end()) {
it->second = NULL;
m_Scans.erase(it);
} else {
std::cout << "Remove Scan: Failed to find scan in m_Scans" << std::endl;
}
}
/**
* Clears the vector of running scans
*/
void ClearRunningScans()
{
m_RunningScans.clear();
}
/**
* Deletes data of this buffered device
*/
void Clear()
{
m_Scans.clear();
m_RunningScans.clear();
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(m_Scans);
ar & BOOST_SERIALIZATION_NVP(m_RunningScans);
ar & BOOST_SERIALIZATION_NVP(m_pLastScan);
ar & BOOST_SERIALIZATION_NVP(m_RunningBufferMaximumSize);
ar & BOOST_SERIALIZATION_NVP(m_RunningBufferMaximumDistance);
ar & BOOST_SERIALIZATION_NVP(m_NextStateId);
}
private:
LocalizedRangeScanMap m_Scans;
LocalizedRangeScanVector m_RunningScans;
LocalizedRangeScan * m_pLastScan;
kt_int32u m_NextStateId;
kt_int32u m_RunningBufferMaximumSize;
kt_double m_RunningBufferMaximumDistance;
}; // ScanManager
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
void MapperSensorManager::RegisterSensor(const Name & rSensorName)
{
if (GetScanManager(rSensorName) == NULL) {
m_ScanManagers[rSensorName] = new ScanManager(
m_RunningBufferMaximumSize,
m_RunningBufferMaximumDistance);
}
}
/**
* Gets scan from given device with given ID
* @param rSensorName
* @param scanNum
* @return localized range scan
*/
LocalizedRangeScan * MapperSensorManager::GetScan(const Name & rSensorName, kt_int32s scanIndex)
{
ScanManager * pScanManager = GetScanManager(rSensorName);
if (pScanManager != NULL) {
LocalizedRangeScanMap::iterator it = pScanManager->GetScans().find(scanIndex);
if (it != pScanManager->GetScans().end()) {
return it->second;
} else {
return nullptr;
}
}
assert(false);
return NULL;
}
/**
* Gets last scan of given device
* @param pLaserRangeFinder
* @return last localized range scan of device
*/
inline LocalizedRangeScan * MapperSensorManager::GetLastScan(const Name & rSensorName)
{
RegisterSensor(rSensorName);
return GetScanManager(rSensorName)->GetLastScan();
}
/**
* Sets the last scan of device of given scan
* @param pScan
*/
void MapperSensorManager::SetLastScan(LocalizedRangeScan * pScan)
{
GetScanManager(pScan)->SetLastScan(pScan);
}
/**
* Clears the last scan of device of given scan
* @param pScan
*/
void MapperSensorManager::ClearLastScan(LocalizedRangeScan* pScan)
{
GetScanManager(pScan)->ClearLastScan();
}
/**
* Clears the last scan of device name
* @param pScan
*/
void MapperSensorManager::ClearLastScan(const Name& name)
{
GetScanManager(name)->ClearLastScan();
}
/**
* Adds scan to scan vector of device that recorded scan
* @param pScan
*/
void MapperSensorManager::AddScan(LocalizedRangeScan * pScan)
{
GetScanManager(pScan)->AddScan(pScan, m_NextScanId);
m_Scans.insert({m_NextScanId, pScan});
m_NextScanId++;
}
/**
* Adds scan to running scans of device that recorded scan
* @param pScan
*/
inline void MapperSensorManager::AddRunningScan(LocalizedRangeScan * pScan)
{
GetScanManager(pScan)->AddRunningScan(pScan);
}
/**
* Finds and replaces a scan from m_Scans with NULL
* @param pScan
*/
void MapperSensorManager::RemoveScan(LocalizedRangeScan * pScan)
{
GetScanManager(pScan)->RemoveScan(pScan);
LocalizedRangeScanMap::iterator it = m_Scans.find(pScan->GetUniqueId());
if (it != m_Scans.end()) {
it->second = NULL;
m_Scans.erase(it);
} else {
std::cout << "RemoveScan: Failed to find scan in m_Scans" << std::endl;
}
}
/**
* Gets scans of device
* @param rSensorName
* @return scans of device
*/
inline LocalizedRangeScanMap & MapperSensorManager::GetScans(const Name & rSensorName)
{
return GetScanManager(rSensorName)->GetScans();
}
/**
* Gets running scans of device
* @param rSensorName
* @return running scans of device
*/
inline LocalizedRangeScanVector & MapperSensorManager::GetRunningScans(const Name & rSensorName)
{
return GetScanManager(rSensorName)->GetRunningScans();
}
void MapperSensorManager::ClearRunningScans(const Name & rSensorName)
{
GetScanManager(rSensorName)->ClearRunningScans();
}
inline kt_int32u MapperSensorManager::GetRunningScanBufferSize(const Name & rSensorName)
{
return GetScanManager(rSensorName)->GetRunningScanBufferSize();
}
void MapperSensorManager::SetRunningScanBufferSize(kt_int32u rScanBufferSize)
{
m_RunningBufferMaximumSize = rScanBufferSize;
std::vector<Name> names = GetSensorNames();
for (uint i = 0; i != names.size(); i++) {
GetScanManager(names[i])->SetRunningScanBufferSize(rScanBufferSize);
}
}
void MapperSensorManager::SetRunningScanBufferMaximumDistance(kt_double rScanBufferMaxDistance)
{
m_RunningBufferMaximumDistance = rScanBufferMaxDistance;
std::vector<Name> names = GetSensorNames();
for (uint i = 0; i != names.size(); i++) {
GetScanManager(names[i])->SetRunningScanBufferMaximumDistance(rScanBufferMaxDistance);
}
}
/**
* Gets all scans of all devices
* @return all scans of all devices
*/
LocalizedRangeScanVector MapperSensorManager::GetAllScans()
{
LocalizedRangeScanVector scans;
forEach(ScanManagerMap, &m_ScanManagers)
{
LocalizedRangeScanMap & rScans = iter->second->GetScans();
LocalizedRangeScanMap::iterator it;
for (it = rScans.begin(); it != rScans.end(); ++it) {
scans.push_back(it->second);
}
}
return scans;
}
/**
* Deletes all scan managers of all devices
*/
void MapperSensorManager::Clear()
{
// SensorManager::Clear();
forEach(ScanManagerMap, &m_ScanManagers)
{
delete iter->second;
iter->second = nullptr;
}
m_ScanManagers.clear();
}
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
ScanMatcher::~ScanMatcher()
{
if (m_pCorrelationGrid) {
delete m_pCorrelationGrid;
}
if (m_pSearchSpaceProbs) {
delete m_pSearchSpaceProbs;
}
if (m_pGridLookup) {
delete m_pGridLookup;
}
}
ScanMatcher * ScanMatcher::Create(
Mapper * pMapper, kt_double searchSize, kt_double resolution,
kt_double smearDeviation, kt_double rangeThreshold)
{
// invalid parameters
if (resolution <= 0) {
return NULL;
}
if (searchSize <= 0) {
return NULL;
}
if (smearDeviation < 0) {
return NULL;
}
if (rangeThreshold <= 0) {
return NULL;
}
assert(math::DoubleEqual(math::Round(searchSize / resolution), (searchSize / resolution)));
// calculate search space in grid coordinates
kt_int32u searchSpaceSideSize = static_cast<kt_int32u>(math::Round(searchSize / resolution) + 1);
// compute requisite size of correlation grid (pad grid so that scan
// points can't fall off the grid
// if a scan is on the border of the search space)
kt_int32u pointReadingMargin = static_cast<kt_int32u>(ceil(rangeThreshold / resolution));
kt_int32s gridSize = searchSpaceSideSize + 2 * pointReadingMargin;
// create correlation grid
assert(gridSize % 2 == 1);
CorrelationGrid * pCorrelationGrid = CorrelationGrid::CreateGrid(gridSize, gridSize, resolution,
smearDeviation);
// create search space probabilities
Grid<kt_double> * pSearchSpaceProbs = Grid<kt_double>::CreateGrid(searchSpaceSideSize,
searchSpaceSideSize, resolution);
ScanMatcher * pScanMatcher = new ScanMatcher(pMapper);
pScanMatcher->m_pCorrelationGrid = pCorrelationGrid;
pScanMatcher->m_pSearchSpaceProbs = pSearchSpaceProbs;
pScanMatcher->m_pGridLookup = new GridIndexLookup<kt_int8u>(pCorrelationGrid);
return pScanMatcher;
}
/**
* Match given scan against set of scans
* @param pScan scan being scan-matched
* @param rBaseScans set of scans whose points will mark cells in grid as being occupied
* @param rMean output parameter of mean (best pose) of match
* @param rCovariance output parameter of covariance of match
* @param doPenalize whether to penalize matches further from the search center
* @param doRefineMatch whether to do finer-grained matching if coarse match is good (default is true)
* @return strength of response
*/
template<class T>
kt_double ScanMatcher::MatchScan(
LocalizedRangeScan * pScan, const T & rBaseScans, Pose2 & rMean,
Matrix3 & rCovariance, kt_bool doPenalize, kt_bool doRefineMatch)
{
///////////////////////////////////////
// set scan pose to be center of grid
// 1. get scan position
Pose2 scanPose = pScan->GetSensorPose();
// scan has no readings; cannot do scan matching
// best guess of pose is based off of adjusted odometer reading
if (pScan->GetNumberOfRangeReadings() == 0) {
rMean = scanPose;
// maximum covariance
rCovariance(0, 0) = MAX_VARIANCE; // XX
rCovariance(1, 1) = MAX_VARIANCE; // YY
rCovariance(2, 2) =
4 * math::Square(m_pMapper->m_pCoarseAngleResolution->GetValue()); // TH*TH
return 0.0;
}
// 2. get size of grid
Rectangle2<kt_int32s> roi = m_pCorrelationGrid->GetROI();
// 3. compute offset (in meters - lower left corner)
Vector2<kt_double> offset;
offset.SetX(scanPose.GetX() - (0.5 * (roi.GetWidth() - 1) * m_pCorrelationGrid->GetResolution()));
offset.SetY(scanPose.GetY() -
(0.5 * (roi.GetHeight() - 1) * m_pCorrelationGrid->GetResolution()));
// 4. set offset
m_pCorrelationGrid->GetCoordinateConverter()->SetOffset(offset);
///////////////////////////////////////
// set up correlation grid
AddScans(rBaseScans, scanPose.GetPosition());
// compute how far to search in each direction
Vector2<kt_double> searchDimensions(m_pSearchSpaceProbs->GetWidth(),
m_pSearchSpaceProbs->GetHeight());
Vector2<kt_double> coarseSearchOffset(0.5 * (searchDimensions.GetX() - 1) *
m_pCorrelationGrid->GetResolution(),
0.5 * (searchDimensions.GetY() - 1) * m_pCorrelationGrid->GetResolution());
// a coarse search only checks half the cells in each dimension
Vector2<kt_double> coarseSearchResolution(2 * m_pCorrelationGrid->GetResolution(),
2 * m_pCorrelationGrid->GetResolution());
// actual scan-matching
kt_double bestResponse = CorrelateScan(pScan, scanPose, coarseSearchOffset,
coarseSearchResolution,
m_pMapper->m_pCoarseSearchAngleOffset->GetValue(),
m_pMapper->m_pCoarseAngleResolution->GetValue(),
doPenalize, rMean, rCovariance, false);
if (m_pMapper->m_pUseResponseExpansion->GetValue() == true) {
if (math::DoubleEqual(bestResponse, 0.0)) {
#ifdef KARTO_DEBUG
std::cout << "Mapper Info: Expanding response search space!" << std::endl;
#endif
// try and increase search angle offset with 20 degrees and do another match
kt_double newSearchAngleOffset = m_pMapper->m_pCoarseSearchAngleOffset->GetValue();
for (kt_int32u i = 0; i < 3; i++) {
newSearchAngleOffset += math::DegreesToRadians(20);
bestResponse = CorrelateScan(pScan, scanPose, coarseSearchOffset, coarseSearchResolution,
newSearchAngleOffset, m_pMapper->m_pCoarseAngleResolution->GetValue(),
doPenalize, rMean, rCovariance, false);
if (math::DoubleEqual(bestResponse, 0.0) == false) {
break;
}
}
#ifdef KARTO_DEBUG
if (math::DoubleEqual(bestResponse, 0.0)) {
std::cout << "Mapper Warning: Unable to calculate response!" << std::endl;
}
#endif
}
}
if (doRefineMatch) {
Vector2<kt_double> fineSearchOffset(coarseSearchResolution * 0.5);
Vector2<kt_double> fineSearchResolution(m_pCorrelationGrid->GetResolution(),
m_pCorrelationGrid->GetResolution());
bestResponse = CorrelateScan(pScan, rMean, fineSearchOffset, fineSearchResolution,
0.5 * m_pMapper->m_pCoarseAngleResolution->GetValue(),
m_pMapper->m_pFineSearchAngleOffset->GetValue(),
doPenalize, rMean, rCovariance, true);
}
#ifdef KARTO_DEBUG
std::cout << " BEST POSE = " << rMean << " BEST RESPONSE = " << bestResponse <<
", VARIANCE = " <<
rCovariance(0, 0) << ", " << rCovariance(1, 1) << std::endl;
#endif
assert(math::InRange(rMean.GetHeading(), -KT_PI, KT_PI));
return bestResponse;
}
void ScanMatcher::operator()(const kt_double & y) const
{
kt_int32u poseResponseCounter;
kt_int32u x_pose;
kt_int32u y_pose = std::find(m_yPoses.begin(), m_yPoses.end(), y) - m_yPoses.begin();
const kt_int32u size_x = m_xPoses.size();
kt_double newPositionY = m_rSearchCenter.GetY() + y;
kt_double squareY = math::Square(y);
for (std::vector<kt_double>::const_iterator xIter = m_xPoses.begin(); xIter != m_xPoses.end();
++xIter)
{
x_pose = std::distance(m_xPoses.begin(), xIter);
kt_double x = *xIter;
kt_double newPositionX = m_rSearchCenter.GetX() + x;
kt_double squareX = math::Square(x);
Vector2<kt_int32s> gridPoint =
m_pCorrelationGrid->WorldToGrid(Vector2<kt_double>(newPositionX, newPositionY));
kt_int32s gridIndex = m_pCorrelationGrid->GridIndex(gridPoint);
assert(gridIndex >= 0);
kt_double angle = 0.0;
kt_double startAngle = m_rSearchCenter.GetHeading() - m_searchAngleOffset;
for (kt_int32u angleIndex = 0; angleIndex < m_nAngles; angleIndex++) {
angle = startAngle + angleIndex * m_searchAngleResolution;
kt_double response = GetResponse(angleIndex, gridIndex);
if (m_doPenalize && (math::DoubleEqual(response, 0.0) == false)) {
// simple model (approximate Gaussian) to take odometry into account
kt_double squaredDistance = squareX + squareY;
kt_double distancePenalty = 1.0 - (DISTANCE_PENALTY_GAIN *
squaredDistance / m_pMapper->m_pDistanceVariancePenalty->GetValue());
distancePenalty = math::Maximum(distancePenalty,
m_pMapper->m_pMinimumDistancePenalty->GetValue());
kt_double squaredAngleDistance = math::Square(angle - m_rSearchCenter.GetHeading());
kt_double anglePenalty = 1.0 - (ANGLE_PENALTY_GAIN *
squaredAngleDistance / m_pMapper->m_pAngleVariancePenalty->GetValue());
anglePenalty = math::Maximum(anglePenalty, m_pMapper->m_pMinimumAnglePenalty->GetValue());
response *= (distancePenalty * anglePenalty);
}
// store response and pose
poseResponseCounter = (y_pose * size_x + x_pose) * (m_nAngles) + angleIndex;
m_pPoseResponse[poseResponseCounter] =
std::pair<kt_double, Pose2>(response, Pose2(newPositionX, newPositionY,
math::NormalizeAngle(angle)));
}
}
}
/**
* Finds the best pose for the scan centering the search in the correlation grid
* at the given pose and search in the space by the vector and angular offsets
* in increments of the given resolutions
* @param rScan scan to match against correlation grid
* @param rSearchCenter the center of the search space
* @param rSearchSpaceOffset searches poses in the area offset by this vector around search center
* @param rSearchSpaceResolution how fine a granularity to search in the search space
* @param searchAngleOffset searches poses in the angles offset by this angle around search center
* @param searchAngleResolution how fine a granularity to search in the angular search space
* @param doPenalize whether to penalize matches further from the search center
* @param rMean output parameter of mean (best pose) of match
* @param rCovariance output parameter of covariance of match
* @param doingFineMatch whether to do a finer search after coarse search
* @return strength of response
*/
kt_double ScanMatcher::CorrelateScan(
LocalizedRangeScan * pScan, const Pose2 & rSearchCenter,
const Vector2<kt_double> & rSearchSpaceOffset,
const Vector2<kt_double> & rSearchSpaceResolution,
kt_double searchAngleOffset, kt_double searchAngleResolution,
kt_bool doPenalize, Pose2 & rMean, Matrix3 & rCovariance, kt_bool doingFineMatch)
{
assert(searchAngleResolution != 0.0);
// setup lookup arrays
m_pGridLookup->ComputeOffsets(pScan,
rSearchCenter.GetHeading(), searchAngleOffset, searchAngleResolution);
// only initialize probability grid if computing positional covariance (during coarse match)
if (!doingFineMatch) {
m_pSearchSpaceProbs->Clear();
// position search grid - finds lower left corner of search grid
Vector2<kt_double> offset(rSearchCenter.GetPosition() - rSearchSpaceOffset);
m_pSearchSpaceProbs->GetCoordinateConverter()->SetOffset(offset);
}
// calculate position arrays
m_xPoses.clear();
kt_int32u nX = static_cast<kt_int32u>(math::Round(rSearchSpaceOffset.GetX() *
2.0 / rSearchSpaceResolution.GetX()) + 1);
kt_double startX = -rSearchSpaceOffset.GetX();
for (kt_int32u xIndex = 0; xIndex < nX; xIndex++) {
m_xPoses.push_back(startX + xIndex * rSearchSpaceResolution.GetX());
}
assert(math::DoubleEqual(m_xPoses.back(), -startX));
m_yPoses.clear();
kt_int32u nY = static_cast<kt_int32u>(math::Round(rSearchSpaceOffset.GetY() *
2.0 / rSearchSpaceResolution.GetY()) + 1);
kt_double startY = -rSearchSpaceOffset.GetY();
for (kt_int32u yIndex = 0; yIndex < nY; yIndex++) {
m_yPoses.push_back(startY + yIndex * rSearchSpaceResolution.GetY());
}
assert(math::DoubleEqual(m_yPoses.back(), -startY));
// calculate pose response array size
kt_int32u nAngles =
static_cast<kt_int32u>(math::Round(searchAngleOffset * 2.0 / searchAngleResolution) + 1);
kt_int32u poseResponseSize = static_cast<kt_int32u>(m_xPoses.size() * m_yPoses.size() * nAngles);
// allocate array
m_pPoseResponse = new std::pair<kt_double, Pose2>[poseResponseSize];
Vector2<kt_int32s> startGridPoint =
m_pCorrelationGrid->WorldToGrid(Vector2<kt_double>(rSearchCenter.GetX() +
startX, rSearchCenter.GetY() + startY));
// this isn't good but its the fastest way to iterate. Should clean up later.
m_rSearchCenter = rSearchCenter;
m_searchAngleOffset = searchAngleOffset;
m_nAngles = nAngles;
m_searchAngleResolution = searchAngleResolution;
m_doPenalize = doPenalize;
tbb::parallel_for_each(m_yPoses, (*this));
// find value of best response (in [0; 1])
kt_double bestResponse = -1;
for (kt_int32u i = 0; i < poseResponseSize; i++) {
bestResponse = math::Maximum(bestResponse, m_pPoseResponse[i].first);
// will compute positional covariance, save best relative probability for each cell
if (!doingFineMatch) {
const Pose2 & rPose = m_pPoseResponse[i].second;
Vector2<kt_int32s> grid = m_pSearchSpaceProbs->WorldToGrid(rPose.GetPosition());
kt_double * ptr;
try {
ptr = (kt_double *)(m_pSearchSpaceProbs->GetDataPointer(grid)); // NOLINT
} catch (...) {
throw std::runtime_error("Mapper FATAL ERROR - "
"unable to get pointer in probability search!");
}
if (ptr == NULL) {
throw std::runtime_error("Mapper FATAL ERROR - "
"Index out of range in probability search!");
}
*ptr = math::Maximum(m_pPoseResponse[i].first, *ptr);
}
}
// average all poses with same highest response
Vector2<kt_double> averagePosition;
kt_double thetaX = 0.0;
kt_double thetaY = 0.0;
kt_int32s averagePoseCount = 0;
for (kt_int32u i = 0; i < poseResponseSize; i++) {
if (math::DoubleEqual(m_pPoseResponse[i].first, bestResponse)) {
averagePosition += m_pPoseResponse[i].second.GetPosition();
kt_double heading = m_pPoseResponse[i].second.GetHeading();
thetaX += cos(heading);
thetaY += sin(heading);
averagePoseCount++;
}
}
Pose2 averagePose;
if (averagePoseCount > 0) {
averagePosition /= averagePoseCount;
thetaX /= averagePoseCount;
thetaY /= averagePoseCount;
averagePose = Pose2(averagePosition, atan2(thetaY, thetaX));
} else {
throw std::runtime_error("Mapper FATAL ERROR - Unable to find best position");
}
// delete pose response array
delete[] m_pPoseResponse;
m_pPoseResponse = nullptr;
#ifdef KARTO_DEBUG
std::cout << "bestPose: " << averagePose << std::endl;
std::cout << "bestResponse: " << bestResponse << std::endl;
#endif
if (!doingFineMatch) {
ComputePositionalCovariance(averagePose, bestResponse, rSearchCenter, rSearchSpaceOffset,
rSearchSpaceResolution, searchAngleResolution, rCovariance);
} else {
ComputeAngularCovariance(averagePose, bestResponse, rSearchCenter,
searchAngleOffset, searchAngleResolution, rCovariance);
}
rMean = averagePose;
#ifdef KARTO_DEBUG
std::cout << "bestPose: " << averagePose << std::endl;
#endif
if (bestResponse > 1.0) {
bestResponse = 1.0;
}
assert(math::InRange(bestResponse, 0.0, 1.0));
assert(math::InRange(rMean.GetHeading(), -KT_PI, KT_PI));
return bestResponse;
}
/**
* Computes the positional covariance of the best pose
* @param rBestPose
* @param bestResponse
* @param rSearchCenter
* @param rSearchSpaceOffset
* @param rSearchSpaceResolution
* @param searchAngleResolution
* @param rCovariance
*/
void ScanMatcher::ComputePositionalCovariance(
const Pose2 & rBestPose, kt_double bestResponse,
const Pose2 & rSearchCenter,
const Vector2<kt_double> & rSearchSpaceOffset,
const Vector2<kt_double> & rSearchSpaceResolution,
kt_double searchAngleResolution, Matrix3 & rCovariance)
{
// reset covariance to identity matrix
rCovariance.SetToIdentity();
// if best response is vary small return max variance
if (bestResponse < KT_TOLERANCE) {
rCovariance(0, 0) = MAX_VARIANCE; // XX
rCovariance(1, 1) = MAX_VARIANCE; // YY
rCovariance(2, 2) = 4 * math::Square(searchAngleResolution); // TH*TH
return;
}
kt_double accumulatedVarianceXX = 0;
kt_double accumulatedVarianceXY = 0;
kt_double accumulatedVarianceYY = 0;
kt_double norm = 0;
kt_double dx = rBestPose.GetX() - rSearchCenter.GetX();
kt_double dy = rBestPose.GetY() - rSearchCenter.GetY();
kt_double offsetX = rSearchSpaceOffset.GetX();
kt_double offsetY = rSearchSpaceOffset.GetY();
kt_int32u nX =
static_cast<kt_int32u>(math::Round(offsetX * 2.0 / rSearchSpaceResolution.GetX()) + 1);
kt_double startX = -offsetX;
assert(math::DoubleEqual(startX + (nX - 1) * rSearchSpaceResolution.GetX(), -startX));
kt_int32u nY =
static_cast<kt_int32u>(math::Round(offsetY * 2.0 / rSearchSpaceResolution.GetY()) + 1);
kt_double startY = -offsetY;
assert(math::DoubleEqual(startY + (nY - 1) * rSearchSpaceResolution.GetY(), -startY));
for (kt_int32u yIndex = 0; yIndex < nY; yIndex++) {
kt_double y = startY + yIndex * rSearchSpaceResolution.GetY();
for (kt_int32u xIndex = 0; xIndex < nX; xIndex++) {
kt_double x = startX + xIndex * rSearchSpaceResolution.GetX();
Vector2<kt_int32s> gridPoint =
m_pSearchSpaceProbs->WorldToGrid(Vector2<kt_double>(rSearchCenter.GetX() + x,
rSearchCenter.GetY() + y));
kt_double response = *(m_pSearchSpaceProbs->GetDataPointer(gridPoint));
// response is not a low response
if (response >= (bestResponse - 0.1)) {
norm += response;
accumulatedVarianceXX += (math::Square(x - dx) * response);
accumulatedVarianceXY += ((x - dx) * (y - dy) * response);
accumulatedVarianceYY += (math::Square(y - dy) * response);
}
}
}
if (norm > KT_TOLERANCE) {
kt_double varianceXX = accumulatedVarianceXX / norm;
kt_double varianceXY = accumulatedVarianceXY / norm;
kt_double varianceYY = accumulatedVarianceYY / norm;
kt_double varianceTHTH = 4 * math::Square(searchAngleResolution);
// lower-bound variances so that they are not too small;
// ensures that links are not too tight
kt_double minVarianceXX = 0.1 * math::Square(rSearchSpaceResolution.GetX());
kt_double minVarianceYY = 0.1 * math::Square(rSearchSpaceResolution.GetY());
varianceXX = math::Maximum(varianceXX, minVarianceXX);
varianceYY = math::Maximum(varianceYY, minVarianceYY);
// increase variance for poorer responses
kt_double multiplier = 1.0 / bestResponse;
rCovariance(0, 0) = varianceXX * multiplier;
rCovariance(0, 1) = varianceXY * multiplier;
rCovariance(1, 0) = varianceXY * multiplier;
rCovariance(1, 1) = varianceYY * multiplier;
rCovariance(2, 2) = varianceTHTH; // this value will be set in ComputeAngularCovariance
}
// if values are 0, set to MAX_VARIANCE
// values might be 0 if points are too sparse and thus don't hit other points
if (math::DoubleEqual(rCovariance(0, 0), 0.0)) {
rCovariance(0, 0) = MAX_VARIANCE;
}
if (math::DoubleEqual(rCovariance(1, 1), 0.0)) {
rCovariance(1, 1) = MAX_VARIANCE;
}
}
/**
* Computes the angular covariance of the best pose
* @param rBestPose
* @param bestResponse
* @param rSearchCenter
* @param rSearchAngleOffset
* @param searchAngleResolution
* @param rCovariance
*/
void ScanMatcher::ComputeAngularCovariance(
const Pose2 & rBestPose,
kt_double bestResponse,
const Pose2 & rSearchCenter,
kt_double searchAngleOffset,
kt_double searchAngleResolution,
Matrix3 & rCovariance)
{
// NOTE: do not reset covariance matrix
// normalize angle difference
kt_double bestAngle = math::NormalizeAngleDifference(
rBestPose.GetHeading(), rSearchCenter.GetHeading());
Vector2<kt_int32s> gridPoint = m_pCorrelationGrid->WorldToGrid(rBestPose.GetPosition());
kt_int32s gridIndex = m_pCorrelationGrid->GridIndex(gridPoint);
kt_int32u nAngles =
static_cast<kt_int32u>(math::Round(searchAngleOffset * 2 / searchAngleResolution) + 1);
kt_double angle = 0.0;
kt_double startAngle = rSearchCenter.GetHeading() - searchAngleOffset;
kt_double norm = 0.0;