Skip to content

IMU Simulation: Tests

In the Gazebo simulation, DiffBot and Remo have a simulated IMU. The simulated IMU publishes on the same topic and with the same message type as the IMU on the real robot. CI checks the simulated IMU with three tests in Gazebo. This page shows what the tests check, how to run the tests yourself and what a pass proves. Read the page before you change where the simulated IMU sits in a robot's URDF model or the code that makes the IMU's message. This page belongs to IMU: Simulation, which explains that message.

Two Python files check the simulated IMU in Gazebo, test_imu.py and test_imu_reset.py, with three tests. Each test reads the topic /diffbot/imu/data_raw:

  1. The test at rest, in test_imu.py: the robot stands still.
    • A pass shows: the message has the form that its readers need. More than 90 messages arrive in 2 s of simulation time, each stamp is later than the one before, the frame is imu_link, the orientation \(\mathbf q\) is marked unavailable, the yaw rate \(\omega_z\) and the upward reading \(f_z\) are finite, the yaw rate's variance is positive, the mean of \(f_z\) lies within 0.5 m/s² of 9.81 m/s², which is gravity, and the mean of \(\omega_z\) lies within 0.05 rad/s of 0 rad/s.
    • Why: the IMU sample validator and the EKF need the message this way, and the firmware publishes it this way.
  2. The left turn, in test_imu.py: the robot turns left on the spot at 0.5 rad/s.
    • A pass shows: more than 90 messages arrive in 2 s of the turn, and the mean of their yaw rate \(\omega_z\) lies within 0.15 rad/s of the commanded 0.5 rad/s, nominally between 0.35 and 0.65 rad/s.
    • Why: the yaw rate is the one value that the EKF fuses, and its sign has to be that of the turn.
  3. The reset test, in test_imu_reset.py: the test resets the simulation after about 3 s.
    • A pass shows: after the test saved its count of samples, just before it calls the reset, at least ten samples arrive whose stamps advance: each later than 0 s, later than the one that counted before it, and below 1 s.
    • Why: the IMU sample validator and the EKF start over at a reset and need samples right away.

What the tests don't show lists what a pass doesn't prove. A yaw rate that stays at one value fails one of the two tests of test_imu.py: about zero fails the left turn, and about the turn rate fails at rest (what a pass of the left turn shows).

Run the tests

You need the dev container with its workspace ~/catkin_ws built and sourced, as the container's setup leaves it. In a terminal of the dev container, each of the two commands runs one robot's simulation test file, which contains the IMU tests:

1
2
rostest diffbot_gazebo sim_drive_diffbot.test
rostest diffbot_gazebo sim_drive_remo.test

Each command takes about two minutes on our test PC, because rostest starts Gazebo again for every test node. A passing run of the first command ends with these lines, with the diffbot repository at cd41ead. The commit that this page shows, 8c83f53, runs the same IMU tests with stricter checks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[diffbot_gazebo.rosunit-drive_diffbot/test_forward][passed]
[diffbot_gazebo.rosunit-drive_diffbot/test_turn][passed]
[diffbot_gazebo.rosunit-imu_diffbot/test_imu_measures_a_positive_yaw_rate_in_a_left_turn][passed]
[diffbot_gazebo.rosunit-imu_diffbot/test_imu_publishes_the_firmware_message_at_rest][passed]
[diffbot_gazebo.rosunit-imu_reset_diffbot/test_imu_publishes_again_right_after_a_simulation_reset][passed]
[diffbot_gazebo.rosunit-publish_diffbot/test_publish][passed]

SUMMARY
 * RESULT: SUCCESS
 * TESTS: 6
 * ERRORS: 0
 * FAILURES: 0

The three highlighted lines are the IMU's tests. At 8c83f53, the test file also runs the test node odom_tf_diffbot, so the output has one more line and counts 7 tests, as read the results on Simulation Test explains. What to expect from each of the IMU's tests:

  • The left turn passes when more than 90 messages arrive in 2 s and their mean yaw rate lies within 0.15 rad/s of 0.5 rad/s. A failure of the mean prints the measured mean. With a yaw rate that stays at 0 rad/s, for example, the message is 0.0 != 0.5 within 0.15 delta (0.5 difference) : turning left at 0.5 rad/s, the IMU measured 0.000 rad/s about z.
  • The test at rest passes without output. A failure names the check that failed and the value that it found.
  • The reset test prints one line, also when it passes. rostest keeps the line in the test node's result file. The next command prints the line of DiffBot's last run:

    1
    grep -o 'last stamp before the reset[^<&]*' ~/.ros/test_results/diffbot_gazebo/rosunit-imu_reset_diffbot.xml
    
    1
    last stamp before the reset 3.000 s; after the reset 10 samples, first stamps ['0.020', '0.040', '0.060'], 10 of them with advancing stamps earlier than 1.0 s
    

    Remo's result file is rosunit-imu_reset_remo.xml. The numbers differ a little from run to run: a run with Remo printed 3.019 s, with the same first stamps. The reset test explains the numbers.

Simulation Test also shows how to run all tests as CI does and how to read the results.

How rostest runs the IMU tests

Both simulation test files, sim_drive_diffbot.test and sim_drive_remo.test, run each of the two Python files as a test node of its own: imu_diffbot and imu_reset_diffbot for DiffBot, imu_remo and imu_reset_remo for Remo. The excerpt shows DiffBot's two test nodes, from sim_drive_diffbot.test, lines 34–40:

sim_drive_diffbot.test: the two IMU test nodes
34
35
36
37
38
39
40
<!-- The simulated IMU (test_imu.py): rate, frame, the orientation marked unavailable, gravity
     and a yaw rate of about zero at rest, and a positive yaw rate in a left turn -->
<test test-name="imu_diffbot" pkg="diffbot_gazebo" type="test_imu.py" time-limit="120"/>

