[Help] : Not Able to Wrap my Head Around the Code!

asked 2021-01-10 14:16:58 -0500

Hello there,

I am building a self-driving vehicle in Gazebo as my graduating project.

I've found a code on Github that does part of my project and decided to use it but the problem is that I'm not able to understand the mathematic model behind that code. the code creates an anonymous node that subscribes to /scan topic, where a Laserscan msg is published through, and publishes a Twist msg to /cmd_vel topic.

The code taken from Vibhutha Kumarage's repository is the following:

!/usr/bin/env python

import rospy from std_msgs.msg import String import sensor_msgs.msg import random import numpy as np from geometry_msgs.msg import Twist from itertools import * from operator import itemgetter

LINX = 0.0 #Always forward linear velocity. THRESHOLD = 1.5 #THRESHOLD value for laser scan. PI = 3.14 Kp = 0.05 angz = 0

def LaserScanProcess(data): range_angels = np.arange(len(data.ranges)) ranges = np.array(data.ranges) range_mask = (ranges > THRESHOLD) ranges = list(range_angels[range_mask]) max_gap = 40 # print(ranges) gap_list = [] for k, g in groupby(enumerate(ranges), lambda (i,x):i-x): gap_list.append(map(itemgetter(1), g)) gap_list.sort(key=len) largest_gap = gap_list[-1] min_angle, max_angle = largest_gap[0]((data.angle_increment)180/PI), largest_gap[-1]((data.angle_increment)180/PI) average_gap = (max_angle - min_angle)/2

turn_angle = min_angle + average_gap

print(min_angle, max_angle)
print(max_gap,average_gap,turn_angle)

global LINX
global angz
if average_gap < max_gap:
    angz = -0.5
else:
    LINX = 0.5
    angz = Kp*(-1)*(90 - turn_angle)

def main(): rospy.init_node('listener', anonymous=True)

pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
rospy.Subscriber("scan", sensor_msgs.msg.LaserScan , LaserScanProcess)

rate = rospy.Rate(10) # 10hz

while not rospy.is_shutdown():
    command = Twist()
    command.linear.x = LINX
    command.angular.z = angz
    pub.publish(command)
    rate.sleep()

if __name__ == '__main__': main() I am stuck with the following part of the code:

for k, g in groupby(enumerate(ranges), lambda (i,x):i-x): gap_list.append(map(itemgetter(1), g)) gap_list.sort(key=len) largest_gap = gap_list[-1] min_angle, max_angle = largest_gap[0]((data.angle_increment)180/PI), largest_gap[-1]((data.angle_increment)180/PI) average_gap = (max_angle - min_angle)/2

turn_angle = min_angle + average_gap

The code works fine in the simulator and I've added to my vehicle that I am creating but I need to understand what happens behind the code to be able to modify and adjust the code more to my project. I am very grateful to any comment or explanation.

edit retag flag offensive close merge delete

Comments

Your code isn't readable. To format the code properly, select the code snippet and press Ctrl + K. Comment once you have reformatted the above code.

skpro19 gravatar image skpro19  ( 2021-01-11 13:05:17 -0500 )edit