Difference between revisions of "Joint Torque Springs Example"

Jump to: navigation , search
(Arguments)
(Add code walkthrough into one page)
Line 8: Line 8:
 
<div class="content-block">
 
<div class="content-block">
  
== Code Walkthrough ==  
+
== Introduction ==
<span style="font-size:120%;">[[Joint Torque Springs Example -_Code_Walkthrough | Joint Torque Springs Example - Code Walkthrough]]</span>
+
 
 +
The Joint Torque Springs Example demonstrates the usage of torque controller to apply torque commands to robot's joints. In the main() function, the dynamic reconfigure from server is initialized and passed to an object of the JointSprings class. On initialization, the object creates an instance of the limb class for the particular side that is passed, and captures the default spring and damping constants from the dynamic reconfigure server. The main() function calls the method, move_to_neutral() to send the limbs to a neutral position. Then, the attach_spring() method captures the initial joint angles of the limb and calls the update_forces() method which calculates the necessary torques based on Hooke's law and publishes them as joint commands.
 +
 
 +
'''Interfaces - '''
 +
<div style="column-count:3;-moz-column-count:3;-webkit-column-count:3">
 +
* Limb.set_joint_torques()
 +
* Limb.move_to_neutral()
 +
* Limb.joint_angles()
 +
* Limb.joint_velocities()
 +
* Limb.set_command_timeout()
 +
* Limb.exit_control_mode()
 +
</div>
  
 
</div>
 
</div>
Line 71: Line 82:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
</div>
 +
 +
<div class="content-block">
 +
 +
== Code Walkthrough ==
 +
 +
Now, let's break down the code.
 +
 +
<syntaxhighlight lang="python" line start="33" enclose="div">
 +
import argparse
 +
import importlib
 +
 +
import rospy
 +
from dynamic_reconfigure.server import (
 +
    Server,
 +
)
 +
from std_msgs.msg import (
 +
    Empty,
 +
)
 +
 +
import intera_interface
 +
from intera_interface import CHECK_VERSION
 +
</syntaxhighlight>
 +
 +
This imports the intera interface for accessing the limb class. The <code>CHECK_VERSION</code> is imported to check if the software running on the robot would be compatible with this local version. It is not necessary to check the version in custom programs.
 +
 +
<syntaxhighlight lang="python" line start="43" enclose="div">
 +
class JointSprings(object):
 +
    """
 +
    Virtual Joint Springs class for torque example.
 +
 +
    @param limb: limb on which to run joint springs example
 +
    @param reconfig_server: dynamic reconfigure server
 +
 +
    JointSprings class contains methods for the joint torque example allowing
 +
    moving the limb to a neutral location, entering torque mode, and attaching
 +
    virtual springs.
 +
    """
 +
    def __init__(self, reconfig_server, limb = "right"):
 +
        self._dyn = reconfig_server
 +
 +
        # control parameters
 +
        self._rate = 1000.0  # Hz
 +
        self._missed_cmds = 20.0  # Missed cycles before triggering timeout
 +
 +
        # create our limb instance
 +
        self._limb = intera_interface.Limb(limb)
 +
 +
        # initialize parameters
 +
        self._springs = dict()
 +
        self._damping = dict()
 +
        self._start_angles = dict()
 +
</syntaxhighlight>
 +
 +
The <code>JointSprings</code> class object is initialized by passing the side of the limb under interest, an object of the reconfigure server that holds the default spring and damping constants for the limb. These default values can be modified at runtime through the dynamic reconfigure server.
 +
 +
<syntaxhighlight lang="python" line start="69" enclose="div">
 +
        # create cuff disable publisher
 +
        cuff_ns = 'robot/limb/' + limb + '/suppress_cuff_interaction'
 +
        self._pub_cuff_disable = rospy.Publisher(cuff_ns, Empty, queue_size=1)
 +
 +
        # verify robot is enabled
 +
        print("Getting robot state... ")
 +
        self._rs = intera_interface.RobotEnable(CHECK_VERSION)
 +
        self._init_state = self._rs.state().enabled
 +
        print("Enabling robot... ")
 +
        self._rs.enable()
 +
        print("Running. Ctrl-c to quit")
 +
</syntaxhighlight>
 +
 +
The zero gravity mode can be enabled by pressing the cuff and so it is important to disable the cuff. A publisher for the cuff interaction suppress topic is created. It is also important to note that the robot should be enabled before trying to manipulate its joints. So, the robot is checked if it is enabled and if not, it is enabled. The initial state of the variable is recorded in <code>_init_state</code> variable. This is to ensure that the robot is sent back to that state once the example program ends.
 +
 +