<!-- The simulated IMU after /gazebo/reset_simulation (test_imu_reset.py): samples with stamps
     of the new simulation time arrive right after the clock went back to zero -->
<test test-name="imu_reset_diffbot" pkg="diffbot_gazebo" type="test_imu_reset.py" time-limit="180"/>

rostest starts Gazebo and the robot again for each of these test nodes, as for the other test nodes in the test file on Simulation Test. So the reset of test_imu_reset.py doesn't reach the other tests.

test_imu.py has two test methods. unittest runs a test class's methods in alphabetical order. So the left turn, test_imu_measures_a_positive_yaw_rate_in_a_left_turn, runs before the test at rest, test_imu_publishes_the_firmware_message_at_rest. This page explains the test at rest first, because its checks are the simpler ones.

Before each of the two test methods, setUp() waits until the IMU publishes and the drive controller listens to commands. Waiting until the robot can drive in the reference part of this page explains these waits.

The test at rest

test_imu_publishes_the_firmware_message_at_rest checks that the message on /diffbot/imu/data_raw is what its readers need. The EKF runs at 50 Hz, the firmware's rate. The IMU sample validator forwards only samples with the frame imu_link, rising stamps, finite values and a positive variance. And the firmware's message has no orientation. The robot stands still during this test, because then the reading on the upward axis, \(f_z\), is known: gravity alone.

The figure shows what happens during the test, from left to right over simulation time: the command that the test sends, the robot, the reading that the test checks, and the IMU's messages that the test keeps.

The test at rest over simulation timeThe test sends the stop command 20 times per second, for SETTLE, 1 s, and then for MEASURE, 2 s. The robot stands still. The test keeps the IMU’s messages of MEASURE, about 100, and needs at least 91. The mean of their readings on the upward axis must lie between 9.31 and 10.31 m/s², and the mean of their yaw rates within 0.05 rad/s of 0 rad/s. A solid line marks a reference value, gravity in the simulation, 9.8 m/s². It is not a reading. The test sends this command, 20 times per second stand still: all velocities 0 SETTLE, 1 s MEASURE, 2 s The robot, seen from above stands still may still brake after the left turn Reading on the upward axis, fz​, in m/s² 9 10 9.31 10.31 the mean over 2 s must lie here reference value: gravity in the simulation, 9.8 m/s² accepted mean of the IMU’s readings: 9.81 ± 0.5 The IMU publishes, 50 messages per second the test keeps these, about 100 pass rule: at least 91 arrivals in 2 s 0 1 2 3 simulation time since the test’s first command, in s
The test at rest, as a plan over simulation time. Blue is the command that the test sends, orange the IMU’s messages. The test keeps only the messages of MEASURE and checks them.

What the robot does: the test sends the command to stand still, first for SETTLE, 1 s, and then for MEASURE, 2 s. The excerpt shows these two lines at the start of the test method, from test_imu.py, lines 100–103:

test_imu.py: stand still, then collect
100
101
102
103
def test_imu_publishes_the_firmware_message_at_rest(self) -> None:
    stand_still = Twist()  # all velocities are 0
    self.send_command(stand_still, SETTLE)
    messages = self.collect_messages(stand_still, MEASURE)

stand_still is Twist(), a command with all velocities 0. The test sends this command for SETTLE first, because the robot may still be braking after the left turn. Then the test collects the IMU's messages of \(T\) = MEASURE = 2 s in the list messages.

The test uses two helpers for this, which the left turn uses too. The excerpt shows both helpers, from test_imu.py, lines 72–87:

test_imu.py: send_command() and collect_messages()
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def send_command(self, command: Twist, seconds: float) -> None:
    """Send the command for seconds of simulation time, COMMAND_RATE times per second."""
    rate = rospy.Rate(COMMAND_RATE)
    end = rospy.Time.now() + rospy.Duration(seconds)
    while rospy.Time.now() < end:
        self.command_publisher.publish(command)
        rate.sleep()

def collect_messages(self, command: Twist, seconds: float) -> List[Imu]:
    """Return the IMU's messages of the next seconds of simulation time.

    The test sends the command during that time, so the robot keeps following it.
    """
    self.messages.clear()
    self.send_command(command, seconds)
    return list(self.messages)
  • send_command() publishes a velocity command for seconds of simulation time, 20 times per second (COMMAND_RATE). One command isn't enough: the drive controller stops the robot when no command arrives for 0.5 s.
  • collect_messages() returns the IMU's messages of the next seconds. It empties the list, sends the command for that time while the subscriber fills the list, and returns a copy of the list.

The checks follow, each with its lines.

The rate: the test passes the messages to assert_message_rate() first, which the left turn uses too. The excerpt shows the helper, from test_imu.py, lines 89–98:

test_imu.py: the rate
89
90
91
92
93
94
95
96
97
98
def assert_message_rate(self, messages: List[Imu]) -> None:
    """Fail unless the messages of MEASURE came at more than RATE_TOLERANCE of RATE.

    So a mean is taken only over more than that share of the messages that RATE gives in
    MEASURE, and never over one message or none.
    """
    rate = len(messages) / MEASURE
    self.assertGreater(rate, RATE_TOLERANCE * RATE,
                       '{} published at {:.1f} Hz, expected {:.0f} Hz'.format(
                           TOPIC, rate, RATE))

rate is \(N / T\), with \(N\) messages in \(T\) = 2 s. The check is \(N / T > 0.9 \cdot 50 \text{ Hz} = 45 \text{ Hz}\). So the test needs more than 90 messages, which is at least 91. The firmware publishes at 50 Hz, and the EKF runs at that rate. Because this check comes first, a mean is never taken over one message or none.

The stamps: the excerpt shows the check of the stamps, from test_imu.py, lines 105–107:

test_imu.py: the stamps
105
106
107
stamps = [message.header.stamp for message in messages]
for earlier, later in zip(stamps, stamps[1:]):
    self.assertGreater(later, earlier, 'each stamp should be later than the one before')

