-
Notifications
You must be signed in to change notification settings - Fork 0
/
CRandomFieldGridMap2D.cpp
2882 lines (2379 loc) · 96 KB
/
CRandomFieldGridMap2D.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
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2014, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include <mrpt/maps.h> // Precompiled header
#include <mrpt/slam/CRandomFieldGridMap2D.h>
#include <mrpt/system/os.h>
#include <mrpt/math/utils.h>
#include <mrpt/utils/CTicTac.h>
#include <mrpt/utils/CTimeLogger.h>
#include <mrpt/utils/color_maps.h>
#include <mrpt/opengl.h>
#include <numeric>
// =========== DEBUG MACROS =============
#define RANDOMFIELDGRIDMAP_VERBOSE 0
#define RANDOMFIELDGRIDMAP_KF2_VERBOSE 0
// ======================================
using namespace mrpt;
using namespace mrpt::slam;
using namespace mrpt::utils;
using namespace mrpt::poses;
using namespace std;
IMPLEMENTS_VIRTUAL_SERIALIZABLE(CRandomFieldGridMap2D, CMetricMap,mrpt::slam)
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CRandomFieldGridMap2D::CRandomFieldGridMap2D(
TMapRepresentation mapType,
float x_min,
float x_max,
float y_min,
float y_max,
float resolution ) :
CDynamicGrid<TRandomFieldCell>( x_min,x_max,y_min,y_max,resolution ),
m_insertOptions_common( NULL ),
m_mapType(mapType),
m_cov(0,0),
m_hasToRecoverMeanAndCov(true),
m_DM_lastCutOff(0),
m_average_normreadings_mean(0),
m_average_normreadings_var(0),
m_average_normreadings_count(0)
{
// We can't set "m_insertOptions_common" here via "getCommonInsertOptions()" since
// it's a pure virtual method and we're at the constructor.
// We need all derived classes to call ::clear() in their constructors so we reach internal_clear()
// and set there that variable...
}
CRandomFieldGridMap2D::~CRandomFieldGridMap2D()
{
}
/*---------------------------------------------------------------
clear
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::internal_clear()
{
// (Read the note in the constructor above)
m_insertOptions_common = getCommonInsertOptions(); // Get the pointer from child class
m_average_normreadings_mean = 0;
m_average_normreadings_var = 0;
m_average_normreadings_count = 0;
switch (m_mapType)
{
case mrKernelDM:
case mrKernelDMV:
{
// Set the grid to initial values:
TRandomFieldCell def(0,0);
fill( def );
}
break;
case mrKalmanFilter:
{
printf("[CRandomFieldGridMap2D::clear] Setting covariance matrix to %ux%u\n",(unsigned int)(m_size_y*m_size_x),(unsigned int)(m_size_y*m_size_x));
TRandomFieldCell def(
m_insertOptions_common->KF_defaultCellMeanValue, // mean
m_insertOptions_common->KF_initialCellStd // std
);
fill( def );
// Reset the covariance matrix:
m_cov.setSize( m_size_y*m_size_x, m_size_y*m_size_x );
// And load its default values:
const double KF_covSigma2 = square(m_insertOptions_common->KF_covSigma);
const double res2 = square(m_resolution);
const double std0sqr = square( m_insertOptions_common->KF_initialCellStd );
for (size_t i = 0;i<m_cov.getRowCount();i++)
{
int cx1 = ( i % m_size_x );
int cy1 = ( i / m_size_x );
for (size_t j = i;j<m_cov.getColCount();j++)
{
int cx2 = ( j % m_size_x );
int cy2 = ( j / m_size_x );
if (i==j)
{
m_cov(i,j) = std0sqr;
}
else
{
m_cov(i,j) = std0sqr * exp( -0.5 * (res2 * static_cast<double>(square(cx1-cx2) + square(cy1-cy2)))/KF_covSigma2 );
m_cov(j,i) = m_cov(i,j);
}
} // for j
} // for i
//m_cov.saveToTextFile("cov_init.txt",1);
}
break;
// and continue with:
case mrKalmanApproximate:
{
m_hasToRecoverMeanAndCov = true;
CTicTac tictac;
tictac.Tic();
printf("[CRandomFieldGridMap2D::clear] Resetting compressed cov. matrix and cells\n");
TRandomFieldCell def(
m_insertOptions_common->KF_defaultCellMeanValue, // mean
m_insertOptions_common->KF_initialCellStd // std
);
fill( def );
// Reset the covariance matrix:
// --------------------------------------
const signed W = m_insertOptions_common->KF_W_size;
const size_t N = m_map.size();
const size_t K = 2*W*(W+1)+1;
const double KF_covSigma2 = square(m_insertOptions_common->KF_covSigma);
const double std0sqr = square( m_insertOptions_common->KF_initialCellStd );
const double res2 = square(m_resolution);
m_stackedCov.setSize( N, K );
// Populate it with the initial cov. values:
// ------------------------------------------
signed Acx, Acy;
const double *ptr_first_row = m_stackedCov.get_unsafe_row(0);
for (size_t i=0;i<N;i++)
{
double *ptr = m_stackedCov.get_unsafe_row(i);
if (i==0)
{
// 1) current cell
*ptr++ = std0sqr;
// 2) W rest of the first row:
Acy = 0;
for (Acx=1;Acx<=W;Acx++)
*ptr++ = std0sqr * exp( -0.5 * (res2 * static_cast<double>(square(Acx) + square(Acy)))/KF_covSigma2 );
// 3) The others W rows:
for (Acy=1;Acy<=W;Acy++)
for (Acx=-W;Acx<=W;Acx++)
*ptr++ = std0sqr * exp( -0.5 * (res2 * static_cast<double>(square(Acx) + square(Acy)))/KF_covSigma2 );
}
else
{
// Just copy the same:
memcpy( ptr,ptr_first_row, sizeof(double)*K );
}
}
//printf("[CRandomFieldGridMap2D::clear] %ux%u cells done in %.03fms\n", unsigned(m_size_x),unsigned(m_size_y),1000*tictac.Tac());
}
break;
case mrGMRF_G:
{
CTicTac tictac;
tictac.Tic();
printf("[CRandomFieldGridMap2D::clear] Generating Prior based on Gaussian\n");
// Set the grid to initial values:
TRandomFieldCell def(0,0); // mean, std
fill( def );
//Set initial restrictions: L "cell Constraints" + 0 "Observations constraints"
const uint16_t Gsize = m_insertOptions_common->GMRF_constraintsSize;
const uint16_t Gside = round((Gsize-1)/2);
const float Gsigma = m_insertOptions_common->GMRF_constraintsSigma;
gauss_val.resize(2*Gside);
const size_t N = m_map.size();
// Weigths of the constratints
for (uint16_t i=1;i<=2*Gside;i++) // Compute larger distances than Gside to account for "diagonal" distances.
gauss_val[i-1] = exp( -0.5 *i /Gsigma ); //Fixed constraints are modeled as Gaussian
//Determine the number of Initial constraints --> L+M
nPriorFactors = 0; // L
nObsFactors = 0; // M
{
// Avoid the costly % and / operations:
size_t cx = 0; // ( j % m_size_x ); // [0, m_size_x-1]
size_t cy = 0; // ( j / m_size_x ); // [0, m_size_y-1]
for (size_t j=0; j<N; j++)
{
//Determine the Number of restrictions of the current cell j
//Determine num of columns out of the gridmap
size_t outc_left = max( 0 , int(Gside-cx) );
size_t outc_right = max(int (0) , int (Gside-(m_size_x-cx-1)) );
size_t outc = outc_left + outc_right;
//Determine num of rows out of the gridmap
size_t outr_down = max( 0 , int(Gside-(cy)) );
size_t outr_up = max(int (0) , int (Gside-(m_size_y-cy-1)) );
size_t outr = outr_up + outr_down;
nPriorFactors += (Gsize - outc -1) + (Gsize - outr -1 ); //only vertical and horizontal restrictions
//Increment (row(x), col(y))
if (++cx>=m_size_x)
{
cx=0;
cy++;
}
}
}
nFactors = nPriorFactors + nObsFactors;
cout << "Generating " << nFactors << "cell constraints for a map size of N=" << N << endl;
//Reset the vector of maps (Hessian_vm), the gradient, and the vector of active observations
#if EIGEN_VERSION_AT_LEAST(3,1,0)
H_prior.clear();
H_prior.reserve(nPriorFactors);
#endif
g.resize(N); //Initially the gradient is all 0
g.fill(0.0);
activeObs.resize(N); //No initial Observations
// Load default values:
{
// Avoid the costly % and / operations:
size_t cx = 0; // ( j % m_size_x ); // [0, m_size_x-1]
size_t cy = 0; // ( j / m_size_x ); // [0, m_size_y-1]
size_t count = 0;
for (size_t j=0; j<N; j++)
{
//Determine the Number of restrictions of the current cell j
//Determine num of columns out of the gridmap
int outc_left = max( 0 , int(Gside-cx) );
int outc_right = max(int (0) , int (Gside-(m_size_x-cx-1)) );
int outc = outc_left + outc_right;
//Determine num of rows out of the gridmap
int outr_down = max( 0 , int(Gside-(cy)) );
int outr_up = max(int (0) , int (Gside-(m_size_y-cy-1)) );
int outr = outr_up + outr_down;
size_t nConsFixed_j = (Gsize - outc -1) + (Gsize - outr -1 ); //only vertical and horizontal restrictions
//Set constraints of cell j with all neighbord cells i
for (int kr=-(Gside-outr_down); kr<=(Gside-outr_up); kr++ )
{
for (int kc=-(Gside-outc_left); kc<=(Gside-outc_right); kc++)
{
// get index of cell i
size_t icx = cx + kc;
size_t icy = cy + kr;
size_t i = icx + icy*m_size_x;
if (j==i)
{
//H_ii = Nº constraints * Lambda_cell * (J_ij^2 +1)
#if EIGEN_VERSION_AT_LEAST(3,1,0)
//std::pair<size_t,float> Hentry (j , nConsFixed_j * m_insertOptions_common->GMRF_lambdaPrior * (square(1.0/gauss_val[abs(kr+kc)]) + 1) );
//H_vm.at(i).insert(Hentry);
Eigen::Triplet<double> Hentry(i,j , nConsFixed_j * m_insertOptions_common->GMRF_lambdaPrior * (square(1.0/gauss_val[abs(kr+kc)]) + 1) );
H_prior.push_back( Hentry );
#endif
}
else
{
if (kr==0 || kc==0) //only vertical and horizontal restrictions/constraints
{
// H_ji = 2 * Lambda_cell * J_ij
#if EIGEN_VERSION_AT_LEAST(3,1,0)
Eigen::Triplet<double> Hentry(i,j , -2 * m_insertOptions_common->GMRF_lambdaPrior * 1/gauss_val[abs(kr+kc)-1]);
H_prior.push_back( Hentry );
#endif
//g_j = [m(j) - alpha*m(i) ]* lambda
g[j] += (m_map[j].gmrf_mean - m_map[i].gmrf_mean) * m_insertOptions_common->GMRF_lambdaPrior;
count++;
}
}
}
}
// Increment (row(x), col(y))
if (++cx>=m_size_x)
{
cx=0;
cy++;
}
} // end for "j"
}
cout << " Ready in: " << tictac.Tac() << "s" << endl;
//Solve system and update map estimation
updateMapEstimation_GMRF();
}
break;
case mrGMRF_SD:
{
CTicTac tictac;
tictac.Tic();
printf("[CRandomFieldGridMap2D::clear] Generating Prior based on 'Squared Differences'\n");
printf("Initial map dimension: %u cells, x=(%.2f,%.2f) y=(%.2f,%.2f)\n", static_cast<unsigned int>(m_map.size()), getXMin(),getXMax(),getYMin(),getYMax());
// Set the gasgridmap (m_map) to initial values:
TRandomFieldCell def(0,0); // mean, std
fill( def );
mrpt::slam::COccupancyGridMap2D m_Ocgridmap;
float res_coef = 1.f; // Default value
if (this->m_insertOptions_common->GMRF_use_occupancy_information)
{
printf("loading simplemap: %s ",m_insertOptions_common->GMRF_simplemap_file.c_str());
printf("%i \n",m_insertOptions_common->GMRF_simplemap_file.compare(""));
printf("loading map_image: %s ",m_insertOptions_common->GMRF_gridmap_image_file.c_str());
printf("%i \n",m_insertOptions_common->GMRF_gridmap_image_file.compare(""));
//Load Occupancy Gridmap and resize
if( m_insertOptions_common->GMRF_simplemap_file.compare("") )
{
//TSetOfMetricMapInitializers mapList;
//mapList.loadFromConfigFile(m_ini,"MetricMap");
//CMultiMetricMap metricMap;
//metricMap.setListOfMaps( &mapList );
/*printf("Loading '.simplemap' file...");
mrpt::slam::CSimpleMap MsimpleMap;
CFileGZInputStream(this->m_insertOptions_common->GMRF_simplemap_file) >> simpleMap;
printf("Ok (%u poses)\n",(unsigned)simpleMap.size());*/
//ASSERT_( simpleMap.size()>0 );
// Build metric map:
// ------------------------------
/*printf("Building metric map(s) from '.simplemap'...");
m_Ocgridmap.loadFromProbabilisticPosesAndObservations(simpleMap);
printf("Ok\n");*/
//ASSERTMSG_(!metricMap.m_gridMaps.empty(),"The simplemap file has no gridmap!");
//m_gridmap = *metricMap.m_gridMaps[0];
//res_coef = XXX;
}
else if( m_insertOptions_common->GMRF_gridmap_image_file.compare("") )
{
//Load from image
bool loaded = m_Ocgridmap.loadFromBitmapFile(this->m_insertOptions_common->GMRF_gridmap_image_file,this->m_insertOptions_common->GMRF_gridmap_image_res,this->m_insertOptions_common->GMRF_gridmap_image_cx,this->m_insertOptions_common->GMRF_gridmap_image_cy);
printf ("Occupancy Gridmap loaded : %s",loaded ? "YES" : "NO");
res_coef = this->getResolution() / this->m_insertOptions_common->GMRF_gridmap_image_res;
}
else
cout << "Neither 'simplemap_file' nor 'gridmap_image_file' found in mission file. Quitting."<< endl;
//Resize GasMap to match Occupancy Gridmap dimmensions
printf("Resizing m_map to match Occupancy Gridmap dimensions \n");
resize(m_Ocgridmap.getXMin(),m_Ocgridmap.getXMax(),m_Ocgridmap.getYMin(),m_Ocgridmap.getYMax(),def,0.0);
printf("Occupancy Gridmap dimensions: x=(%.2f,%.2f)m y=(%.2f,%.2f)m \n",m_Ocgridmap.getXMin(),m_Ocgridmap.getXMax(),m_Ocgridmap.getYMin(),m_Ocgridmap.getYMax());
printf("Occupancy Gridmap dimensions: %u cells, cx=%i cy=%i\n\n", static_cast<unsigned int>(m_Ocgridmap.getSizeX()*m_Ocgridmap.getSizeY()), m_Ocgridmap.getSizeX(), m_Ocgridmap.getSizeY());
printf("New map dimensions: %u cells, x=(%.2f,%.2f) y=(%.2f,%.2f)\n", static_cast<unsigned int>(m_map.size()), getXMin(),getXMax(),getYMin(),getYMax());
printf("New map dimensions: %u cells, cx=%u cy=%u\n", static_cast<unsigned int>(m_map.size()), static_cast<unsigned int>(getSizeX()), static_cast<unsigned int>(getSizeY()));
m_Ocgridmap.saveAsBitmapFile("./obstacle_map_from_MRPT.png");
}
//m_map number of cells
const size_t N = m_map.size();
//Set initial factors: L "prior factors" + 0 "Observation factors"
nPriorFactors = (this->getSizeX() -1) * this->getSizeY() + this->getSizeX() * (this->getSizeY() -1); // L = (Nr-1)*Nc + Nr*(Nc-1); Full connected
nObsFactors = 0; // M
nFactors = nPriorFactors + nObsFactors;
cout << "Generating " << nFactors << "factors for a map size of N=" << N << endl;
#if EIGEN_VERSION_AT_LEAST(3,1,0)
//Initialize H_prior, gradient = 0, and the vector of active observations = empty
H_prior.clear();
H_prior.reserve(nPriorFactors);
g.resize(N); //Initially the gradient is all 0
g.fill(0.0);
activeObs.resize(N); //No initial Observations
//-------------------------------------
// Load default values for H_prior:
//-------------------------------------
if (this->m_insertOptions_common->GMRF_use_occupancy_information)
{
printf("LOADING PRIOR BASED ON OCCUPANCY GRIDMAP \n");
printf("Gas Map Dimmensions: %u x %u cells \n", static_cast<unsigned int>(m_size_x), static_cast<unsigned int>(m_size_y));
printf("Occupancy map Dimmensions: %i x %i cells \n", m_Ocgridmap.getSizeX(), m_Ocgridmap.getSizeY());
printf("Res_Coeff = %f pixels/celda",res_coef);
//Use region growing algorithm to determine the gascell interconnections (Factors)
size_t cx = 0;
size_t cy = 0;
size_t cxoj_min, cxoj_max, cyoj_min, cyoj_max, seed_cxo, seed_cyo; //Cell j limits in the Occupancy
size_t cxoi_min, cxoi_max, cyoi_min, cyoi_max, objective_cxo, objective_cyo; //Cell i limits in the Occupancy
size_t cxo_min, cxo_max, cyo_min, cyo_max; //Cell i+j limits in the Occupancy
//bool first_obs = false;
for (size_t j=0; j<N; j++) //For each cell in the gas_map
{
// Get cell_j indx-limits in Occuppancy gridmap
cxoj_min = floor(cx*res_coef);
cxoj_max = cxoj_min + ceil(res_coef-1);
cyoj_min = floor(cy*res_coef);
cyoj_max = cyoj_min + ceil(res_coef-1);
seed_cxo = cxoj_min + ceil(res_coef/2-1);
seed_cyo = cyoj_min + ceil(res_coef/2-1);
//DEBUG
//If cell occpuped then add observation
if ( m_Ocgridmap.getCell(seed_cxo,seed_cyo) < 0.5 )
{
TobservationGMRF new_obs;
new_obs.obsValue = 0.0;
new_obs.Lambda = 10e-5f;
new_obs.time_invariant = true; //Obs that will not dissapear with time.
activeObs[j].push_back(new_obs);
}
//// Insert 1 observation in the vector of Active Observations for a free cell
//if( ( m_Ocgridmap.getCell(seed_cxo,seed_cyo) > 0.5 ) && first_obs )
//{
// TobservationGMRF new_obs;
// new_obs.obsValue = 0.0;
// new_obs.Lambda = m_insertOptions_common->GMRF_lambdaObs;
// activeObs[j].push_back(new_obs);
// first_obs = false;
// cout << " **** Inserting Observation at cell: " << j << endl;
//}
//Factor with the right node: H_ji = - Lamda_prior
//-------------------------------------------------
if (cx<(m_size_x-1))
{
size_t i = j+1;
size_t cxi = cx+1;
size_t cyi = cy;
// Get cell_i indx-limits in Occuppancy gridmap
cxoi_min = floor(cxi*res_coef);
cxoi_max = cxoi_min + ceil(res_coef-1);
cyoi_min = floor(cyi*res_coef);
cyoi_max = cyoi_min + ceil(res_coef-1);
objective_cxo = cxoi_min + ceil(res_coef/2-1);
objective_cyo = cyoi_min + ceil(res_coef/2-1);
//Get overall indx of both cells together
cxo_min = min(cxoj_min, cxoi_min );
cxo_max = max(cxoj_max, cxoi_max );
cyo_min = min(cyoj_min, cyoi_min );
cyo_max = max(cyoj_max, cyoi_max );
//Check using Region growing if cell j is connected to cell i (Occupancy gridmap)
if( exist_relation_between2cells(&m_Ocgridmap, cxo_min,cxo_max,cyo_min,cyo_max,seed_cxo,seed_cyo,objective_cxo,objective_cyo))
{
Eigen::Triplet<double> Hentry(i,j, - m_insertOptions_common->GMRF_lambdaPrior);
H_prior.push_back( Hentry );
//Save relation between cells
cell_interconnections.insert ( std::pair<size_t,size_t>(j,i) );
cell_interconnections.insert ( std::pair<size_t,size_t>(i,j) );
}
}
//Factor with the upper node: H_ji = - Lamda_prior
//-------------------------------------------------
if (cy<(m_size_y-1))
{
size_t i = j+m_size_x;
size_t cxi = cx;
size_t cyi = cy+1;
// Get cell_i indx-limits in Occuppancy gridmap
cxoi_min = floor(cxi*res_coef);
cxoi_max = cxoi_min + ceil(res_coef-1);
cyoi_min = floor(cyi*res_coef);
cyoi_max = cyoi_min + ceil(res_coef-1);
objective_cxo = cxoi_min + ceil(res_coef/2-1);
objective_cyo = cyoi_min + ceil(res_coef/2-1);
//Get overall indx-limits of both cells together
cxo_min = min(cxoj_min, cxoi_min );
cxo_max = max(cxoj_max, cxoi_max );
cyo_min = min(cyoj_min, cyoi_min );
cyo_max = max(cyoj_max, cyoi_max );
//Check using Region growing if cell j is connected to cell i (Occupancy gridmap)
if( exist_relation_between2cells(&m_Ocgridmap, cxo_min,cxo_max,cyo_min,cyo_max,seed_cxo,seed_cyo,objective_cxo,objective_cyo))
{
Eigen::Triplet<double> Hentry(i,j, - m_insertOptions_common->GMRF_lambdaPrior);
H_prior.push_back( Hentry );
//Save relation
cell_interconnections.insert ( std::pair<size_t,size_t>(j,i) );
cell_interconnections.insert ( std::pair<size_t,size_t>(i,j) );
}
}
//Factors of cell_j: H_jj = Nº factors * Lambda_prior
//----------------------------------------------------
std::pair < std::multimap<size_t,size_t>::iterator, std::multimap<size_t,size_t>::iterator > range;
range = cell_interconnections.equal_range(j);
size_t nFactors_j = 0;
while ( range.first!=range.second )
{
nFactors_j++;
range.first++;
}
Eigen::Triplet<double> Hentry(j,j , nFactors_j * m_insertOptions_common->GMRF_lambdaPrior );
H_prior.push_back( Hentry );
// Increment j coordinates (row(x), col(y))
if (++cx>=m_size_x)
{
cx=0;
cy++;
}
} // end for "j"
//DEBUG - Save cell interconnections to file
ofstream myfile;
myfile.open("MRF.txt");
for (std::multimap<size_t,size_t>::iterator it=cell_interconnections.begin(); it!=cell_interconnections.end(); ++it)
myfile << (*it).first << " " << (*it).second << '\n';
myfile.close();
}
else
{
cout << "LOADING FULL PRIOR" << endl;
//---------------------------------------------------------------
// Load default values for H_prior without Occupancy information:
//---------------------------------------------------------------
size_t cx = 0;
size_t cy = 0;
size_t count = 0;
for (size_t j=0; j<N; j++)
{
//Factor with the right node: H_ji = - Lamda_prior
//-------------------------------------------------
if (cx<(m_size_x-1))
{
size_t i = j+1;
Eigen::Triplet<double> Hentry(i,j, - m_insertOptions_common->GMRF_lambdaPrior);
H_prior.push_back( Hentry );
count = count +1;
}
//Factor with the above node: H_ji = - Lamda_prior
//-------------------------------------------------
if (cy<(m_size_y-1))
{
size_t i = j+m_size_x;
Eigen::Triplet<double> Hentry(i,j, - m_insertOptions_common->GMRF_lambdaPrior);
H_prior.push_back( Hentry );
count = count +1;
}
//Factors of cell_i: H_ii = Nº factors * Lambda_prior
//----------------------------------------------------
size_t nFactors_j = 4 - (cx==0) - (cx==m_size_x-1) - (cy==0) - (cy==m_size_y-1);
Eigen::Triplet<double> Hentry(j,j , nFactors_j * m_insertOptions_common->GMRF_lambdaPrior );
H_prior.push_back( Hentry );
// Increment j coordinates (row(x), col(y))
if (++cx>=m_size_x)
{
cx=0;
cy++;
}
} // end for "j"
} // end if_use_Occupancy
cout << "---------- Prior Built in: " << tictac.Tac() << "s ----------" << endl;
//Solve system and update map estimation
updateMapEstimation_GMRF();
#endif
}//end case
break;
default:
cout << "MAP TYPE NOT RECOGNICED... QUITTING" << endl;
break;
} //end switch
}
/*---------------------------------------------------------------
isEmpty
---------------------------------------------------------------*/
bool CRandomFieldGridMap2D::isEmpty() const
{
return false;
}
/*---------------------------------------------------------------
insertObservation_KernelDM_DMV
---------------------------------------------------------------*/
/** The implementation of "insertObservation" for Achim Lilienthal's map models DM & DM+V.
* \param normReading Is a [0,1] normalized concentration reading.
* \param is_DMV = false -> map type is Kernel DM; true -> map type is DM+V
*/
void CRandomFieldGridMap2D::insertObservation_KernelDM_DMV(
float normReading,
const mrpt::math::TPoint2D &point,
bool is_DMV )
{
MRPT_START
static const TRandomFieldCell defCell(0,0);
// Assure we have room enough in the grid!
resize( point.x - m_insertOptions_common->cutoffRadius*2,
point.x + m_insertOptions_common->cutoffRadius*2,
point.y - m_insertOptions_common->cutoffRadius*2,
point.y + m_insertOptions_common->cutoffRadius*2,
defCell );
// Compute the "parzen Gaussian" once only:
// -------------------------------------------------
int Ac_cutoff = round(m_insertOptions_common->cutoffRadius / m_resolution);
unsigned Ac_all = 1+2*Ac_cutoff;
double minWinValueAtCutOff = exp(-square(m_insertOptions_common->cutoffRadius/m_insertOptions_common->sigma) );
if ( m_DM_lastCutOff!=m_insertOptions_common->cutoffRadius ||
m_DM_gaussWindow.size() != square(Ac_all) )
{
printf("[CRandomFieldGridMap2D::insertObservation_KernelDM_DMV] Precomputing window %ux%u\n",Ac_all,Ac_all);
double dist;
double std = m_insertOptions_common->sigma;
// Compute the window:
m_DM_gaussWindow.resize(Ac_all*Ac_all);
m_DM_lastCutOff=m_insertOptions_common->cutoffRadius;
// Actually the array could be 1/4 of this size, but this
// way it's easier and it's late night now :-)
vector<float>::iterator it = m_DM_gaussWindow.begin();
for (unsigned cx=0;cx<Ac_all;cx++)
{
for (unsigned cy=0;cy<Ac_all;cy++)
{
dist = m_resolution * sqrt( static_cast<double>(square( Ac_cutoff+1-cx ) + square( Ac_cutoff+1-cy ) ) );
*(it++) = std::exp( - square(dist/std) );
}
}
printf("[CRandomFieldGridMap2D::insertObservation_KernelDM_DMV] Done!\n");
} // end of computing the gauss. window.
// Fuse with current content of grid (the MEAN of each cell):
// --------------------------------------------------------------
const int sensor_cx = x2idx( point.x );
const int sensor_cy = y2idx( point.y );
TRandomFieldCell *cell;
vector<float>::iterator windowIt = m_DM_gaussWindow.begin();
for (int Acx=-Ac_cutoff;Acx<=Ac_cutoff;Acx++)
{
for (int Acy=-Ac_cutoff;Acy<=Ac_cutoff;++Acy, ++windowIt)
{
const double windowValue = *windowIt;
if (windowValue>minWinValueAtCutOff)
{
cell = cellByIndex(sensor_cx+Acx,sensor_cy+Acy);
ASSERT_( cell!=NULL )
cell->dm_mean_w += windowValue;
cell->dm_mean += windowValue * normReading;
if (is_DMV)
{
const double cell_var = square(normReading - computeMeanCellValue_DM_DMV(cell) );
cell->dmv_var_mean += windowValue * cell_var;
}
}
}
}
MRPT_END
}
/*---------------------------------------------------------------
TInsertionOptionsCommon
---------------------------------------------------------------*/
CRandomFieldGridMap2D::TInsertionOptionsCommon::TInsertionOptionsCommon() :
sigma ( 0.15f ),
cutoffRadius ( sigma * 3.0 ),
R_min ( 0 ),
R_max ( 3 ),
dm_sigma_omega ( 0.05 ), // See IROS 2009 paper (a scale parameter for the confidence)
KF_covSigma ( 0.35f ), // in meters
KF_initialCellStd ( 1.0 ), // std in normalized concentration units
KF_observationModelNoise ( 0.25f ), // in normalized concentration units
KF_defaultCellMeanValue ( 0.25f ),
KF_W_size ( 4 ),
GMRF_lambdaPrior ( 0.01f ), // [GMRF model] The information (Lambda) of fixed map constraints
GMRF_lambdaObs ( 10.0f ), // [GMRF model] The initial information (Lambda) of each observation (this information will decrease with time)
GMRF_lambdaObsLoss ( 1.0f ), //!< The loss of information of the observations with each iteration
GMRF_use_occupancy_information ( false ),
GMRF_simplemap_file ( "" ),
GMRF_gridmap_image_file ( "" ),
GMRF_gridmap_image_res ( 0.01f ),
GMRF_gridmap_image_cx ( 0 ),
GMRF_gridmap_image_cy ( 0 ),
GMRF_constraintsSize ( 3 ), // [GMRF model] The size (cells) of the Gaussian window to impose fixed restrictions between cells.
GMRF_constraintsSigma ( 4.0f ) // [GMRF model] The sigma of the Gaussian window to impose fixed restrictions between cells.
{
}
/*---------------------------------------------------------------
internal_dumpToTextStream_common
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::TInsertionOptionsCommon::internal_dumpToTextStream_common(CStream &out) const
{
out.printf("sigma = %f\n", sigma);
out.printf("cutoffRadius = %f\n", cutoffRadius);
out.printf("R_min = %f\n", R_min);
out.printf("R_max = %f\n", R_max);
out.printf("dm_sigma_omega = %f\n", dm_sigma_omega);
out.printf("KF_covSigma = %f\n", KF_covSigma);
out.printf("KF_initialCellStd = %f\n", KF_initialCellStd);
out.printf("KF_observationModelNoise = %f\n", KF_observationModelNoise);
out.printf("KF_defaultCellMeanValue = %f\n", KF_defaultCellMeanValue);
out.printf("KF_W_size = %u\n", (unsigned)KF_W_size);
out.printf("GMRF_lambdaPrior = %f\n", GMRF_lambdaPrior);
out.printf("GMRF_lambdaObs = %f\n", GMRF_lambdaObs);
out.printf("GMRF_lambdaObsLoss = %f\n", GMRF_lambdaObs);
out.printf("GMRF_use_occupancy_information = %s\n", GMRF_use_occupancy_information ? "YES":"NO" );
out.printf("GMRF_simplemap_file = %s\n", GMRF_simplemap_file.c_str());
out.printf("GMRF_gridmap_image_file = %s\n", GMRF_gridmap_image_file.c_str());
out.printf("GMRF_gridmap_image_res = %f\n", GMRF_gridmap_image_res);
out.printf("GMRF_gridmap_image_cx = %u\n", static_cast<unsigned int>(GMRF_gridmap_image_cx));
out.printf("GMRF_gridmap_image_cy = %u\n", static_cast<unsigned int>(GMRF_gridmap_image_cy));
out.printf("GMRF_constraintsSize = %u\n", (unsigned)GMRF_constraintsSize);
out.printf("GMRF_constraintsSigma = %f\n", GMRF_constraintsSigma);
}
/*---------------------------------------------------------------
internal_loadFromConfigFile_common
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::TInsertionOptionsCommon::internal_loadFromConfigFile_common(
const mrpt::utils::CConfigFileBase &iniFile,
const std::string §ion)
{
sigma = iniFile.read_float(section.c_str(),"sigma",sigma);
cutoffRadius = iniFile.read_float(section.c_str(),"cutoffRadius",cutoffRadius);
R_min = iniFile.read_float(section.c_str(),"R_min",R_min);
R_max = iniFile.read_float(section.c_str(),"R_max",R_max);
MRPT_LOAD_CONFIG_VAR(dm_sigma_omega, double, iniFile, section );
KF_covSigma = iniFile.read_float(section.c_str(),"KF_covSigma",KF_covSigma);
KF_initialCellStd = iniFile.read_float(section.c_str(),"KF_initialCellStd",KF_initialCellStd);
KF_observationModelNoise= iniFile.read_float(section.c_str(),"KF_observationModelNoise",KF_observationModelNoise);
KF_defaultCellMeanValue = iniFile.read_float(section.c_str(),"KF_defaultCellMeanValue",KF_defaultCellMeanValue);
MRPT_LOAD_CONFIG_VAR(KF_W_size, int, iniFile, section );
GMRF_lambdaPrior = iniFile.read_float(section.c_str(),"GMRF_lambdaPrior",GMRF_lambdaPrior);
GMRF_lambdaObs = iniFile.read_float(section.c_str(),"GMRF_lambdaObs",GMRF_lambdaObs);
GMRF_lambdaObsLoss = iniFile.read_float(section.c_str(),"GMRF_lambdaObsLoss",GMRF_lambdaObsLoss);
GMRF_use_occupancy_information = iniFile.read_bool(section.c_str(),"GMRF_use_occupancy_information",false,false);
GMRF_simplemap_file = iniFile.read_string(section.c_str(),"simplemap_file","",false);
GMRF_gridmap_image_file = iniFile.read_string(section.c_str(),"gridmap_image_file","",false);
GMRF_gridmap_image_res = iniFile.read_float(section.c_str(),"gridmap_image_res",0.01,false);
GMRF_gridmap_image_cx = iniFile.read_int(section.c_str(),"gridmap_image_cx",0,false);
GMRF_gridmap_image_cy = iniFile.read_int(section.c_str(),"gridmap_image_cy",0,false);
GMRF_constraintsSigma = iniFile.read_float(section.c_str(),"GMRF_constraintsSigma",GMRF_constraintsSigma);
MRPT_LOAD_CONFIG_VAR(GMRF_constraintsSize, int, iniFile, section );
}
/*---------------------------------------------------------------
saveAsBitmapFile
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::saveAsBitmapFile(const std::string &filName) const
{
MRPT_START
mrpt::utils::CImage img;
getAsBitmapFile(img);
img.saveToFile(filName);
MRPT_END
}
/*---------------------------------------------------------------
getAsBitmapFile
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::getAsBitmapFile(mrpt::utils::CImage &out_img) const
{
MRPT_START
unsigned int x,y;
double c;
const TRandomFieldCell *cell;
mrpt::math::CMatrixDouble cells_mat(m_size_y,m_size_x);
recoverMeanAndCov(); // Only has effects for KF2 method
for (y=0;y<m_size_y;y++)
{
for (x=0;x<m_size_x;x++)
{
cell = cellByIndex(x,y);
ASSERT_( cell!=NULL );
switch (m_mapType)
{
case mrKernelDM:
case mrKernelDMV:
c = computeMeanCellValue_DM_DMV(cell);
break;
case mrKalmanFilter:
case mrKalmanApproximate:
c = cell->kf_mean;
break;
case mrGMRF_G:
case mrGMRF_SD:
c = cell->gmrf_mean;
break;
default:
THROW_EXCEPTION("Unknown m_mapType!!");
};
if (c<0) c=0;
if (c>1) c=1;
cells_mat(m_size_y-1-y,x) = c;
}
}
out_img.setFromMatrix(cells_mat, true /* vals are normalized in [0,1] */);
MRPT_END
}
/*---------------------------------------------------------------
resize
---------------------------------------------------------------*/
void CRandomFieldGridMap2D::resize(
float new_x_min,
float new_x_max,
float new_y_min,
float new_y_max,
const TRandomFieldCell& defaultValueNewCells,
float additionalMarginMeters)
{
MRPT_START
size_t old_sizeX = m_size_x;
size_t old_sizeY = m_size_y;
float old_x_min = m_x_min;
float old_y_min = m_y_min;
// The parent class method:
CDynamicGrid<TRandomFieldCell>::resize(new_x_min,new_x_max,new_y_min,new_y_max,defaultValueNewCells,additionalMarginMeters);
// Do we really resized?
if ( m_size_x != old_sizeX || m_size_y != old_sizeY )
{
// YES:
// If we are in a Kalman Filter representation, also build the new covariance matrix:
if (m_mapType==mrKalmanFilter)
{
// ------------------------------------------
// Update the covariance matrix
// ------------------------------------------
size_t i,j,N = m_size_y*m_size_x; // The new number of cells
CMatrixD oldCov( m_cov ); // Make a copy
//m_cov.saveToTextFile("__debug_cov_before_resize.txt");
printf("[CRandomFieldGridMap2D::resize] Resizing from %ux%u to %ux%u (%u cells)\n",
static_cast<unsigned>(old_sizeX),
static_cast<unsigned>(old_sizeY),
static_cast<unsigned>(m_size_x),
static_cast<unsigned>(m_size_y),
static_cast<unsigned>(m_size_x*m_size_y) );
m_cov.setSize( N,N );
// Compute the new cells at the left and the bottom:
size_t Acx_left = round((old_x_min - m_x_min)/m_resolution);
size_t Acy_bottom = round((old_y_min - m_y_min)/m_resolution);
// -------------------------------------------------------
// STEP 1: Copy the old map values:
// -------------------------------------------------------
for (i = 0;i<N;i++)
{
size_t cx1 = i % m_size_x;
size_t cy1 = i / m_size_x;
bool C1_isFromOldMap = Acx_left<=cx1 && cx1<(Acx_left+old_sizeX) &&
Acy_bottom<=cy1 && cy1<(Acy_bottom+old_sizeY);
if ( C1_isFromOldMap )
{
for (j = i;j<N;j++)
{
size_t cx2 = j % m_size_x;
size_t cy2 = j / m_size_x;
bool C2_isFromOldMap = Acx_left<=cx2 && cx2<(Acx_left+old_sizeX) &&
Acy_bottom<=cy2 && cy2<(Acy_bottom+old_sizeY);
// Were both cells in the old map??? --> Copy it!
if ( C1_isFromOldMap && C2_isFromOldMap )
{
// Copy values for the old matrix:
unsigned int idx_c1 = ( (cx1 - Acx_left) + old_sizeX * (cy1 - Acy_bottom ) );
unsigned int idx_c2 = ( (cx2 - Acx_left) + old_sizeX * (cy2 - Acy_bottom ) );
MRPT_START
ASSERT_( cx1 >= Acx_left );
ASSERT_( cy1 >= Acy_bottom );
ASSERT_( (cx1 - Acx_left )<old_sizeX );
ASSERT_( (cy1 - Acy_bottom )<old_sizeY );
ASSERT_( cx2 >= Acx_left );
ASSERT_( cy2 >= Acy_bottom );
ASSERT_( (cx2 - Acx_left )<old_sizeX );
ASSERT_( (cy2 - Acy_bottom )<old_sizeY );
ASSERT_( idx_c1<old_sizeX*old_sizeY );
ASSERT_( idx_c2<old_sizeX*old_sizeY );