<syntaxhighlight lang="python" line start="81" enclose="div">
 +
    def _update_parameters(self):
 +
        for joint in self._limb.joint_names():
 +
            self._springs[joint] = self._dyn.config[joint[-2:] + '_spring_stiffness']
 +
            self._damping[joint] = self._dyn.config[joint[-2:] + '_damping_coefficient']
 +
</syntaxhighlight>
 +
 +
The <code>_update_parameters()</code> method captures the dynamically entered user's input for the spring and damping constants through the dynamic reconfigure server.
 +
 +
<syntaxhighlight lang="python" line start="86" enclose="div">
 +
    def _update_forces(self):
 +
        """
 +
        Calculates the current angular difference between the start position
 +
        and the current joint positions applying the joint torque spring forces
 +
        as defined on the dynamic reconfigure server.
 +
        """
 +
        # get latest spring constants
 +
        self._update_parameters()
 +
 +
        # disable cuff interaction
 +
        self._pub_cuff_disable.publish()
 +
</syntaxhighlight>
 +
 +
The cuff interaction is disabled as long as the example runs and each time the forces are updated, the <code>_pub_cuff_disable</code> publisher publishes an empty message.
 +
 +
<syntaxhighlight lang="python" line start="98" enclose="div">
 +
        # create our command dict
 +
        cmd = dict()
 +
        # record current angles/velocities
 +
        cur_pos = self._limb.joint_angles()
 +
        cur_vel = self._limb.joint_velocities()
 +
        # calculate current forces
 +
        for joint in self._start_angles.keys():
 +
            # spring portion
 +
            cmd[joint] = self._springs[joint] * (self._start_angles[joint] -
 +
                                                  cur_pos[joint])
 +
            # damping portion
 +
            cmd[joint] -= self._damping[joint] * cur_vel[joint]
 +
        # command new joint torques
 +
        self._limb.set_joint_torques(cmd)
 +
</syntaxhighlight>
 +
 +
Hooke's law is applied to calculate the necessary torques to be applied on each joints. The updated spring and damping constants are used in the calculation. The <code>set_joint_torques()</code> method of the limb interface publishes the set of joint torques and their corresponding names with the mode as 3 to the topic <code>robot/limb/right/joint_command </code>. The mode indicates that the joint commands are to be passed to the torque controller.
 +
 +
<syntaxhighlight lang="python" line start="113" enclose="div">
 +
    def move_to_neutral(self):
 +
        """
 +
        Moves the limb to neutral location.
 +
        """
 +
        self._limb.move_to_neutral()
 +
</syntaxhighlight>
 +
 +
The <code>move_to_neutral()</code> method of the limb interface, moves all the joints to their neutral pose. This method employs the position controller to send the joints to a pre-defined neutral position.
 +
 +
<syntaxhighlight lang="python" line start="119" enclose="div">
 +
    def attach_springs(self):
 +
        """
 +
        Switches to joint torque mode and attached joint springs to current
 +
        joint positions.
 +
        """
 +
        # record initial joint angles
 +
        self._start_angles = self._limb.joint_angles()
 +
 +
        # set control rate
 +
        control_rate = rospy.Rate(self._rate)
 +
 +
        # for safety purposes, set the control rate command timeout.
 +
        # if the specified number of command cycles are missed, the robot
 +
        # will timeout and disable
 +
        self._limb.set_command_timeout((1.0 / self._rate) * self._missed_cmds)
 +
 +
        # loop at specified rate commanding new joint torques
 +
        while not rospy.is_shutdown():
 +
            if not self._rs.state().enabled:
 +
                rospy.logerr("Joint torque example failed to meet "
 +
                            "specified control rate timeout.")
 +
                break
 +
            self._update_forces()
 +
            control_rate.sleep()
 +
</syntaxhighlight>
 +
 +
The start angles recorded here are used by the <code>_update_forces</code> method to determine the dx, which is the displacement caused from the starting position of the joints. The <code>_update_forces</code> method is invoked at 1000Hz, which performs the spring motion as explained above.
 +
 +
<syntaxhighlight lang="python" line start="144" enclose="div">
 +
    def clean_shutdown(self):
 +
        """
 +
        Switches out of joint torque mode to exit cleanly
 +
        """
 +
        print("\nExiting example...")
 +
        self._limb.exit_control_mode()
 +
        if not self._init_state and self._rs.state().enabled:
 +
            print("Disabling robot...")
 +
            self._rs.disable()
 +
