-
Notifications
You must be signed in to change notification settings - Fork 1
/
RadarModel.cpp
1786 lines (1447 loc) · 62.7 KB
/
RadarModel.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
#include "RadarModel.hpp"
#include <unsupported/Eigen/SpecialFunctions>
using namespace std;
using namespace grid_map;
// http://eigen.tuxfamily.org/dox/AsciiQuickReference.txt
////////////////// SPLINE FUNCTIONS //////////////////
// The spline is used to interpolate antenna gain values, as we only have the
// graphs
SplineFunction::SplineFunction() {}
SplineFunction::SplineFunction(Eigen::VectorXd const &x_vec,
Eigen::VectorXd const &y_vec)
: x_min(x_vec.minCoeff()), x_max(x_vec.maxCoeff()), y_min(y_vec.minCoeff()),
y_max(y_vec.maxCoeff()),
// Spline fitting here. X values are scaled down to [0, 1] for this.
spline_(Eigen::SplineFitting<Eigen::Spline<double, 1>>::Interpolate(
y_vec.transpose(), std::min<int>(x_vec.rows() - 1, 6),
scaled_values(
x_vec))) // No more than cubic spline, but accept short vectors.
{}
// x values need to be scaled down in extraction as well.
double SplineFunction::interpDeg(double x) const {
double y;
y = spline_(scaled_value(x))(0);
// interpolation may produce values bigger and lower than our limits ...
y = max(min(y, y_max), y_min);
return y;
}
double SplineFunction::interpRad(double x) const {
return interpDeg(x * 180.0 / M_PI);
}
float SplineFunction::interpRadf(float x) const {
return (float) interpDeg(( (double) x) *180.0/M_PI);
}
// Helpers to scale X values down to [0, 1]
double SplineFunction::scaled_value(double x) const {
return (x - x_min) / (x_max - x_min);
}
Eigen::RowVectorXd
SplineFunction::scaled_values(Eigen::VectorXd const &x_vec) const {
return x_vec.unaryExpr([this](double x) { return scaled_value(x); })
.transpose();
}
//////////////////
RadarModel::RadarModel(){};
RadarModel::RadarModel(const double resolution, const double sigma_power, const double sigma_phase, const double txtPower, const std::vector<double> freqs, const std::vector<std::pair<double,double>> tags_coords, const std::string imageFileURI ) {
_sigma_power = sigma_power;
_sigma_phase = sigma_phase;
_txtPower = txtPower;
_freqs = freqs;
_resolution = resolution;
_tags_coords = tags_coords;
_numTags = tags_coords.size();
initRefMap(imageFileURI);
// build spline to interpolate antenna gains;
std::vector<double> xVec(ANTENNA_ANGLES_LIST, ANTENNA_ANGLES_LIST + 25);
Eigen::VectorXd xvals = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(xVec.data(), xVec.size());
std::vector<double> yVec(ANTENNA_LOSSES_LIST, ANTENNA_LOSSES_LIST + 25);
Eigen::VectorXd yvals= Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(yVec.data(), yVec.size());
_antenna_gains= SplineFunction(xvals, yvals);
// rfid beliefs global map: One layer per tag
std::string layerName;
for(int i = 0; i <_numTags; ++i) {
layerName = getTagLayerName(i);
_rfid_belief_maps.add(layerName, 0.5); // the cells need to have a uniform distribution at the beginning
}
clearObstacleCellsRFIDMap();
normalizeRFIDMap();
debugInfo();
// mesh grid layers
_rfid_belief_maps.add("X", 0);
_rfid_belief_maps.add("Y", 0);
Position point;
Index ind;
for (grid_map::GridMapIterator iterator(_rfid_belief_maps); !iterator.isPastEnd(); ++iterator) {
// matrix indexes...
ind = *iterator;
// get cell center of the cell in the map frame.
_rfid_belief_maps.getPosition(ind, point);
// that is where the tag supposedly is in map coordinates
_rfid_belief_maps.at("X",*iterator) = point.x();
_rfid_belief_maps.at("Y",*iterator) = point.y();
}
}
void RadarModel::initRefMap(const std::string imageURI) {
std::cout << "\nIniting Ref map." << std::endl;
cv::Mat _imageCV = cv::imread(imageURI, CV_LOAD_IMAGE_UNCHANGED);
// this alligns image with our coordinate systems
cv::flip(_imageCV, _imageCV, -1);
_Ncol = _imageCV.cols; // radar model total x-range space (cells).
_Nrow = _imageCV.rows; // radar model total y-range space (cells).
// cell value ranges
double minValue;
double maxValue;
double orig_x, len_x, orig_y, len_y;
len_x = _Nrow * _resolution;
len_y = _Ncol * _resolution;
// 2D position of the grid map in the grid map frame [m].
// orig will be placed at the UPPER LEFT CORNER THE IMAGE, thus all
// coordinates will be positive
orig_x = (_Nrow - 1) * (_resolution / 2.0);
orig_y = (_Ncol - 1) * (_resolution / 2.0);
_rfid_belief_maps = grid_map::GridMap(vector<string>({"ref_map"}));
_rfid_belief_maps.setGeometry(Length(len_x, len_y), _resolution,
Position(orig_x, orig_y));
_tmp_rfid_c_map.setGeometry(Length(2, 2), _resolution);
_tmp_rfid_c_map.add("temp", 0.0);
cv::minMaxLoc(_imageCV, &minValue, &maxValue);
_free_space_val = maxValue;
_rfid_belief_maps["ref_map"].setConstant(NAN);
GridMapCvConverter::addLayerFromImage<unsigned char, 3>(
_imageCV, "ref_map", _rfid_belief_maps, minValue, maxValue);
std::cout << " Input map has " << _rfid_belief_maps.getSize()(1)
<< " cols by " << _rfid_belief_maps.getSize()(0) << " rows "
<< std::endl;
std::cout << " Orig at: (" << orig_x << ", " << orig_y << ") m. "
<< std::endl;
std::cout << " Size: (" << _rfid_belief_maps.getLength().x() << ", "
<< _rfid_belief_maps.getLength().y() << ") m. " << std::endl;
std::cout << " Values range: (" << minValue << ", " << maxValue << ") "
<< std::endl;
std::cout << " Using : (" << maxValue << ") value as free space value "
<< std::endl;
grid_map::Position p;
grid_map::Index index;
// std::cout<<"\nTesting boundaries: " <<std::endl;
index = grid_map::Index(0, 0);
// std::cout<<"P: Index(" << 0 << ", " << 0 << ") " <<std::endl;
if (_rfid_belief_maps.getPosition(index, p)) {
// std::cout<<"P: Cell(" << index(0) << ", " << index(1) << ") is at (" <<
// p(0) << ", " << p(1)<<") m. " <<std::endl;
} else {
// std::cout<<" Cell(" << index(0) << ", " << index(1) << ") is out
// bounds!" <<std::endl;
}
index = grid_map::Index(_Nrow - 1, 0);
// std::cout<<"P: Index(" << (_Nrow-1) << ", " << 0 << ") " <<std::endl;
if (_rfid_belief_maps.getPosition(index, p)) {
// std::cout<<"P: Cell(" << index(0) << ", " << index(1) << ") is at (" <<
// p(0) << ", " << p(1)<<") m. " <<std::endl;
} else {
// std::cout<<" Cell(" << index(0) << ", " << index(1) << ") is out
// bounds!" <<std::endl;
}
index = grid_map::Index(0, _Ncol - 1);
// std::cout<<"P: Index(" << (0) << ", " << (_Ncol-1) << ") " <<std::endl;
if (_rfid_belief_maps.getPosition(index, p)) {
// std::cout<<"P: Cell(" << index(0) << ", " << index(1) << ") is at (" <<
// p(0) << ", " << p(1)<<") m. " <<std::endl;
} else {
// std::cout<<" Cell(" << index(0) << ", " << index(1) << ") is out
// bounds!" <<std::endl;
}
index = grid_map::Index(_Nrow - 1, _Ncol - 1);
// std::cout << "P: Index(" << (_Nrow-1) << ", " << (_Ncol-1) << ") "
// <<std::endl;
if (_rfid_belief_maps.getPosition(index, p)) {
// std::cout<<"P: Cell(" << index(0) << ", " << index(1) << ") is at (" <<
// p(0) << ", " << p(1)<<") m. " <<std::endl;
} else {
// std::cout<<" Cell(" << index(0) << ", " << index(1) << ") is out
// bounds!" <<std::endl;
}
// std::cout << "............................. " << std::endl << std::endl;
}
void RadarModel::saveProbMaps(std::string savePath) {
std::string tagLayerName;
std::string fileURI;
Eigen::MatrixXf data_mat;
// PrintMap(savePath);
// prob distribution maps
for (int i = 0; i < _numTags; ++i) {
tagLayerName = getTagLayerName(i);
// std::cout << " Saving layer [" << tagLayerName << "]" << std::endl ;
fileURI = savePath + "final_prob_" + tagLayerName + ".png";
getImage(&_rfid_belief_maps, tagLayerName, fileURI);
// data_mat = _rfid_belief_maps[tagLayerName];
// PrintProb(fileURI, &data_mat, _Ncol*_resolution, _Nrow*_resolution,
// _resolution);
}
}
////////////////////////// GETTERS
///////////////////////////////////////////////////////
Eigen::MatrixXf RadarModel::getPowProbCond(double rxPw, double f_i){
return getPowProbCond( rxPw, 0, 0, 0, f_i);
}
Eigen::MatrixXf RadarModel::getPowProbCond(double rxPw, double x_m, double y_m, double orientation_deg, double f_i){
Eigen::MatrixXf PW_mat = getFriisMat(x_m,y_m,orientation_deg, f_i);
Eigen::MatrixXf ans = getProbCond(PW_mat, rxPw, _sigma_power);
return ans;
}
Eigen::MatrixXf RadarModel::getPhaseProbCond(double rxPw, double f_i){
return getPhaseProbCond( rxPw, 0, 0, 0, f_i);
}
Eigen::MatrixXf RadarModel::getPhaseProbCond(double ph_i, double x_m, double y_m, double orientation_deg, double f_i){
Eigen::MatrixXf PH_mat = getPhaseMat(x_m,y_m,orientation_deg, f_i);
Eigen::MatrixXf ans = getProbCond(PH_mat, ph_i, _sigma_phase);
return ans;
}
Eigen::MatrixXf RadarModel::getProbCond(Eigen::MatrixXf X_mat, double x, double sig){
Eigen::MatrixXf likl_mat;
// gaussian pdf
// fddp(x,mu,sigma) = exp( -0.5 * ( (x - mu)/sigma )^2 ) / (sigma * sqrt(2 pi ))
likl_mat = ( x - X_mat.array() ) /_sigma_power;
likl_mat = -0.5 * ( likl_mat.array().pow(2.0) );
likl_mat = likl_mat.array().exp() / ( _sigma_power * sqrt( 2.0 * M_PI ) ) ;
return likl_mat;
}
Eigen::MatrixXf RadarModel::getFriisMat(double x_m, double y_m, double orientation_deg, double freq){
if (useFast)
return getFriisMatFast(x_m, y_m, orientation_deg, freq);
else
return getFriisMatSlow(x_m, y_m, orientation_deg, freq);
}
Eigen::MatrixXf RadarModel::getFriisMatSlow(double x_m, double y_m, double orientation_deg, double freq){
Eigen::MatrixXf rxPw_mat;
double tag_x, tag_y, rxP;
Position glob_point;
Index ind;
Size siz = _rfid_belief_maps.getSize();
rxPw_mat = Eigen::MatrixXf(siz(0), siz(1));
double orientation_rad = orientation_deg * M_PI / 180.0;
// Obtain rel dist and friis to all points
// MFC: can I turn this iteration into matrix operations?
for (grid_map::GridMapIterator iterator(_rfid_belief_maps);
!iterator.isPastEnd(); ++iterator) {
// matrix indexes...
ind = *iterator;
// get cell center of the cell in the map frame.
_rfid_belief_maps.getPosition(ind, glob_point);
// that is where the tag supposedly is in map coordinates
tag_x = glob_point.x();
tag_y = glob_point.y();
rxP = received_power_friis_with_obstacles(x_m, y_m, orientation_rad, tag_x,
tag_y, 0, freq);
rxPw_mat(ind(0), ind(1)) = rxP;
}
return rxPw_mat;
}
Eigen::MatrixXf RadarModel::getFriisMatFast(double x_m, double y_m, double orientation_deg, double freq){
// https://eigen.tuxfamily.org/dox/AsciiQuickReference.txt
// https://github.com/ANYbotics/grid_map
Eigen::MatrixXf X, Y, R, A, propL, antL,totalLoss, rxPower;
Eigen::VectorXf x,y;
Index i00,i0M,iNM,iN0, iRobot;
double lambda = C/freq;
double orientation_rad = orientation_deg * M_PI/180.0;
// rotate and translate
Eigen::MatrixXf X0 = _rfid_belief_maps["X"];
Eigen::MatrixXf Y0 = _rfid_belief_maps["Y"];
double cA =cos(orientation_rad);
double sA =sin(orientation_rad);
X = ( X0 * cA + Y0 * sA).array() - (x_m*cA + y_m*sA);
Y = (-X0 * sA + Y0 * cA).array() + (x_m*sA - y_m*cA);
// create R,Ang matrixes
R = (X.array().square() + Y.array().square()).array().sqrt();
A = Y.binaryExpr(X, std::ptr_fun(atan2f)).array();
// 1. Create a friis losses propagation matrix without taking obstacles
auto funtor = std::bind(&SplineFunction::interpRadf, _antenna_gains, _1) ;
antL = TAG_LOSSES + A.unaryExpr( funtor ).array();
propL = LOSS_CONSTANT - (20.0 * (R * freq).array().log10()).array() ;
// signal goes from antenna to tag and comes back again, so we double the losses
totalLoss = 2.0*antL + 2.0*propL ;
rxPower = totalLoss.array() + _txtPower;
// this should remove points where friis is not applicable
rxPower = (R.array()>2.0*lambda).select(rxPower,_txtPower);
//2. Create a NaN filled matrix for obstacles loses
_rfid_belief_maps.add("obst_losses",NAN);
// iterate over four lines to fill obst_losses layer ...................
// line 1: (0,0) to (0,M)
i00 =grid_map::Index(0,0);
i0M =grid_map::Index(0,_Ncol-1);
_rfid_belief_maps.getIndex(Position( x_m, y_m), iRobot);
addLossesTillEdgeLine(i00, i0M, iRobot );
// line 2: (0,M) to (N,M)
iNM =grid_map::Index(_Nrow-1,_Ncol-1);
addLossesTillEdgeLine(i0M, iNM, iRobot );
// line 3: (N,M) to (N,0)
iN0 =grid_map::Index(_Nrow-1,0);
addLossesTillEdgeLine(iNM, iN0, iRobot );
// line 4: (N,0) to (0,0)
addLossesTillEdgeLine(iN0, i00, iRobot );
// And finally add obstacle losses and propagation losses
rxPower = rxPower - _rfid_belief_maps.get("obst_losses");
//std::cout << "Still running at line: " << __LINE__<< std::endl;
// this should remove points where received power is too low
rxPower = (rxPower.array()>SENSITIVITY).select(rxPower,SENSITIVITY);
// mfc trick used to see temp matrixes as images
//_rfid_belief_maps.add("obst_losses",rxPower);
return rxPower;
}
void RadarModel::addLossesTillEdgeLine(Index edge_index_start, Index edge_index_end, Index antenna_index){
Index edge_index;
double obst_loss_ray, obst_cell_inc;
// Each "wall" adds around 3dB losses. A wall is ~15cm thick, then each cell adds (3 * resolution / 0.15) dB losses
obst_cell_inc = 20.0 * _resolution; // db
// move along the map edge defined by those two indexes
for (grid_map::LineIterator edge_iterator(_rfid_belief_maps, edge_index_start, edge_index_end); !edge_iterator.isPastEnd(); ++edge_iterator) {
edge_index = *edge_iterator;
// - initializate cummulated losses to 0.
obst_loss_ray = 0;
//Now iterate from xm,ym to the point xi,yi in the edge
for (grid_map::LineIterator loss_ray_iterator(_rfid_belief_maps, antenna_index, edge_index); !loss_ray_iterator.isPastEnd(); ++loss_ray_iterator) {
// if the cell is obstacle, add L to cummulated_L
if (( _rfid_belief_maps.at("ref_map", *loss_ray_iterator) != _free_space_val )){
obst_loss_ray += obst_cell_inc;
}
// obstacles losses in cell is cummulated_L. Avoid multiple edits
if (( _rfid_belief_maps.at("obst_losses", *loss_ray_iterator) != NAN )){
_rfid_belief_maps.at("obst_losses", *loss_ray_iterator) = obst_loss_ray;
}
}
}
}
Eigen::MatrixXf RadarModel::getPhaseMat(double x_m, double y_m, double orientation_deg, double freq){
Eigen::MatrixXf rxPh_mat;
double tag_x, tag_y, tag_r, tag_h, rxPh;
Position glob_point;
Index ind;
Size siz = _rfid_belief_maps.getSize();
rxPh_mat = Eigen::MatrixXf(siz(0), siz(1));
double orientation_rad = orientation_deg * M_PI / 180.0;
// Obtain rel dist and to all points
// MFC: can I turn this iteration into matrix operations?
for (grid_map::GridMapIterator iterator(_rfid_belief_maps);
!iterator.isPastEnd(); ++iterator) {
// matrix indexes...
ind = *iterator;
// get cell center of the cell in the map frame.
_rfid_belief_maps.getPosition(ind, glob_point);
// that is where the tag supposedly is in map coordinates
tag_x = glob_point.x();
tag_y = glob_point.y();
// now get robot - tag relative pose!
double delta_x = (tag_x - x_m);
double delta_y = (tag_y - y_m);
// rotate
tag_x = delta_x * cos(orientation_rad) + delta_y * sin(orientation_rad);
tag_y = -delta_x * sin(orientation_rad) + delta_y * cos(orientation_rad);
getSphericCoords(tag_x, tag_y, tag_r, tag_h);
rxPh = phaseDifference(tag_r, tag_h, freq);
rxPh_mat(ind(0), ind(1)) = rxPh;
}
return rxPh_mat;
}
void RadarModel::getImage(std::string layerName, std::string fileURI){
//std::cout << "Still running at line: " << __LINE__<< std::endl;
getImage(&_rfid_belief_maps, layerName, fileURI);
}
void RadarModel::getImage(GridMap* gm,std::string layerName, std::string fileURI){
// Convert to image.
cv::Mat image = layerToImage(gm, layerName);
cv::imwrite( fileURI, image );
}
double RadarModel::getTotalWeight(int tag_i) {
return getTotalWeight((_Ncol - 1) * (_resolution / 2.0),
(_Nrow - 1) * (_resolution / 2.0), 0,
_Ncol * _resolution, _Nrow * _resolution, tag_i);
}
double RadarModel::getTotalWeight(double x, double y, double orientation,
double size_x, double size_y, int tag_i) {
// TODO: I'm not using the orientation. Maybe it would be better to use a
// polygon iterator,
// so we can rotate edges around the center and have a more flexible thing
// submapStartIndex the start index of the submap, typically top-left index.
grid_map::Index submapStartIndex, submapEndIndex, submapBufferSize;
grid_map::Position submapStartPosition(x + (size_x / 2), y + (size_y / 2));
grid_map::Position submapEndPosition(x - (size_x / 2), y - (size_y / 2));
if (!_rfid_belief_maps.getIndex(submapStartPosition, submapStartIndex)) {
submapStartIndex = grid_map::Index(0, 0);
// std::cout<<"Clip start!" << std::endl;
}
if (!_rfid_belief_maps.getIndex(submapEndPosition, submapEndIndex)) {
Size siz = _rfid_belief_maps.getSize();
submapEndIndex = grid_map::Index(siz(0) - 1, siz(1) - 1);
// std::cout<<"Clip end!" << std::endl;
}
submapBufferSize = submapEndIndex - submapStartIndex;
grid_map::SubmapIterator iterator(_rfid_belief_maps, submapStartIndex,
submapBufferSize);
// std::cout<<"\nGet prob.:" << std::endl;
// std::cout<<" Centered at Position (" << x << ", " << y << ") m. / Size ("
// << size_x << ", " << size_y << ")" << std::endl; std::cout<<" Start pose ("
// << submapStartPosition(0) << ", " << submapStartPosition(1) << ") m. to
// pose " << submapEndPosition(0) << ", " << submapEndPosition(1) << ") m."<<
// std::endl; std::cout<<" Start Cell (" << submapStartIndex(0) << ", " <<
// submapStartIndex(1) << ") to cell(" << submapEndIndex(0) << ", " <<
// submapEndIndex(1) << ")"<< std::endl;
return getTotalWeight(x, y, orientation, iterator, tag_i);
}
double RadarModel::getTotalWeight(double x, double y, double orientation,
grid_map::SubmapIterator iterator,
int tag_i) {
double total_weight;
Position point;
std::string tagLayerName = getTagLayerName(tag_i);
total_weight = 0;
for (iterator; !iterator.isPastEnd(); ++iterator) {
_rfid_belief_maps.getPosition(*iterator, point);
// check if is inside global map
if (_rfid_belief_maps.isInside(point)) {
// We don't add belief from positions considered obstacles...
if (_rfid_belief_maps.atPosition("ref_map", point) == _free_space_val) {
total_weight += _rfid_belief_maps.atPosition(tagLayerName, point);
}
}
}
return total_weight;
}
void RadarModel::getImageDebug(GridMap *gm, std::string layerName,
std::string fileURI) {
// plots circles in the edges of the corresponding layer
// Convert to image.
cv::Mat image = layerToImage(gm, layerName);
cv::Scalar green( 0, 255, 0 );
cv::Scalar blue( 255, 0, 0 );
cv::Scalar red( 0, 0, 255 );
cv::Scalar yellow( 0, 255, 255 );
grid_map::Index index;
double maxX = (*gm).getLength().x() / 2;
double maxY = (*gm).getLength().y() / 2;
grid_map::Position p(maxX, maxY);
(*gm).getIndex(p, index);
cv::Point gree(index.x(), index.x());
std::cout << "Green: (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
p = Position(maxX, -maxY);
(*gm).getIndex(p, index);
cv::Point blu(index.y(), index.x());
std::cout << "Blue (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
p = Position(-maxX, -maxY);
(*gm).getIndex(p, index);
cv::Point re(index.y(), index.x());
std::cout << "Red (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
p = Position(-maxX, maxY);
(*gm).getIndex(p, index);
cv::Point yell(index.y(), index.x());
std::cout << "Yellow (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
cv::circle(image, gree, 20, green, -1);
cv::circle(image, blu, 20, blue, -1);
cv::circle(image, re, 20, red, -1);
cv::circle(image, yell, 20, yellow, -1);
cv::Point triang_points[1][3];
double h = 0.2;
p = Position(h / 2.0, 0);
(*gm).getIndex(p, index);
triang_points[0][0] = cv::Point(index.y(), index.x());
std::cout << "p (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
p = Position(-h / 2.0, -h / 2.0);
(*gm).getIndex(p, index);
triang_points[0][1] = cv::Point(index.y(), index.x());
std::cout << "p (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
p = Position(-h / 2.0, h / 2.0);
(*gm).getIndex(p, index);
triang_points[0][2] = cv::Point(index.y(), index.x());
std::cout << "p (" << p(0) << ", " << p(1) << ") m. == Cell(" << index(0)
<< ", " << index(1) << ")" << std::endl;
const cv::Point *ppt[1] = {triang_points[0]};
int npt[] = {3};
cv::fillPoly(image, ppt, npt, 1, red, 8);
// Rotate 90 Degrees Clockwise To get our images to have increasing X to right
// and increasing Y up
cv::transpose(image, image);
cv::flip(image, image, 1);
cv::imwrite(fileURI, image);
}
std::string RadarModel::getPowLayerName(double freq_i) {
return "P_" + getLayerName(freq_i / 1e6);
}
std::string RadarModel::getPhaseLayerName(double freq_i) {
return "D_" + getLayerName(freq_i / 1e6);
}
std::string RadarModel::getTagLayerName(int tag_num) {
return std::to_string(tag_num);
}
std::string RadarModel::getLayerName(double x) {
// Create an output string stream
std::ostringstream streamObj3;
// Set Fixed -Point Notation
streamObj3 << std::fixed;
// Set precision to 2 digits
streamObj3 << std::setprecision(2);
// Add double to stream
streamObj3 << x;
// Get string from output string stream
std::string strObj3 = streamObj3.str();
return strObj3;
}
cv::Point RadarModel::getPoint(double x_m, double y_m) {
Length mlen = _rfid_belief_maps.getLength();
grid_map::Position orig = _rfid_belief_maps.getPosition();
double min_x = orig(0) - mlen(0) / 2 + _resolution;
double max_x = orig(0) + mlen(0) / 2 - _resolution;
double min_y = orig(1) - mlen(1) / 2 + _resolution;
double max_y = orig(1) + mlen(1) / 2 - _resolution;
grid_map::Index index;
grid_map::Position p(x_m, y_m);
if (!_rfid_belief_maps.getIndex(p, index)) {
// std::cout<<" Position (" << p(0) << ", " << p(1) << ") is out of
// _rfid_belief_maps bounds!!" <<std::endl;
x_m = std::min(std::max(x_m, min_x), max_x);
y_m = std::min(std::max(y_m, min_y), max_y);
p = grid_map::Position(x_m, y_m);
_rfid_belief_maps.getIndex(p, index);
}
// cast from gridmap indexes to opencv indexes
int cv_y = (_Nrow - 1) - index.x();
int cv_x = (_Ncol - 1) - index.y();
// std::cout<<"Which equals to opencv cell (" << cv_x << ", " << cv_y << ") "
// << std::endl;
return cv::Point(cv_x, cv_y);
}
void RadarModel::getSphericCoords(double x, double y, double &r, double &phi) {
r = sqrt(x * x + y * y);
phi = atan2(y, x);
}
////////////////////////// Print and visualization
///////////////////////////////////////////////////////
void RadarModel::PrintRecPower(std::string fileURI, double f_i){
PrintRecPower(fileURI, 0,0,0, f_i);
}
void RadarModel::PrintRecPower(std::string fileURI,double x_m, double y_m, double orientation_deg, double f_i){
// create a copy of the average values
//std::cout << "Still running at line: " << __LINE__<< std::endl;
Eigen::MatrixXf av_mat = getFriisMat(x_m, y_m, orientation_deg, f_i);
//std::cout << "Still running at line: " << __LINE__<< std::endl;
PrintProb(fileURI, &av_mat);
//std::cout << "Still running at line: " << __LINE__<< std::endl;
}
void RadarModel::PrintPhase(std::string fileURI, double f_i){
PrintPhase(fileURI, 0,0,0, f_i);
}
void RadarModel::PrintPhase(std::string fileURI,double x_m, double y_m, double orientation_deg, double f_i){
// create a copy of the average values
Eigen::MatrixXf av_mat = getPhaseMat(x_m, y_m, orientation_deg, f_i);
PrintProb(fileURI, &av_mat);
}
void RadarModel::PrintPowProb(std::string fileURI, double rxPw, double x_m, double y_m, double orientation_deg, double f_i){
Eigen::MatrixXf prob_mat = getPowProbCond(rxPw, x_m, y_m, orientation_deg, f_i);
PrintProb(fileURI, &prob_mat);
}
void RadarModel::PrintPowProb(std::string fileURI, double rxPw, double f_i){
PrintPowProb(fileURI, rxPw, 0,0,0, f_i);
}
void RadarModel::PrintPhaseProb(std::string fileURI, double phi, double f_i){
PrintPhaseProb(fileURI, phi, 0, 0, 0, f_i);
}
void RadarModel::PrintPhaseProb(std::string fileURI, double phi, double x_m, double y_m, double orientation_deg, double f_i){
Eigen::MatrixXf prob_mat = getPhaseProbCond(phi, x_m, y_m, orientation_deg, f_i);
PrintProb(fileURI, &prob_mat);
}
void RadarModel::PrintBothProb(std::string fileURI, double rxPw, double phi, double f_i){
PrintBothProb(fileURI, rxPw, phi, 0,0,0, f_i);
}
void RadarModel::PrintBothProb(std::string fileURI, double rxPw, double phi, double x_m, double y_m, double orientation_deg, double f_i){
Eigen::MatrixXf prob_mat = getPowProbCond(rxPw, x_m, y_m, orientation_deg, f_i).cwiseProduct(getPhaseProbCond(phi, x_m, y_m, orientation_deg, f_i));
prob_mat = prob_mat/prob_mat.sum();
PrintProb(fileURI, &prob_mat);
}
void RadarModel::PrintProb(std::string fileURI, Eigen::MatrixXf *prob_mat) {
PrintProb(fileURI, prob_mat, prob_mat->rows(), prob_mat->cols(), _resolution);
}
void RadarModel::PrintProb(std::string fileURI, Eigen::MatrixXf* prob_mat, double sX, double sY, double res){
GridMap tempMap;
tempMap.setGeometry(Length(sX, sY), res);
tempMap.add("res", *prob_mat);
getImage(&tempMap, "res", fileURI);
}
void RadarModel::PrintRefMapWithTags(std::string fileURI) {
std::vector<std::pair<cv::Scalar, std::string>> color_list;
// Some color ...
cv::Scalar red(0, 0, 255);
color_list.push_back(std::make_pair(red, "red"));
cv::Scalar green(0, 255, 0);
color_list.push_back(std::make_pair(green, "green"));
cv::Scalar blue(255, 0, 0);
color_list.push_back(std::make_pair(blue, "blue"));
cv::Scalar yellow(0, 255, 255);
color_list.push_back(std::make_pair(yellow, "yellow"));
cv::Scalar blueviolet(226, 138, 43);
color_list.push_back(std::make_pair(blueviolet, "blueviolet"));
cv::Scalar turquoise(224, 208, 64);
color_list.push_back(std::make_pair(turquoise, "turquoise"));
cv::Scalar orange(165, 0, 255);
color_list.push_back(std::make_pair(orange, "orange"));
cv::Scalar pink(192, 203, 255);
color_list.push_back(std::make_pair(pink, "pink"));
cv::Scalar chocolate(105, 30, 210);
color_list.push_back(std::make_pair(chocolate, "chocolate"));
cv::Scalar dodgerblue(144, 255, 30);
color_list.push_back(std::make_pair(dodgerblue, "dodgerblue"));
// Convert to image.
cv::Mat image = rfidBeliefToCVImg("ref_map");
cv::Point center;
for (int i = 0; i < _tags_coords.size(); i++) {
double x = _tags_coords[i].first;
double y = _tags_coords[i].second;
center = getPoint(x, y);
cv::circle(image, center, 5, color_list[i % color_list.size()].first, -1);
}
/// overlay active map edges
/// .............................................................................................
overlayMapEdges(image);
cv::imwrite(fileURI, image);
}
void RadarModel::overlayMapEdges(cv::Mat image) {
cv::Point square_points[1][4];
cv::Scalar red(0, 255, 255);
int cv_y, cv_x;
cv_y = (_Nrow - 1);
cv_x = (_Ncol - 1);
square_points[0][0] = cv::Point(0, 0);
square_points[0][1] = cv::Point(0, cv_y);
square_points[0][2] = cv::Point(cv_x, cv_y);
square_points[0][3] = cv::Point(cv_x, 0);
const cv::Point *pts[1] = {square_points[0]};
int npts[] = {4};
cv::polylines(image, pts, npts, 1, true, red);
}
void RadarModel::overlayRobotPoseT(double robot_x, double robot_y,
double robot_head, cv::Mat &image) {
grid_map::Index index;
cv::Point center;
grid_map::Position p;
cv::Point pentag_points[1][5];
cv::Scalar red(0, 0, 255);
center = getPoint(robot_x, robot_y);
// create a pentagone pointing x+
int h = 4; // pixels?
pentag_points[0][0] = cv::Point(center.x - h, center.y - h);
pentag_points[0][1] = cv::Point(center.x - h, center.y + h);
pentag_points[0][2] = cv::Point(center.x, center.y + 2 * h);
pentag_points[0][3] = cv::Point(center.x + h, center.y + h);
pentag_points[0][4] = cv::Point(center.x + h, center.y - h);
const cv::Point *pts[1] = {pentag_points[0]};
rotatePoints(pentag_points[0], 5, center.x, center.y, robot_head);
int npts[] = {5};
cv::fillPoly(image, pts, npts, 1, red, 8);
}
void RadarModel::overlayRobotPose(double robot_x, double robot_y,
double robot_head, cv::Mat &image) {
cv::Point center;
cv::Scalar red(0, 0, 255);
center = getPoint(robot_x, robot_y);
cv::circle(image, center, 5, red, -1);
}
void RadarModel::rotatePoints(cv::Point *points, int npts, int cxi, int cyi,
double ang) {
double offsetx, offsety, cx, cy, px, py, cosA, sinA;
cx = (double)cxi;
cy = (double)cyi;
cosA = cos(ang);
sinA = sin(ang);
for (int i = 0; i < npts; i++) {
px = points[i].x;
py = points[i].y;
offsetx = (cosA * (px - cx)) + (sinA * (py - cy));
offsety = -(sinA * (px - cx)) + (cosA * (py - cy));
points[i].x = ((int)offsetx) + cxi;
points[i].y = ((int)offsety) + cyi;
}
}
cv::Mat RadarModel::rfidBeliefToCVImg(std::string layer_i){
return layerToImage(&_rfid_belief_maps,layer_i);
}
cv::Mat RadarModel::layerToImage(GridMap* gm,std::string layerName){
cv::Mat image;
const float minValue = (*gm)[layerName].minCoeff();
const float maxValue = (*gm)[layerName].maxCoeff();
GridMapCvConverter::toImage<unsigned char, 3>(*gm, layerName, CV_8UC3, minValue, maxValue, image);
cv::flip(image, image, -1);
return image;
}
grid_map::Position RadarModel::fromPoint(cv::Point cvp) {
grid_map::Position p;
int gm_x, gm_y;
// cast from opencv indexes to gridmap indexes
gm_x = (_Nrow - 1) - cvp.y;
gm_y = (_Ncol - 1) - cvp.x;
grid_map::Index index(gm_x, gm_y);
if (!_rfid_belief_maps.getPosition(index, p)) {
// std::cout<<" Index (" << index(0) << ", " << index(1) << ") is out of
// _rfid_belief_maps bounds!!" <<std::endl;
gm_x = std::min(std::max(gm_x, 0), _Nrow - 1);
gm_y = std::min(std::max(gm_y, 0), _Ncol - 1);
index = grid_map::Index(gm_x, gm_y);
_rfid_belief_maps.getPosition(index, p);
}
return p;
}
//////////////////////////// Other functions ////////////////////////////
void RadarModel::debugInfo() {
std::cout << ".................." << std::endl;
Length mlen = _rfid_belief_maps.getLength();
std::cout << "RFID belief area is: " << mlen(0) << " by " << mlen(1)
<< " m. (x,y)" << std::endl;
std::cout << "Resolution is: " << _resolution << " m. /cell" << std::endl;
std::cout << "RFID belief grid is: " << _rfid_belief_maps.getSize()(0)
<< " by " << _rfid_belief_maps.getSize()(1) << " cells (i,j axis)"
<< std::endl;
std::cout << ". " << std::endl;
std::cout << "Total grid Map is: " << _Ncol << " by " << _Nrow
<< " cells (i,j axis)" << std::endl;
std::cout << ".................." << std::endl;
}
void RadarModel::saveProbMapDebug(std::string savePATH, int tag_num, int step,
double robot_x, double robot_y,
double robot_head) {
char buffer[10];
int n;
std::string fileURI = savePATH + "T";
n = sprintf(buffer, "%01d", tag_num);
fileURI += std::string(buffer) + "_S";
n = sprintf(buffer, "%03d", step);
fileURI += std::string(buffer) + "_tempMap.png";
std::string layerName = getTagLayerName(tag_num);
// Some color ...
cv::Scalar green(0, 255, 0);
// Convert to image.
cv::Mat image = rfidBeliefToCVImg(layerName);
cv::Point tag_center;
/// overlay tag position
/// .................................................................................................
double tx = _tags_coords[tag_num].first;
double ty = _tags_coords[tag_num].second;
tag_center = getPoint(tx, ty);
cv::circle(image, tag_center, 5, green, 1);
/// overlay robot position
/// .................................................................................................
overlayRobotPoseT(robot_x, robot_y, robot_head, image);
// and save
cv::imwrite( fileURI, image );
// mfc trick used to see temp matrixes as images
// add on ......................................................................................................
// if (_rfid_belief_maps.exists("obst_losses")){
// image = rfidBeliefToCVImg("obst_losses");
// // overlay tag position
// cv::circle(image, tag_center , 5, green, 1);
// // overlay robot position
// overlayRobotPoseT(robot_x, robot_y, robot_head, image);
// fileURI = savePATH + "T";
// n=sprintf (buffer, "%01d", tag_num);
// fileURI += std::string(buffer) +"_rxPower_S";
// n=sprintf (buffer, "%03d", step);
// fileURI += std::string(buffer)+ ".png";
// cv::imwrite( fileURI, image );
// }
}
void RadarModel::clearObstacles(cv::Mat &image) {
// MFC this method does not work .... dont use it!
int b = 0;
int a = 1 / b;
//////////////////////////////////
cv::Vec<unsigned char, 3> red = {0, 0, 255};
// Initialize result image.
cv::Mat result = image.clone().setTo(cv::Scalar(255, 255, 255));
// Convert to image.
cv::Mat ref_img = rfidBeliefToCVImg("ref_map");
uint8_t ref_val;
// Copy pixels from background to result image, where pixel in mask is 0.
for (int x = 0; x < image.size().width; x++) {
for (int y = 0; y < image.size().height; y++) {
ref_val = ref_img.at<uint8_t>(y, x);
if (ref_val == 0) {
result.at<cv::Vec3b>(y, x) = red;
} else {
result.at<cv::Vec3b>(y, x) = image.at<cv::Vec3b>(y, x);
}
if ((ref_val != 0) && (ref_val != 255)) {
std::cout << "Map image NOT BINARY AT (" << x << ", " << y
<< ") = " << ref_val << std::endl;
}
}
}
// there you go ...
image = result;
// std::cout<<"Map image (" << ref_img.size().width << ", "
// <<ref_img.size().height<<") pixels" <<std::endl; std::cout<<"Out image ("
// << image.size().width << ", " <<image.size().height<<") pixels"
// <<std::endl; and save
cv::imwrite("/tmp/refMap.png", ref_img);
// cv::Mat rgba;
// // First create the image with alpha channel
// cv::cvtColor(image, rgba , cv::cv::COLOR_GRAY2RGBA);
// // Split the image for access to alpha channel
// std::vector<cv::Mat>channels(4);
// cv::split(rgba, channels);