ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

beginner at reinforcement learning need help with code

asked 2021-02-08 21:49:14 -0600

PGTKing gravatar image

updated 2021-02-09 17:29:17 -0600

I'm trying to print the reward, but nothing is printing on the terminal

here is my code

#!/usr/bin/env python3   
# license removed for brevity

import rospy
from std_msgs.msg import Float64
import math
import random
from sensor_msgs.msg import JointState
import numpy as np
import time
###from keras.models import Sequential
###from keras.layers import Dense, Dropout


start_time = time.time()

class RobotControl():
    def __init__(self):
        rospy.init_node('robot_control_node', anonymous=True)
        self.talker = rospy.Publisher('/rrbot/joint1_position_controller/command', Float64, queue_size=10)
         rospy.Subscriber('/rrbot/joint_states', JointState, self.joint_callback)
         self.force = None  # Generally, it's good to initialize member variables.  What if callback() is called before give_force()?
        rate = rospy.Rate(10)
        while not rospy.is_shutdown():
            self.give_force()
            rate.sleep()

    def give_force(self):
        self.force = random.choice([-2,2])  # Changes force every time, right before publishing
        self.talker.publish(self.force)

    def joint_callback(self, data):
        self.joint = data.position[0]

    def observation_check(self):
        max_height = -3.2
        if (self.joint < max_height):
            done = True
        else:
            done = False
        return done

    def get_reward_for_observations(done):
        if done == True:
            reward = (time.time() - start_time)
        else:
            pass
        print(reward)
def robot_arm_system_test():

robotcontrol()

done = robotcontrol.observation_check()
reward = robotcontrol.get_reward(done)
print(reward)

if __name__=="__main__":
    robot_arm_system_test()
edit retag flag offensive close merge delete

Comments

1

Are you only running this code? The get_reward_for_observations that is executing print doesn't seem to be called from anywhere.

miura gravatar image miura  ( 2021-02-09 07:02:19 -0600 )edit
2

fix your formatting and first do some debuggin yourself please, your robotcontrol class doesn't have a function 'get_reward'. also passing a 'done' function parameter is not required, and bad practise, just don't execute that function

crnewton gravatar image crnewton  ( 2021-02-10 07:37:16 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-02-10 10:38:00 -0600

carlosmR gravatar image

updated 2021-02-10 10:39:25 -0600

Hello,

In the class constructor there is a while statement blocking the remaining code execution which is not what you want, I believe. So even if the sintax in your robot_arm_system_test was correct on your code, the functions would not execute.

I believe that what you want is to setup a simple publish subscriber in the same class. To do so you can create a thread handling the publisher. However, if your class is driven only by a single publisher and subscriber you can keep your constructor as is (while ros is ok, publish).

Here is an example of how you could do it (WITH THREAD and rospy.spin if nothing is to be done after it):

#!/usr/bin/env python3

import rospy
from std_msgs.msg import Float64
import math
import random
from sensor_msgs.msg import JointState
import numpy as np
import time
import threading

start_time = time.time()


class RobotControl:

    def __init__(self):
        rospy.init_node('robot_control_node', anonymous=True)
        self.talker = rospy.Publisher('/rrbot/joint1_position_controller/command', Float64, queue_size=10)
        rospy.Subscriber('/rrbot/joint_states', JointState, self.joint_callback)
        self.force = None
        self.joint = None
        self.rate = rospy.Rate(10)
        #HERE EITHER USE THE THREAD if you do not want the code to be stuck
        self.pub_thread = threading.Thread(target=self.publisher)
        # start separate entity publishing data
        self.pub_thread.start()
        # SPIN SINCE WE DO NOT NEED TO DO ANYTHING 
        rospy.spin()

    def publisher(self):
        while not rospy.is_shutdown():
            self.give_force()
            self.rate.sleep()

    def give_force(self):
        self.force = random.choice([-2,2])  # Changes force every time, right before publishing
        self.talker.publish(self.force)

    def joint_callback(self, data):
        self.joint = data.position[0]
        reward = None
        if self.observation_check() is True:
            reward = (time.time() - start_time)
        else:
            pass

        print(reward)

    def observation_check(self):
        max_height = -3.2
        if self.joint < max_height:
            done = True
        else:
            done = False
        return done


if __name__ == "__main__":
    # Instantiate the class
    my_robot = RobotControl()
edit flag offensive delete link more

Comments

@carlosmR, Hey this worked for me, appreaciate it. I don't understand the threading part. Why is it needed?

PGTKing gravatar image PGTKing  ( 2021-02-10 17:34:03 -0600 )edit

The threading part is only needed if you want the have to keep publishing and still be able to do other stuff in parallel. In this case you could keep your while loop because the functions you were calling are now being called in the subscription callback

carlosmR gravatar image carlosmR  ( 2021-02-10 18:19:47 -0600 )edit

@pregnantghettoteen I received the reply on the email, but somehow your comment is not here. As I told you in the last comment, since I removed your calls in the robot_arm_system_test function, and placed them in the subscription callback "joint_callback" the thread is not needed. Maybe you missed this change I did? reward = None if self.observation_check() is True: reward = (time.time() - start_time) else: pass

    print(reward)

I was just presenting a scenario in which thread could be useful. Summing up: - If you want to keep your function robot_arm_system_test and call it in the main function, you need the thread and you need to make sure that the program is not stoping after it. - If you do not want to keep your robot_arm_system_test, and given the fact that the print is located in the call back, you can keep your while loop in the class constructor.

carlosmR gravatar image carlosmR  ( 2021-02-11 14:10:58 -0600 )edit

I took out the threading portion, and it seems to work the exact same. So to make things clear, the threading would be necessary if I had another function running as well. Sorry, if my question appears dumb, trying to get a grasp on this.Yeah I deleted the last comment. Ok, your last comment made things clear, thanks!

PGTKing gravatar image PGTKing  ( 2021-02-11 15:09:13 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2021-02-08 21:49:14 -0600

Seen: 94 times

Last updated: Feb 10 '21