</syntaxhighlight>
 +
 +
The method <code>exit_control_mode()</code> of the limb interface switches to position controller mode from torque/velocity controller and saves the current joint angles as the current joint position. Finally, it checks if the robot was initially disabled and if so disables it.
 +
 +
<syntaxhighlight lang="python" line start="155" enclose="div">
 +
def main():
 +
    """RSDK Joint Torque Example: Joint Springs
 +
 +
    Moves the default limb to a neutral location and enters
 +
    torque control mode, attaching virtual springs (Hooke's Law)
 +
    to each joint maintaining the start position.
 +
 +
    Run this example and interact by grabbing, pushing, and rotating
 +
    each joint to feel the torques applied that represent the
 +
    virtual springs attached. You can adjust the spring
 +
    constant and damping coefficient for each joint using
 +
    dynamic_reconfigure.
 +
    """
 +
    # Querying the parameter server to determine Robot model and limb name(s)
 +
    rp = intera_interface.RobotParams()
 +
    valid_limbs = rp.get_limb_names()
 +
    if not valid_limbs:
 +
        rp.log_message(("Cannot detect any limb parameters on this robot. "
 +
                        "Exiting."), "ERROR")
 +
    robot_name = intera_interface.RobotParams().get_robot_name().lower().capitalize()
 +
    # Parsing Input Arguments
 +
    arg_fmt = argparse.ArgumentDefaultsHelpFormatter
 +
    parser = argparse.ArgumentParser(formatter_class=arg_fmt)
 +
    parser.add_argument(
 +
        "-l", "--limb", dest="limb", default=valid_limbs[0],
 +
        choices=valid_limbs,
 +
        help='limb on which to attach joint springs'
 +
        )
 +
    args = parser.parse_args(rospy.myargv()[1:])
 +
    # Grabbing Robot-specific parameters for Dynamic Reconfigure
 +
    config_name = ''.join([robot_name,"JointSpringsExampleConfig"])
 +
    config_module = "intera_examples.cfg"
 +
    cfg = importlib.import_module('.'.join([config_module,config_name]))
 +
    # Starting node connection to ROS
 +
    print("Initializing node... ")
 +
    rospy.init_node("sdk_joint_torque_springs_{0}".format(args.limb))
 +
    dynamic_cfg_srv = Server(cfg, lambda config, level: config)
 +
    js = JointSprings(dynamic_cfg_srv, limb=args.limb)
 +
    # register shutdown callback
 +
    rospy.on_shutdown(js.clean_shutdown)
 +
    js.move_to_neutral()
 +
    js.attach_springs()
 +
 +
 +
if __name__ == "__main__":
 +
    main()
 +
</syntaxhighlight>
 +
 +
The rospy node is initialized and then an instance of the dynamic reconfigure is created. As indicated above, this supplies the default and runtime, spring and dynamic constants. In custom programs this can be avoided by assigning spring and damping constants directly in the code.
  
 
</div>
 
</div>

Revision as of 08:52, 25 November 2016

This example shows joint torque control usage. After moving to neutral, the robot will enter torque control mode, applying torques representing virtual springs holding the joints to their start position. The example calculates and applies torques linearly relative to offset from the start position creating the illusion that springs of configurable stiffness are attached to each joint.

Introduction

The Joint Torque Springs Example demonstrates the usage of torque controller to apply torque commands to robot's joints. In the main() function, the dynamic reconfigure from server is initialized and passed to an object of the JointSprings class. On initialization, the object creates an instance of the limb class for the particular side that is passed, and captures the default spring and damping constants from the dynamic reconfigure server. The main() function calls the method, move_to_neutral() to send the limbs to a neutral position. Then, the attach_spring() method captures the initial joint angles of the limb and calls the update_forces() method which calculates the necessary torques based on Hooke's law and publishes them as joint commands.

Interfaces -

  • Limb.set_joint_torques()
  • Limb.move_to_neutral()
  • Limb.joint_angles()
  • Limb.joint_velocities()
  • Limb.set_command_timeout()
  • Limb.exit_control_mode()

Usage

Start the joint torque springs example from an RSDK terminal session using:

$ rosrun intera_examples joint_torque_springs.py

Some messages will appear after start:

Initializing node...
Getting robot state...
Enabling robot...
Running. Ctrl-c to quit

The robot will move to neutral pose first, when done moving to neutral pose, you can interact with the robot by grabbing, pushing, and rotating each joint to feel the torques applied that represent the virtual springs attached.

Pressing Control-C at any time will stop torque mode and exit the example.

Arguments

