Read the following Part I of the project I started implementing. I’ll provide you all…
- User
Read the following Part I of the project I started implementing. I’ll provide you all the necessary code down below. Part I - Building the Environment
I implemented independent ROS nodes for part - I. ROS Node - → Implemented a node that enables the car to scan its environment using a laser range finder and avoid obstacles in front of it.
Prerequisites Dependencies: ROS (Robot Operating System) ; Gazebo (Simulation Environment) The car uses Ackermann driving. You can drive the car by publishing AckermannDrive messages to the topic car_1/command . The car is also equipped with a laser scanner which publishes LaserScan messages on the topic car_1/scan. The laser scanner on the car has a field of view from -3π/4 to 3π/4 with a resolution of 0.0043633 radians. The car publishes its odometry on the topic car_1/base/odom using an Odometry message (nav_msgs/odometry) . You can get the global position and orientation of the car from this message. Setup
Launch the Gazebo simulator using roslaunch audubon-gazebo world.launch. Command to use: This will launch the testing environment in gazebo. Now launch file pa2_spawner.launch to populate the testing space with randomly placed obstacles. Here is the command : roslaunch audubon-gazebo spawner.launch Once all obstacles are spawned, you can control the car using your keyboard. Note : Gazebo terminal needs to be in focus to take keyboard inputs.
Part II - Implementing the Deep Reinforcement Learning Algorithm
Modify the below deep Q-network (DQN) to learn the control policy for robot navigation. Feel free to go out of the box for this task. You can also add or remove the layers to make it best suitable for our task. class DQNAgentPytorch: def init(self, env, memory_size=10000, epsilon=1.0, gamma=0.99, learning_rate=0.001): self.env = env self.observation_space = env.observation_space self.action_space = env.action_space self.memory = deque(maxlen=memory_size) self.epsilon = epsilon self.gamma = gamma self.lr = learning_rate self.model = self.build_model() self.target_model = self.build_model() self.optimizer = optim.AdamW(self.model.parameters(), lr=self.lr, amsgrad= True) self.criterion = nn.SmoothL1Loss() self.update_target_net()
def build_model(self): model = nn.Sequential( nn.Linear(self.observation_space.shape[0], 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, self.action_space.n) ) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def choose_action(self, state, test=False): if test or random.random() > self.epsilon: with torch.no_grad(): state_t = torch.tensor(state, dtype=torch.float32).unsqueeze(0) q_values = self.model(state_t) return torch.argmax(q_values).item() else: return np.random.randint(self.action_space.n) def train(self, batch_size): if len(self.memory) < batch_size: return minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = self.target_model(torch.tensor(state, dtype=torch.float32).unsqueeze(0)).squeeze(0) if done: target[action] = reward else: next_q_values = self.target_model(torch.tensor(next_state, dtype=torch.float32).unsqueeze(0)).squeeze(0) target[action] = reward + self.gamma * torch.max(next_q_values) inputs = torch.tensor(state, dtype=torch.float32).unsqueeze(0) targets = target.unsqueeze(0) self.optimizer.zero_grad() outputs = self.model(inputs) loss = self.criterion(outputs, targets) loss.backward() # In-place gradient clipping torch.nn.utils.clip_grad_value_(self.model.parameters(), 100) self.optimizer.step() def update_target_net(self): self.target_model.load_state_dict(self.model.state_dict()) def update_epsilon(self, new_epsilon): self.epsilon = new_epsilon def save_weights(self, file_name): torch.save(self.model.state_dict(), file_name) def load_weights(self, file_name): self.epsilon = 0 self.model.load_state_dict(torch.load(file_name)) - Assistant
- User
Wonderful. Now I want you to implement the following: Implement the complete evader function for our task and also modify the DQN code accordingly. For the reward function, I think in my idea Let's say in the worst case scenario if the car hits a obstacle or if get's too close to one and unable to move then it can take reverse. So, for every reverse it takes we can minus the reward and for every obstacle it avoids we'll reward it accordingly. You are free to choose what ever you seem fit. Now let's rock this task by implementing end to end EvaderNode and DQN.Let's go!. I'm here to help you in every step. You can do this!
- Assistant
- User
Again Wonderful and Tq so much for your help. But here are few things to notice. I'll provide the code keyboard_teleop.py. This code uses keyboard keys as mentioned in the code to make up,down, left and right actions. So, either you can modify our Evader code based on this or you can import the necessary functions. See which one you see fit And Also can you provide me the final updated code of DQN as it is confusing for me. Here is the code: #!/usr/bin/env python3
import rospy import sys import select import termios import tty
from ackermann_msgs.msg import AckermannDrive
keyBindings = {'w':(2.0, 0.0), # move forward 'd':(2.0, -0.5), # move foward and right 'a':(2.0 , 0.5), # move forward and left 's':(-2.0, 0.0), # move reverse 'q':(0.0, 0.0)} # all stop
- Assistant
- User
Wonderful work. But sorry to bother you with this question . Can you provide me the complete updated DQN with our newly implemented reward method calculate_reward? And also implement the code to initalize the agent and make it work with our Evader node. Like code to make a connection b/w the both.
- Assistant
- User
Again Sry for this question. I'm a bit lost. I really want the complete updated DQN code without any placeholders. The complete end to end DQN code with all the modifications we made that fit our task.
- Assistant
- User
Visit this link to understand about the LaserScan msgs: http://docs.ros.org/en/noetic/api/sensor_msgs/html/msg/LaserScan.html and Also here are few details related to the laser sensor: The car is also equipped with a laser scanner which publishes LaserScan messages on the topic car_1/scan. You can print the messages published by the laser using rostopic echo or write a node to do so. Read the metadata of the LaserScan message using rostopic echo (you can echo only one message by passing arguments to this command) to check the metadata values of this particular scanner. The laser scanner on the car has a field of view from -3π/4 to 3π/4 with a resolution of 0.0043633 radians The car publishes it's odometry on the topic car_1/base/odom using an Odometry message (nav_msgs/odometry) You can get the global position and orientation of the car from this message. Orientations are represented using Quaternions and not Euler angles. ROS provides functions to convert between them. Based on this info, See if you can make some adjustments or changes to our code. Also Now with this information update the observation space accordingly.
- Assistant
Thank you for providing additional details about the laser scanner. Based on the information you provided about the car's laser scanner, I'll update the EvaderNode class and the observation_space in the main function.
- Update the
process_scanmethod in the EvaderNode class:
class EvaderNode: # ... def process_scan(self, scan): # Process the laser scan data to get the state input for the DQN state = np.array(scan.ranges)[::10] # Downsample the scan data for faster processing return state # ...In the updated code, the
process_scanmethod now downsamples the laser scan data to include only every 10th data point (`[ - Update the