-
Notifications
You must be signed in to change notification settings - Fork 895
/
ros_filter.cpp
3367 lines (2921 loc) · 143 KB
/
ros_filter.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 (c) 2014, 2015, 2016, Charles River Analytics, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "robot_localization/ros_filter.h"
#include "robot_localization/filter_utilities.h"
#include "robot_localization/ekf.h"
#include "robot_localization/ukf.h"
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <limits>
#if defined(_WIN32) && defined(ERROR)
#undef ERROR
#endif
namespace RobotLocalization
{
template<typename T>
RosFilter<T>::RosFilter(ros::NodeHandle nh,
ros::NodeHandle nh_priv,
std::string node_name,
std::vector<double> args) :
disabledAtStartup_(false),
enabled_(false),
invertTransform_(false),
predictToCurrentTime_(false),
printDiagnostics_(true),
publishAcceleration_(false),
publishTransform_(true),
resetOnTimeJump_(false),
smoothLaggedData_(false),
toggledOn_(true),
twoDMode_(false),
useControl_(false),
dynamicDiagErrorLevel_(diagnostic_msgs::DiagnosticStatus::OK),
staticDiagErrorLevel_(diagnostic_msgs::DiagnosticStatus::OK),
frequency_(30.0),
gravitationalAcc_(9.80665),
historyLength_(0),
minFrequency_(frequency_ - 2.0),
maxFrequency_(frequency_ + 2.0),
baseLinkFrameId_("base_link"),
mapFrameId_("map"),
odomFrameId_("odom"),
worldFrameId_(odomFrameId_),
lastDiagTime_(0),
lastSetPoseTime_(0),
latestControlTime_(0),
tfTimeOffset_(ros::Duration(0)),
tfTimeout_(ros::Duration(0)),
filter_(args),
nh_(nh),
nhLocal_(nh_priv),
diagnosticUpdater_(nh, nh_priv, node_name),
tfListener_(tfBuffer_)
{
stateVariableNames_.push_back("X");
stateVariableNames_.push_back("Y");
stateVariableNames_.push_back("Z");
stateVariableNames_.push_back("ROLL");
stateVariableNames_.push_back("PITCH");
stateVariableNames_.push_back("YAW");
stateVariableNames_.push_back("X_VELOCITY");
stateVariableNames_.push_back("Y_VELOCITY");
stateVariableNames_.push_back("Z_VELOCITY");
stateVariableNames_.push_back("ROLL_VELOCITY");
stateVariableNames_.push_back("PITCH_VELOCITY");
stateVariableNames_.push_back("YAW_VELOCITY");
stateVariableNames_.push_back("X_ACCELERATION");
stateVariableNames_.push_back("Y_ACCELERATION");
stateVariableNames_.push_back("Z_ACCELERATION");
diagnosticUpdater_.setHardwareID("none");
}
template<typename T>
RosFilter<T>::RosFilter(ros::NodeHandle nh, ros::NodeHandle nh_priv, std::vector<double> args) :
RosFilter<T>::RosFilter(nh, nh_priv, ros::this_node::getName(), args)
{}
template<typename T>
RosFilter<T>::~RosFilter()
{
topicSubs_.clear();
}
template<typename T>
void RosFilter<T>::initialize()
{
loadParams();
if (printDiagnostics_)
{
diagnosticUpdater_.add("Filter diagnostic updater", this, &RosFilter<T>::aggregateDiagnostics);
}
// Set up the frequency diagnostic
minFrequency_ = frequency_ - 2;
maxFrequency_ = frequency_ + 2;
freqDiag_ = std::make_unique<diagnostic_updater::HeaderlessTopicDiagnostic>(
"odometry/filtered",
diagnosticUpdater_,
diagnostic_updater::FrequencyStatusParam(
&minFrequency_,
&maxFrequency_,
0.1,
10));
// Publisher
positionPub_ = nh_.advertise<nav_msgs::Odometry>("odometry/filtered", 20);
// Optional acceleration publisher
if (publishAcceleration_)
{
accelPub_ = nh_.advertise<geometry_msgs::AccelWithCovarianceStamped>("accel/filtered", 20);
}
lastDiagTime_ = ros::Time::now();
periodicUpdateTimer_ = nh_.createTimer(ros::Duration(1./frequency_), &RosFilter<T>::periodicUpdate, this);
}
template<typename T>
void RosFilter<T>::reset()
{
// Get rid of any initial poses (pretend we've never had a measurement)
initialMeasurements_.clear();
previousMeasurements_.clear();
previousMeasurementCovariances_.clear();
clearMeasurementQueue();
filterStateHistory_.clear();
measurementHistory_.clear();
// Also set the last set pose time, so we ignore all messages
// that occur before it
lastSetPoseTime_ = ros::Time(0);
// clear tf buffer to avoid TF_OLD_DATA errors
tfBuffer_.clear();
// clear last message timestamp, so older messages will be accepted
lastMessageTimes_.clear();
// reset filter to uninitialized state
filter_.reset();
// clear all waiting callbacks
ros::getGlobalCallbackQueue()->clear();
}
template<typename T>
bool RosFilter<T>::toggleFilterProcessingCallback(robot_localization::ToggleFilterProcessing::Request& req,
robot_localization::ToggleFilterProcessing::Response& resp)
{
if (req.on == toggledOn_)
{
ROS_WARN_STREAM("Service was called to toggle filter processing but state was already as requested.");
resp.status = false;
}
else
{
ROS_INFO("Toggling filter measurement filtering to %s.", req.on ? "On" : "Off");
toggledOn_ = req.on;
resp.status = true;
}
return true;
}
// @todo: Replace with AccelWithCovarianceStamped
template<typename T>
void RosFilter<T>::accelerationCallback(const sensor_msgs::Imu::ConstPtr &msg, const CallbackData &callbackData,
const std::string &targetFrame)
{
// If we've just reset the filter, then we want to ignore any messages
// that arrive with an older timestamp
if (msg->header.stamp <= lastSetPoseTime_)
{
return;
}
const std::string &topicName = callbackData.topicName_;
RF_DEBUG("------ RosFilter::accelerationCallback (" << topicName << ") ------\n"
"Twist message:\n" << *msg);
if (lastMessageTimes_.count(topicName) == 0)
{
lastMessageTimes_.insert(std::pair<std::string, ros::Time>(topicName, msg->header.stamp));
}
// Make sure this message is newer than the last one
if (msg->header.stamp >= lastMessageTimes_[topicName])
{
RF_DEBUG("Update vector for " << topicName << " is:\n" << topicName);
Eigen::VectorXd measurement(STATE_SIZE);
Eigen::MatrixXd measurementCovariance(STATE_SIZE, STATE_SIZE);
measurement.setZero();
measurementCovariance.setZero();
// Make sure we're actually updating at least one of these variables
std::vector<int> updateVectorCorrected = callbackData.updateVector_;
// Prepare the twist data for inclusion in the filter
if (prepareAcceleration(msg, topicName, targetFrame, callbackData.relative_, updateVectorCorrected, measurement,
measurementCovariance))
{
// Store the measurement. Add an "acceleration" suffix so we know what kind of measurement
// we're dealing with when we debug the core filter logic.
enqueueMeasurement(topicName,
measurement,
measurementCovariance,
updateVectorCorrected,
callbackData.rejectionThreshold_,
msg->header.stamp);
RF_DEBUG("Enqueued new measurement for " << topicName << "_acceleration\n");
}
else
{
RF_DEBUG("Did *not* enqueue measurement for " << topicName << "_acceleration\n");
}
lastMessageTimes_[topicName] = msg->header.stamp;
RF_DEBUG("Last message time for " << topicName << " is now " <<
lastMessageTimes_[topicName] << "\n");
}
else if (resetOnTimeJump_ && ros::Time::isSimTime())
{
reset();
}
else
{
std::stringstream stream;
stream << "The " << topicName << " message has a timestamp before that of the previous message received," <<
" this message will be ignored. This may indicate a bad timestamp. (message time: " <<
msg->header.stamp.toSec() << ")";
addDiagnostic(diagnostic_msgs::DiagnosticStatus::WARN,
topicName + "_timestamp",
stream.str(),
false);
RF_DEBUG("Message is too old. Last message time for " << topicName <<
" is " << lastMessageTimes_[topicName] << ", current message time is " <<
msg->header.stamp << ".\n");
}
RF_DEBUG("\n----- /RosFilter::accelerationCallback (" << topicName << ") ------\n");
}
template<typename T>
void RosFilter<T>::controlCallback(const geometry_msgs::Twist::ConstPtr &msg)
{
geometry_msgs::TwistStampedPtr twistStampedPtr = geometry_msgs::TwistStampedPtr(new geometry_msgs::TwistStamped());
twistStampedPtr->twist = *msg;
twistStampedPtr->header.frame_id = baseLinkFrameId_;
twistStampedPtr->header.stamp = ros::Time::now();
controlCallback(twistStampedPtr);
}
template<typename T>
void RosFilter<T>::controlCallback(const geometry_msgs::TwistStamped::ConstPtr &msg)
{
if (msg->header.frame_id == baseLinkFrameId_ || msg->header.frame_id == "")
{
latestControl_(ControlMemberVx) = msg->twist.linear.x;
latestControl_(ControlMemberVy) = msg->twist.linear.y;
latestControl_(ControlMemberVz) = msg->twist.linear.z;
latestControl_(ControlMemberVroll) = msg->twist.angular.x;
latestControl_(ControlMemberVpitch) = msg->twist.angular.y;
latestControl_(ControlMemberVyaw) = msg->twist.angular.z;
latestControlTime_ = msg->header.stamp;
// Update the filter with this control term
filter_.setControl(latestControl_, msg->header.stamp.toSec());
}
else
{
ROS_WARN_STREAM_THROTTLE(5.0, "Commanded velocities must be given in the robot's body frame (" <<
baseLinkFrameId_ << "). Message frame was " << msg->header.frame_id);
}
}
template<typename T>
void RosFilter<T>::enqueueMeasurement(const std::string &topicName,
const Eigen::VectorXd &measurement,
const Eigen::MatrixXd &measurementCovariance,
const std::vector<int> &updateVector,
const double mahalanobisThresh,
const ros::Time &time)
{
MeasurementPtr meas = MeasurementPtr(new Measurement());
meas->topicName_ = topicName;
meas->measurement_ = measurement;
meas->covariance_ = measurementCovariance;
meas->updateVector_ = updateVector;
meas->time_ = time.toSec();
meas->mahalanobisThresh_ = mahalanobisThresh;
meas->latestControl_ = latestControl_;
meas->latestControlTime_ = latestControlTime_.toSec();
measurementQueue_.push(meas);
}
template<typename T>
void RosFilter<T>::forceTwoD(Eigen::VectorXd &measurement,
Eigen::MatrixXd &measurementCovariance,
std::vector<int> &updateVector)
{
measurement(StateMemberZ) = 0.0;
measurement(StateMemberRoll) = 0.0;
measurement(StateMemberPitch) = 0.0;
measurement(StateMemberVz) = 0.0;
measurement(StateMemberVroll) = 0.0;
measurement(StateMemberVpitch) = 0.0;
measurement(StateMemberAz) = 0.0;
measurementCovariance(StateMemberZ, StateMemberZ) = 1e-6;
measurementCovariance(StateMemberRoll, StateMemberRoll) = 1e-6;
measurementCovariance(StateMemberPitch, StateMemberPitch) = 1e-6;
measurementCovariance(StateMemberVz, StateMemberVz) = 1e-6;
measurementCovariance(StateMemberVroll, StateMemberVroll) = 1e-6;
measurementCovariance(StateMemberVpitch, StateMemberVpitch) = 1e-6;
measurementCovariance(StateMemberAz, StateMemberAz) = 1e-6;
updateVector[StateMemberZ] = 1;
updateVector[StateMemberRoll] = 1;
updateVector[StateMemberPitch] = 1;
updateVector[StateMemberVz] = 1;
updateVector[StateMemberVroll] = 1;
updateVector[StateMemberVpitch] = 1;
updateVector[StateMemberAz] = 1;
}
template<typename T>
bool RosFilter<T>::getFilteredOdometryMessage(nav_msgs::Odometry &message)
{
// If the filter has received a measurement at some point...
if (filter_.getInitializedStatus())
{
// Grab our current state and covariance estimates
const Eigen::VectorXd &state = filter_.getState();
const Eigen::MatrixXd &estimateErrorCovariance = filter_.getEstimateErrorCovariance();
// Convert from roll, pitch, and yaw back to quaternion for
// orientation values
tf2::Quaternion quat;
quat.setRPY(state(StateMemberRoll), state(StateMemberPitch), state(StateMemberYaw));
// Fill out the message
message.pose.pose.position.x = state(StateMemberX);
message.pose.pose.position.y = state(StateMemberY);
message.pose.pose.position.z = state(StateMemberZ);
message.pose.pose.orientation.x = quat.x();
message.pose.pose.orientation.y = quat.y();
message.pose.pose.orientation.z = quat.z();
message.pose.pose.orientation.w = quat.w();
message.twist.twist.linear.x = state(StateMemberVx);
message.twist.twist.linear.y = state(StateMemberVy);
message.twist.twist.linear.z = state(StateMemberVz);
message.twist.twist.angular.x = state(StateMemberVroll);
message.twist.twist.angular.y = state(StateMemberVpitch);
message.twist.twist.angular.z = state(StateMemberVyaw);
// Our covariance matrix layout doesn't quite match
for (size_t i = 0; i < POSE_SIZE; i++)
{
for (size_t j = 0; j < POSE_SIZE; j++)
{
message.pose.covariance[POSE_SIZE * i + j] = estimateErrorCovariance(i, j);
}
}
// POSE_SIZE and TWIST_SIZE are currently the same size, but we can spare a few
// cycles to be meticulous and not index a twist covariance array on the size of
// a pose covariance array
for (size_t i = 0; i < TWIST_SIZE; i++)
{
for (size_t j = 0; j < TWIST_SIZE; j++)
{
message.twist.covariance[TWIST_SIZE * i + j] =
estimateErrorCovariance(i + POSITION_V_OFFSET, j + POSITION_V_OFFSET);
}
}
message.header.stamp = ros::Time(filter_.getLastMeasurementTime());
message.header.frame_id = worldFrameId_;
message.child_frame_id = baseLinkOutputFrameId_;
}
return filter_.getInitializedStatus();
}
template<typename T>
bool RosFilter<T>::getFilteredAccelMessage(geometry_msgs::AccelWithCovarianceStamped &message)
{
// If the filter has received a measurement at some point...
if (filter_.getInitializedStatus())
{
// Grab our current state and covariance estimates
const Eigen::VectorXd &state = filter_.getState();
const Eigen::MatrixXd &estimateErrorCovariance = filter_.getEstimateErrorCovariance();
//! Fill out the accel_msg
message.accel.accel.linear.x = state(StateMemberAx);
message.accel.accel.linear.y = state(StateMemberAy);
message.accel.accel.linear.z = state(StateMemberAz);
message.accel.accel.angular.x = angular_acceleration_.x();
message.accel.accel.angular.y = angular_acceleration_.y();
message.accel.accel.angular.z = angular_acceleration_.z();
// Fill the covariance (only the left-upper matrix since we are not estimating
// the rotational accelerations arround the axes
for (size_t i = 0; i < ACCELERATION_SIZE; i++)
{
for (size_t j = 0; j < ACCELERATION_SIZE; j++)
{
// We use the POSE_SIZE since the accel cov matrix of ROS is 6x6
message.accel.covariance[POSE_SIZE * i + j] =
estimateErrorCovariance(i + POSITION_A_OFFSET, j + POSITION_A_OFFSET);
}
}
for (size_t i = ACCELERATION_SIZE; i < POSE_SIZE; i++)
{
for (size_t j = ACCELERATION_SIZE; j < POSE_SIZE; j++)
{
// fill out the angular portion. We assume the linear and angular portions are independent.
message.accel.covariance[POSE_SIZE * i + j] =
angular_acceleration_cov_(i - ACCELERATION_SIZE, j - ACCELERATION_SIZE);
}
}
// Fill header information
message.header.stamp = ros::Time(filter_.getLastMeasurementTime());
message.header.frame_id = baseLinkOutputFrameId_;
}
return filter_.getInitializedStatus();
}
template<typename T>
void RosFilter<T>::imuCallback(const sensor_msgs::Imu::ConstPtr &msg,
const std::string &topicName,
const CallbackData &poseCallbackData,
const CallbackData &twistCallbackData,
const CallbackData &accelCallbackData)
{
RF_DEBUG("------ RosFilter::imuCallback (" << topicName << ") ------\n" << "IMU message:\n" << *msg);
// If we've just reset the filter, then we want to ignore any messages
// that arrive with an older timestamp
if (msg->header.stamp <= lastSetPoseTime_)
{
std::stringstream stream;
stream << "The " << topicName << " message has a timestamp equal to or before the last filter reset, " <<
"this message will be ignored. This may indicate an empty or bad timestamp. (message time: " <<
msg->header.stamp.toSec() << ")";
addDiagnostic(diagnostic_msgs::DiagnosticStatus::WARN,
topicName + "_timestamp",
stream.str(),
false);
RF_DEBUG("Received message that preceded the most recent pose reset. Ignoring...");
return;
}
// As with the odometry message, we can separate out the pose- and twist-related variables
// in the IMU message and pass them to the pose and twist callbacks (filters)
if (poseCallbackData.updateSum_ > 0)
{
// Per the IMU message specification, if the IMU does not provide orientation,
// then its first covariance value should be set to -1, and we should ignore
// that portion of the message. robot_localization allows users to explicitly
// ignore data using its parameters, but we should also be compliant with
// message specs.
if (::fabs(msg->orientation_covariance[0] + 1) < 1e-9)
{
RF_DEBUG("Received IMU message with -1 as its first covariance value for orientation. "
"Ignoring orientation...");
}
else
{
// Extract the pose (orientation) data, pass it to its filter
geometry_msgs::PoseWithCovarianceStamped *posPtr = new geometry_msgs::PoseWithCovarianceStamped();
posPtr->header = msg->header;
posPtr->pose.pose.orientation = msg->orientation;
// Copy the covariance for roll, pitch, and yaw
for (size_t i = 0; i < ORIENTATION_SIZE; i++)
{
for (size_t j = 0; j < ORIENTATION_SIZE; j++)
{
posPtr->pose.covariance[POSE_SIZE * (i + ORIENTATION_SIZE) + (j + ORIENTATION_SIZE)] =
msg->orientation_covariance[ORIENTATION_SIZE * i + j];
}
}
// IMU data gets handled a bit differently, since the message is ambiguous and has only a single frame_id,
// even though the data in it is reported in two different frames. As we assume users will specify a base_link
// to imu transform, we make the target and child frame baseLinkFrameId_ and tell the poseCallback that it is
// working with IMU data. This will cause it to apply different logic to the data.
geometry_msgs::PoseWithCovarianceStampedConstPtr pptr(posPtr);
poseCallback(pptr, poseCallbackData, baseLinkFrameId_,
baseLinkFrameId_, true);
}
}
if (twistCallbackData.updateSum_ > 0)
{
// Ignore rotational velocity if the first covariance value is -1
if (::fabs(msg->angular_velocity_covariance[0] + 1) < 1e-9)
{
RF_DEBUG("Received IMU message with -1 as its first covariance value for angular "
"velocity. Ignoring angular velocity...");
}
else
{
// Repeat for velocity
geometry_msgs::TwistWithCovarianceStamped *twistPtr = new geometry_msgs::TwistWithCovarianceStamped();
twistPtr->header = msg->header;
twistPtr->twist.twist.angular = msg->angular_velocity;
// Copy the covariance
for (size_t i = 0; i < ORIENTATION_SIZE; i++)
{
for (size_t j = 0; j < ORIENTATION_SIZE; j++)
{
twistPtr->twist.covariance[TWIST_SIZE * (i + ORIENTATION_SIZE) + (j + ORIENTATION_SIZE)] =
msg->angular_velocity_covariance[ORIENTATION_SIZE * i + j];
}
}
geometry_msgs::TwistWithCovarianceStampedConstPtr tptr(twistPtr);
twistCallback(tptr, twistCallbackData, baseLinkFrameId_);
}
}
if (accelCallbackData.updateSum_ > 0)
{
// Ignore linear acceleration if the first covariance value is -1
if (::fabs(msg->linear_acceleration_covariance[0] + 1) < 1e-9)
{
RF_DEBUG("Received IMU message with -1 as its first covariance value for linear "
"acceleration. Ignoring linear acceleration...");
}
else
{
// Pass the message on
accelerationCallback(msg, accelCallbackData, baseLinkFrameId_);
}
}
RF_DEBUG("\n----- /RosFilter::imuCallback (" << topicName << ") ------\n");
}
template<typename T>
void RosFilter<T>::integrateMeasurements(const ros::Time ¤tTime)
{
const double currentTimeSec = currentTime.toSec();
RF_DEBUG("------ RosFilter::integrateMeasurements ------\n\n"
"Integration time is " << std::setprecision(20) << currentTimeSec << "\n"
<< measurementQueue_.size() << " measurements in queue.\n");
bool predictToCurrentTime = predictToCurrentTime_;
// If we have any measurements in the queue, process them
if (!measurementQueue_.empty())
{
// Check if the first measurement we're going to process is older than the filter's last measurement.
// This means we have received an out-of-sequence message (one with an old timestamp), and we need to
// revert both the filter state and measurement queue to the first state that preceded the time stamp
// of our first measurement.
const MeasurementPtr& firstMeasurement = measurementQueue_.top();
int restoredMeasurementCount = 0;
if (smoothLaggedData_ && firstMeasurement->time_ < filter_.getLastMeasurementTime())
{
RF_DEBUG("Received a measurement that was " << filter_.getLastMeasurementTime() - firstMeasurement->time_ <<
" seconds in the past. Reverting filter state and measurement queue...");
int originalCount = static_cast<int>(measurementQueue_.size());
const double firstMeasurementTime = firstMeasurement->time_;
const std::string firstMeasurementTopic = firstMeasurement->topicName_;
if (!revertTo(firstMeasurementTime - 1e-9)) // revertTo may invalidate firstMeasurement
{
RF_DEBUG("ERROR: history interval is too small to revert to time " << firstMeasurementTime << "\n");
ROS_WARN_STREAM_DELAYED_THROTTLE(historyLength_, "Received old measurement for topic " <<
firstMeasurementTopic << ", but history interval is insufficiently sized. Measurement time is " <<
std::setprecision(20) << firstMeasurementTime << ", current time is " << currentTime.toSec() <<
", history length is " << historyLength_ << ".");
restoredMeasurementCount = 0;
}
restoredMeasurementCount = static_cast<int>(measurementQueue_.size()) - originalCount;
}
while (!measurementQueue_.empty() && ros::ok())
{
MeasurementPtr measurement = measurementQueue_.top();
// If we've reached a measurement that has a time later than now, it should wait until a future iteration.
// Since measurements are stored in a priority queue, all remaining measurements will be in the future.
if (measurement->time_ > currentTime.toSec())
{
break;
}
measurementQueue_.pop();
// When we receive control messages, we call this directly in the control callback. However, we also associate
// a control with each sensor message so that we can support lagged smoothing. As we cannot guarantee that the
// new control callback will fire before a new measurement, we should only perform this operation if we are
// processing messages from the history. Otherwise, we may get a new measurement, store the "old" latest
// control, then receive a control, call setControl, and then overwrite that value with this one (i.e., with
// the "old" control we associated with the measurement).
if (useControl_ && restoredMeasurementCount > 0)
{
filter_.setControl(measurement->latestControl_, measurement->latestControlTime_);
restoredMeasurementCount--;
}
// This will call predict and, if necessary, correct
filter_.processMeasurement(*(measurement.get()));
// Store old states and measurements if we're smoothing
if (smoothLaggedData_)
{
// Invariant still holds: measurementHistoryDeque_.back().time_ < measurementQueue_.top().time_
measurementHistory_.push_back(measurement);
// We should only save the filter state once per unique timstamp
if (measurementQueue_.empty() ||
::fabs(measurementQueue_.top()->time_ - filter_.getLastMeasurementTime()) > 1e-9)
{
saveFilterState(filter_);
}
}
}
}
else if (filter_.getInitializedStatus())
{
// In the event that we don't get any measurements for a long time,
// we still need to continue to estimate our state. Therefore, we
// should project the state forward here.
double lastUpdateDelta = currentTimeSec - filter_.getLastMeasurementTime();
// If we get a large delta, then continuously predict until
if (lastUpdateDelta >= filter_.getSensorTimeout())
{
predictToCurrentTime = true;
RF_DEBUG("Sensor timeout! Last measurement time was " << filter_.getLastMeasurementTime() <<
", current time is " << currentTimeSec <<
", delta is " << lastUpdateDelta << "\n");
}
}
else
{
RF_DEBUG("Filter not yet initialized.\n");
}
if (filter_.getInitializedStatus() && predictToCurrentTime)
{
double lastUpdateDelta = currentTimeSec - filter_.getLastMeasurementTime();
filter_.validateDelta(lastUpdateDelta);
filter_.predict(currentTimeSec, lastUpdateDelta);
// Update the last measurement time and last update time
filter_.setLastMeasurementTime(filter_.getLastMeasurementTime() + lastUpdateDelta);
}
RF_DEBUG("\n----- /RosFilter::integrateMeasurements ------\n");
}
template<typename T>
void RosFilter<T>::differentiateMeasurements(const ros::Time ¤tTime)
{
if (filter_.getInitializedStatus())
{
const double dt = (currentTime - lastDiffTime_).toSec();
const Eigen::VectorXd &state = filter_.getState();
// Specific to angular acceleration for now...
tf2::Vector3 newStateTwistRot(state(StateMemberVroll),
state(StateMemberVpitch),
state(StateMemberVyaw));
angular_acceleration_ = (newStateTwistRot - lastStateTwistRot_)/dt;
const Eigen::MatrixXd &cov = filter_.getEstimateErrorCovariance();
for (size_t i = 0; i < 3; i ++)
{
for (size_t j = 0; j < 3; j ++)
{
angular_acceleration_cov_(i, j) = cov(i+ORIENTATION_V_OFFSET, j+ORIENTATION_V_OFFSET)
* 2. / (dt * dt);
}
}
lastStateTwistRot_ = newStateTwistRot;
lastDiffTime_ = currentTime;
}
}
template<typename T>
void RosFilter<T>::loadParams()
{
/* For diagnostic purposes, collect information about how many different
* sources are measuring each absolute pose variable and do not have
* differential integration enabled.
*/
std::map<StateMembers, int> absPoseVarCounts;
absPoseVarCounts[StateMemberX] = 0;
absPoseVarCounts[StateMemberY] = 0;
absPoseVarCounts[StateMemberZ] = 0;
absPoseVarCounts[StateMemberRoll] = 0;
absPoseVarCounts[StateMemberPitch] = 0;
absPoseVarCounts[StateMemberYaw] = 0;
// Same for twist variables
std::map<StateMembers, int> twistVarCounts;
twistVarCounts[StateMemberVx] = 0;
twistVarCounts[StateMemberVy] = 0;
twistVarCounts[StateMemberVz] = 0;
twistVarCounts[StateMemberVroll] = 0;
twistVarCounts[StateMemberVpitch] = 0;
twistVarCounts[StateMemberVyaw] = 0;
// Determine if we'll be printing diagnostic information
nhLocal_.param("print_diagnostics", printDiagnostics_, true);
// Check for custom gravitational acceleration value
nhLocal_.param("gravitational_acceleration", gravitationalAcc_, 9.80665);
// Grab the debug param. If true, the node will produce a LOT of output.
bool debug;
nhLocal_.param("debug", debug, false);
if (debug)
{
std::string debugOutFile;
try
{
nhLocal_.param("debug_out_file", debugOutFile, std::string("robot_localization_debug.txt"));
debugStream_.open(debugOutFile.c_str());
// Make sure we succeeded
if (debugStream_.is_open())
{
filter_.setDebug(debug, &debugStream_);
}
else
{
ROS_WARN_STREAM("RosFilter::loadParams() - unable to create debug output file " << debugOutFile);
}
}
catch(const std::exception &e)
{
ROS_WARN_STREAM("RosFilter::loadParams() - unable to create debug output file" << debugOutFile
<< ". Error was " << e.what() << "\n");
}
}
// These params specify the name of the robot's body frame (typically
// base_link) and odometry frame (typically odom)
nhLocal_.param("map_frame", mapFrameId_, std::string("map"));
nhLocal_.param("odom_frame", odomFrameId_, std::string("odom"));
nhLocal_.param("base_link_frame", baseLinkFrameId_, std::string("base_link"));
nhLocal_.param("base_link_frame_output", baseLinkOutputFrameId_, baseLinkFrameId_);
/*
* These parameters are designed to enforce compliance with REP-105:
* http://www.ros.org/reps/rep-0105.html
* When fusing absolute position data from sensors such as GPS, the state
* estimate can undergo discrete jumps. According to REP-105, we want three
* coordinate frames: map, odom, and base_link. The map frame can have
* discontinuities, but is the frame with the most accurate position estimate
* for the robot and should not suffer from drift. The odom frame drifts over
* time, but is guaranteed to be continuous and is accurate enough for local
* planning and navigation. The base_link frame is affixed to the robot. The
* intention is that some odometry source broadcasts the odom->base_link
* transform. The localization software should broadcast map->base_link.
* However, tf does not allow multiple parents for a coordinate frame, so
* we must *compute* map->base_link, but then use the existing odom->base_link
* transform to compute *and broadcast* map->odom.
*
* The state estimation nodes in robot_localization therefore have two "modes."
* If your world_frame parameter value matches the odom_frame parameter value,
* then robot_localization will assume someone else is broadcasting a transform
* from odom_frame->base_link_frame, and it will compute the
* map_frame->odom_frame transform. Otherwise, it will simply compute the
* odom_frame->base_link_frame transform.
*
* The default is the latter behavior (broadcast of odom->base_link).
*/
nhLocal_.param("world_frame", worldFrameId_, odomFrameId_);
ROS_FATAL_COND(mapFrameId_ == odomFrameId_ ||
odomFrameId_ == baseLinkFrameId_ ||
mapFrameId_ == baseLinkFrameId_ ||
odomFrameId_ == baseLinkOutputFrameId_ ||
mapFrameId_ == baseLinkOutputFrameId_,
"Invalid frame configuration! The values for map_frame, odom_frame, "
"and base_link_frame must be unique. If using a base_link_frame_output values, it "
"must not match the map_frame or odom_frame.");
// Try to resolve tf_prefix
std::string tfPrefix = "";
std::string tfPrefixPath = "";
if (nhLocal_.searchParam("tf_prefix", tfPrefixPath))
{
nhLocal_.getParam(tfPrefixPath, tfPrefix);
}
// Append the tf prefix in a tf2-friendly manner
FilterUtilities::appendPrefix(tfPrefix, mapFrameId_);
FilterUtilities::appendPrefix(tfPrefix, odomFrameId_);
FilterUtilities::appendPrefix(tfPrefix, baseLinkFrameId_);
FilterUtilities::appendPrefix(tfPrefix, baseLinkOutputFrameId_);
FilterUtilities::appendPrefix(tfPrefix, worldFrameId_);
// Whether we're publishing the world_frame->base_link_frame transform
nhLocal_.param("publish_tf", publishTransform_, true);
// Whether we should invert the transform before publishing:
// word_frame->base_link_frame to base_link_frame->world_frame
nhLocal_.param("invert_tf", invertTransform_, false);
// Whether we're publishing the acceleration state transform
nhLocal_.param("publish_acceleration", publishAcceleration_, false);
// Whether we'll allow old measurements to cause a re-publication of the updated state
nhLocal_.param("permit_corrected_publication", permitCorrectedPublication_, false);
// Transform future dating
double offsetTmp;
nhLocal_.param("transform_time_offset", offsetTmp, 0.0);
tfTimeOffset_.fromSec(offsetTmp);
// Transform timeout
double timeoutTmp;
nhLocal_.param("transform_timeout", timeoutTmp, 0.0);
tfTimeout_.fromSec(timeoutTmp);
// Update frequency and sensor timeout
double sensorTimeout;
nhLocal_.param("frequency", frequency_, 30.0);
nhLocal_.param("sensor_timeout", sensorTimeout, 1.0 / frequency_);
filter_.setSensorTimeout(sensorTimeout);
// Determine if we're in 2D mode
nhLocal_.param("two_d_mode", twoDMode_, false);
// Smoothing window size
nhLocal_.param("smooth_lagged_data", smoothLaggedData_, false);
nhLocal_.param("history_length", historyLength_, 0.0);
// Wether we reset filter on jump back in time
nhLocal_.param("reset_on_time_jump", resetOnTimeJump_, false);
if (!smoothLaggedData_ && ::fabs(historyLength_) > 1e-9)
{
ROS_WARN_STREAM("Filter history interval of " << historyLength_ <<
" specified, but smooth_lagged_data is set to false. Lagged data will not be smoothed.");
}
if (smoothLaggedData_ && historyLength_ < -1e9)
{
ROS_WARN_STREAM("Negative history interval of " << historyLength_ <<
" specified. Absolute value will be assumed.");
}
historyLength_ = ::fabs(historyLength_);
nhLocal_.param("predict_to_current_time", predictToCurrentTime_, false);
// Determine if we're using a control term
bool stampedControl = false;
double controlTimeout = sensorTimeout;
std::vector<int> controlUpdateVector(TWIST_SIZE, 0);
std::vector<double> accelerationLimits(TWIST_SIZE, 1.0);
std::vector<double> accelerationGains(TWIST_SIZE, 1.0);
std::vector<double> decelerationLimits(TWIST_SIZE, 1.0);
std::vector<double> decelerationGains(TWIST_SIZE, 1.0);
nhLocal_.param("use_control", useControl_, false);
nhLocal_.param("stamped_control", stampedControl, false);
nhLocal_.param("control_timeout", controlTimeout, sensorTimeout);
if (useControl_)
{
if (nhLocal_.getParam("control_config", controlUpdateVector))
{
if (controlUpdateVector.size() != TWIST_SIZE)
{
ROS_ERROR_STREAM("Control configuration must be of size " << TWIST_SIZE << ". Provided config was of "
"size " << controlUpdateVector.size() << ". No control term will be used.");
useControl_ = false;
}
}
else
{
ROS_ERROR_STREAM("use_control is set to true, but control_config is missing. No control term will be used.");
useControl_ = false;
}
if (nhLocal_.getParam("acceleration_limits", accelerationLimits))
{
if (accelerationLimits.size() != TWIST_SIZE)
{
ROS_ERROR_STREAM("Acceleration configuration must be of size " << TWIST_SIZE << ". Provided config was of "
"size " << accelerationLimits.size() << ". No control term will be used.");
useControl_ = false;
}
}
else
{
ROS_WARN_STREAM("use_control is set to true, but acceleration_limits is missing. Will use default values.");
}
if (nhLocal_.getParam("acceleration_gains", accelerationGains))
{
const int size = accelerationGains.size();
if (size != TWIST_SIZE)
{
ROS_ERROR_STREAM("Acceleration gain configuration must be of size " << TWIST_SIZE <<
". Provided config was of size " << size << ". All gains will be assumed to be 1.");
std::fill_n(accelerationGains.begin(), std::min(size, TWIST_SIZE), 1.0);
accelerationGains.resize(TWIST_SIZE, 1.0);
}
}
if (nhLocal_.getParam("deceleration_limits", decelerationLimits))
{
if (decelerationLimits.size() != TWIST_SIZE)
{
ROS_ERROR_STREAM("Deceleration configuration must be of size " << TWIST_SIZE <<
". Provided config was of size " << decelerationLimits.size() << ". No control term will be used.");
useControl_ = false;
}
}
else
{
ROS_INFO_STREAM("use_control is set to true, but no deceleration_limits specified. Will use acceleration "
"limits.");
decelerationLimits = accelerationLimits;
}
if (nhLocal_.getParam("deceleration_gains", decelerationGains))
{
const int size = decelerationGains.size();
if (size != TWIST_SIZE)
{
ROS_ERROR_STREAM("Deceleration gain configuration must be of size " << TWIST_SIZE <<
". Provided config was of size " << size << ". All gains will be assumed to be 1.");
std::fill_n(decelerationGains.begin(), std::min(size, TWIST_SIZE), 1.0);
decelerationGains.resize(TWIST_SIZE, 1.0);
}
}
else
{
ROS_INFO_STREAM("use_control is set to true, but no deceleration_gains specified. Will use acceleration "