Each stamp must be later than the one before. The IMU sample validator drops a sample that isn't later than the last one it forwarded.

The frame and the orientation: the excerpt shows the first two checks that the test makes for each message, from test_imu.py, lines 108–111:

test_imu.py: the frame and the orientation
108
109
110
111
for message in messages:
    self.assertEqual(message.header.frame_id, FRAME)
    self.assertEqual(message.orientation_covariance[0], ORIENTATION_UNAVAILABLE,
                     'the orientation should be marked unavailable')
  • The frame must be imu_link. The EKF looks up this frame to convert the yaw rate into the robot's axes.
  • orientation_covariance[0] must be −1: the orientation \(\mathbf q\), a quaternion with four numbers, is marked unavailable, as in the firmware's message. The adapter sets it.

The values and the yaw rate's variance: the excerpt shows the other checks in the same loop, from test_imu.py, lines 112–117:

test_imu.py: the values and the variance
112
113
114
115
116
117
for value in (message.angular_velocity.z, message.linear_acceleration.z):
    self.assertTrue(math.isfinite(value))
# The EKF needs a positive, finite variance for the yaw rate it fuses
variance = message.angular_velocity_covariance[YAW_RATE_VARIANCE_INDEX]
self.assertTrue(math.isfinite(variance) and variance > 0.0,
                "the yaw rate's variance should be positive, is {}".format(variance))
  • angular_velocity.z, the yaw rate \(\omega_z\), and linear_acceleration.z, the upward reading \(f_z\), must be finite: not NaN, not infinite. The IMU sample validator drops samples with values that aren't finite. Whether the yaw rate is near 0 rad/s is the test's last check, after gravity.
  • variance, the message's angular_velocity_covariance[8], must be positive and finite. Element 8 is the yaw rate's variance, \(\sigma^2 = 2.5 \cdot 10^{-5}\) (rad/s)² in the simulation, as how the message stores a covariance and filling the covariances show. The EKF weighs the yaw rate with it, and the validator drops samples without a positive, finite variance.

Gravity: the excerpt shows the check of the upward reading, from test_imu.py, lines 118–122:

test_imu.py: gravity
118
119
120
121
122
upward_readings = [message.linear_acceleration.z for message in messages]
mean_upward_reading = sum(upward_readings) / len(upward_readings)
self.assertAlmostEqual(mean_upward_reading, GRAVITY, delta=GRAVITY_TOLERANCE,
                       msg='at rest, the upward axis should read gravity, '
                           'read {:.2f} m/s²'.format(mean_upward_reading))

mean_upward_reading is the average of the upward axis's \(N\) readings, \(\bar f_z = \frac{1}{N} \sum_{i=1}^{N} f_{z,i}\). The check needs

\[ |\bar f_z - 9.81 \text{ m/s}^2| \le 0.5 \text{ m/s}^2 \]

At rest, the upward axis reads gravity, \(f_z = +9.8\) m/s² in Gazebo, as the linear acceleration explains. An IMU frame that is upside down reads about −9.8 m/s², and a plugin that leaves gravity out reads about 0 m/s².

The yaw rate at rest: the excerpt shows the last check, from test_imu.py, lines 123–127:

test_imu.py: the yaw rate at rest
123
124
125
126
127
yaw_rates = [message.angular_velocity.z for message in messages]
mean_yaw_rate = sum(yaw_rates) / len(yaw_rates)
self.assertAlmostEqual(mean_yaw_rate, 0.0, delta=YAW_RATE_AT_REST_TOLERANCE,
                       msg='at rest, the yaw rate should be about zero, the IMU '
                           'measured {:.3f} rad/s about z'.format(mean_yaw_rate))

mean_yaw_rate is the average of the \(N\) yaw rates, \(\bar\omega_z\). The check needs

\[ |\bar\omega_z| \le 0.05 \text{ rad/s} \]

The tolerance is YAW_RATE_AT_REST_TOLERANCE, a tenth of the turn rate of the left turn. It is far more than the mean of the simulated noise and far less than a yaw rate that stays at the turn rate. So an IMU whose yaw rate stays at 0.5 rad/s fails here, although it passes the left turn.

The left turn

test_imu_measures_a_positive_yaw_rate_in_a_left_turn checks the yaw rate \(\omega_z\), the one value that the EKF fuses, while the robot turns. At rest, the yaw rate is 0 rad/s however the IMU is mounted. Only a turn shows the sign of the yaw rate.

The figure shows what happens during the test: the turn command, the robot's headings that follow from the command at the start, after SPEED_UP and after MEASURE, the yaw rate \(\omega_z\) that the test checks, and the IMU's messages that the test keeps.

The left turn over simulation timeThe test sends a turn command of 0.5 rad/s about the upward axis, 20 times per second, for SPEED_UP, 1 s, and then for MEASURE, 2 s. Then it sends one stop command. The robot turns left on the spot, by about 0.5 rad after SPEED_UP and about 1.5 rad after MEASURE. These headings are ideal: they follow from the command, not from a run. The test keeps the IMU’s messages of MEASURE, about 100, and needs at least 91. The mean of their yaw rates must lie between 0.35 and 0.65 rad/s. The test sends this command, 20 times per second turn left: angular.z = 0.5 rad/s stop SPEED_UP, 1 s MEASURE, 2 s The robot from above: ideal headings from the command start about 0.5 rad, 29° about 1.5 rad, 86° Turn rate about the upward axis, ωz​, in rad/s 0 0.5 0.35 0.65 the mean over 2 s must lie here the test’s command: 0.5 rad/s accepted mean of the IMU’s yaw rates: 0.5 ± 0.15 The IMU publishes, 50 messages per second the test keeps these, about 100 pass rule: at least 91 arrivals in 2 s 0 1 2 3 simulation time since the test’s first command, in s
The left turn, as a plan over simulation time. The robot’s headings follow from the commanded turn rate: 0.5 rad/s turns the robot by 0.5 rad, about 29°, in each second. The simulated robot needs a moment to reach the turn rate, so it turns a little less.