Important Arguments:

-l or --limb : The robot arm name (default="right")

See the joint torque spring's available arguments on the command line by passing joint_torque_springs.py the -h, help argument:

$ rosrun intera_examples joint_torque_springs.py -h
usage: joint_torque_springs.py [-h] [-l LIMB]

RSDK Joint Torque Example: Joint Springs

    Moves the default limb to a neutral location and enters
    torque control mode, attaching virtual springs (Hooke.s Law)
    to each joint maintaining the start position.

    Run this example and interact by grabbing, pushing, and rotating
    each joint to feel the torques applied that represent the
    virtual springs attached. You can adjust the spring
    constant and damping coefficient for each joint using
    dynamic_reconfigure.
    

optional arguments:
  -h, --help            show this help message and exit
  -l LIMB, --limb LIMB
                        limb on which to attach joint springs

Code Walkthrough

Now, let's break down the code.

33 import argparse
34 import importlib
35 
36 import rospy
37 from dynamic_reconfigure.server import (
38     Server,
39 )
40 from std_msgs.msg import (
41     Empty,
42 )
43 
44 import intera_interface
45 from intera_interface import CHECK_VERSION

This imports the intera interface for accessing the limb class. The CHECK_VERSION is imported to check if the software running on the robot would be compatible with this local version. It is not necessary to check the version in custom programs.

43 class JointSprings(object):
44     """
45     Virtual Joint Springs class for torque example.
46 
47     @param limb: limb on which to run joint springs example
48     @param reconfig_server: dynamic reconfigure server
49 
50     JointSprings class contains methods for the joint torque example allowing
51     moving the limb to a neutral location, entering torque mode, and attaching
52     virtual springs.
53     """
54     def __init__(self, reconfig_server, limb = "right"):
55         self._dyn = reconfig_server
56 
57         # control parameters
58         self._rate = 1000.0  # Hz
59         self._missed_cmds = 20.0  # Missed cycles before triggering timeout
60 
61         # create our limb instance
62         self._limb = intera_interface.Limb(limb)
63 
64         # initialize parameters
65         self._springs = dict()
66         self._damping = dict()
67         self._start_angles = dict()

The JointSprings class object is initialized by passing the side of the limb under interest, an object of the reconfigure server that holds the default spring and damping constants for the limb. These default values can be modified at runtime through the dynamic reconfigure server.

69         # create cuff disable publisher
70         cuff_ns = 'robot/limb/' + limb + '/suppress_cuff_interaction'
71         self._pub_cuff_disable = rospy.Publisher(cuff_ns, Empty, queue_size=1)
72 
73         # verify robot is enabled
74         print("Getting robot state... ")
75         self._rs = intera_interface.RobotEnable(CHECK_VERSION)
76         self._init_state = self._rs.state().enabled
77         print("Enabling robot... ")
78         self._rs.enable()
79         print("Running. Ctrl-c to quit")

The zero gravity mode can be enabled by pressing the cuff and so it is important to disable the cuff. A publisher for the cuff interaction suppress topic is created. It is also important to note that the robot should be enabled before trying to manipulate its joints. So, the robot is checked if it is enabled and if not, it is enabled. The initial state of the variable is recorded in _init_state variable. This is to ensure that the robot is sent back to that state once the example program ends.

81     def _update_parameters(self):
82         for joint in self._limb.joint_names():
83             self._springs[joint] = self._dyn.config[joint[-2:] + '_spring_stiffness']
84             self._damping[joint] = self._dyn.config[joint[-2:] + '_damping_coefficient']

The _update_parameters() method captures the dynamically entered user's input for the spring and damping constants through the dynamic reconfigure server.

86     def _update_forces(self):
87         """
88         Calculates the current angular difference between the start position
89         and the current joint positions applying the joint torque spring forces
90         as defined on the dynamic reconfigure server.
91         """
92         # get latest spring constants
93         self._update_parameters()
94 
95         # disable cuff interaction
96         self._pub_cuff_disable.publish()

The cuff interaction is disabled as long as the example runs and each time the forces are updated, the _pub_cuff_disable publisher publishes an empty message.

 98         # create our command dict
 99         cmd = dict()
100         # record current angles/velocities
101         cur_pos = self._limb.joint_angles()
102         cur_vel = self._limb.joint_velocities()
103         # calculate current forces
104         for joint in self._start_angles.keys():
105             # spring portion
106             cmd[joint] = self._springs[joint] * (self._start_angles[joint] -
107                                                    cur_pos[joint])
108             # damping portion
109             cmd[joint] -= self._damping[joint] * cur_vel[joint]
110         # command new joint torques
111         self._limb.set_joint_torques(cmd)

