# Exercise 3.12.........Navigation

**URL:** <https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715>\
**Category:** Uncategorized\
**Created:** [December 6, 2020, 10:00am UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715 "2020-12-06T10:00:05Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![abdulbasitisdost](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/abdulbasitisdost/32/9348_2.png) [@abdulbasitisdost](https://get-help.theconstruct.ai/u/abdulbasitisdost)\
**Post date:** [December 6, 2020, 10:00am UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715/1 "2020-12-06T10:00:05Z")

</div>

Respected Professor,  
I’m sorry if my doubts are too much, but I’ve to understand these codes because I have my project final review on 9th and I’m the one who has to manage the code for **Navigation** with my friend.  
So I, being in hurry, straight away jumped to the solution of exercise 3.12 when I couldn’t do it.  
#!/usr/bin/env python  
import rospy  
from geometry\_msgs.msg import Twist, PoseWithCovarianceStamped  
from std\_srvs.srv import Empty, EmptyRequest  
import time  
import math

```
class MoveHusky():
    
    def __init__ (self):
        
        # Init Publisher
        self.husky_vel_publisher = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
        self.cmd = Twist()
        # Init Subscriber
        self.amcl_pose_sub = rospy.Subscriber('/amcl_pose', PoseWithCovarianceStamped, self.sub_callback)
        self.sub_msg = PoseWithCovarianceStamped()
        # Initialize Service Client
        rospy.wait_for_service('/global_localization')
        self.disperse_particles_service = rospy.ServiceProxy('/global_localization', Empty)
        self.srv_request = EmptyRequest()
        # Other stuff
        self.ctrl_c = False
        rospy.on_shutdown(self.shutdownhook)
        self.rate = rospy.Rate(10)
        
    def shutdownhook(self):
        
        # works better than the rospy.is_shut_down()
        self.stop_husky()
        self.ctrl_c = True

    def stop_husky(self):
        
        rospy.loginfo("Shutdown time! Stop the robot")
        self.cmd.linear.x = 0.0
        self.cmd.angular.z = 0.0
        i = 0
        
        while i < 20:
            self.husky_vel_publisher.publish(self.cmd)
            self.rate.sleep()
            i += 1

    def move_forward(self, linear_speed=0.5, angular_speed=0.0):
        
        self.cmd.linear.x = linear_speed
        self.cmd.angular.z = angular_speed
        i = 0
        
        while i < 50:
            self.husky_vel_publisher.publish(self.cmd)
            self.rate.sleep()
            i += 1
        
    def turn(self, linear_speed=0.0, angular_speed=0.8):
        
        self.cmd.linear.x = linear_speed
        self.cmd.angular.z = angular_speed
        i = 0
        
        while i < 25:
            self.husky_vel_publisher.publish(self.cmd)
            self.rate.sleep()
            i += 1
    
    def move_square(self):
        
        i = 0
        
        while not self.ctrl_c and i < 4:
            # Move Forwards
            rospy.loginfo("######## Going Forwards...")
            self.move_forward()
            self.stop_husky()
            # Turn
            rospy.loginfo("######## Turning...")
            self.turn()
            self.stop_husky()
            i += 1
            
        self.stop_husky()
        rospy.loginfo("######## Finished Moving in a Square")
        
    def call_service(self):
        
        rospy.loginfo("######## Calling Service...")
        result = self.disperse_particles_service(self.srv_request)
        
    def sub_callback(self, msg):
        
        self.sub_msg = msg

    def calculate_covariance(self):
        
        rospy.loginfo("######## Calculating Covariance...")
        cov_x = self.sub_msg.pose.covariance[0]
        cov_y = self.sub_msg.pose.covariance[7]
        cov_z = self.sub_msg.pose.covariance[35]
        rospy.loginfo("## Cov X: " + str(cov_x) + " ## Cov Y: " + str(cov_y) + " ## Cov Z: " + str(cov_z))
        cov = (cov_x+cov_y+cov_z)/3
        
        return cov
        
            
if __name__ == ' __main__':
    rospy.init_node('move_husky_node', anonymous=True)
    MoveHusky_object = MoveHusky()
    
    cov = 1
    
    while cov > 0.65:
        MoveHusky_object.call_service()
        MoveHusky_object.move_square()
        cov = MoveHusky_object.calculate_covariance()
        rospy.loginfo("######## Total Covariance: " + str(cov))
        if cov > 0.65:
            rospy.loginfo("######## Total Covariance is greater than 0.65. Repeating the process...")
        else:
            rospy.loginfo("######## Total Covariance is lower than 0.65. Robot correctly localized!")
            rospy.loginfo("######## Exiting...")

```

My doubts are:

1. Where is the main logic where it checks if the **covariance** is **less** than **0.65** and then stopping the program? I can see the logic in the last part for checking for **greater than** value, but nothing seems to be there for less than **0.65** to stop the program. In the very end they are checking for condition `if cov > 0.65` or not, but that part is just printing some message.

2. Till now I didn’t understand, crystal clear, why do we import **Empty** and **EmptyRequest**?

3. In `def move_forward()` function, how long is it going to move linearly before taking turn? **This is how I thought it works:** There is this `rospy.Rate(10)`, and the loop goes upto **50**. So in each loop it stays for **10** seconds and **10 \* 50 = 500** , hence it moves **500** sec forward before it takes a turn. But, that doesn’t make sense since that much big square cannot fit into map. Even after running the code, I realised my calculation is wrong. I wonder why what I just calculated is not what is actually happening ?

4. What is **covariance** and why is the code based on the logic that the covariance should be below **0.65**? Also, What are the covariance values **other than** **1st(x)**, **8th(y)** and **last(z)** shown in the command line ?

5. I’m guessing that `call_service()` function is publishing into the **/global\_localization** service. But, what about the `sub_callback()` function ?

6. What is the following line doing?  
`cov_x = self.sub_msg.pose.covariance[0]`  
Would you please break down it’s pieces? like **sub\_msg** , then **pose** then **covariance** …

7. Why are the few logics defined in the very end of the program in `if __name__ == ' __main__'` part. Logics like:  
a. Why is `MoveHusky()` class called in the `if __name__ == ' __main__'` ?  
b. I’m seeing this for the second time that `rospy.init_node()` is called here in the end in `if __name__ == ' __main__'` , why ?  
c. Similarly calculating **covariance** is also called here and not anywhere else.  
d. So are there specific parts of the program that has to be called from `if __name__ == ' __main__'`. Is there some specific structure to what has to be called from here. If yes, would you please tell me that. If no, then what is going on here?  
e. What happens if we just skip this `if __name__ == ' __main__'` part in our normal codes.

I really appreciate the time of all my respected professors. Once again, I cordially thank you, in advance, for making everything clear to me.

---

<div class="post-metadata">

**Author:** ![duckfrost2](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/duckfrost2/32/9365_2.png) [@duckfrost2](https://get-help.theconstruct.ai/u/duckfrost2)\
**Post date:** [December 7, 2020, 9:23am UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715/2 "2020-12-07T09:23:46Z")

</div>

Hi,

Well lets go step by step:

1. The covariance is only used to check that the robot is correctly localized. The movement is made in open loop , without any sensor readings.

2. We import EMptyRequetsbecause we use it in the initializer for the service request message called self.srv\_request.

3. The rate is 10hz, that means that rate.sleep() will wait only 0.1 seconds. If we do it 50 times, it will only perform the move action 50\*0.1=5 seconds.

4. The [Covariance](https://en.wikipedia.org/wiki/Covariance) here related to how well its localized the robot using mapping. Because its based in probabilities, we want that there is not a lot of deviation between what the robot reads and what it thinks its position is.

5. Sub\_callback its only storing the amcl pose in the python class variable self.sub\_msg. So that when someone need to get that, it will be updated.

6. That line is getting the first element of the covariance array that you can find in the amcl pose message that we are storing all the time through the sub\_callback method.

7. If **name** == “ **main** ” is just to tell python that if we execute this script then it executed the code inside this if. This is used because python scripts can be used as executables for programs and also be imported to get the classes defined inside. Have a look at the [python free course :](https://app.theconstructsim.com/#/Course/38). The MoveHusky is called to initialize the class. The init\_node to start ros systems ( without it rospy.loginfo wouldn’t work or subscribers ). The other questions I think they are getting answered with what I just explained in the other answers.

Hope it helped and I highly recommend you to do the Python Basics course and the ROSBasics in 5 days based on your doubt and questions, I think they would help you a lot .

---

<div class="post-metadata">

**Author:** ![abdulbasitisdost](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/abdulbasitisdost/32/9348_2.png) [@abdulbasitisdost](https://get-help.theconstruct.ai/u/abdulbasitisdost)\
**Post date:** [December 7, 2020, 11:48am UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715/3 "2020-12-07T11:48:52Z")

</div>

Sure Professor **Miguel** @duckfrost. Even Professor **Alberto** told me the same thing. Even though I have done both of those courses, I think my basics are still weak and I need to make them strong enough.  
Thank you Professor for recommending it to me and for all your answers. Can’t thank you more.

---

<div class="post-metadata">

**Author:** ![robotino](https://get-help.theconstruct.ai/letter_avatar_proxy/v4/letter/r/c89c15/32.png) [@robotino](https://get-help.theconstruct.ai/u/robotino)\
**Post date:** [August 18, 2023, 8:50pm UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715/4 "2023-08-18T20:50:24Z")

</div>

in the course it says this:

_The only values that you need to pay attention to is the first one (which is the covariance in x), the 8th one (which is the covariance in y), and the last one (which is the covariance in z)._

But instead of the last one shouldn’t be the 15th element?

---

<div class="post-metadata">

**Author:** ![duckfrost2](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/duckfrost2/32/9365_2.png) [@duckfrost2](https://get-help.theconstruct.ai/u/duckfrost2)\
**Post date:** [August 24, 2023, 9:33am UTC](https://get-help.theconstruct.ai/t/exercise-3-12-navigation/6715/5 "2023-08-24T09:33:21Z")

</div>

Let me clear it up a bit more:

The covariance matrix provided in the `PoseWithCovarianceStamped` message from ROS’s `amcl_pose` topic is a 6x6 matrix. This matrix represents the uncertainty in the robot’s pose, which is represented as `[x, y, z, roll, pitch, yaw]`.

The matrix is flattened into an array of 36 elements. The primary diagonal of the matrix represents the variance of each variable:

- `self.sub_msg.pose.covariance[0]` represents the variance in the x position (cov\_x).
- `self.sub_msg.pose.covariance[7]` represents the variance in the y position (cov\_y).
- `self.sub_msg.pose.covariance[35]` represents the variance in the yaw orientation (cov\_z).

Note that in 2D robot localization with ROS’s AMCL, the z position, roll, and pitch are typically ignored since the robot is considered to be operating on a plane. That’s why the only elements you are concerned with are `x`, `y`, and `yaw`.

The off-diagonal elements of the covariance matrix represent the covariances between pairs of variables. If two variables increase or decrease together, then their covariance is positive. If one variable tends to increase when the other decreases, their covariance is negative. If the covariance is zero, it suggests that the two variables do not change together.

For instance:

- Element `[1]` would be the covariance between `x` and `y`.
- Element `[6]` would be the covariance between `y` and `x`, which should be the same as the covariance between `x` and `y`.
- Element `[30]` would represent the covariance between `yaw` and `x`.
