KalmanFilter.cpp
Go to the documentation of this file.
1 // -*- C++ -*-
10 #include "KalmanFilter.h"
11 #include "hrpsys/util/VectorConvert.h"
12 #include <rtm/CorbaNaming.h>
13 #include <hrpModel/ModelLoaderUtil.h>
14 #include <math.h>
15 #include <hrpModel/Link.h>
16 #include <hrpModel/Sensor.h>
17 
18 //#define USE_EKF
19 
20 // Module specification
21 // <rtc-template block="module_spec">
22 static const char* kalmanfilter_spec[] =
23  {
24  "implementation_id", "KalmanFilter",
25  "type_name", "KalmanFilter",
26  "description", "kalman filter",
27  "version", HRPSYS_PACKAGE_VERSION,
28  "vendor", "AIST",
29  "category", "example",
30  "activity_type", "DataFlowComponent",
31  "max_instance", "10",
32  "language", "C++",
33  "lang_type", "compile",
34  // Configuration variables
35  "conf.default.debugLevel", "0",
36  ""
37  };
38 // </rtc-template>
39 
41  : RTC::DataFlowComponentBase(manager),
42  // <rtc-template block="initializer">
43  m_rateIn("rate", m_rate),
44  m_accIn("acc", m_acc),
45  m_accRefIn("accRef", m_accRef),
46  m_rpyIn("rpyIn", m_rate),
47  m_qCurrentIn("qCurrent", m_qCurrent),
48  m_rpyOut("rpy", m_rpy),
49  m_rpyRawOut("rpy_raw", m_rpyRaw),
50  m_baseRpyCurrentOut("baseRpyCurrent", m_baseRpyCurrent),
51  m_KalmanFilterServicePort("KalmanFilterService"),
52  // </rtc-template>
53  m_robot(hrp::BodyPtr()),
54  m_debugLevel(0),
55  dummy(0),
56  loop(0)
57 {
58  m_service0.kalman(this);
59 }
60 
62 {
63 }
64 
65 
66 #define DEBUGP ((m_debugLevel==1 && loop%200==0) || m_debugLevel > 1 )
67 RTC::ReturnCode_t KalmanFilter::onInitialize()
68 {
69  std::cerr << "[" << m_profile.instance_name << "] onInitialize()" << std::endl;
70  // <rtc-template block="bind_config">
71  // Bind variables and configuration variable
72  bindParameter("debugLevel", m_debugLevel, "0");
73 
74  // </rtc-template>
75 
76  // Registration: InPort/OutPort/Service
77  // <rtc-template block="registration">
78  // Set InPort buffers
79  addInPort("rate", m_rateIn);
80  addInPort("acc", m_accIn);
81  addInPort("accRef", m_accRefIn);
82  addInPort("rpyIn", m_rpyIn);
83  addInPort("qCurrent", m_qCurrentIn);
84 
85  // Set OutPort buffer
86  addOutPort("rpy", m_rpyOut);
87  addOutPort("rpy_raw", m_rpyRawOut);
88  addOutPort("baseRpyCurrent", m_baseRpyCurrentOut);
89 
90  // Set service provider to Ports
91  m_KalmanFilterServicePort.registerProvider("service0", "KalmanFilterService", m_service0);
92 
93  // Set service consumers to Ports
94 
95  // Set CORBA Service Ports
97 
98  // </rtc-template>
99 
100  // Setup robot model
102  if ( ! coil::stringTo(m_dt, prop["dt"].c_str()) ) {
103  std::cerr << "[" << m_profile.instance_name << "]failed to get dt" << std::endl;
104  return RTC::RTC_ERROR;
105  }
106 
107  m_robot = hrp::BodyPtr(new hrp::Body());
108 
109  RTC::Manager& rtcManager = RTC::Manager::instance();
110  std::string nameServer = rtcManager.getConfig()["corba.nameservers"];
111  int comPos = nameServer.find(",");
112  if (comPos < 0){
113  comPos = nameServer.length();
114  }
115  nameServer = nameServer.substr(0, comPos);
116  RTC::CorbaNaming naming(rtcManager.getORB(), nameServer.c_str());
117  if (!loadBodyFromModelLoader(m_robot, prop["model"].c_str(),
118  CosNaming::NamingContext::_duplicate(naming.getRootContext())
119  )){
120  std::cerr << "[" << m_profile.instance_name << "]failed to load model[" << prop["model"] << "]" << std::endl;
121  }
122 
123  m_rpy.data.r = 0;
124  m_rpy.data.p = 0;
125  m_rpy.data.y = 0;
126 
127  if (m_robot->numSensors(hrp::Sensor::ACCELERATION) > 0) {
128  hrp::Sensor* sensor = m_robot->sensor(hrp::Sensor::ACCELERATION, 0);
129  m_sensorR = sensor->link->R * sensor->localR;
130  } else {
131  m_sensorR = hrp::Matrix33::Identity();
132  }
133  rpy_kf.setParam(m_dt, 0.001, 0.003, 1000, std::string(m_profile.instance_name));
136  kf_algorithm = OpenHRP::KalmanFilterService::RPYKalmanFilter;
137  m_qCurrent.data.length(m_robot->numJoints());
138  acc_offset = hrp::Vector3::Zero();
139  sensorR_offset = hrp::Matrix33::Identity();
140 
141  return RTC::RTC_OK;
142 }
143 
144 
145 
146 /*
147  RTC::ReturnCode_t KalmanFilter::onFinalize()
148  {
149  return RTC::RTC_OK;
150  }
151 */
152 
153 /*
154  RTC::ReturnCode_t KalmanFilter::onStartup(RTC::UniqueId ec_id)
155  {
156  return RTC::RTC_OK;
157  }
158 */
159 
160 /*
161  RTC::ReturnCode_t KalmanFilter::onShutdown(RTC::UniqueId ec_id)
162  {
163  return RTC::RTC_OK;
164  }
165 */
166 
167 RTC::ReturnCode_t KalmanFilter::onActivated(RTC::UniqueId ec_id)
168 {
169  std::cerr << "[" << m_profile.instance_name<< "] onActivated(" << ec_id << ")" << std::endl;
170  return RTC::RTC_OK;
171 }
172 
174 {
175  std::cerr << "[" << m_profile.instance_name<< "] onDeactivated(" << ec_id << ")" << std::endl;
176  return RTC::RTC_OK;
177 }
178 
179 RTC::ReturnCode_t KalmanFilter::onExecute(RTC::UniqueId ec_id)
180 {
181  loop++;
182  static int initialize = 0;
183  //std::cerr << m_profile.instance_name<< ": onExecute(" << ec_id << ") " << std::endl;
184  if (m_rpyIn.isNew() ) {
185  m_rpyIn.read();
186  m_rpy.data.r = m_rate.data.avx;
187  m_rpy.data.p = m_rate.data.avy;
188  m_rpy.data.y = m_rate.data.avz;
189  m_rpy.tm = m_rate.tm;
190  m_rpyOut.write();
191  return RTC::RTC_OK;
192  }
193  if (m_rateIn.isNew()){
194  m_rateIn.read();
195  }
196  if (m_qCurrentIn.isNew()) {
197  m_qCurrentIn.read();
198  for ( int i = 0; i < m_robot->numJoints(); i++ ){
199  m_robot->joint(i)->q = m_qCurrent.data[i];
200  }
201  }
202  double sx_ref = 0.0, sy_ref = 0.0, sz_ref = 0.0;
203  if (m_accRefIn.isNew()){
204  m_accRefIn.read();
205  sx_ref = m_accRef.data.ax, sy_ref = m_accRef.data.ay, sz_ref = m_accRef.data.az;
206  }
207  if (m_accIn.isNew()){
208  m_accIn.read();
209 
210  Eigen::Vector3d acc = m_sensorR * hrp::Vector3(m_acc.data.ax-sx_ref+acc_offset(0), m_acc.data.ay-sy_ref+acc_offset(1), m_acc.data.az-sz_ref+acc_offset(2)); // transform to imaginary acc data
211  acc = sensorR_offset * acc;
212  Eigen::Vector3d gyro = m_sensorR * hrp::Vector3(m_rate.data.avx, m_rate.data.avy, m_rate.data.avz); // transform to imaginary rate data
213  gyro = sensorR_offset * gyro;
214  if (DEBUGP) {
215  std::cerr << "[" << m_profile.instance_name << "] raw data acc : " << std::endl << acc << std::endl;
216  std::cerr << "[" << m_profile.instance_name << "] raw data gyro : " << std::endl << gyro << std::endl;
217  }
218  hrp::Vector3 rpy, rpyRaw, baseRpyCurrent;
219  if (kf_algorithm == OpenHRP::KalmanFilterService::QuaternionExtendedKalmanFilter) {
220  ekf_filter.main_one(rpy, rpyRaw, acc, gyro);
221  } else if (kf_algorithm == OpenHRP::KalmanFilterService::RPYKalmanFilter) {
222  double sl_y;
223  hrp::Matrix33 BtoS;
224  m_robot->calcForwardKinematics();
225  if (m_robot->numSensors(hrp::Sensor::ACCELERATION) > 0) {
226  hrp::Sensor* sensor = m_robot->sensor(hrp::Sensor::ACCELERATION, 0);
227  sl_y = hrp::rpyFromRot(sensor->link->R)[2];
228  BtoS = (m_robot->rootLink()->R).transpose() * (sensor->link->R * sensor->localR);
229  } else {
230  sl_y = 0.0;
231  BtoS = (m_robot->rootLink()->R).transpose();
232  }
233  rpy_kf.main_one(rpy, rpyRaw, baseRpyCurrent, acc, gyro, sl_y, BtoS);
234  }
235  m_rpyRaw.data.r = rpyRaw(0);
236  m_rpyRaw.data.p = rpyRaw(1);
237  m_rpyRaw.data.y = rpyRaw(2);
238  m_rpy.data.r = rpy(0);
239  m_rpy.data.p = rpy(1);
240  m_rpy.data.y = rpy(2);
241  m_baseRpyCurrent.data.r = baseRpyCurrent(0);
242  m_baseRpyCurrent.data.p = baseRpyCurrent(1);
243  m_baseRpyCurrent.data.y = baseRpyCurrent(2);
244  // add time stamp
245  m_rpyRaw.tm = m_acc.tm;
246  m_rpy.tm = m_acc.tm;
247  m_baseRpyCurrent.tm = m_acc.tm;
248 
249  m_rpyOut.write();
250  m_rpyRawOut.write();
252  }
253  return RTC::RTC_OK;
254 }
255 
256 /*
257  RTC::ReturnCode_t KalmanFilter::onAborting(RTC::UniqueId ec_id)
258  {
259  return RTC::RTC_OK;
260  }
261 */
262 
263 /*
264  RTC::ReturnCode_t KalmanFilter::onError(RTC::UniqueId ec_id)
265  {
266  return RTC::RTC_OK;
267  }
268 */
269 
270 /*
271  RTC::ReturnCode_t KalmanFilter::onReset(RTC::UniqueId ec_id)
272  {
273  return RTC::RTC_OK;
274  }
275 */
276 
277 /*
278  RTC::ReturnCode_t KalmanFilter::onStateUpdate(RTC::UniqueId ec_id)
279  {
280  return RTC::RTC_OK;
281  }
282 */
283 
284 /*
285  RTC::ReturnCode_t KalmanFilter::onRateChanged(RTC::UniqueId ec_id)
286  {
287  return RTC::RTC_OK;
288  }
289 */
290 
291 bool KalmanFilter::setKalmanFilterParam(const OpenHRP::KalmanFilterService::KalmanFilterParam& i_param)
292 {
293  std::cerr << "[" << m_profile.instance_name << "] setKalmanFilterParam" << std::endl;
294  rpy_kf.setParam(m_dt, i_param.Q_angle, i_param.Q_rate, i_param.R_angle, std::string(m_profile.instance_name));
295  kf_algorithm = i_param.kf_algorithm;
296  for (size_t i = 0; i < 3; i++) {
297  acc_offset(i) = i_param.acc_offset[i];
298  }
299  hrp::Vector3 rpyoff;
300  for (size_t i = 0; i < 3; i++) {
301  rpyoff(i) = i_param.sensorRPY_offset[i];
302  }
304  std::cerr << "[" << m_profile.instance_name << "] kf_algorithm=" << (kf_algorithm==OpenHRP::KalmanFilterService::RPYKalmanFilter?"RPYKalmanFilter":"QuaternionExtendedKalmanFilter") << std::endl;
305  std::cerr << "[" << m_profile.instance_name << "] acc_offset = " << acc_offset.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", " [", "]")) << std::endl;
306  std::cerr << "[" << m_profile.instance_name << "] sensorRPY_offset = " << rpyoff.format(Eigen::IOFormat(Eigen::StreamPrecision, 0, ", ", ", ", "", "", " [", "]")) << std::endl;
307  return true;
308 }
309 
311 {
314 };
315 
316 bool KalmanFilter::getKalmanFilterParam(OpenHRP::KalmanFilterService::KalmanFilterParam& i_param)
317 {
318  i_param.Q_angle = rpy_kf.getQangle();
319  i_param.Q_rate = rpy_kf.getQrate();
320  i_param.R_angle = rpy_kf.getRangle();
321  i_param.kf_algorithm = kf_algorithm;
322  for (size_t i = 0; i < 3; i++) {
323  i_param.acc_offset[i] = acc_offset(i);
324  }
326  for (size_t i = 0; i < 3; i++) {
327  i_param.sensorRPY_offset[i] = rpyoff(i);
328  }
329  return true;
330 }
331 
332 extern "C"
333 {
334 
336  {
338  manager->registerFactory(profile,
339  RTC::Create<KalmanFilter>,
340  RTC::Delete<KalmanFilter>);
341  }
342 
343 };
344 
345 
ComponentProfile m_profile
void setdt(const double _dt)
Definition: EKFilter.h:173
png_infop png_charpp int png_charpp profile
unsigned int m_debugLevel
Definition: KalmanFilter.h:166
void resetKalmanFilterState()
TimedAcceleration3D m_acc
Definition: KalmanFilter.h:115
bool resetKalmanFilterState()
virtual RTC::ReturnCode_t onInitialize()
virtual ReturnCode_t initialize()
double getRangle() const
bool stringTo(To &val, const char *str)
OutPort< TimedOrientation3D > m_rpyOut
Definition: KalmanFilter.h:133
OpenHRP::KalmanFilterService::KFAlgorithm kf_algorithm
Definition: KalmanFilter.h:168
RTC::InPort< RTC::TimedDoubleSeq > m_qCurrentIn
Definition: KalmanFilter.h:136
void main_one(hrp::Vector3 &rpy, hrp::Vector3 &rpyRaw, const hrp::Vector3 &acc, const hrp::Vector3 &gyro)
Definition: EKFilter.h:162
RTC::OutPort< RTC::TimedOrientation3D > m_baseRpyCurrentOut
Definition: KalmanFilter.h:138
#define DEBUGP
TimedOrientation3D m_rpyRaw
Definition: KalmanFilter.h:118
virtual RTC::ReturnCode_t onExecute(RTC::UniqueId ec_id)
double getQangle() const
EKFilter ekf_filter
Definition: KalmanFilter.h:162
OutPort< TimedOrientation3D > m_rpyRawOut
Definition: KalmanFilter.h:134
CORBA::ORB_ptr getORB()
png_uint_32 i
coil::Properties & getProperties()
static Manager & instance()
Matrix33 localR
void setSensorR(const hrp::Matrix33 &sr)
bool getKalmanFilterParam(OpenHRP::KalmanFilterService::KalmanFilterParam &i_param)
bool addOutPort(const char *name, OutPortBase &outport)
InPort< TimedAcceleration3D > m_accIn
Definition: KalmanFilter.h:125
boost::shared_ptr< Body > BodyPtr
double getQrate() const
virtual ~KalmanFilter()
Destructor.
RTC::TimedDoubleSeq m_qCurrent
Definition: KalmanFilter.h:135
Eigen::Vector3d Vector3
InPort< TimedAngularVelocity3D > m_rpyIn
Definition: KalmanFilter.h:127
Matrix33 rotFromRpy(const Vector3 &rpy)
Eigen::Matrix3d Matrix33
void setParam(const double _dt, const double _Q_angle, const double _Q_rate, const double _R_angle, const std::string print_str="")
virtual RTC::ReturnCode_t onActivated(RTC::UniqueId ec_id)
coil::Properties & getConfig()
KalmanFilterService_impl m_service0
Definition: KalmanFilter.h:155
ExecutionContextHandle_t UniqueId
bool bindParameter(const char *param_name, VarType &var, const char *def_val, bool(*trans)(VarType &, const char *)=coil::stringTo)
void resetKalmanFilterState()
Definition: EKFilter.h:174
RTC::TimedOrientation3D m_baseRpyCurrent
Definition: KalmanFilter.h:137
TimedAcceleration3D m_accRef
Definition: KalmanFilter.h:116
void main_one(hrp::Vector3 &rpy, hrp::Vector3 &rpyRaw, hrp::Vector3 &baseRpyCurrent, const hrp::Vector3 &acc, const hrp::Vector3 &gyro, const double &sl_y, const hrp::Matrix33 &BtoS)
hrp::Matrix33 m_sensorR
Definition: KalmanFilter.h:164
void kalman(KalmanFilter *i_kalman)
bool setKalmanFilterParam(const OpenHRP::KalmanFilterService::KalmanFilterParam &i_param)
int loadBodyFromModelLoader(::World *world, const char *name, const char *url, CosNaming::NamingContext_var cxt)
static const char * kalmanfilter_spec[]
hrp::BodyPtr m_robot
Definition: KalmanFilter.h:163
hrp::Vector3 acc_offset
Definition: KalmanFilter.h:165
prop
InPort< TimedAcceleration3D > m_accRefIn
Definition: KalmanFilter.h:126
HRP_UTIL_EXPORT Vector3 rpyFromRot(const Matrix33 &m)
naming
null component
virtual RTC::ReturnCode_t onDeactivated(RTC::UniqueId ec_id)
virtual bool isNew()
bool addPort(PortBase &port)
virtual bool write(DataType &value)
hrp::BodyPtr m_robot
bool addInPort(const char *name, InPortBase &inport)
TimedAngularVelocity3D m_rate
Definition: KalmanFilter.h:114
RPYKalmanFilter rpy_kf
Definition: KalmanFilter.h:161
bool registerFactory(coil::Properties &profile, RtcNewFunc new_func, RtcDeleteFunc delete_func)
RTC::CorbaPort m_KalmanFilterServicePort
Definition: KalmanFilter.h:149
TimedOrientation3D m_rpy
Definition: KalmanFilter.h:117
InPort< TimedAngularVelocity3D > m_rateIn
Definition: KalmanFilter.h:124
bool registerProvider(const char *instance_name, const char *type_name, PortableServer::RefCountServantBase &provider)
KalmanFilter(RTC::Manager *manager)
Constructor.
void KalmanFilterInit(RTC::Manager *manager)
hrp::Matrix33 sensorR_offset
Definition: KalmanFilter.h:164


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Thu May 6 2021 02:41:50