Hooke's law is applied to calculate the necessary torques to be applied on each joints. The updated spring and damping constants are used in the calculation. The set_joint_torques() method of the limb interface publishes the set of joint torques and their corresponding names with the mode as 3 to the topic robot/limb/right/joint_command . The mode indicates that the joint commands are to be passed to the torque controller.

113     def move_to_neutral(self):
114         """
115         Moves the limb to neutral location.
116         """
117         self._limb.move_to_neutral()

The move_to_neutral() method of the limb interface, moves all the joints to their neutral pose. This method employs the position controller to send the joints to a pre-defined neutral position.

119     def attach_springs(self):
120         """
121         Switches to joint torque mode and attached joint springs to current
122         joint positions.
123         """
124         # record initial joint angles
125         self._start_angles = self._limb.joint_angles()
126 
127         # set control rate
128         control_rate = rospy.Rate(self._rate)
129 
130         # for safety purposes, set the control rate command timeout.
131         # if the specified number of command cycles are missed, the robot
132         # will timeout and disable
133         self._limb.set_command_timeout((1.0 / self._rate) * self._missed_cmds)
134 
135         # loop at specified rate commanding new joint torques
136         while not rospy.is_shutdown():
137             if not self._rs.state().enabled:
138                 rospy.logerr("Joint torque example failed to meet "
139                              "specified control rate timeout.")
140                 break
141             self._update_forces()
142             control_rate.sleep()

The start angles recorded here are used by the _update_forces method to determine the dx, which is the displacement caused from the starting position of the joints. The _update_forces method is invoked at 1000Hz, which performs the spring motion as explained above.

144     def clean_shutdown(self):
145         """
146         Switches out of joint torque mode to exit cleanly
147         """
148         print("\nExiting example...")
149         self._limb.exit_control_mode()
150         if not self._init_state and self._rs.state().enabled:
151             print("Disabling robot...")
152             self._rs.disable()

The method exit_control_mode() of the limb interface switches to position controller mode from torque/velocity controller and saves the current joint angles as the current joint position. Finally, it checks if the robot was initially disabled and if so disables it.

155 def main():
156     """RSDK Joint Torque Example: Joint Springs
157 
158     Moves the default limb to a neutral location and enters
159     torque control mode, attaching virtual springs (Hooke's Law)
160     to each joint maintaining the start position.
161 
162     Run this example and interact by grabbing, pushing, and rotating
163     each joint to feel the torques applied that represent the
164     virtual springs attached. You can adjust the spring
165     constant and damping coefficient for each joint using
166     dynamic_reconfigure.
167     """
168     # Querying the parameter server to determine Robot model and limb name(s)
169     rp = intera_interface.RobotParams()
170     valid_limbs = rp.get_limb_names()
171     if not valid_limbs:
172         rp.log_message(("Cannot detect any limb parameters on this robot. "
173                         "Exiting."), "ERROR")
174     robot_name = intera_interface.RobotParams().get_robot_name().lower().capitalize()
175     # Parsing Input Arguments
176     arg_fmt = argparse.ArgumentDefaultsHelpFormatter
177     parser = argparse.ArgumentParser(formatter_class=arg_fmt)
178     parser.add_argument(
179         "-l", "--limb", dest="limb", default=valid_limbs[0],
180         choices=valid_limbs,
181         help='limb on which to attach joint springs'
182         )
183     args = parser.parse_args(rospy.myargv()[1:])
184     # Grabbing Robot-specific parameters for Dynamic Reconfigure
185     config_name = ''.join([robot_name,"JointSpringsExampleConfig"])
186     config_module = "intera_examples.cfg"
187     cfg = importlib.import_module('.'.join([config_module,config_name]))
188     # Starting node connection to ROS
189     print("Initializing node... ")
190     rospy.init_node("sdk_joint_torque_springs_{0}".format(args.limb))
191     dynamic_cfg_srv = Server(cfg, lambda config, level: config)
192     js = JointSprings(dynamic_cfg_srv, limb=args.limb)
193     # register shutdown callback
194     rospy.on_shutdown(js.clean_shutdown)
195     js.move_to_neutral()
196     js.attach_springs()
197 
198 
199 if __name__ == "__main__":
200     main()

The rospy node is initialized and then an instance of the dynamic reconfigure is created. As indicated above, this supplies the default and runtime, spring and dynamic constants. In custom programs this can be avoided by assigning spring and damping constants directly in the code.