The excerpt shows the whole test method, from test_imu.py, lines 129–140:

test_imu.py: the left turn
129
130
131
132
133
134
135
136
137
138
139
140
def test_imu_measures_a_positive_yaw_rate_in_a_left_turn(self) -> None:
    turn_left = Twist()
    turn_left.angular.z = TURN_RATE
    self.send_command(turn_left, SPEED_UP)
    messages = self.collect_messages(turn_left, MEASURE)
    self.command_publisher.publish(Twist())  # stop the robot
    self.assert_message_rate(messages)
    yaw_rates = [message.angular_velocity.z for message in messages]
    mean_yaw_rate = sum(yaw_rates) / len(yaw_rates)
    self.assertAlmostEqual(mean_yaw_rate, TURN_RATE, delta=TURN_RATE_TOLERANCE,
                           msg='turning left at {} rad/s, the IMU measured {:.3f} rad/s '
                               'about z'.format(TURN_RATE, mean_yaw_rate))
  • What the robot does: turn_left is the command, a turn on the spot at TURN_RATE, 0.5 rad/s, in the command's angular.z. send_command() sends turn_left for SPEED_UP, 1 s, so that the robot reaches the turn rate. Then collect_messages() keeps the robot turning for MEASURE, 2 s, and returns the IMU's messages of that time, which the test keeps in messages. Then the test stops the robot with Twist().
  • What the test checks: first the rate, with assert_message_rate(): more than 90 messages in the 2 s of MEASURE. Then mean_yaw_rate is the average of the yaw rates of messages, \(\bar\omega_z\). The check is assertAlmostEqual(mean_yaw_rate, TURN_RATE, delta=TURN_RATE_TOLERANCE), which needs \(|\bar\omega_z - 0.5 \text{ rad/s}| \le 0.15 \text{ rad/s}\). So the nominal range of the mean is 0.35 to 0.65 rad/s. The comparison runs with floating-point numbers: a mean of exactly 0.35 or 0.65 rad/s fails, because the computed difference is 0.15000000000000002. A left turn, counterclockwise seen from above, is positive about the upward z axis, as the angular velocity shows.

What a pass of the left turn shows

A pass shows two things: more than 90 messages arrived in the 2 s of MEASURE, and the mean of their yaw rates lies within 0.15 rad/s of 0.5 rad/s. So the test fails when the IMU's frame is upside down, which gives about −0.5 rad/s, when the yaw rate stays near 0 rad/s, and when one message or none arrives, with the rate's message instead of an error.

A yaw rate that stays at one value fails one of the two tests of test_imu.py: about 0 rad/s fails the left turn, and about 0.5 rad/s fails the test at rest. Neither test alone shows that the yaw rate follows the robot's motion, and together they show it only at rest and in this one turn.

The reset test

test_imu_reset.py checks that the IMU publishes again right after a reset of the simulation. A reset sets Gazebo's clock back to zero. A plugin that doesn't notice this stays silent for as long as the simulation ran before the reset, and the EKF gets no yaw rate in that time. Publishing again after a reset explains how the robots' plugin handles a clock that went back.

The figure shows the stamps of the IMU's samples during the test, with the robots' IMU plugin and with a plugin that keeps the time from before the reset. The figure is an idealized example: the reset comes at exactly 3 s, and the IMU publishes exactly 50 samples per second. In a run, the reset comes a little later, for example at 3.019 s. The robot stands still in this test. What changes is the simulation's clock.

The reset test with the robots’ IMU pluginThe stamps of the IMU’s samples rise with Gazebo’s clock to 3 s. Then the test resets the simulation, and the clock starts from 0 again. The first sample after the reset is stamped about 0.02 s. Samples that arrive after the test saved its count, just before the reset call, count as fresh when each stamp is later than 0 s, later than the last fresh stamp and below 1 s. The test passes with 10 of them. A dot marks sample 10, stamped about 0.20 s. With the robots’ IMU plugin Stamp of the IMU’s samples, in s of simulation time 0 1 3 the test resets the simulation 0 3 6 seconds that the simulation has run Gazebo’s clock the IMU’s samples sample 10: 0.20 s counted: rising, < 1 s 10 fresh samples: the test passes The reset test with a plugin that keeps the old timeThe stamps of the IMU’s samples rise with Gazebo’s clock to 3 s. Then the test resets the simulation, and the clock starts from 0 again. The plugin stays silent until the clock has passed 3 s again. No sample after the reset has a stamp below 1 s, so none counts as fresh, and the test fails. With a plugin that keeps the old time Stamp of the IMU’s samples, in s of simulation time 0 1 3 the test resets the simulation 0 3 6 seconds that the simulation has run Gazebo’s clock the IMU’s samples next: about 3.02 s no fresh sample silent no fresh sample: the test fails
The reset test, as an idealized example: the reset comes at exactly 3 s, and the IMU publishes exactly 50 samples per second. The robot stands still, and the test sends no command. Each panel shows the stamps of the IMU’s samples while the simulation runs. The horizontal axis doesn’t start over at the reset. The test counts a sample as fresh when the sample arrives after the test saved its count of samples, just before the reset call, with a stamp later than 0 s, later than the last fresh stamp and below RECOVERY, 1 s. In this ideal run, these are the samples in the gray area. The test passes with 10 fresh samples. It polls with a wall-time timeout of 30 s. The dot in the first panel is sample 10, stamped about 0.20 s. A repeated stamp doesn’t count, so a stream that repeats one stamp fails.

The excerpt shows the test's constants, from test_imu_reset.py, lines 35–50:

test_imu_reset.py: the constants
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
TOPIC = '/diffbot/imu/data_raw'
RESET_SERVICE = '/gazebo/reset_simulation'
QUEUE_SIZE = 100  # messages, 2 s at the IMU's 50 Hz: the test notes them all

