Skip to content

IMU Simulation: From Measurement to Message

This page follows one sample of the simulated IMU from Gazebo's IMU sensor to the message on /diffbot/imu/data_raw, in the order in which the code runs. Read the page to find where a value of the message is set. This page belongs to IMU: Simulation, which shows the finished message.

One sample, through the three parts

Three parts make the sample, one after the other. The numbers are from a run of Remo's simulation, taken while Remo turned left on the spot at 0.5 rad/s. The run recorded Gazebo's own IMU messages and the two ROS topics side by side. The sample pairs one ROS message with Gazebo's newest IMU message whose stamp isn't later than the ROS message's stamp:

  1. Gazebo's IMU sensor measures: the IMU sensor measures the angular velocity \(\boldsymbol\omega\) and the specific force \(\mathbf f\) of imu_link. In Gazebo's message of this pair, the yaw rate \(\omega_z\), the angular velocity about the upward axis, is 0.50000 rad/s, and the measurement's time is 9.592 s of simulation time. Part 1 shows Gazebo's code.
  2. The robots' IMU plugin makes the message: when the plugin publishes, it reads the IMU sensor's latest values and adds noise to each of them. The message's yaw rate \(\tilde\omega_z\) is 0.49882 rad/s, which is 0.00118 rad/s less than the yaw rate of Gazebo's paired message. The plugin fills the covariances and stamps the message with 9.593 s, the IMU sensor's update time, which is 1 ms later than the paired measurement's time. The plugin publishes the message on /diffbot/imu/gazebo. This message also has an orientation \(\mathbf q\), a quaternion with four numbers. Part 2 shows the plugin's code.
  3. The adapter gives the message the firmware's form: the firmware's message on the real robot has no orientation. So the adapter marks the orientation unavailable, with four zeros and −1 in orientation_covariance[0], and publishes the message on /diffbot/imu/data_raw. The yaw rate, 0.49882 rad/s, and the stamp, 9.593 s, stay as the plugin set them. Part 3 shows the adapter's code.

The pairing is by time alone. The recording can't tell which of Gazebo's measurements the plugin read for a message, so the 0.00118 rad/s is the difference between the two paired readings, not a measured noise value.

The robot's URDF model declares the IMU sensor and its plugin. The IMU sensor in the robot's URDF model shows where, before anything runs.

The code's flow

The figure shows what each part does, in the order in which the code runs. The sections of this page follow the figure from top to bottom. The arrows show how the data reaches the message, not who calls whom. Gazebo runs the IMU sensor and the plugin in two separate loops, and the plugin reads the IMU sensor's latest measurement. Most calls of the plugin's UpdateChild() end at its checks and publish nothing. The checks before a call publishes has a figure of the checks with their exits.

graph TB subgraph PART1 [ ] MEASURE["<b>1. Gazebo's IMU sensor</b><br/>UpdateImpl(), every 20 ms<br/>of simulation time on average<br/>measures angularVel and linearAcc<br/>of imu_link"] end subgraph PART2 [ ] CHECKS["<b>2. The robots' IMU plugin</b><br/>UpdateChild(), at every simulation step<br/>the checks: clock went back,<br/>rate limit, subscriber<br/>most calls end here"] READ["reads the sensor and adds noise<br/>gyroscope_data, accelerometer_data<br/>GuassianKernel()"] COVARIANCE["fills the covariances<br/>gaussian_noise squared<br/>at the elements 0, 4 and 8"] PUBLISH["sets the header and publishes<br/>frame_id, stamp, publish()<br/>then stores last_time"] CHECKS -->|a call that passes the checks| READ READ --> COVARIANCE COVARIANCE --> PUBLISH end subgraph PART3 [ ] CALLBACK["<b>3. The adapter</b><br/>callback(), for every received message<br/>marks the orientation unavailable"] end MEASURE -->|the plugin reads the latest measurement| CHECKS PUBLISH -->|imu/gazebo| CALLBACK CALLBACK -->|imu/data_raw| READERS["IMU sample validator, tests"]

The IMU sensor in the robot's URDF model

Each robot's URDF model declares the simulated IMU sensor in a xacro macro named imu_sensor. Position and Axes explains what a macro and its call are. The diagram shows the macro's call, what the macro adds to the robot's URDF model, and who reads each part. Read the diagram from top to bottom. The call supplies two things, the parent link and the origin, and both meet in the joint. The two boxes with a bold first line hold what the macro adds. The labels on the arrows are the names that xacro and the URDF use for these connections:

graph TB CALL["The robot's xacro file<br/>calls the macro imu_sensor"] PARENT["chassis_link<br/>a link of the robot's URDF model,<br/>there before the call"] ORIGIN["the call's origin<br/>the IMU's xyz and rpy<br/>on chassis_link"] subgraph BOTH [ ] JOINT["<b>The macro adds, for ROS and Gazebo</b><br/>imu_joint: a fixed joint"] LINK["imu_link: a link with<br/>the board's shape and mass"] JOINT -->|child| LINK end subgraph BLOCK [ ] SENSOR["<b>The macro adds, for Gazebo only</b><br/>the Gazebo block of imu_link:<br/>Gazebo's IMU sensor, type imu,<br/>50 measurements per second"] PLUGIN["in the IMU sensor's element:<br/>the robots' IMU plugin,<br/>a library file"] SENSOR -->|contains| PLUGIN end CALL -->|parent_link| PARENT CALL -->|origin| ORIGIN PARENT -->|parent| JOINT ORIGIN -->|places| JOINT LINK -->|the Gazebo block's reference| SENSOR
  • imu_joint and imu_link: ROS and Gazebo both read them. The joint names chassis_link as its parent and imu_link as its child, and the call's origin places the joint. robot_state_publisher publishes the joint's transform, and Gazebo places the IMU sensor with this transform.
  • The Gazebo block: only Gazebo reads this block. URDF tools and ROS ignore the block. The block's attribute reference names imu_link, the link that carries the IMU sensor. The IMU sensor's element contains the plugin's element.

DiffBot's macro is in common_sensors.xacro of diffbot_description, Remo's in remo_description's file of the same name.

The complete macro imu_sensor of DiffBot's URDF model

The excerpt shows the whole macro with the comment above it, from common_sensors.xacro, lines 191–258. The link is in lines 208–234, the joint in lines 236–240 and the Gazebo block in lines 242–257:

common_sensors.xacro: the macro imu_sensor
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
<!-- IMU: a Bosch BNO055 board, as a small box (sensor_prop['imu']: mass, size, mesh), and a Gazebo
     IMU sensor that stands in for the real one in the simulation.
     - imu_link is the sensor's own frame; *origin places it on parent_link, as the board sits on
       the robot. The real robot's firmware publishes in the same frame (diffbot_base).
     - The Gazebo plugin, libdiffbot_gazebo_ros_imu_sensor.so from diffbot_gazebo_plugins, is a
       copy of gazebo_plugins' GazeboRosImuSensor (ROS 1) that doesn't run ROS callbacks in
       Gazebo's physics thread. gazebo_plugins' own plugin does, and that can stop the simulation
       while the controllers load (#185). The plugin publishes sensor_msgs/Imu on
       /diffbot/imu/gazebo at 50 Hz, the firmware's rate. Its message includes an orientation that
       the real sensor doesn't provide, so the simulation passes it through an adapter in
       diffbot_gazebo, which publishes /diffbot/imu/data_raw like the firmware.
     - gaussianNoise is one standard deviation that the plugin adds to every value; it's a
       simulation setting, not the BNO055's measured noise. -->
<xacro:macro name="imu_sensor" params="parent_link sensor_prop *origin">

  <xacro:property name="imu" value="${sensor_prop['imu']}"/>

  <link name="imu_link">
    <xacro:if value="${imu['mesh'] != ''}">
      <visual>
        <origin xyz="0 0 0" rpy="0 0 0"/>
        <geometry>
          <mesh filename="package://${package_name}/meshes/sensors/${imu['mesh']}" scale="${imu['scale']}"/>
        </geometry>
        <material name="dark_grey"/>
      </visual>
    </xacro:if>
    <xacro:if value="${imu['mesh'] == ''}">
      <visual>
        <origin xyz="0 0 0" rpy="0 0 0"/>
        <geometry>
          <box size="${imu['size']['x']} ${imu['size']['y']} ${imu['size']['z']}"/>
        </geometry>
        <material name="red"/>
      </visual>
    </xacro:if>
    <collision>
      <origin xyz="0 0 0" rpy="0 0 0"/>
      <geometry>
        <box size="${imu['size']['x']} ${imu['size']['y']} ${imu['size']['z']}"/>
      </geometry>
    </collision>
    <xacro:box_inertia m="${imu['mass']}" x="${imu['size']['x']}" y="${imu['size']['y']}" z="${imu['size']['z']}"/>
  </link>

  <joint name="imu_joint" type="fixed">
    <parent link="${parent_link}"/>
    <child link="imu_link"/>
    <xacro:insert_block name="origin"/>
  </joint>

  <gazebo reference="imu_link">
    <sensor type="imu" name="imu">
      <always_on>true</always_on>
      <update_rate>50</update_rate>
      <plugin name="imu_plugin" filename="libdiffbot_gazebo_ros_imu_sensor.so">
        <robotNamespace>/diffbot</robotNamespace>
        <topicName>imu/gazebo</topicName>
        <frameName>imu_link</frameName>
        <updateRateHZ>50</updateRateHZ>
        <gaussianNoise>0.005</gaussianNoise>
        <xyzOffset>0 0 0</xyzOffset>
        <rpyOffset>0 0 0</rpyOffset>
        <initialOrientationAsReference>false</initialOrientationAsReference>
      </plugin>
    </sensor>
  </gazebo>
</xacro:macro>

The next excerpt shows the macro's Gazebo block, which declares the IMU sensor and its plugin, from common_sensors.xacro, lines 242–257:

common_sensors.xacro: the IMU sensor and its plugin
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<gazebo reference="imu_link">
  <sensor type="imu" name="imu">
    <always_on>true</always_on>
    <update_rate>50</update_rate>
    <plugin name="imu_plugin" filename="libdiffbot_gazebo_ros_imu_sensor.so">
      <robotNamespace>/diffbot</robotNamespace>
      <topicName>imu/gazebo</topicName>
      <frameName>imu_link</frameName>
      <updateRateHZ>50</updateRateHZ>
      <gaussianNoise>0.005</gaussianNoise>
      <xyzOffset>0 0 0</xyzOffset>
      <rpyOffset>0 0 0</rpyOffset>
      <initialOrientationAsReference>false</initialOrientationAsReference>
    </plugin>
  </sensor>
</gazebo>

The lines inside <plugin> are the plugin's parameters:

Where the IMU sensor sits and how it's turned comes from the joint's origin in the robot's URDF model, not from the two offsets.

If you inspect the SDF model that Gazebo makes from the robot's URDF model

Gazebo converts the robot's URDF model into a model in its own format, SDF, before it simulates the robot. This SDF model has no imu_link. Gazebo merges links that are joined by fixed joints into one link, and imu_link hangs on a fixed joint.

The IMU sensor is still there, at the same place. In the SDF model, the IMU sensor belongs to the link that remains, base_footprint for DiffBot, and the sensor's pose in that link is imu_link's position and rotation. gz sdf -p prints the SDF model when you convert the robot's URDF model as on the Gazebo Package page.

For ROS nothing changes. imu_link stays the IMU's frame, in the message's header and in the transforms.

Part 1: Gazebo's IMU sensor measures

The IMU sensor derives its measurements from motion that Gazebo has already computed. Gazebo's physics engine computes the motion of every link in every simulation step, and the IMU sensor reads the motion of the link that carries it. From that motion, the IMU sensor computes two vectors along imu_link's axes: the angular velocity \(\boldsymbol\omega\) and the specific force \(\mathbf f\).

Who runs this code, and when: Gazebo's sensor manager runs the sensors in a loop of its own, apart from the physics engine. For each sensor, the loop calls Sensor::Update(). This function reads the world's simulation time into simTime. It adds two times: the time since the sensor's last update, and updateDelay, the lateness that an earlier update left over. Once this sum reaches the update period, Sensor::Update() calls the IMU sensor's ImuSensor::UpdateImpl(), which measures. Then Sensor::Update() stores simTime as the sensor's lastUpdateTime. With the update_rate of 50 in the robot's URDF model, the period is 20 ms of simulation time. Because of the carried lateness, two updates can be less than 20 ms apart: with 1 ms carried, the next update can run as early as 19 ms later. In the recorded run, the stamps of Gazebo's consecutive IMU messages, which are the measurements' times, were 19, 20 or 21 ms apart. The robots' IMU plugin takes no part in the measurement. The plugin only reads the results afterwards.

Sensor::Update(): when Gazebo runs a measurement, and the update time that it stores

The excerpt shows the part of Sensor::Update() that runs for the robots' IMU sensor, from Sensor.cc of Gazebo Classic 11.15.1, lines 254–295. Line 260 reads the world's simulation time. Lines 272–273 compute adjustedElapsed: the time since the last update plus updateDelay. Lines 275–276 return while adjustedElapsed is less than the update period. Lines 278–279 keep by how much adjustedElapsed exceeds the period, as the updateDelay of the next update. Lines 285–286 clear this carried delay when it reaches a full period: with a period of 20 ms, an adjustedElapsed of 40 ms leaves no delay for the next call. Line 289 calls UpdateImpl(), and line 292 stores simTime as lastUpdateTime:

Sensor.cc (Gazebo Classic 11.15.1): the update period and lastUpdateTime
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
else
{
  common::Time simTime;
  if (this->dataPtr->category == IMAGE && this->scene)
    simTime = this->scene->SimTime();
  else
    simTime = this->world->SimTime();

  {
    std::lock_guard<std::mutex> lock(this->dataPtr->mutexLastUpdateTime);

    if (simTime <= this->lastUpdateTime && !_force)
      return;

    // Adjust time-to-update period to compensate for delays caused by
    // another sensor's update in the same thread.
    // NOTE: If you change this equation, also change the matching equation
    // in Sensor::NeedsUpdate
    common::Time adjustedElapsed = simTime -
      this->lastUpdateTime + this->dataPtr->updateDelay;

    if (adjustedElapsed < this->updatePeriod && !_force)
      return;

    this->dataPtr->updateDelay = std::max(common::Time::Zero,
        adjustedElapsed - this->updatePeriod);

    // if delay is more than a full update period, then give up trying
    // to catch up. This happens normally when the sensor just changed from
    // an inactive to an active state, or the sensor just cannot hit its
    // target update rate (worst case).
    if (this->dataPtr->updateDelay >= this->updatePeriod)
      this->dataPtr->updateDelay = common::Time::Zero;
  }

  if (this->UpdateImpl(_force))
  {
    std::lock_guard<std::mutex> lock(this->dataPtr->mutexLastUpdateTime);
    this->lastUpdateTime = simTime;
    this->updated();
  }
}

The excerpt shows the lines of Gazebo's source code that compute both vectors, from ImuSensor::UpdateImpl() in ImuSensor.cc of Gazebo Classic 11.15.1, lines 322–380, under the Apache License 2.0:

ImuSensor.cc (Gazebo Classic 11.15.1): the two vectors
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
msg.CopyFrom(*this->dataPtr->incomingLinkData[readIndex].get());

common::Time timestamp = msgs::Convert(msg.time());

double dt = (timestamp - this->lastMeasurementTime).Double();

this->lastMeasurementTime = timestamp;

if (dt > 0.0)
{
  std::lock_guard<std::mutex> lock(this->dataPtr->mutex);

  this->dataPtr->imuMsg.set_entity_name(this->ParentName());

  this->dataPtr->gravity = this->world->Gravity();

  msgs::Set(this->dataPtr->imuMsg.mutable_stamp(), timestamp);

  ignition::math::Pose3d parentEntityPose =
    this->dataPtr->parentEntity->WorldPose();
  ignition::math::Pose3d imuWorldPose = this->pose + parentEntityPose;

  // Get the angular velocity
  ignition::math::Vector3d linkWorldAngularVel = msgs::ConvertIgn(
      msg.angular_velocity());

  /////////////////////////////////////////////////////////////////////
  // Set the IMU angular velocity (defined in imu's local frame)
  /////////////////////////////////////////////////////////////////////
  this->dataPtr->angularVel = imuWorldPose.Rot().Inverse().RotateVector(
      linkWorldAngularVel);
  msgs::Set(this->dataPtr->imuMsg.mutable_angular_velocity(),
      this->dataPtr->angularVel);

  /////////////////////////////////////////////////////////////////////
  // Compute and set the IMU linear acceleration in the imu local frame
  /////////////////////////////////////////////////////////////////////
  // first get imu link's linear velocity in world frame
  ignition::math::Vector3d linkWorldLinearVel
      = msgs::ConvertIgn(msg.linear_velocity());
  // next, account for vel in world frame of the imu
  // given the imu frame is offset from link frame, and link is rotating
  // compute the velocity of the imu axis origin in world frame
  ignition::math::Vector3d imuWorldLinearVel = linkWorldLinearVel +
      linkWorldAngularVel.Cross(imuWorldPose.Pos() - parentEntityPose.Pos());
  // compute acceleration by differentiating velocity in world frame,
  // and rotate into imu local frame
  this->dataPtr->linearAcc = imuWorldPose.Rot().Inverse().RotateVector(
    (imuWorldLinearVel - this->dataPtr->lastImuWorldLinearVel) / dt);

  // Add contribution from gravity
  // Do we want to skip if link does not have gravity enabled?
  //   e.g. if (this->dataPtr->parentEntity->GetGravityMode())
  this->dataPtr->linearAcc -= imuWorldPose.Rot().Inverse().RotateVector(
      this->dataPtr->gravity);

  // publish linear acceleration
  msgs::Set(this->dataPtr->imuMsg.mutable_linear_acceleration(),
      this->dataPtr->linearAcc);

The variables, in the order in which the code computes them:

  1. msg: in line 322, the latest motion data of the link that carries the IMU sensor. In Gazebo's SDF model that is the link that remains after the merging, as the box above explains. At the end of every simulation step, this link publishes its linear and angular velocity, in Link::PublishData(). The IMU sensor receives each of these messages in ImuSensor::OnLinkData() and keeps the newest one. These messages stay inside Gazebo. They aren't ROS messages.
  2. timestamp: in line 324, the simulation time of this motion data. This time is the measurement's time. Line 338 writes the measurement's time into Gazebo's own IMU message, which stays inside Gazebo as the link's messages do.
  3. dt: in line 326, the time between this motion data and the motion data of the IMU sensor's last measurement.
  4. imuWorldPose: in line 342, where the IMU sensor is in the simulated world, and how the IMU sensor is turned. imuWorldPose combines the link's pose with the sensor's pose in the link.
  5. linkWorldAngularVel: in line 345, the link's angular velocity from msg, along the world's axes.
  6. angularVel: in line 351, the same angular velocity along the IMU sensor's axes, which are imu_link's. imuWorldPose.Rot().Inverse().RotateVector() converts a vector from the world's axes to the sensor's. This is the angular velocity \(\boldsymbol\omega\):

    \[ \boldsymbol\omega = \begin{pmatrix} \omega_x \\ \omega_y \\ \omega_z \end{pmatrix} \]
  7. linkWorldLinearVel: in line 360, the link's linear velocity from msg, along the world's axes.

  8. imuWorldLinearVel: in line 365, the velocity of the point where the IMU sensor sits. That point isn't the link's origin, so a turning link moves that point too. The cross product adds this share.
  9. linearAcc: in line 369, how much imuWorldLinearVel changed since the last measurement, lastImuWorldLinearVel, divided by dt, and converted to the sensor's axes. This is the acceleration \(\mathbf a\) of the point where the IMU sensor sits.
  10. linearAcc again: in line 375, the code subtracts gravity \(\mathbf g\), converted to the sensor's axes too. linearAcc is now the specific force \(\mathbf f\), in m/s²:

    \[ \mathbf f = \mathbf a - \mathbf g = \begin{pmatrix} a_x - g_x \\ a_y - g_y \\ a_z - g_z \end{pmatrix} \]

The IMU sensor keeps both results. The plugin fetches them later with sensor->AngularVelocity() and sensor->LinearAcceleration().

Two times of a measurement: Gazebo keeps two times for the IMU sensor, and they aren't the same.

  • The measurement's time is timestamp, the simulation time of the motion data that the measurement was computed from. Gazebo's own IMU message carries this time.
  • The sensor's update time is lastUpdateTime, the world's simulation time that Sensor::Update() read when it ran the measurement. sensor->LastUpdateTime() returns the update time. The plugin stamps the ROS message with this time, as the header and publishing shows.

The sensor loop runs apart from the physics engine, so the world's clock has usually moved on since the link published its motion data. The run of the sample above paired each of 524 ROS messages with Gazebo's newest IMU message whose stamp wasn't later. For 523 of them, the ROS message's stamp was 1 ms later than the stamp of Gazebo's message, one simulation step. For one, the two stamps were equal. These numbers are from one run and from a pairing by time. They aren't a rule of Gazebo.

At rest, \(\mathbf a\) is zero. With imu_link's z axis up, gravity is \(\mathbf g = (0, 0, -9.8)\) m/s², so the IMU sensor reads \(\mathbf f = (0, 0, +9.8)\) m/s². The overview shows the angular velocity and the linear acceleration each in a figure, and explains why an accelerometer reads the acceleration minus gravity.

Gazebo's gravity is 9.8 m/s² in the robots' worlds. That is the default of SDF, Gazebo's format for worlds and models, as the SDF specification of <gravity> says.

Part 2: the plugin makes the message

The robots' IMU plugin makes the message in one function, UpdateChild(). Load() connects UpdateChild() to Gazebo's world update event. The excerpt shows this call, from gazebo_ros_imu_sensor.cpp, lines 131–132:

gazebo_ros_imu_sensor.cpp: Load() connects UpdateChild()
131
132
connection = gazebo::event::Events::ConnectWorldUpdateBegin(
  boost::bind(&GazeboRosImuSensor::UpdateChild, this, boost::placeholders::_1));

So Gazebo's physics thread, the part of Gazebo that computes the simulation's steps, calls UpdateChild() at the start of every step. With the 1 ms step of the simulation test's world, that is 1000 calls per second of simulation time. Most calls end after the checks. A call that passes them goes through the four steps below in this order, and publishes at the end.

The checks before a call publishes

The first lines of UpdateChild() decide whether this call makes a message at all. The figure shows the two decisions and where a call leaves:

graph TB CALL["UpdateChild() starts<br/>reads current_time<br/>clock went back:<br/>last_time = current_time"] RATE{"one period<br/>since last_time?"} RETURN["returns,<br/>publishes nothing"] SUBSCRIBER{"a subscriber?"} MESSAGE["fills and publishes<br/>the message"] STORE["stores<br/>last_time = current_time"] CALL --> RATE RATE -->|no| RETURN RATE -->|yes| SUBSCRIBER SUBSCRIBER -->|yes| MESSAGE MESSAGE --> STORE SUBSCRIBER -->|no| STORE

The excerpt shows these lines, from gazebo_ros_imu_sensor.cpp, lines 137–147:

gazebo_ros_imu_sensor.cpp: the start of UpdateChild()
137
138
139
140
141
142
143
144
145
146
147
void GazeboRosImuSensor::UpdateChild(const gazebo::common::UpdateInfo &/*_info*/)
{
  gazebo::common::Time current_time = sensor->LastUpdateTime();

  if(current_time < last_time) //the clock went back (a reset): start the update rate check anew
    last_time = current_time;

  if(update_rate>0 && (current_time-last_time).Double() < 1.0/update_rate) //update rate check
    return;

  if(imu_data_publisher.getNumSubscribers() > 0)
  • Two times: current_time is the IMU sensor's update time, sensor->LastUpdateTime() in line 139: the world's simulation time at which Gazebo last ran a measurement of the IMU sensor. It isn't the measurement's own time, as two times of a measurement in Part 1 explains. last_time is the value that current_time had in the last call that got past the rate limit.
  • A clock that went back: this is the first if, lines 141–142. A reset of the simulation sets Gazebo's clock back to zero. Then current_time is earlier than last_time, and the plugin sets last_time to current_time. The rate limit counts from the new time, and the plugin can publish again one period later. Publishing again after a reset explains what would happen without these two lines.
  • The rate limit: this is the second if, lines 144–145, the figure's first diamond. update_rate is the parameter updateRateHZ, 50. A call returns right away while less than one period, 1/50 s = 20 ms, has passed since last_time. So at most 50 calls per second of simulation time go on. Of the 1000 calls per second, about 950 end here.
  • A subscriber: this is the third if, line 147, the figure's second diamond. A call that got past the rate limit fills and publishes a message only while the topic has a subscriber. Without one, the call skips to the line that stores last_time. In the simulation, the adapter always subscribes.

Reading the sensor and adding noise

A call that passed the checks reads the IMU sensor's latest values and writes them into the IMU message, with noise. The excerpt shows these lines, from gazebo_ros_imu_sensor.cpp, lines 149–166:

gazebo_ros_imu_sensor.cpp: the sensor's values, with noise
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//applying offsets to the orientation measurement
orientation = offset.Rot()*sensor->Orientation();
accelerometer_data = sensor->LinearAcceleration();
gyroscope_data = sensor->AngularVelocity();

//Guassian noise is applied to all measurements
imu_msg.orientation.x = orientation.X() + GuassianKernel(0,gaussian_noise);
imu_msg.orientation.y = orientation.Y() + GuassianKernel(0,gaussian_noise);
imu_msg.orientation.z = orientation.Z() + GuassianKernel(0,gaussian_noise);
imu_msg.orientation.w = orientation.W() + GuassianKernel(0,gaussian_noise);

imu_msg.linear_acceleration.x = accelerometer_data.X() + GuassianKernel(0,gaussian_noise);
imu_msg.linear_acceleration.y = accelerometer_data.Y() + GuassianKernel(0,gaussian_noise);
imu_msg.linear_acceleration.z = accelerometer_data.Z() + GuassianKernel(0,gaussian_noise);

imu_msg.angular_velocity.x = gyroscope_data.X() + GuassianKernel(0,gaussian_noise);
imu_msg.angular_velocity.y = gyroscope_data.Y() + GuassianKernel(0,gaussian_noise);
imu_msg.angular_velocity.z = gyroscope_data.Z() + GuassianKernel(0,gaussian_noise);
  • accelerometer_data and gyroscope_data: the highlighted lines fetch the two results of Part 1 from Gazebo's IMU sensor. accelerometer_data is the specific force \(\mathbf f\), and gyroscope_data is the angular velocity \(\boldsymbol\omega\).
  • orientation: line 150 fetches the IMU sensor's orientation \(\mathbf q\) in the simulated world, a quaternion of length 1.
  • imu_msg: the lines from 155 on write each number into the message and add one random number to each.

The orientation on /diffbot/imu/gazebo isn't ready to use

Lines 155–158 add a separate random number to each of the quaternion's four numbers, x, y, z and w. The plugin doesn't bring the result back to the length 1. A quaternion describes a rotation only with the length 1. In one run of Remo's simulation, the length of the plugin's quaternion lay between 0.983 and 1.016. So don't read the robot's attitude from /diffbot/imu/gazebo. The topic that the robots' nodes read, /diffbot/imu/data_raw, has no orientation: the adapter marks it unavailable in Part 3.

The message's values are the IMU sensor's values plus noise:

\[ \tilde{\boldsymbol\omega} = \boldsymbol\omega + \mathbf n_\omega, \qquad \tilde{\mathbf f} = \mathbf f + \mathbf n_f \]

\(\tilde{\boldsymbol\omega}\) and \(\tilde{\mathbf f}\) are what the message carries. Each component \(n\) of \(\mathbf n_\omega\) and \(\mathbf n_f\) is a new random number in every message, from a normal distribution with mean 0 and standard deviation \(\sigma\):

\[ n \sim \mathcal N(0, \sigma^2), \qquad \sigma = \begin{cases} 0.005 \text{ rad/s} & \text{for } \mathbf n_\omega \\ 0.005 \text{ m/s}^2 & \text{for } \mathbf n_f \end{cases} \]

Where \(\sigma\) comes from: \(\sigma\) is the plugin's parameter gaussianNoise, 0.005, one number without a unit for both quantities, in the Gazebo block of the robot's URDF model, line 251 of the macro. The plugin reads the parameter into its variable gaussian_noise when Gazebo loads the plugin. The excerpt shows these lines, from gazebo_ros_imu_sensor.cpp, lines 263–273:

gazebo_ros_imu_sensor.cpp: the parameter gaussianNoise
263
264
265
266
267
268
269
270
271
272
273
//NOISE
if (sdf->HasElement("gaussianNoise"))
{
  gaussian_noise =  sdf->Get<double>("gaussianNoise");
  ROS_INFO_STREAM("<gaussianNoise> set to: " << gaussian_noise);
}
else
{
  gaussian_noise = 0.0;
  ROS_WARN_STREAM("missing <gaussianNoise>, set to default: " << gaussian_noise);
}

How a random number is drawn: GuassianKernel(0, gaussian_noise) returns one random number with mean 0 and the standard deviation gaussian_noise. The excerpt above calls GuassianKernel() once for each value.

The function GuassianKernel()

The excerpt shows the function that draws one random number, from gazebo_ros_imu_sensor.cpp, lines 194–206. It turns two evenly distributed random numbers into one normally distributed number, and scales that number with sigma:

gazebo_ros_imu_sensor.cpp: GuassianKernel()
194
195
196
197
198
199
200
201
202
203
204
205
206
double GazeboRosImuSensor::GuassianKernel(double mu, double sigma)
{
  // generation of two normalized uniform random variables
  double U1 = ignition::math::Rand::DblUniform();
  double U2 = ignition::math::Rand::DblUniform();

  // using Box-Muller transform to obtain a varaible with a standard normal distribution
  double Z0 = sqrt(-2.0 * ::log(U1)) * cos(2.0*M_PI * U2);

  // scaling
  Z0 = sigma * Z0 + mu;
  return Z0;
}

Two places where noise can be set: the simulated IMU could get noise from two parts, and the robots use one of them.

  • Gazebo's IMU sensor can add noise of its own, before the plugin reads the values. A URDF model asks for this noise with <noise> elements inside the sensor's <imu> element, one for each axis of the angular velocity and of the linear acceleration, as the SDF specification of the IMU sensor lists them. The robots' URDF models have no such element. So Gazebo's IMU sensor adds no noise.
  • The plugin adds noise when it fills the message. gaussianNoise is its only setting for that. All the noise that the robots' URDF models configure comes from the plugin.

One value for both quantities: \(\sigma\) is 0.005 rad/s for the angular velocity and 0.005 m/s² for the specific force. This is a limit of the plugin, which has one parameter for all values, and not a model of a real sensor. A gyroscope's noise in rad/s and an accelerometer's noise in m/s² are different quantities with different sizes. The acceleration's noise doesn't matter to the EKF today, because the EKF fuses only the yaw rate \(\omega_z\). The yaw rate's noise and variance do reach the EKF. They are simulation settings too. So the simulation doesn't show how the real sensor's noise affects the EKF.

A simulation setting, not a measurement: 0.005 isn't the BNO055's noise. At rest on Remo, the real BNO055's gyroscope scatters with a standard deviation of 0.0005 to 0.0008 rad/s, and its accelerometer with about 0.01 to 0.04 m/s². Bias and noise at rest on the BNO055 page has these measurements.

Filling the covariances

After the values, the same call writes the covariances. The excerpt shows these lines, from gazebo_ros_imu_sensor.cpp, lines 168–178:

gazebo_ros_imu_sensor.cpp: the covariances
168
169
170
171
172
173
174
175
176
177
178
//covariance is related to the Gaussian noise
double gn2 = gaussian_noise*gaussian_noise;
imu_msg.orientation_covariance[0] = gn2;
imu_msg.orientation_covariance[4] = gn2;
imu_msg.orientation_covariance[8] = gn2;
imu_msg.angular_velocity_covariance[0] = gn2;
imu_msg.angular_velocity_covariance[4] = gn2;
imu_msg.angular_velocity_covariance[8] = gn2;
imu_msg.linear_acceleration_covariance[0] = gn2;
imu_msg.linear_acceleration_covariance[4] = gn2;
imu_msg.linear_acceleration_covariance[8] = gn2;

gn2 is gaussian_noise squared, the variance \(\sigma^2 = 2.5 \cdot 10^{-5}\). The plugin writes this variance into the elements 0, 4 and 8 of each covariance, in (rad/s)² for the angular velocity and in (m/s²)² for the specific force. These three elements are the matrix's diagonal, as how the message stores a covariance on the overview shows. Element 8 of angular_velocity_covariance is the variance of the yaw rate \(\omega_z\), which the EKF uses. The other elements stay 0. For the angular velocity:

\[ \Sigma_\omega = \begin{pmatrix} \sigma^2 & 0 & 0 \\ 0 & \sigma^2 & 0 \\ 0 & 0 & \sigma^2 \end{pmatrix} = \sigma^2 I_3 \]

\(I_3\) is the 3 × 3 identity matrix. The specific force's covariance \(\Sigma_f\) has the same numbers, in (m/s²)².

Why the other elements are 0: an element off the diagonal is the covariance of two axes' errors. The plugin draws a separate random number for each axis, so the noise on one axis says nothing about the noise on another. The two numbers are independent, and the covariance of two independent numbers is 0, as Wikipedia's article on covariance shows. On a real sensor, the errors of two axes can be correlated: they tend to rise and fall together. Correlated errors can give elements off the diagonal that aren't 0.

Lines 170–172 of the excerpt write the orientation's covariance. The adapter replaces this covariance in Part 3.

The header and publishing

The last lines of UpdateChild() set the header, publish the message and store the time for the next call's rate limit. The excerpt shows them, from gazebo_ros_imu_sensor.cpp, lines 180–192:

gazebo_ros_imu_sensor.cpp: the end of UpdateChild()
180
181
182
183
184
185
186
187
188
189
190
191
192
    //preparing message header
    imu_msg.header.frame_id = body_name;
    imu_msg.header.stamp.sec = current_time.sec;
    imu_msg.header.stamp.nsec = current_time.nsec;

    imu_data_publisher.publish(imu_msg);
    // No ros::spinOnce() here: this function runs in Gazebo's physics thread, which must not
    // run ROS callbacks. A controller manager service that it ran would wait for this thread
    // (see the notice at the top of this file).
  }

  last_time = current_time;
}
  • The frame: body_name is the parameter frameName, imu_link.
  • The stamp: current_time is the IMU sensor's update time, from the first line of UpdateChild(). So header.stamp is the time at which Gazebo ran the measurement, not the measurement's own time, which only Gazebo's own IMU message carries. Two times of a measurement in Part 1 explains the difference. In the recorded run, the stamp was 1 ms later than the paired Gazebo stamp for 523 of the 524 paired messages.
  • publish(): line 185, the first highlighted line, publishes the finished message on /diffbot/imu/gazebo. This is the one place where the plugin publishes.
  • last_time: line 191, the second highlighted line, stores current_time for the rate limit of the next calls. Line 191 also runs when no node subscribes.

The original plugin calls ros::spinOnce() after publish()

gazebo_plugins' original IMU plugin calls ros::spinOnce() right after publish(), in line 150 of its source. The robots' copy has the comment of lines 186–188 at this place instead. This one call is the main reason why the robots have their own plugin: with ros::spinOnce() at this place, the simulation's clock can stop for good while the controllers start. Why the plugin doesn't spin explains how.

Part 3: the adapter

The adapter is there so that the nodes that read the IMU get its message in the same form in the simulation as on the real robot: a sensor_msgs/Imu message on /diffbot/imu/data_raw, with the orientation marked unavailable. On the real robot, the Teensy's firmware publishes this topic without an orientation, as what the firmware publishes shows. The plugin's message on /diffbot/imu/gazebo has an orientation \(\mathbf q\). So imu_raw_adapter.py takes each of the plugin's messages, marks the orientation unavailable as the firmware does, and publishes the result on /diffbot/imu/data_raw. Of the plugin's values, the adapter changes nothing else. The stamp, the frame, the angular velocity, the specific force and the two vectors' covariances stay as the plugin set them. So the noise and the variances are the simulation's, not the firmware's, as the simulation and the real robot compares.

diffbot_view.launch starts the adapter in the diffbot namespace. So the adapter's relative topic names become /diffbot/imu/gazebo and /diffbot/imu/data_raw. The excerpt shows the line that starts the adapter, with its comment, from diffbot_view.launch, lines 37–39:

diffbot_view.launch: the adapter's node
37
38
39
<!-- The simulated IMU publishes imu/gazebo; this node republishes it as imu/data_raw, without
     the orientation, as the real robot's firmware publishes it (scripts/imu_raw_adapter.py) -->
<node name="imu_raw_adapter" pkg="diffbot_gazebo" type="imu_raw_adapter.py" ns="diffbot" output="screen"/>

The next excerpt shows the adapter's code, from imu_raw_adapter.py, lines 16–36:

imu_raw_adapter.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
INPUT_TOPIC = 'imu/gazebo'
OUTPUT_TOPIC = 'imu/data_raw'
QUEUE_SIZE = 10  # messages, 0.2 s at the IMU's 50 Hz
# REP 145: the first element -1 marks the orientation as unavailable, the others are unused
ORIENTATION_UNAVAILABLE = [-1.0] + [0.0] * 8


class ImuRawAdapter:

    def __init__(self) -> None:
        self.publisher = rospy.Publisher(OUTPUT_TOPIC, Imu, queue_size=QUEUE_SIZE)
        rospy.Subscriber(INPUT_TOPIC, Imu, self.callback, queue_size=QUEUE_SIZE)

    def callback(self, message: Imu) -> None:
        """Publish the message without its orientation."""
        message.orientation.x = 0.0
        message.orientation.y = 0.0
        message.orientation.z = 0.0
        message.orientation.w = 0.0
        message.orientation_covariance = list(ORIENTATION_UNAVAILABLE)
        self.publisher.publish(message)
  • How a field is marked unavailable: a sensor_msgs/Imu message always has an orientation field. To say that a field holds no data, a publisher sets the first element of the field's covariance to −1. The message definition's comments ask for that, and so does REP 145, the ROS convention for IMU drivers. A node that reads the message should check that element and ignore the field. ORIENTATION_UNAVAILABLE is such a covariance: −1, then eight zeros. How the message stores a covariance shows the array next to the other cases.
  • A convention, not a rule to drop the orientation: REP 145 doesn't ask an IMU driver to leave out the orientation. A driver whose sensor estimates an orientation can publish the orientation on imu/data. The firmware's topic, imu/data_raw, is REP 145's name for the accelerometer's and the gyroscope's data alone.
  • callback(): the callback sets the four numbers of the quaternion \(\mathbf q\) to 0 and the orientation covariance to a copy of the constant. list() makes the copy, so that the messages don't share the constant's list. Then the callback publishes the same message object.
  • What stays: the header's stamp and frame, the angular velocity \(\tilde{\boldsymbol\omega}\), the specific force \(\tilde{\mathbf f}\) and their covariances \(\Sigma_\omega\) and \(\Sigma_f\). The adapter doesn't stamp the message again. The IMU sample validator checks how old each sample is, and a new stamp would hide a delay.
  • What doesn't stay, besides the orientation: the header's sequence number, header.seq. ROS numbers the messages of each publisher when it sends them. So the adapter's messages count on their own. In the sample above, the plugin's message had the seq 460 and the adapter's message the seq 447.
Where rospy sets header.seq

The excerpt shows the lines of rospy's serialize_message() that write the publisher's own count into the header before a message is sent, from msg.py in ros_comm 1.17.4, lines 142–145, under the BSD license. seq is the number that the publisher counts up with each message. The adapter's callback never sets header.seq itself:

msg.py (rospy 1.17.4): the publisher's count goes into header.seq
142
143
144
145
#update Header object in top-level message
if getattr(msg.__class__, "_has_header", False):
    header = msg.header
    header.seq = seq

Comments

Comments are GitHub Discussions, shown with giscus. Loading them connects to giscus.app (hosted by Vercel, USA) and GitHub (USA); you need a GitHub account to comment.