RUN_BEFORE_RESET = 3.0  # s of simulation time that the IMU publishes for before the reset
RECOVERY = 1.0  # s of simulation time after the reset in which the IMU has to publish again
# Samples with advancing stamps from the first RECOVERY after the reset that the test waits for:
# 0.2 s at the IMU's 50 Hz, which shows that the IMU keeps publishing. The IMU's rate is
# test_imu.py's check
FRESH_SAMPLE_COUNT = 10
STARTUP_TIMEOUT = 60.0  # s of wall time for Gazebo to start and offer its reset service
# s of wall time for the IMU's stamps to reach RUN_BEFORE_RESET. The world runs the simulation
# at real time at most (diffbot_empty.world), and slower on a busy computer
RUN_TIMEOUT = 60.0
RECOVERY_TIMEOUT = 30.0  # s of wall time for the fresh samples to arrive after the reset
POLL_INTERVAL = 0.02  # s of wall time between two looks at the received samples

RUN_BEFORE_RESET and RECOVERY, the highlighted lines, are seconds of simulation time. The test compares them with the samples' stamps. The three timeouts and POLL_INTERVAL are seconds of wall time.

setUp() subscribes to /diffbot/imu/data_raw with the callback note_stamp(), which notes each sample's stamp in the list self.stamps. Then setUp() waits for Gazebo's reset service.

setUp(), note_stamp() and imu_ran_before_reset()

The excerpt shows how the test collects the stamps and how it decides that the IMU has run long enough, from test_imu_reset.py, lines 55–68. self.stamps[-1] is the stamp of the sample that arrived last:

test_imu_reset.py: setUp(), note_stamp() and imu_ran_before_reset()
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def setUp(self) -> None:
    self.stamps: List[float] = []  # s of simulation time, in the order the samples arrived
    self.sample_count_at_reset = 0
    rospy.Subscriber(TOPIC, Imu, self.note_stamp, queue_size=QUEUE_SIZE)
    rospy.wait_for_service(RESET_SERVICE, timeout=STARTUP_TIMEOUT)
    self.reset_simulation = rospy.ServiceProxy(RESET_SERVICE, Empty)

def note_stamp(self, message: Imu) -> None:
    """Note the sample's stamp."""
    self.stamps.append(message.header.stamp.to_sec())

def imu_ran_before_reset(self) -> bool:
    """Return whether the IMU's stamps have reached RUN_BEFORE_RESET."""
    return bool(self.stamps) and self.stamps[-1] >= RUN_BEFORE_RESET

The next excerpt shows the start of the test method, from test_imu_reset.py, lines 100–107:

test_imu_reset.py: run, reset, wait for fresh samples
100
101
102
103
104
105
106
107
def test_imu_publishes_again_right_after_a_simulation_reset(self) -> None:
    self.assertTrue(self.wait_for(self.imu_ran_before_reset, RUN_TIMEOUT),
                    "{}'s stamps didn't reach {} s within {} s of wall time, got {} "
                    'samples'.format(TOPIC, RUN_BEFORE_RESET, RUN_TIMEOUT, len(self.stamps)))
    self.sample_count_at_reset = len(self.stamps)
    stamp_before_reset = self.stamps[-1]
    self.reset_simulation()
    recovered = self.wait_for(self.imu_recovered, RECOVERY_TIMEOUT)
  1. Run: the test waits until the latest stamp is at least RUN_BEFORE_RESET, 3 s. The test looks at the stamps every POLL_INTERVAL, 0.02 s of wall time, so the last stamp before the reset is 3 s or a little later. In the two runs of Run the tests, the last stamp was 3.000 s and 3.019 s. last_time in the plugin then holds about that time.
  2. Reset: the test notes how many samples have arrived, in sample_count_at_reset, and calls /gazebo/reset_simulation, the highlighted line. Gazebo's clock starts from zero again.
  3. Wait for fresh samples: the test waits for FRESH_SAMPLE_COUNT fresh samples, ten here. Each poll checks the count first. If the count is still too low and the wall clock has passed RECOVERY_TIMEOUT, 30 s, the wait fails.

Which samples count as fresh

The excerpt shows which samples count as fresh, from test_imu_reset.py, lines 70–88:

test_imu_reset.py: fresh_stamps() and imu_recovered()
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def fresh_stamps(self) -> List[float]:
    """Return the advancing stamps from the first RECOVERY of simulation time after the reset.

    A stamp counts when it is later than zero, later than the last stamp that counted, and
    earlier than RECOVERY. So a stamp that repeats or goes back doesn't count. A sample that
    the IMU published before the reset can still arrive after it. Its stamp is
    RUN_BEFORE_RESET or later, so it doesn't count either.
    """
    fresh_stamps: List[float] = []
    latest_fresh_stamp = 0.0
    for stamp in self.stamps[self.sample_count_at_reset:]:
        if latest_fresh_stamp < stamp < RECOVERY:
            fresh_stamps.append(stamp)
            latest_fresh_stamp = stamp
    return fresh_stamps

def imu_recovered(self) -> bool:
    """Return whether enough fresh samples have arrived."""
    return len(self.fresh_stamps()) >= FRESH_SAMPLE_COUNT

fresh_stamps() goes through the stamps that arrived after the test noted sample_count_at_reset, in the order of their arrival. A stamp counts when it is later than 0 s, later than latest_fresh_stamp, the last stamp that counted, and below RECOVERY, 1 s. imu_recovered() is true when ten stamps count. So a pass shows this much: after the test saved the count, at least ten samples arrived whose stamps advance and lie below 1 s. Such a stamp belongs to the new simulation time, because the stamps had reached 3 s before the reset.

  • With the robots' plugin, the first sample after the reset is stamped about 0.02 s, one period after the clock went back. Ten fresh samples then take about 0.2 s of simulation time. The test doesn't require these two values: it accepts any ten advancing stamps below 1 s.
  • With a plugin that keeps the old time, the next sample comes only after the clock has passed 3 s again. Then no sample is stamped below 1 s, and the test fails.
  • Stamps that don't advance: a stamp of 0 s, a stamp that repeats the last one that counted, and a stamp that goes back don't count. So ten samples with one and the same stamp give one fresh sample at most, and the test fails. The IMU sample validator would forward one of them at most too. A sample that the IMU published before the reset and that arrives after it has a stamp of 3 s or later, so it doesn't count either.
  • Repeated stamps: a repeat adds nothing to the count. The test can still pass if ten other stamps advance and lie below 1 s.

After the wait, the test prints one line and then checks the result.

The printed line and the failure message

The excerpt shows the end of the test method, from test_imu_reset.py, lines 108–122. print() writes the line that Run the tests shows: the last stamp before the reset, the number of samples after the reset, the first three of their stamps, and how many of them are fresh. The failure message of assertTrue() adds the limits:

test_imu_reset.py: the printed line and the failure message
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
fresh_stamps = self.fresh_stamps()
stamps_after_reset = self.stamps[self.sample_count_at_reset:]
print('last stamp before the reset {:.3f} s; after the reset {} samples, first stamps {}, '
      '{} of them with advancing stamps earlier than {} s'.format(
          stamp_before_reset, len(stamps_after_reset),
          ['{:.3f}'.format(stamp) for stamp in stamps_after_reset[:3]],
          len(fresh_stamps), RECOVERY))
self.assertTrue(
    recovered,
    'after the reset at stamp {:.3f} s, {} published {} samples with advancing stamps '
    'earlier than {} s within {} s of wall time, expected {}. It published {} samples '
    'in all, the first stamped {}'.format(
        stamp_before_reset, TOPIC, len(fresh_stamps), RECOVERY, RECOVERY_TIMEOUT,
        FRESH_SAMPLE_COUNT, len(stamps_after_reset),
        ['{:.3f} s'.format(stamp) for stamp in stamps_after_reset[:3]]))

What the tests don't show

Each item says what isn't tested, why not, and what a pass therefore doesn't prove.

  • That the yaw rate follows the robot's motion: the two tests of test_imu.py check the yaw rate's mean at rest and in one left turn, as what a pass of the left turn shows explains. A yaw rate that keeps one value fails one of them, but a pass doesn't show how the yaw rate follows other motions.
  • That a repeated stamp after a reset is rare: test_imu_reset.py doesn't count a repeated stamp and needs ten advancing ones. A stream with a few repeats among them still passes.
  • That the simulation can't stall while the controllers start: the stall of gazebo_plugins' original plugin depends on timing: it needs a request of the controller spawner in the global callback queue at the moment that the plugin spins, as one request, with each plugin explains. Most starts pass, with the original too, and each test node starts the simulation once. So a pass of test_imu.py doesn't show that the deadlock is gone. The counts of many starts, with the original and with the copy, are in diffbot#185. If a start did stall, setUp() would end with an error, because no odometry comes. A longer STARTUP_TIMEOUT wouldn't help, because a stopped clock doesn't start again.
  • Which way the IMU's x and y axes point: test_imu.py checks only the upward axis: the yaw rate and the reading of gravity. A rotation of the IMU about that axis changes neither. So a pass doesn't show that the imu_rpy of the robot's URDF model is right. Without the −90° of Remo's mounting, the test would still pass.
  • The size and the direction of the horizontal acceleration: no test drives the robot forward and compares the reading with the robot's acceleration. A pass says nothing about the size and the sign of \(f_x\) and \(f_y\), the message's linear_acceleration.x and linear_acceleration.y. The EKF doesn't fuse the acceleration, but the IMU sample validator still reads it: the validator drops a sample when one of its six values isn't finite, with the sample's yaw rate. The excerpt shows this check, from imu_validator.py, lines 268–273:

    imu_validator.py: check_finite_values()
    268
    269
    270
    271
    272
    273
    def check_finite_values(self, message: Imu, now: rospy.Time) -> Optional[DropReason]:
        """Return NOT_FINITE unless the angular velocity and linear acceleration are finite."""
        components = (message.angular_velocity.x, message.angular_velocity.y,
                      message.angular_velocity.z, message.linear_acceleration.x,
                      message.linear_acceleration.y, message.linear_acceleration.z)
        return None if all(math.isfinite(value) for value in components) else DropReason.NOT_FINITE
    

    The test at rest checks that \(\omega_z\) and \(f_z\) are finite. It doesn't look at the other four values, \(\omega_x\), \(\omega_y\), \(f_x\) and \(f_y\).

  • The real BNO055: the simulated noise is a setting, \(\sigma\) = 0.005 rad/s and 0.005 m/s², and the simulation adds no bias and no sensor delay to the values. So a pass says nothing about the real sensor's noise, bias, delay and mounting. The bench checks measure the real sensor's rate, noise, bias and axes on the robot. They don't measure a delay of the sensor. Without an added delay, a subscriber of the simulation still gets each sample a little after its stamp. In one run of Remo's simulation, a subscriber's callback for the messages on /diffbot/imu/data_raw ran 1 to 2 ms of simulation time after the messages' stamps.

  • The rest of the simulation after a reset: test_imu_reset.py checks the IMU's topic after one reset, about 3 s after the start. A pass doesn't show that the other publishers come back at once. Two of them don't:

    • The drive controller's odometry: the EKF's limits on the Localization page explain why, with the times of a run.
    • The joint states: joint_state_controller publishes only when the clock has passed last_publish_time_ by one publishing period. A reset sets the clock back to zero, and last_publish_time_ keeps its value from before the reset. So the controller publishes the joint states again only when the clock has reached that time again. This follows from the controller's code and isn't measured in a run. The excerpt shows the condition in the controller's update(), from joint_state_controller.cpp in ros_controllers 0.22.0, lines 104–110:

      joint_state_controller.cpp: when update() publishes the joint states
      104
      105
      106
      107
      108
      109
      110
      // limit rate of publishing
      if (publish_rate_ > 0.0 && last_publish_time_ + ros::Duration(1.0/publish_rate_) < time){
      
        // try to publish
        if (realtime_pub_->trylock()){
          // we're actually publishing, so increment time
          last_publish_time_ = last_publish_time_ + ros::Duration(1.0/publish_rate_);
      
  • The EKF: these tests read /diffbot/imu/data_raw, the validator's input. Whether the validator forwards the samples and the EKF uses them is the subject of the EKF's tests on the Localization page.

Reference: how the tests wait

This part explains the code around the checks: the constants, what setUp() waits for, and which clock each wait of the tests counts.

The constants of test_imu.py

The excerpt shows all constants of the file, from test_imu.py, lines 23–53. The comments say what each number is. STARTUP_TIMEOUT and POLL_INTERVAL are seconds of wall time, the computer's clock. SETTLE, SPEED_UP and MEASURE are seconds of simulation time, Gazebo's clock. Wall time and simulation time explains the difference.

test_imu.py: the constants
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
TOPIC = '/diffbot/imu/data_raw'
COMMAND = '/diffbot/mobile_base_controller/cmd_vel'
ODOMETRY = '/diffbot/mobile_base_controller/odom'
FRAME = 'imu_link'
QUEUE_SIZE = 100  # messages, 2 s at RATE: the test collects them all
COMMAND_QUEUE_SIZE = 1  # only the latest command matters

RATE = 50.0  # Hz, the firmware's rate
RATE_TOLERANCE = 0.9  # the share of RATE that the topic must reach at least
STARTUP_TIMEOUT = 60.0  # s of wall time, for Gazebo and the controller spawner
POLL_INTERVAL = 0.1  # s of wall time between checks for the drive controller's subscription
# The drive controller stops the robot when no command arrives for 0.5 s (diff_drive_controller's
# default cmd_vel_timeout), so the test sends its command again at this rate, as test_drive.py does
COMMAND_RATE = 20  # Hz
SETTLE = 1.0  # s of simulation time at rest before the test measures
SPEED_UP = 1.0  # s of simulation time for the robot to reach the turn rate
MEASURE = 2.0  # s of simulation time that each test collects the IMU's messages for

# REP 145: orientation_covariance[0] = -1 marks the orientation as unavailable
ORIENTATION_UNAVAILABLE = -1.0
# The index of the z-z element in the row-major 3x3 angular velocity covariance, which holds
# the yaw rate's variance
YAW_RATE_VARIANCE_INDEX = 8
GRAVITY = 9.81  # m/s², what the upward axis reads at rest
GRAVITY_TOLERANCE = 0.5  # m/s²
TURN_RATE = 0.5  # rad/s, the commanded left turn
TURN_RATE_TOLERANCE = 0.15  # rad/s
# How far the mean yaw rate may lie from zero while the robot stands still. A tenth of TURN_RATE
# is far more than the mean of the plugin's noise, and far less than a yaw rate that stays at
# the turn rate
YAW_RATE_AT_REST_TOLERANCE = TURN_RATE / 10  # rad/s

Waiting until the robot can drive

Both tests of test_imu.py send velocity commands to the robot. A command that the robot doesn't receive would make the test measure a robot at rest. So before each test, setUp() waits until the IMU publishes and the drive controller listens. unittest calls setUp() before each test method. The excerpt shows setUp(), from test_imu.py, lines 58–70:

test_imu.py: setUp()
58
59
60
61
62
63
64
65
66
67
68
69
70
def setUp(self) -> None:
    self.messages: List[Imu] = []
    rospy.Subscriber(TOPIC, Imu, self.messages.append, queue_size=QUEUE_SIZE)
    self.command_publisher = rospy.Publisher(COMMAND, Twist, queue_size=COMMAND_QUEUE_SIZE)
    rospy.wait_for_message(TOPIC, Imu, timeout=STARTUP_TIMEOUT)
    # Gazebo's IMU publishes before the controller spawner has started the drive controller:
    # wait until the controller publishes its odometry and listens to the commands
    rospy.wait_for_message(ODOMETRY, Odometry, timeout=STARTUP_TIMEOUT)
    deadline = time.monotonic() + STARTUP_TIMEOUT
    while self.command_publisher.get_num_connections() == 0:
        self.assertLess(time.monotonic(), deadline,
                        "the drive controller doesn't subscribe to " + COMMAND)
        time.sleep(POLL_INTERVAL)
  • List[Imu]: Imu is the Python class of the message type sensor_msgs/Imu, imported from sensor_msgs.msg in line 21. Each IMU message arrives as an Imu object. List[Imu] is a type hint from Python's typing module: it says that self.messages is a list of Imu messages. Python doesn't check it when the test runs. It tells readers and tools such as mypy what the list holds.
  • The subscriber: rospy.Subscriber(TOPIC, Imu, self.messages.append, queue_size=QUEUE_SIZE) subscribes to /diffbot/imu/data_raw. Its arguments are the topic, the message class, and the callback that rospy calls for each message. The callback is the list's append method, so each message is added to self.messages. rospy runs the callback in one of its background threads, so the list fills while the test method waits. The test keeps no variable for the subscriber: rospy keeps the subscription until the node shuts down.
  • The publisher: rospy.Publisher(COMMAND, Twist, queue_size=COMMAND_QUEUE_SIZE) creates a publisher for geometry_msgs/Twist velocity commands on the drive controller's topic. self.command_publisher keeps it for the test methods.
  • The first IMU message: rospy.wait_for_message() waits for this message. The message comes early, because Gazebo's IMU sensor, the plugin and the adapter publish soon after the robot is in the simulation.
  • An IMU message doesn't mean that the robot can drive: the controller spawner starts the drive controller, mobile_base_controller, later, as the launch file on Simulation Test shows. So setUp() waits for the controller's first odometry message, which shows that the controller runs.
  • A running controller can still miss the first commands: ROS connects a publisher and a subscriber only after both exist, and a message published before the connection is lost. get_num_connections() counts the subscribers connected to the test's publisher. The loop waits until the drive controller has connected, at most STARTUP_TIMEOUT, 60 s.

Wall time and simulation time

The tests wait on two clocks:

  • Wall time is the computer's clock, the time that a clock on the wall shows.
  • Simulation time is Gazebo's clock. It starts at 0 s when the simulation starts and moves on by 1 ms with every simulation step. It stands still while Gazebo starts, and for good when the simulation stalls.

Where the two differ: the two clocks don't run at the same speed. Their ratio is Gazebo's real time factor: 1 when a second of simulation takes a second of wall time, and less than 1 when the computer is too slow for that, as Gazebo's tutorial on physics parameters explains. The test world requests real time: 1000 steps of 1 ms per second. A busy computer, such as a CI runner, reaches less. So 2 s of simulation time can take 2 s of wall time, or 5 s.

Which clock a ROS node reads: a ROS node reads the computer's clock, unless the parameter use_sim_time is set. Then rospy.Time.now(), rospy.sleep() and rospy.Rate follow Gazebo's clock, which Gazebo publishes on the topic /clock. The ROS wiki's page on the clock describes this. The simulation's launch file enables use_sim_time by default. Python's own time.monotonic() and time.sleep() always count wall time.

Not every rospy function follows use_sim_time. rospy.wait_for_message() counts its timeout on the computer's clock, with time.time(). The excerpt shows rospy's lines that count this timeout, from client.py in ros_comm 1.17.4, lines 413–420, under the BSD license:

client.py (rospy 1.17.4): the timeout of wait_for_message()
413
414
415
416
417
418
419
420
if timeout is not None:
    if isinstance(timeout, rospy.Duration):
        timeout = timeout.to_sec()
    timeout_t = time.time() + timeout
    while not rospy.core.is_shutdown() and wfm.msg is None:
        rospy.rostime.wallsleep(0.01)
        if time.time() >= timeout_t:
            raise rospy.exceptions.ROSException("timeout exceeded while waiting for message on topic %s"%resolve_name)

rospy.wait_for_service() also measures its timeout on the computer's clock.

Which clock each wait of the tests counts: the waits in wall time:

  • test_imu.py, the first IMU message and the first odometry message, each at most STARTUP_TIMEOUT, 60 s, in lines 62 and 65: while Gazebo starts, the simulation's clock stands still. A limit in simulation time would never run out.
  • test_imu.py, the drive controller's connection, at most STARTUP_TIMEOUT, 60 s, with time.monotonic() and time.sleep() in lines 66–70: the same reason.
  • test_imu_reset.py, Gazebo's reset service, at most STARTUP_TIMEOUT, 60 s, in line 59: while Gazebo starts, the simulation's clock stands still.
  • test_imu_reset.py, wait_for() with RUN_TIMEOUT, 60 s, and RECOVERY_TIMEOUT, 30 s, with time.monotonic() and time.sleep(): the test sets the simulation's clock back on purpose. In simulation time, rospy.sleep() raises ROSTimeMovedBackwardsException if it observes a clock value earlier than the sleep's start time. The polling loop checks the condition before comparing the wall clock with its deadline:

    test_imu_reset.py: wait_for()
    90
    91
    92
    93
    94
    95
    96
    97
    98
    @staticmethod
    def wait_for(condition: Callable[[], bool], timeout: float) -> bool:
        """Return whether the condition became true within timeout seconds of wall time."""
        deadline = time.monotonic() + timeout
        while not condition():
            if time.monotonic() > deadline:
                return False
            time.sleep(POLL_INTERVAL)
        return True
    
  • Both files, rostest's time-limit, 120 s for test_imu.py and 180 s for test_imu_reset.py, in lines 36 and 40 of sim_drive_diffbot.test: the limit stops a test node that hangs.

The waits in simulation time:

  • test_imu.py, send_command() for SETTLE, SPEED_UP and MEASURE, 1 s, 1 s and 2 s, with rospy.Time.now() and rospy.Rate in lines 72–78: the robot's motion and the number of IMU messages depend on simulated seconds. MEASURE sets a target of 2 s of simulation time. At 50 Hz the test expects about 100 messages and requires at least 91.
  • test_imu_reset.py, RUN_BEFORE_RESET, 3 s, and RECOVERY, 1 s, in line 68 and line 81: the test reads no clock for them. It reads the samples' stamps. They say how long the IMU ran before the reset and how early it came back, in the IMU's own time.

One wait counts no clock:

  • test_imu_reset.py, the call of /gazebo/reset_simulation, between the two wait_for() waits, in line 106: the service call sends the request and waits for a response. The excerpt shows these lines, from tcpros_service.py in ros_comm 1.17.4, lines 518–523, under the BSD license:

    tcpros_service.py (rospy 1.17.4): a service call sends its request and waits
    518
    519
    520
    521
    522
    523
    # send the actual request message
    self.seq += 1
    transport.send_message(request, self.seq)
    
    try:
        responses = transport.receive_once()
    

    The test gives the call no time limit, and RECOVERY_TIMEOUT starts only after the call returns. If the answer never came, only rostest's time-limit would end the test.

When a wait in wall time runs out in test_imu.py: without an IMU message or an odometry message in time, rospy.wait_for_message() raises an exception, and the test reports an error. When the drive controller doesn't connect in time, assertLess() fails, and the test reports a failure. In test_imu_reset.py, the three timeouts only limit how long a failing run takes. The reset call has no timeout of its own, so rostest's time-limit of 180 s is its only bound.

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.