major refactoring to be consistent with PEP8

This commit is contained in:
Brian Delhaisse
2019-03-23 03:35:23 +01:00
parent ff6446e684
commit bd079c9cb7
150 changed files with 5289 additions and 4840 deletions
@@ -35,7 +35,7 @@ sim = BulletSim()
world = BasicWorld(sim)
# load robot in the world
robot = world.loadRobot(KukaIIWA)
robot = world.load_robot(KukaIIWA)
print("Robot's actuated joint ids: {}".format(robot.joints))
# create state/action
+4 -4
View File
@@ -14,15 +14,15 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
robot = Aibo(sim) # , useFixedBase=True)
robot = Aibo(sim) # , fixed_base=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.left_front_leg + robot.right_front_leg)
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+6 -6
View File
@@ -14,19 +14,19 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
right_hand = AllegroHand(sim) # , init_pos=(0.,0.,0.), init_orient=(0,0,1,0))
right_hand = AllegroHand(sim) # , position=(0.,0.,0.), orientation=(0,0,1,0))
# print information about the robot
right_hand.printRobotInfo()
# H = right_hand.calculateMassMatrix()
right_hand.print_info()
# H = right_hand.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# Position control using sliders
right_hand.addJointSlider()
right_hand.add_joint_slider()
for i in count():
right_hand.updateJointSlider()
# right_hand.setJointPositions([0.] * right_hand.getNumberOfDoFs())
right_hand.update_joint_slider()
# right_hand.set_joint_positions([0.] * right_hand.num_dofs)
# step in simulation
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -14,15 +14,15 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
robot = Ant(sim) # , useFixedBase=True)
robot = Ant(sim) # , fixed_base=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.left_front_leg + robot.right_front_leg)
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Atlas(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# position control using sliders
robot.addJointSlider(robot.getLeftLegIds())
robot.add_joint_slider(robot.left_leg)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+2 -2
View File
@@ -17,10 +17,10 @@ world = BasicWorld(sim)
robot = Ballbot(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
for i in count():
# robot.setJointVelocities([0, -1, 0])
# robot.set_joint_velocities([0, -1, 0])
# step in simulation
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Baxter(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+2 -2
View File
@@ -17,10 +17,10 @@ world = BasicWorld(sim)
robot = BB8(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
for i in count():
robot.setJointVelocities([0, -1, 0])
robot.set_joint_velocities([0, -1, 0])
# step in simulation
world.step(sleep_dt=1./240)
+5 -5
View File
@@ -100,12 +100,12 @@ if __name__ == "__main__":
robot = CartPole(sim, num_links=num_links)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
robot.getSymbolicEquationsOfMotion()
robot.get_symbolic_equations_of_motion()
eq_point = np.zeros((num_links + 1) * 2) # state = [q, dq]
A, B = robot.linearizeEquationOfMotion(eq_point)
A, B = robot.linearize_equations_of_motion(eq_point)
# LQR controller
lqr = LQR(A, B)
@@ -113,9 +113,9 @@ if __name__ == "__main__":
for i in count():
# control
x = np.concatenate((robot.getJointPositions(), robot.getJointVelocities()))
x = np.concatenate((robot.get_joint_positions(), robot.get_joint_velocities()))
u = K.dot(eq_point - x)
robot.setJointTorques(u[0], 0)
robot.set_joint_torques(u[0], 0)
print("U[0] = {}".format(u[0]))
+4 -4
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = Cassie(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.moveJointHomePositions()
# robot.update_joint_slider()
robot.move_joint_home_positions()
world.step(sleep_dt=1./240)
+6 -6
View File
@@ -14,17 +14,17 @@ sim = BulletSim()
world = BasicWorld(sim)
# load robot
robot = Centauro(sim) # , useFixedBase=True)
robot = Centauro(sim) # , fixed_base=True)
# print information about the robot
robot.printRobotInfo()
print("Number of Legs: {}".format(robot.getNumberOfLegs()))
print("Number of Arms: {}".format(robot.getNumberOfArms()))
robot.print_info()
print("Number of Legs: {}".format(robot.num_legs))
print("Number of Arms: {}".format(robot.num_arms))
# robot.addJointSlider(robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.getRightFrontLegIds())
robot.drive(speed=3)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Cogimon(sim, lower_body=False)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider(robot.left_leg)
robot.add_joint_slider(robot.left_leg)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+10 -10
View File
@@ -14,23 +14,23 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
robot = Coman(sim, useFixedBase=True)
robot = Coman(sim, fixed_base=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
print(robot.link_names)
# # Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
robot.changeTransparency()
# robot.drawLinkCoMs()
robot.drawLinkFrames()
# robot.drawBoundingBoxes(robot.right_leg[4])
robot.change_transparency()
# robot.draw_link_coms()
robot.draw_link_frames()
# robot.draw_bounding_boxes(robot.right_leg[4])
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.computeAndDrawCoMPosition()
# robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
# robot.compute_and_draw_com_position()
# robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = Crab(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
robot.addJointSlider(robot.right_middle_leg)
robot.add_joint_slider(robot.right_middle_leg)
# run simulation
for i in count():
robot.updateJointSlider()
robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+8 -7
View File
@@ -4,7 +4,8 @@
import numpy as np
from itertools import count
from pyrobolearn.simulators import BulletSim, pybullet
from pyrobolearn.utils.orientation import get_rpy_from_quaternion
from pyrobolearn.simulators import BulletSim
from pyrobolearn.worlds import BasicWorld
from pyrobolearn.robots import Cubli
@@ -21,8 +22,8 @@ orientation = [0.383, 0, 0, 0.924]
robot = Cubli(sim, position, orientation, scaling=scale)
# print information about the robot
robot.printRobotInfo()
H = robot.calculateMassMatrix(qIdx=slice(6, 6+len(robot.joints))) # floating base, thus keep only the last q
robot.print_info()
H = robot.get_mass_matrix(q_idx=slice(6, 6 + len(robot.joints))) # floating base, thus keep only the last q
print("Inertia matrix: H(q) = {}\n".format(H))
# PD control
@@ -32,13 +33,13 @@ desired_roll = np.pi / 4.
for i in count():
# get state
quaternion = robot.getBaseOrientation(False)
w = robot.getBaseAngularVelocity()
euler = pybullet.getEulerFromQuaternion(quaternion.tolist())
quaternion = robot.get_base_orientation()
w = robot.get_base_angular_velocity()
euler = get_rpy_from_quaternion(quaternion)
# PD control
torques = [-Kp * (desired_roll - euler[0]) + Kd * w[0], 0., 0.]
robot.setJointTorques(torques)
robot.set_joint_torques(torques)
# step in simulation
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -14,16 +14,16 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
robot = Darwin(sim, useFixedBase=False)
robot = Darwin(sim, fixed_base=False)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
print(robot.link_names)
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+2 -2
View File
@@ -17,8 +17,8 @@ world = BasicWorld(sim)
robot = Edo(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
for i in count():
+4 -4
View File
@@ -18,18 +18,18 @@ world = BasicWorld(sim)
robots = []
for _ in range(5):
x, y = np.random.uniform(low=-2, high=2, size=2)
robot = world.loadRobot(Epuck, position=(x, y, 0))
robot = world.load_robot(Epuck, position=(x, y, 0))
robots.append(robot)
# print information about the robot
robots[0].printRobotInfo()
robots[0].print_info()
# Position control using sliders
# robots[0].addJointSlider()
# robots[0].add_joint_slider()
# run simulator
for _ in count():
# robots[0].updateJointSlider()
# robots[0].update_joint_slider()
for robot in robots:
robot.drive(5)
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = F10Racecar(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.driveForward(10)
# robot.update_joint_slider()
robot.drive_forward(10)
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Fetch(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
robot.addJointSlider()
robot.add_joint_slider()
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = Franka(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = HalfCheetah(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = Hopper(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Hubo(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = Humanoid(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulation
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = Husky(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.driveForward(2)
# robot.update_joint_slider()
robot.drive_forward(2)
world.step(sleep_dt=1./240)
+5 -5
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = HyQ(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider(robot.getLeftFrontLegIds())
robot.add_joint_slider(robot.left_front_leg)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.computeAndDrawCoMPosition()
robot.computeAndDrawProjectedCoMPosition()
robot.update_joint_slider()
robot.compute_and_draw_com_position()
robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+6 -6
View File
@@ -12,21 +12,21 @@ sim = BulletSim()
# create world
world = BasicWorld(sim)
world.loadJapaneseMonastery()
world.load_japanese_monastery()
# create robot
robot = HyQ2Max(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds())
# robot.add_joint_slider(robot.getLeftFrontLegIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.computeAndDrawCoMPosition()
robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
robot.compute_and_draw_com_position()
robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = Jaco(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+2 -2
View File
@@ -17,8 +17,8 @@ world = BasicWorld(sim)
robot = KR5(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
for i in count():
+12 -12
View File
@@ -18,11 +18,11 @@ world = BasicWorld(sim)
robot = KukaIIWA(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# print(robot.getLinkWorldPositions(flatten=False))
# print(robot.get_link_world_positions(flatten=False))
K = 5000*np.identity(3)
# D = 2 * np.sqrt(K)
@@ -30,22 +30,22 @@ K = 5000*np.identity(3)
D = 100 * np.identity(3)
x_des = np.array([0.3, 0.0, 0.8])
x_des = np.array([0.52557296, 0.09732758, 0.80817658])
linkId = robot.getLinkIds('iiwa_link_ee')
link_id = robot.get_link_ids('iiwa_link_ee')
for i in count():
# print(robot.getLinkWorldPositions(flatten=False))
# print(robot.get_link_world_positions(flatten=False))
# get state
q = robot.getJointPositions()
dq = robot.getJointVelocities()
x = robot.getLinkWorldPositions(linkId)
dx = robot.getLinkWorldLinearVelocities(linkId)
q = robot.get_joint_positions()
dq = robot.get_joint_velocities()
x = robot.get_link_world_positions(link_id)
dx = robot.get_link_world_linear_velocities(link_id)
# get (linear) jacobian
J = robot.getLinearJacobian(linkId, q)
J = robot.get_linear_jacobian(link_id, q)
# get coriolis, gravity compensation torques
torques = robot.getCoriolisAndGravityCompensationTorques(q, dq)
torques = robot.get_coriolis_and_gravity_compensation_torques(q, dq)
# Impedance control: attractor point
F = K.dot(x_des - x) - D.dot(dx)
@@ -53,7 +53,7 @@ for i in count():
tau = J.T.dot(F)
print(tau)
torques += tau
robot.setJointTorques(torques)
robot.set_joint_torques(torques)
# step in simulation
world.step(sleep_dt=1./240)
+2 -2
View File
@@ -17,8 +17,8 @@ world = BasicWorld(sim)
robot = KukaLWR(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
for i in count():
+4 -4
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = Laikago(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.moveJointHomePositions()
# robot.update_joint_slider()
robot.move_joint_home_positions()
world.step(sleep_dt=1./240)
+5 -5
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = LittleDog(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.computeAndDrawCoMPosition()
# robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
# robot.compute_and_draw_com_position()
# robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -18,11 +18,11 @@ world = BasicWorld(sim)
for i, robot_name in enumerate(implemented_robots):
if robot_name not in robot_not_working:
# instantiate the given robot
robot = world.loadRobot(robot_name)
robot = world.load_robot(robot_name)
# print info about the robot
print("Robot n{}: {}".format(i+1, robot))
# robot.printRobotInfo()
# robot.print_info()
# run for few moments in the world
for t in range(250):
@@ -30,4 +30,4 @@ for i, robot_name in enumerate(implemented_robots):
world.step(sleep_dt=1./240)
# remove the robot from the world
world.removeObject(robot)
world.remove(robot)
+5 -5
View File
@@ -14,14 +14,14 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
robot = Manipulator2D(sim, init_pos=(0, -0.25, 0))
robot1 = Manipulator2D(sim, init_pos=(0, 0.25, 0))
robot.printRobotInfo()
robot = Manipulator2D(sim, position=(0, -0.25, 0))
robot1 = Manipulator2D(sim, position=(0, 0.25, 0))
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+5 -5
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = Minitaur(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
robot.addJointSlider(robot.getLeftFrontLegIds())
# robot.add_joint_slider(robot.left_front_leg)
# run simulator
for _ in count():
robot.updateJointSlider()
# robot.computeAndDrawCoMPosition()
# robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
# robot.compute_and_draw_com_position()
# robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -17,13 +17,13 @@ world = BasicWorld(sim)
robot = MKZ(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.driveForward(2)
# robot.update_joint_slider()
robot.drive_forward(2)
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = Morphex(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Nao(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftArmIds())
# robot.add_joint_slider(robot.getLeftArmIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = OpenDog(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds())
# robot.add_joint_slider(robot.getLeftFrontLegIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+4 -4
View File
@@ -18,14 +18,14 @@ world = BasicWorld(sim)
robot = Pepper(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
if i % 20 == 0:
robot.cameraTop.getRGBImage()
robot.camera_top.get_rgb_image()
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = PhantomX(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+5 -5
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = Pleurobot(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.computeAndDrawCoMPosition()
# robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
# robot.compute_and_draw_com_position()
# robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = PR2(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+2 -2
View File
@@ -18,7 +18,7 @@ world = BasicWorld(sim)
robot = Quadcopter(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
rpm = robot.getStationaryRPM()
print("Stationary RPM: {}".format(rpm))
@@ -27,6 +27,6 @@ v = [v, -v, v, -v]
# run simulation
for i in count():
robot.setJointVelocities(v)
robot.set_joint_velocities(v)
# step in simulation
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,14 +17,14 @@ world = BasicWorld(sim)
robot = Rhex(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.right_back_leg)
# robot.add_joint_slider(robot.right_back_leg)
# run simulation
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
robot.drive(2)
# step in simulation
world.step(sleep_dt=1./240)
+49 -49
View File
@@ -15,35 +15,35 @@ world = BasicWorld(sim)
# load robot
robot = RRBot(sim)
# robot.addJointSlider()
# robot.add_joint_slider()
print("Robot: {}".format(robot))
print("Total number of joints: {}".format(robot.getNumberOfJoints()))
print("Joint names: {}".format(robot.getJointNames(range(robot.getNumberOfJoints()))))
print("Link names: {}".format(robot.getLinkNames(range(robot.getNumberOfJoints()))))
print("Total number of joints: {}".format(robot.num_joints))
print("Joint names: {}".format(robot.get_joint_names(range(robot.num_joints))))
print("Link names: {}".format(robot.get_link_names(range(robot.num_joints))))
print("Number of DoFs: {}".format(robot.getNumberOfDoFs()))
print("Number of DoFs: {}".format(robot.num_dofs))
print("Robot actuated joint ids: {}".format(robot.joints))
print("Actuated joint names: {}".format(robot.getJointNames()))
print("Actuated link names: {}".format(robot.getLinkNames()))
print("Current joint positions: {}".format(robot.getJointPositions()))
print("Actuated joint names: {}".format(robot.get_joint_names()))
print("Actuated link names: {}".format(robot.get_link_names()))
print("Current joint positions: {}".format(robot.get_joint_positions()))
print("Number of end-effectors: {}".format(robot.getNumberOfEndEffectors()))
print("End-effector names: {}".format(robot.getEndEffectorNames()))
print("Number of end-effectors: {}".format(robot.num_end_effectors))
print("End-effector names: {}".format(robot.get_link_names(robot.end_effectors)))
print("Robot base position: {}".format(robot.getBasePosition()))
robot.changeTransparency()
visuals = robot.sim.getVisualShapeData(robot.id)
print("Robot base position: {}".format(robot.get_base_position()))
robot.change_transparency()
visuals = robot.sim.get_visual_shape_data(robot.id)
visuals = {visual[1]: visual[3] for visual in visuals}
# robot.drawLinkCoMs()
robot.drawLinkFrames()
# robot.drawBoundingBoxes()
# robot.draw_link_coms()
robot.draw_link_frames()
# robot.draw_bounding_boxes()
for i in robot.joints:
print("Link {}".format(i))
state = robot.sim.getLinkState(robot.id, i)
info = robot.sim.getJointInfo(robot.id, i)
state = robot.sim.get_link_state(robot.id, i)
info = robot.sim.get_joint_info(robot.id, i)
print("\t CoM world position: {}".format(state[0]))
print("\t Local inertial frame position: {}".format(state[2]))
@@ -62,71 +62,71 @@ for _ in count():
raw_input('press enter')
print("Inertia matrix: {}".format(np.array(sim.calculateMassMatrix(robot.id, [0.,0.,0.,0.,0.,0.]))))
print("Inertia matrix: {}".format(np.array(sim.calculate_mass_matrix(robot.id, [0., 0., 0., 0., 0., 0.]))))
linkId = 2
com_frame = robot.getLinkStates(linkId)[2]
q = robot.getJointPositions()
com_frame = robot.get_link_states(linkId)[2]
q = robot.get_joint_positions()
print(com_frame)
# com_frame = [0.,0.,0.]
print("Jacobian matrix: {}".format(np.vstack((sim.calculateJacobian(robot.id, linkId, com_frame, q.tolist(), [0.,0.], [0.,0.])))))
print("Jacobian matrix: {}".format(sim.calculate_jacobian(robot.id, linkId, com_frame)))
Jlin = robot.calculateJacobian(linkId+1, localPosition=(0.,0.,0.))[:3]
Jlin = robot.get_jacobian(linkId + 1)[:3]
print("Jacobian matrix: {}".format(Jlin))
robot.drawVelocityManipulabilityEllipsoid(linkId+1, Jlin)
robot.draw_velocity_manipulability_ellipsoid(linkId + 1, Jlin)
Jlin = robot.calculateJacobian(linkId)[:3]
robot.drawVelocityManipulabilityEllipsoid(linkId, Jlin, color=(1,0,0,0.7))
Jlin = robot.get_jacobian(linkId)[:3]
robot.draw_velocity_manipulability_ellipsoid(linkId, Jlin, color=(1, 0, 0, 0.7))
cnt = 0
for i in count():
if i%240 == 0:
if cnt < 3:
Jlin = robot.calculateJacobian(linkId + 1, localPosition=(0., 0., 0.))[:3]
robot.drawVelocityManipulabilityEllipsoid(linkId + 1, Jlin)
Jlin = robot.get_jacobian(linkId + 1)[:3]
robot.draw_velocity_manipulability_ellipsoid(linkId + 1, Jlin)
cnt += 1
world.step(sleep_dt=1./240)
# robot.setJointTorques()
# robot.set_joint_torques()
raw_input('press enter')
print(robot.getLinkNames())
print(robot.get_link_names())
force = np.array([1., 0., 0.])
pos = np.array([0., 0., 0.])
sim.applyExternalForce(robot.id, 1, force, pos, flags=p.LINK_FRAME) # link_frame = 1
sim.apply_external_force(robot.id, 1, force, pos, flags=p.LINK_FRAME) # link_frame = 1
slider = sim.addUserDebugParameter('force', -1000., 1000., 0)
slider = sim.add_user_debug_parameter('force', -1000., 1000., 0)
dq, ddq = [0., 0.], [0., 0.]
J = sim.calculateJacobian(robot.id, 1, [0.,0.,0.], [0.,0.], dq, ddq)
J = sim.calculate_jacobian(robot.id, 1, [0., 0., 0.])
print(np.array(J[0]))
a = robot.getJointPositions()
a = robot.get_joint_positions()
# print(robot.getJacobianMatrix(1, np.array([0.,0.]))) # TODO: need to convert numpy array to list
linkId = 2
com_frame = robot.getLinkStates(linkId)[2]
xdes = np.array(robot.getLinkWorldPositions(linkId))
com_frame = robot.get_link_states(linkId)[2]
xdes = np.array(robot.get_link_world_positions(linkId))
K = 100*np.identity(3)
D = 2*np.sqrt(K) # critically damped
D = 3*D # manually increase damping
# run simulator
for i in range(10000):
joint_states = p.getJointStates(robot.id, robot.joints)
joint_states = p.get_joint_states(robot.id, robot.joints)
# print("joint state: ", joint_states)
q = [joint_state[0] for joint_state in joint_states]
dq = [joint_state[1] for joint_state in joint_states]
# q = robot.getJointPositions().tolist()
# dq = robot.getJointVelocities().tolist()
x = np.array(robot.getLinkWorldPositions(linkId))
dx = np.array(robot.getLinkWorldLinearVelocities(linkId))
tau = robot.calculateID(q, dq, ddq) # Coriolis, centrifugal and gravity compensation
Jlin = np.array(sim.calculateJacobian(robot.id, linkId, com_frame, q, [0.,0.], ddq)[0])
F = K.dot(xdes - x) - D.dot(dx) # compute cartesian forces
# q = robot.get_joint_positions().tolist()
# dq = robot.get_joint_velocities().tolist()
x = np.array(robot.get_link_world_positions(linkId))
dx = np.array(robot.get_link_world_linear_velocities(linkId))
tau = robot.calculate_inverse_dynamics(ddq, dq, q) # Coriolis, centrifugal and gravity compensation
Jlin = np.array(sim.calculate_jacobian(robot.id, linkId, com_frame)[0])
F = K.dot(xdes - x) - D.dot(dx) # compute cartesian forces
# print("force: {}".format(F))
tau += Jlin.T.dot(F) # cartesian PD with gravity compensation
tau += Jlin.T.dot(F) # cartesian PD with gravity compensation
# tau += Jlin.T.dot(- D.dot(dx)) # active compliance
# tau = Jlin.T.dot(F)
@@ -137,14 +137,14 @@ for i in range(10000):
# print("manipulability: {}".format(w))
# Impedance/Torque control
sim.setJointMotorControlArray(robot.id, robot.joint_indices, sim.TORQUE_CONTROL, forces=tau)
sim.set_joint_motor_control(robot.id, robot.joints, sim.TORQUE_CONTROL, forces=tau)
force = sim.readUserDebugParameter(slider)
force = sim.read_user_debug_parameter(slider)
if force > 0:
force = np.array([0., 0., 1.])
else:
force = np.array([0., 0., 0.])
sim.applyExternalForce(robot.id, linkId, force, pos, flags=p.LINK_FRAME) # p.LINK_FRAME = 1
sim.apply_external_force(robot.id, linkId, force, pos, flags=p.LINK_FRAME) # p.LINK_FRAME = 1
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+3 -3
View File
@@ -17,12 +17,12 @@ world = BasicWorld(sim)
robot = Sawyer(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider()
robot.add_joint_slider()
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = SEAHexapod(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = SEASnake(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+10 -10
View File
@@ -14,23 +14,23 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
left_hand = SoftHand(sim, init_pos=(-0.15, 0, 0), left=True)
right_hand = SoftHand(sim, init_pos=(0.15, 0., 0.), init_orient=(0, 0, 1, 0), left=False)
left_hand = SoftHand(sim, position=(-0.15, 0, 0), left=True)
right_hand = SoftHand(sim, position=(0.15, 0., 0.), orientation=(0, 0, 1, 0), left=False)
# print information about the robot
left_hand.printRobotInfo()
# H = left_hand.calculateMassMatrix()
left_hand.print_info()
# H = left_hand.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# Position control using sliders
# left_hand.addJointSlider()
# left_hand.add_joint_slider()
left_hand.setJointPositions([0.] * left_hand.getNumberOfDoFs())
right_hand.setJointPositions([0.] * right_hand.getNumberOfDoFs())
left_hand.set_joint_positions([0.] * left_hand.num_dofs)
right_hand.set_joint_positions([0.] * right_hand.num_dofs)
for i in count():
# left_hand.updateJointSlider()
# left_hand.setJointPositions([0.] * left_hand.getNumberOfDoFs())
# right_hand.setJointPositions([0.] * right_hand.getNumberOfDoFs())
# left_hand.update_joint_slider()
# left_hand.set_joint_positions([0.] * left_hand.getNumberOfDoFs())
# right_hand.set_joint_positions([0.] * right_hand.getNumberOfDoFs())
world.step(sleep_dt=1./240)
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = Swimmer(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+1 -1
View File
@@ -17,7 +17,7 @@ world = BasicWorld(sim)
robot = Walker2D(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+7 -7
View File
@@ -12,22 +12,22 @@ sim = BulletSim()
# Create world
world = BasicWorld(sim)
world.loadSphere([2., 0, 2.], mass=0., color=(1, 0, 0, 1))
world.loadSphere([2., 1., 2.], mass=0., color=(0, 0, 1, 1))
world.load_sphere([2., 0, 2.], mass=0., color=(1, 0, 0, 1))
world.load_sphere([2., 1., 2.], mass=0., color=(0, 0, 1, 1))
# load robot
robot = Walkman(sim, useFixedBase=False, lower_body=False)
robot = Walkman(sim, fixed_base=False, lower_body=False)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider(robot.left_leg)
robot.add_joint_slider(robot.left_leg)
# run simulator
for i in count():
robot.updateJointSlider()
robot.update_joint_slider()
if i % 60 == 0:
img = robot.left_camera.getRGBImage()
img = robot.left_camera.get_rgb_image()
world.step(sleep_dt=1./240)
+12 -12
View File
@@ -18,29 +18,29 @@ world = BasicWorld(sim)
robot = WAM(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
robot.setJointPositions([np.pi / 4, np.pi / 2], jointId=[0,1]) #2, 4])
robot.set_joint_positions([np.pi / 4, np.pi / 2], joint_ids=[0, 1]) #2, 4])
Jlin = robot.calculateJacobian(6, localPosition=(0., 0., 0.))[:3]
robot.drawVelocityManipulabilityEllipsoid(6, Jlin, color=(1,0,0,0.7))
Jlin = robot.get_jacobian(6)[:3]
robot.draw_velocity_manipulability_ellipsoid(6, Jlin, color=(1, 0, 0, 0.7))
for _ in range(5):
world.step(sleep_dt=1./240)
Jlin = robot.calculateJacobian(6, localPosition=(0., 0., 0.))[:3]
robot.drawVelocityManipulabilityEllipsoid(6, Jlin, color=(0, 0, 1, 0.7))
Jlin = robot.get_jacobian(6)[:3]
robot.draw_velocity_manipulability_ellipsoid(6, Jlin, color=(0, 0, 1, 0.7))
for _ in range(45):
world.step(sleep_dt=1./240)
Jlin = robot.calculateJacobian(6, localPosition=(0., 0., 0.))[:3]
robot.drawVelocityManipulabilityEllipsoid(6, Jlin)
Jlin = robot.get_jacobian(6)[:3]
robot.draw_velocity_manipulability_ellipsoid(6, Jlin)
for i in count():
if i%1000 == 0:
print("Joint Torques: {}".format(robot.getJointTorques()))
print("Gravity Torques: {}".format(robot.getGravityCompensationTorques()))
print("Compensation Torques: {}".format(robot.getCoriolisAndGravityCompensationTorques()))
print("Joint Torques: {}".format(robot.get_joint_torques()))
print("Gravity Torques: {}".format(robot.get_gravity_compensation_torques()))
print("Compensation Torques: {}".format(robot.get_coriolis_and_gravity_compensation_torques()))
# step in simulation
world.step(sleep_dt=1./240)
+7 -7
View File
@@ -16,23 +16,23 @@ sim = BulletSim()
world = BasicWorld(sim)
# create robot
youbot_base = YoubotBase(sim, init_pos=(0, -0.75))
kuka_arm = KukaYoubotArm(sim, init_pos=(0, -0.25))
youbot = Youbot(sim, init_pos=(0, 0.25))
youbot_dual_arm = YoubotDualArm(sim, init_pos=(0, 0.75))
youbot_base = YoubotBase(sim, position=(0, -0.75))
kuka_arm = KukaYoubotArm(sim, position=(0, -0.25))
youbot = Youbot(sim, position=(0, 0.25))
youbot_dual_arm = YoubotDualArm(sim, position=(0, 0.75))
robots = [youbot_base, kuka_arm, youbot, youbot_dual_arm]
# print information about the robot
for robot in robots:
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robots[0].updateJointSlider()
# robots[0].update_joint_slider()
# for robot in robots:
# robot.drive(5)
world.step(sleep_dt=1./240)
@@ -37,7 +37,7 @@ class JointAction(RobotAction):
# get the joints of the robot
if joint_ids is None:
joint_ids = robot.getJointIds()
joint_ids = robot.get_joint_ids()
elif isinstance(joint_ids, int):
joint_ids = [joint_ids]
self.joints = joint_ids
@@ -47,7 +47,7 @@ class JointAction(RobotAction):
# return len(self.joints)
def bounds(self):
return self.robot.getJointLimits(self.joints)
return self.robot.get_joint_limits(self.joints)
class JointPositionAction(JointAction):
@@ -59,13 +59,13 @@ class JointPositionAction(JointAction):
def __init__(self, robot, joint_ids=None, kp=None, kd=None, max_force=None):
self.kp, self.kd, self.max_force = kp, kd, max_force
super(JointPositionAction, self).__init__(robot, joint_ids)
self.data = robot.getJointPositions(self.joints)
self.data = robot.get_joint_positions(self.joints)
def _write(self, data=None):
if data is None:
self.robot.setJointPositions(self._data, self.joints, kp=self.kp, kd=self.kd, maxTorque=self.max_force)
self.robot.set_joint_positions(self._data, self.joints, kp=self.kp, kd=self.kd, forces=self.max_force)
else:
self.robot.setJointPositions(data, self.joints, kp=self.kp, kd=self.kd, maxTorque=self.max_force)
self.robot.set_joint_positions(data, self.joints, kp=self.kp, kd=self.kd, forces=self.max_force)
class JointVelocityAction(JointAction):
@@ -76,13 +76,13 @@ class JointVelocityAction(JointAction):
def __init__(self, robot, joint_ids=None):
super(JointVelocityAction, self).__init__(robot, joint_ids)
self.data = robot.getJointVelocities(self.joints)
self.data = robot.get_joint_velocities(self.joints)
def _write(self, data=None):
if data is None:
self.robot.setJointVelocities(self._data, self.joints)
self.robot.set_joint_velocities(self._data, self.joints)
else:
self.robot.setJointVelocities(data, self.joints)
self.robot.set_joint_velocities(data, self.joints)
class JointForceAction(JointAction):
@@ -93,16 +93,16 @@ class JointForceAction(JointAction):
def __init__(self, robot, joint_ids=None, f_min=-np.infty, f_max=np.infty):
super(JointForceAction, self).__init__(robot, joint_ids)
self.data = robot.getJointTorques(self.joints)
self.data = robot.get_joint_torques(self.joints)
self.f_min = f_min
self.f_max = f_max
def _write(self, data=None):
if data is None:
self.robot.setJointTorques(self._data, self.joints)
self.robot.set_joint_torques(self._data, self.joints)
else:
data = np.clip(data, self.f_min, self.f_max)
self.robot.setJointTorques(data, self.joints)
self.robot.set_joint_torques(data, self.joints)
class JointAccelerationAction(JointAction):
@@ -115,13 +115,13 @@ class JointAccelerationAction(JointAction):
def __init__(self, robot, joint_ids=None, a_min=-np.infty, a_max=np.infty):
super(JointAccelerationAction, self).__init__(robot, joint_ids)
self.data = robot.getJointAccelerations(self.joints)
self.data = robot.get_joint_accelerations(self.joints)
self.a_min = a_min
self.a_max = a_max
def _write(self, data=None):
if data is None:
self.robot.setJointAccelerations(self._data, self.joints)
self.robot.set_joint_accelerations(self._data, self.joints)
else:
data = np.clip(data, self.a_min, self.a_max)
self.robot.setJointAccelerations(data, self.joints)
self.robot.set_joint_accelerations(data, self.joints)
@@ -36,7 +36,7 @@ class LinkAction(RobotAction):
# get the joints of the robot
if link_ids is None:
link_ids = robot.getLinkIds()
link_ids = robot.get_link_ids()
self.links = link_ids
@@ -50,9 +50,9 @@ class LinkPositionAction(LinkAction):
def _write(self, data=None):
if data is None:
self.robot.setLinkPositions(self.links, self._data)
self.robot.set_link_positions(self.links, self._data)
else:
self.robot.setLinkPositions(self.links, data)
self.robot.set_link_positions(self.links, data)
########################
@@ -63,7 +63,7 @@ class EndEffectorAction(LinkAction):
def __init__(self, robot, end_effector_ids=None):
if end_effector_ids is None:
end_effector_ids = robot.getEndEffectorIds()
end_effector_ids = robot.get_end_effector_ids()
super(EndEffectorAction, self).__init__(robot, end_effector_ids)
@@ -10,8 +10,8 @@ Dependencies:
from abc import ABCMeta
from pyrobolearn.actions.action import Action
from pyrobolearn.robots.robot import Robot
from pyrobolearn.actions import Action
from pyrobolearn.robots import Robot
__author__ = "Brian Delhaisse"
@@ -42,8 +42,8 @@ class RobotAction(Action):
def robot(self):
return self._robot
def isDiscrete(self):
def is_discrete(self):
return False
def isContinuous(self):
def is_continuous(self):
return True
+11 -1
View File
@@ -1,3 +1,13 @@
# import rewards
# import abstract reward class and operations
from .reward import *
# import basic rewards
from .basic_rewards import *
# import gym wrapper reward
from .gym_reward import GymReward
# import costs
from .cost import *
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python
"""Define some basic rewards used in reinforcement learning and optimization.
Dependencies:
- `pyrobolearn.states`
- `pyrobolearn.actions`
"""
import numpy as np
# from objective import Objective
from pyrobolearn.robots.robot import Robot
import pyrobolearn.states as states
import pyrobolearn.actions as actions
from pyrobolearn.rewards.reward import Reward
__author__ = "Brian Delhaisse"
__copyright__ = "Copyright 2018, PyRoboLearn"
__credits__ = ["Brian Delhaisse"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Brian Delhaisse"
__email__ = "briandelhaisse@gmail.com"
__status__ = "Development"
class FixedReward(Reward):
r"""Fixed reward.
This is a dummy class which always returns a fixed reward. This is fixed initially.
"""
def __init__(self, value):
super(FixedReward, self).__init__()
if not isinstance(value, (int, float)):
raise TypeError("Expecting a number")
self.value = value
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, str(self.value))
def compute(self):
return self.value
class FunctionalReward(Reward):
r"""Functional reward.
This is a reward class which calls a given function/class to compute the reward.
"""
def __init__(self, function):
super(FunctionalReward, self).__init__()
self.function = function
def __repr__(self):
return self.function.__name__
def compute(self):
return self.function()
class ForwardProgressReward(Reward):
r"""Forward progress reward
Compute the forward progress based on a forward direction, a previous and current positions.
"""
def __init__(self, state, direction=(1, 0, 0), normalize=False, update_state=False):
"""
Initialize the Forward Progress Reward.
Args:
state (BasePositionState, PositionState, Robot): robot or base position state.
direction (np.float[3], None): forward direction vector. If None, it will take the initial forward vector.
normalize (bool): if we should normalize the direction vector.
update_state (bool): if we should call the state and update its value.
"""
# check state argument
self.update_state = update_state
if isinstance(state, Robot):
state = states.BasePositionState(state)
self.update_state = True
elif not isinstance(state, (states.BasePositionState, states.PositionState)):
raise TypeError("Expecting the state to be an instance of `BasePositionState`, `PositionState`, or `Robot`"
", instead got: {}".format(type(state)))
super(ForwardProgressReward, self).__init__(state=state)
# if no direction specified, take the body forward vector
if direction is None:
self.direction = state.body.forward_vector
else:
self.direction = np.array(direction)
# normalize the direction vector if specified
if normalize:
self.direction = self.normalize(self.direction)
# remember current position
self.prev_pos = np.copy(self.state.data[0])
self.value = 0
@staticmethod
def normalize(x):
"""
Normalize the given vector.
"""
if np.allclose(x, 0):
return x
return x / np.linalg.norm(x)
def compute(self):
"""Compute the difference vector between the current and previous position (i.e. ~ velocity vector), and
compute the dot product between this velocity vector and the direction vector."""
if self.update_state:
self.state()
curr_pos = self.state.data[0]
velocity = curr_pos - self.prev_pos
self.value = self.direction.dot(velocity)
self.prev_pos = np.copy(curr_pos)
return self.value
class DirectiveReward(Reward):
r"""Directive Reward
Provide reward if the vector state is in the specified direction. Specifically, it computes the dot product
between the state vector and the specified direction.
If normalize, the reward is between -1 and 1.
"""
def __init__(self, state, direction=(1, 0, 0), normalize=True):
super(DirectiveReward, self).__init__(state=state)
self.normalize = normalize
if self.normalize:
self.direction = self.norm(np.array(direction))
# TODO uncomment
# if not isinstance(state, (PositionState, BasePositionState)):
# raise ValueError("Expecting state to be a PositionState or BasePositionState")
self.value = 0
@staticmethod
def norm(x):
"""
Normalize the given vector.
"""
if np.allclose(x, 0):
return x
return x / np.linalg.norm(x)
def compute(self):
pos = self.state.data[0]
if self.normalize:
pos = self.norm(pos)
self.value = self.direction.dot(pos)
return self.value
class L2SimilarityReward(Reward):
"""
Compute the square of the L2 norm between two vectors.
"""
def __init__(self):
super(L2SimilarityReward, self).__init__()
def value(self, vector1, vector2):
return np.dot(vector1, vector2)
class ImitationReward(Reward):
def __init__(self, human, robot):
super(ImitationReward, self).__init__()
self.human = human # instance of HumanKinematic class
self.robot = robot # instance of Robot class
def compute(self):
# check
pass
+50 -3
View File
@@ -19,7 +19,10 @@ import copy
import numpy as np
import torch
from pyrobolearn.robots.robot import Robot
# from objective import Objective
import pyrobolearn.states as states
import pyrobolearn.actions as actions
from pyrobolearn.rewards.reward import Reward
@@ -182,7 +185,7 @@ class TorqueCost(Cost):
self.tau = torque_state
def compute(self):
return - np.sum(self.tau.data**2)
return - np.sum(self.tau.data[0]**2)
class PowerCost(Cost):
@@ -199,7 +202,51 @@ class PowerCost(Cost):
self.vel = velocity_state
def compute(self):
return - np.sum(np.maximum(self.tau.data * self.vel.data, 0))
return - np.sum(np.maximum(self.tau.data[0] * self.vel.data[0], 0))
class JointPowerConsumptionCost(Cost):
r"""Joint Power Consumption Cost
Return the joint power consumption cost, where the power is computed as the torque times the velocity.
"""
def __init__(self, state, joint_ids=None, update_state=False):
"""
Initialize the Joint Power Consumption cost.
Args:
torque (Robot, State): robot instance, or the state. The state must contains the `JointForceTorqueState`
and the `JointVelocityState`.
joint_ids (None, int, list of int): joint ids. This used if `torque` is a `Robot` instance.
update_state (bool): If True, it will update the state.
"""
self.update_state = update_state
if isinstance(state, Robot):
torque = states.JointForceTorqueState(state, joint_ids=joint_ids)
velocity = states.JointVelocityState(state, joint_ids=joint_ids)
self.update_state = True
# state = torque + velocity
elif isinstance(state, states.State):
# check if they have the correct state
torque = state.lookfor(states.JointForceTorqueState)
if torque is None:
raise ValueError("Didn't find a `JointForceTorqueState` instance in the given states.")
velocity = state.lookfor(states.JointVelocityState)
if velocity is None:
raise ValueError("Didn't find a `JointVelocityState` instance in the given states.")
else:
raise TypeError("Expecting the state to be an instance of `State` or `Robot`.")
super(JointPowerConsumptionCost, self).__init__() # state=state)
self.tau = torque
self.vel = velocity
self.update_state = update_state
def compute(self):
if self.update_state:
self.tau()
self.vel()
return - np.sum((self.tau.data[0] * self.vel.data[0])**2)
class JointAccelerationCost(Cost):
@@ -369,7 +416,7 @@ class PowerConsumptionCost(Cost):
super(PowerConsumptionCost, self).__init__()
def loss(self, robot):
return np.dot(robot.getJointTorques(), robot.getJointVelocities())
return np.dot(robot.get_joint_torques(), robot.get_joint_velocities())
class DistanceCost(Cost):
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Provide the Gym wrapper reward.
"""
from pyrobolearn.rewards.basic_rewards import FixedReward
__author__ = "Brian Delhaisse"
__copyright__ = "Copyright 2018, PyRoboLearn"
__credits__ = ["Brian Delhaisse"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Brian Delhaisse"
__email__ = "briandelhaisse@gmail.com"
__status__ = "Development"
class GymReward(FixedReward):
r"""OpenAI Gym reward
This provides a wrapper around the gym reward value. It is the same as the FixedReward.
"""
pass
+4 -162
View File
@@ -216,6 +216,10 @@ class Reward(object):
def is_maximized():
return True
def reset(self):
for reward in self.rewards:
reward.reset()
def compute(self):
pass
@@ -645,169 +649,7 @@ def trunc(x):
# Rewards #
##############################################################
class FixedReward(Reward):
r"""Fixed reward.
This is a dummy class which always returns a fixed reward. This is fixed initially.
"""
def __init__(self, value):
super(FixedReward, self).__init__()
if not isinstance(value, (int, float)):
raise TypeError("Expecting a number")
self.value = value
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, str(self.value))
def compute(self):
return self.value
class FunctionalReward(Reward):
r"""Functional reward.
This is a reward class which calls a given function/class to compute the reward.
"""
def __init__(self, function):
super(FunctionalReward, self).__init__()
self.function = function
def __repr__(self):
return self.function.__name__
def compute(self):
return self.function()
class ForwardProgressReward(Reward):
r"""Forward progress reward
Compute the forward progress based on a forward direction, a previous and current positions.
"""
def __init__(self, state, direction=(1, 0, 0), normalize=False):
super(ForwardProgressReward, self).__init__(state=state)
# if direction is None:
# # takes the robot initial direction
# #direction = ...
# #init_pos
# pass
# if isinstance(direction, np.ndarray):
# pass
# elif isinstance(direction, Robot):
# # takes the
# pass
#
# self.direction = direction
# #self.init_pos = init_pos
self.direction = self.normalize(np.array(direction))
# TODO uncomment
# if not isinstance(state, (PositionState, BasePositionState)):
# raise ValueError("Expecting state to be a PositionState or BasePositionState")
self.init_pos = np.copy(self.state._data)
self.value = 0
@staticmethod
def normalize(x):
"""
Normalize the given vector.
"""
if np.allclose(x, 0):
return x
return x / np.linalg.norm(x)
def compute(self):
curr_pos = self.state._data
delta_pos = curr_pos - self.init_pos
self.value = self.direction.dot(delta_pos)
# self.value = curr_pos[0] - self.init_pos[0]
self.init_pos = np.copy(curr_pos)
return self.value
class DirectiveReward(Reward):
r"""Directive Reward
Provide reward if the vector state is in the specified direction. Specifically, it computes the dot product
between the state vector and the specified direction.
If normalize, the reward is between -1 and 1.
"""
def __init__(self, state, direction=(1, 0, 0), normalize=True):
super(DirectiveReward, self).__init__(state=state)
self.normalize = normalize
if self.normalize:
self.direction = self.norm(np.array(direction))
# TODO uncomment
# if not isinstance(state, (PositionState, BasePositionState)):
# raise ValueError("Expecting state to be a PositionState or BasePositionState")
self.value = 0
@staticmethod
def norm(x):
"""
Normalize the given vector.
"""
if np.allclose(x, 0):
return x
return x / np.linalg.norm(x)
def compute(self):
pos = self.state._data
if self.normalize:
pos = self.norm(pos)
self.value = self.direction.dot(pos)
return self.value
class L2SimilarityReward(Reward):
"""
Compute the square of the L2 norm between two vectors.
"""
def __init__(self):
super(L2SimilarityReward, self).__init__()
def value(self, vector1, vector2):
return np.dot(vector1, vector2)
class ImitationReward(Reward):
def __init__(self, human, robot):
super(ImitationReward, self).__init__()
self.human = human # instance of HumanKinematic class
self.robot = robot # instance of Robot class
def compute(self):
# check
pass
class GymReward(Reward):
r"""OpenAI Gym reward
This provides a wrapper
"""
def __init__(self, value):
super(GymReward, self).__init__()
if not isinstance(value, (int, float)):
raise TypeError("Expecting a number")
self.value = value
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, str(self.value))
def compute(self):
return self.value
# Test
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python
"""Provide some reward processors.
It processes the rewards before returning them; this can be useful to standardize, normalize, center them for instance.
"""
import numpy as np
from reward import Reward
__author__ = "Brian Delhaisse"
__copyright__ = "Copyright 2018, PyRoboLearn"
__credits__ = ["Brian Delhaisse"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Brian Delhaisse"
__email__ = "briandelhaisse@gmail.com"
__status__ = "Development"
class RewardProcessor(Reward):
r"""Reward Processor
Wraps the reward and process it. It also acts as a memory of the last received reward signal.
Examples:
reward = Reward1() + Reward2()
reward = RewardProcessor(reward, <args>)
"""
def __init__(self, reward):
super(RewardProcessor, self).__init__()
self.reward = reward
self.value = 0
def compute(self):
self.value = self.reward()
return self.value
class ShiftRewardProcessor(RewardProcessor):
r"""Shift Reward Processor
Shift the reward by the given amount; that is, it returned: :math:`\hat{r} = r + x` where :math:`x` is the
specified amount to shift the original reward.
"""
def __init__(self, reward, x):
"""
Initialize the Center Reward Processor.
Args:
reward (Reward): Reward instance to process.
x (int, float): amount to be shifted.
"""
super(ShiftRewardProcessor, self).__init__(reward)
self.x = x
def compute(self):
reward = self.reward()
self.value = reward + self.x
return self.value
class ClipRewardProcessor(RewardProcessor):
r"""Clip Reward Processor
Processor that clips the given reward to be between [low, high], where `low` and `high` are respectively the
specified lower and higher bound.
"""
def __init__(self, reward, low=-10, high=10):
"""
Initialize the Clip processor.
Args:
reward (Reward): Reward instance to process.
low (int, float): lower bound
high (int, float): higher bound
"""
super(ClipRewardProcessor, self).__init__(reward)
self.low = low
self.high = high
def compute(self):
reward = self.reward()
self.value = np.clip(reward, self.low, self.high)
return self.value
class CenterRewardProcessor(RewardProcessor):
r"""Center Reward Processor
Center the reward using the running mean.
"""
def __init__(self, reward):
super(CenterRewardProcessor, self).__init__(reward)
self.mean = 0
self.N = 0
def reset(self):
self.mean = 0
self.N = 0
self.reward.reset()
def compute(self):
reward = self.reward()
# update the mean
self.mean = self.N / (self.N + 1.) * self.mean + 1. / (self.N + 1) * reward
self.N += 1
# center reward
self.value = self.value - self.mean
return self.value
class NormalizeRewardProcessor(RewardProcessor):
r"""Normalize Reward Processor
Normalize the reward such that it is between 0 and 1. That is, it returned
:math:`\hat{r} = \frac{r - r_{min}}{r_{max} - r_{min}}`, where :math:`r \in [r_{min}, r_{max}]`.
Warnings: the first returned reward will be 0.
"""
def __init__(self, reward):
super(NormalizeRewardProcessor, self).__init__(reward)
self.min = np.infty
self.max = -np.infty
def reset(self):
self.min = np.infty
self.max = -np.infty
self.reward.reset()
def compute(self):
reward = self.reward()
self.min = np.minimum(reward, self.min)
self.max = np.maximum(reward, self.max)
den = self.max - self.min
if den == 0:
den = 1.
self.value = (reward - self.min) / den
return self.value
class StandardizeRewardProcessor(RewardProcessor):
r"""Standardize Reward Processor
Standardize the reward such that it returns :math:`\hat{r} = \frac{r - \mu}{\sigma}` where :math:`\mu` is the
running mean, and :math:`\sigma` is the running standard deviation. The returned reward will have a mean of 0
and standard deviation of 1.
"""
def __init__(self, reward, epsilon=1.e-4, center=True):
super(StandardizeRewardProcessor, self).__init__(reward)
self.eps = epsilon
self.mean = 0
self.var = 1
self.N = 0
self.center = center
def reset(self):
self.mean = 0
self.var = 1
self.N = 0
self.reward.reset()
def compute(self):
reward = self.reward()
# update the mean
old_mean = self.mean
self.mean = self.N / (self.N + 1.) * self.mean + 1. / (self.N + 1) * reward
# update the var / stddev
self.var = self.N / (self.N + 1) * self.var + \
1. / (self.N + 1) * (self.value - old_mean) * (self.value - self.mean)
std = np.sqrt(self.var)
# update total number of data points
self.N += 1
# standardize the reward
if self.center:
self.value = (reward - self.mean) / (std + self.eps)
else:
self.value = reward / (std + self.eps)
return self.value
class GammaAccumulatedRewardProcessor(RewardProcessor):
r"""Gamma reward processor
It will return the accumulated reward until now: :math:`R = \sum_{t'=0}^t \gamma^{t'} r_{t'}`.
"""
def __init__(self, reward, gamma=0.99):
super(GammaAccumulatedRewardProcessor, self).__init__(reward)
self.gamma = gamma
self.ret = 0.
def reset(self):
self.ret = 0.
self.reward.reset()
def compute(self):
reward = self.reward()
self.ret = reward + self.gamma * self.ret
return self.ret
class GammaStandardizeRewardProcessor(RewardProcessor):
r"""Gamma Standardize Reward Processor
References:
[1] https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py
"""
def __init__(self, reward, gamma=0.99, epsilon=1.e-4):
super(GammaStandardizeRewardProcessor, self).__init__(reward)
self.gamma = gamma
self.eps = epsilon
self.ret = 0
self.mean = 0
self.var = 1
self.N = 0
def reset(self):
self.ret = 0
self.mean = 0
self.var = 1
self.N = 0
self.reward.reset()
def compute(self):
reward = self.reward()
# update return
self.ret = reward + self.gamma * self.ret
# update the return mean
old_mean = self.mean
self.mean = self.N / (self.N + 1.) * self.mean + 1. / (self.N + 1) * self.ret
# update the return variance
self.var = self.N / (self.N + 1) * self.var + 1. / (self.N + 1) * (self.ret - old_mean) * (self.ret - self.mean)
std = np.sqrt(self.var)
# update total number of data points
self.N += 1
self.value = reward / (std + self.eps)
return self.value
class ScaleRewardProcessor(RewardProcessor):
r"""Scale Reward Processor
Processor that scales the reward x which is between [x1, x2] to the output y which is between [y1, y2].
"""
def __init__(self, reward, x1, x2, y1, y2):
"""
Initialize the scale reward processor
Args:
reward (Reward): reward function to process.
x1 (int, float): lower bound of the original reward
x2 (int, float): upper bound of the original reward
y1 (int, float): lower bound of the final reward
y2 (int, float): upper bound of the final reward
"""
super(ScaleRewardProcessor, self).__init__(reward)
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.ratio = (self.y2 - self.y1) / (self.x2 - self.x1)
@convert_numpy
def compute(self):
reward = self.reward()
self.value = self.y1 + (reward - self.x1) * self.ratio
return self.value
+18 -18
View File
@@ -17,31 +17,31 @@ class Aibo(QuadrupedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.02),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.02),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/aibo/aibo.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/aibo/aibo.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.02)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.02,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.02)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.02,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Aibo, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Aibo, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'aibo'
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['LF_up_leg_rot_y', 'LF_up_leg_rot_x', 'LF_down_leg'],
['RF_up_leg_rot_y', 'RF_up_leg_rot_x', 'RF_down_leg'],
['LB_up_leg_rot_y', 'LB_up_leg_rot_x', 'LB_down_leg'],
['RB_up_leg_rot_y', 'RB_up_leg_rot_x', 'RB_down_leg']]]
self.feet = [self.getLinkIds(link) for link in ['LF_paw', 'RF_paw', 'LB_paw', 'RB_paw']
self.feet = [self.get_link_ids(link) for link in ['LF_paw', 'RF_paw', 'LB_paw', 'RB_paw']
if link in self.link_names]
@@ -61,12 +61,12 @@ if __name__ == "__main__":
robot = Aibo(sim) # , useFixedBase=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+17 -17
View File
@@ -18,27 +18,27 @@ class AllegroHand(Hand):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
scaling=1.,
left=False,
useFixedBase=True):
fixed_base=True):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
# if left:
# urdf_path = '../robots/urdfs/allegrohand/allegro_left_hand.urdf'
# else:
urdf_path = os.path.dirname(__file__) + '/urdfs/allegrohand/allegro_right_hand.urdf'
super(AllegroHand, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(AllegroHand, self).__init__(simulator, urdf_path, position, orientation, fixed_base, scaling)
self.name = 'allegro_hand'
@@ -58,16 +58,16 @@ if __name__ == "__main__":
right_hand = AllegroHand(sim) # , init_pos=(0.,0.,0.), init_orient=(0,0,1,0))
# print information about the robot
right_hand.printRobotInfo()
# H = right_hand.calculateMassMatrix()
right_hand.print_info()
# H = right_hand.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# Position control using sliders
right_hand.addJointSlider()
right_hand.add_joint_slider()
for i in count():
right_hand.updateJointSlider()
# right_hand.setJointPositions([0.] * right_hand.getNumberOfDoFs())
right_hand.update_joint_slider()
# right_hand.set_joint_positions([0.] * right_hand.getNumberOfDoFs())
# step in simulation
world.step(sleep_dt=1./240)
+18 -18
View File
@@ -13,31 +13,31 @@ class Ant(QuadrupedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.2),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.2),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/mjcfs/ant.xml'):
urdf=os.path.dirname(__file__) + '/mjcfs/ant.xml'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.2)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.2,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.2)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.2,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Ant, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Ant, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'ant'
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['link0_3', 'link0_5'],
['link0_18', 'link0_20'],
['link0_13', 'link0_15'],
['link0_8', 'link0_10']]]
self.feet = [self.getLinkIds(link) for link in ['front_left_foot', 'front_right_foot',
self.feet = [self.get_link_ids(link) for link in ['front_left_foot', 'front_right_foot',
'left_back_foot', 'right_back_foot']
if link in self.link_names]
@@ -58,12 +58,12 @@ if __name__ == "__main__":
robot = Ant(sim) # , useFixedBase=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.getLeftFrontLegIds() + robot.getRightFrontLegIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+22 -22
View File
@@ -20,39 +20,39 @@ class Atlas(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 1.),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 1.),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/atlas/atlas_v4_with_multisense.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/atlas/atlas_v4_with_multisense.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 1.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (1.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 1.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (1.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Atlas, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Atlas, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'atlas'
self.head = self.getLinkIds('head') if 'head' in self.link_names else None
self.head = self.get_link_ids('head') if 'head' in self.link_names else None
self.torso = [self.getLinkIds(link) for link in ['ltorso', 'mtorso', 'utorso'] if link in self.link_names]
self.torso = [self.get_link_ids(link) for link in ['ltorso', 'mtorso', 'utorso'] if link in self.link_names]
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['l_uglut', 'l_lglut', 'l_uleg', 'l_lleg', 'l_talus', 'l_foot'],
['r_uglut', 'r_lglut', 'r_uleg', 'r_lleg', 'r_talus', 'r_foot']]]
self.feet = [self.getLinkIds(link) for link in ['l_foot', 'r_foot'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['l_foot', 'r_foot'] if link in self.link_names]
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['l_clav', 'l_scap', 'l_uarm', 'l_larm', 'l_ufarm', 'l_lfarm', 'l_hand'],
['r_clav', 'r_scap', 'r_uarm', 'r_larm', 'r_ufarm', 'r_lfarm', 'r_hand']]]
self.hands = [self.getLinkIds(link) for link in ['l_hand', 'r_hand'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['l_hand', 'r_hand'] if link in self.link_names]
# Test
@@ -71,12 +71,12 @@ if __name__ == "__main__":
robot = Atlas(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# position control using sliders
robot.addJointSlider(robot.getLeftLegIds())
robot.add_joint_slider(robot.getLeftLegIds())
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+14 -14
View File
@@ -16,20 +16,20 @@ class Ballbot(Robot):
[2] http://www.theconstructsim.com/bb-8-gazebo-model/
"""
def __init__(self, simulator, init_pos=(0, 0, 0.), init_orient=(0, 0, 0, 1), useFixedBase=False,
scaling=1., urdf_path=os.path.dirname(__file__) + '/urdfs/ballbot/ballbot.urdf'):
def __init__(self, simulator, position=(0, 0, 0.), orientation=(0, 0, 0, 1), fixed_base=False,
scaling=1., urdf=os.path.dirname(__file__) + '/urdfs/ballbot/ballbot.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Ballbot, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
self.ball = self.sim.loadURDF(os.path.dirname(__file__) + '/urdfs/ballbot/ball.urdf', init_pos, init_orient)
super(Ballbot, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.ball = self.sim.load_urdf(os.path.dirname(__file__) + '/urdfs/ballbot/ball.urdf', position, orientation)
self.name = 'ballbot'
@@ -49,10 +49,10 @@ if __name__ == "__main__":
robot = Ballbot(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
for i in count():
# robot.setJointVelocities([0, -1, 0])
# robot.set_joint_velocities([0, -1, 0])
# step in simulation
world.step(sleep_dt=1./240)
+61 -19
View File
@@ -29,7 +29,7 @@ class Body(object):
Define a physical body in the simulator/world.
"""
def __init__(self, simulator, body_id, name=None):
def __init__(self, simulator, body_id=0, name=None):
"""
Initialize the Body.
@@ -41,6 +41,7 @@ class Body(object):
self.simulator = simulator
self.id = body_id
self.name = name
self._mass = None
self.joints = None
##############
@@ -68,8 +69,8 @@ class Body(object):
@id.setter
def id(self, id_):
"""Set the unique body id."""
if not isinstance(id_, int):
raise TypeError("Expecting the given simulator to be an integer, instead got: {}".format(type(id_)))
# if not isinstance(id_, int):
# raise TypeError("Expecting the given simulator to be an integer, instead got: {}".format(type(id_)))
self._id = id_
@property
@@ -82,10 +83,32 @@ class Body(object):
@name.setter
def name(self, name):
"""Set the name of the body."""
if name is None:
name = self.__class__.__name__.lower()
if not isinstance(name, str):
raise TypeError("Expecting the given name to be a string, instead got: {}".format(type(name)))
self._name = name
@property
def base_link_id(self):
"""Return the base link id."""
return -1
@property
def base_name(self):
"""Return the base name."""
return self.sim.get_base_name(self.id)
@property
def base_mass(self):
"""Return the base mass."""
return self.sim.get_base_mass(self.id)
@property
def base_linear_momentum(self):
"""Return the base linear momentum. Warnings: this is not the same as the total linear momentum."""
return self.mass * self.linear_velocity
@property
def pose(self):
"""Return the body pose."""
@@ -114,6 +137,21 @@ class Body(object):
"""Return the orientation as a rotation matrix."""
return get_matrix_from_quaternion(self.orientation)
@property
def forward_vector(self):
"""Return the vector pointing forward."""
return self.rotation_matrix[:, 0]
@property
def left_vector(self):
"""Return the vector pointing on the left."""
return self.rotation_matrix[:, 1]
@property
def up_vector(self):
"""Return the vector pointing upward."""
return self.rotation_matrix[:, 2]
@property
def linear_velocity(self):
"""Return the linear velocity of the body's base."""
@@ -136,7 +174,9 @@ class Body(object):
@property
def mass(self):
"""Return the total mass of the body."""
return self.sim.get_mass(self.id)
if self._mass is None:
self._mass = self.sim.get_mass(self.id)
return self._mass
@property
def dimensions(self):
@@ -153,22 +193,10 @@ class Body(object):
"""Return the total number of links. This is the same as the number of joints."""
return self.sim.num_links(self.id)
@property
def num_actuated_joints(self):
"""Return the total number of actuated joints. This property should be overwritten in the child class."""
return self.sim.num_actuated_joints(self.id)
@property
def actuated_joints(self):
"""Return the total number of actuated joints."""
if self.joints is None:
self.joints = self.sim.get_actuated_joint_ids(self.id)
return self.joints
@property
def center_of_mass(self):
"""Return the center of mass."""
return self.sim.get_center_of_mass(self.id)
return self.sim.get_center_of_mass_position(self.id)
class MovableBody(Body):
@@ -177,7 +205,7 @@ class MovableBody(Body):
Define a movable object in the world.
"""
def __init__(self, simulator, object_id, name=None):
def __init__(self, simulator, object_id=0, name=None):
super(MovableBody, self).__init__(simulator, object_id, name=name)
# def move(self, position=None, orientation=None):
@@ -190,5 +218,19 @@ class ControllableBody(MovableBody):
Define a controllable object in the world.
"""
def __init__(self, simulator, object_id, name=None):
def __init__(self, simulator, object_id=0, name=None):
super(ControllableBody, self).__init__(simulator, object_id, name=name)
@property
def actuated_joints(self):
"""Return the total number of actuated joints."""
if self.joints is None:
self.joints = self.sim.get_actuated_joint_ids(self.id)
return self.joints
@property
def num_actuated_joints(self):
"""Return the total number of actuated joints. This property should be overwritten in the child class."""
if self.joints is None:
return self.sim.num_actuated_joints(self.id)
return len(self.joints)
+19 -19
View File
@@ -18,27 +18,27 @@ class Baxter(BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.95),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.95),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/baxter/baxter.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/baxter/baxter.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.95)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.95,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.95)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.95,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Baxter, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Baxter, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'baxter'
self.head = self.getLinkIds('head') if 'head' in self.link_names else None
self.head = self.get_link_ids('head') if 'head' in self.link_names else None
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['left_upper_shoulder', 'left_lower_shoulder', 'left_upper_elbow',
'left_lower_elbow', 'left_upper_forearm', 'left_lower_forearm',
'left_wrist', 'l_gripper_l_finger', 'l_gripper_r_finger'],
@@ -46,7 +46,7 @@ class Baxter(BiManipulatorRobot):
'right_lower_elbow', 'right_upper_forearm', 'right_lower_forearm',
'right_wrist', 'r_gripper_l_finger', 'r_gripper_r_finger']]]
self.hands = [self.getLinkIds(link) for link in ['left_gripper', 'right_gripper'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['left_gripper', 'right_gripper'] if link in self.link_names]
if __name__ == "__main__":
@@ -64,12 +64,12 @@ if __name__ == "__main__":
robot = Baxter(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+13 -13
View File
@@ -15,19 +15,19 @@ class BB8(Robot):
[2] http://www.theconstructsim.com/bb-8-gazebo-model/
"""
def __init__(self, simulator, init_pos=(0, 0, 0.4), init_orient=(0, 0, 0, 1), useFixedBase=False,
scaling=1., urdf_path=os.path.dirname(__file__) + '/urdfs/bb8/bb8.urdf'):
def __init__(self, simulator, position=(0, 0, 0.4), orientation=(0, 0, 0, 1), fixed_base=False,
scaling=1., urdf=os.path.dirname(__file__) + '/urdfs/bb8/bb8.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.4)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.4,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.4)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.4,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(BB8, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(BB8, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'bb8'
@@ -47,10 +47,10 @@ if __name__ == "__main__":
robot = BB8(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
for i in count():
robot.setJointVelocities([0, -1, 0])
robot.set_joint_velocities([0, -1, 0])
# step in simulation
world.step(sleep_dt=1./240)
+21 -21
View File
@@ -20,44 +20,44 @@ class Blackbird(BipedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 1.2),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 1.2),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/blackbird/blackbird_biped.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/blackbird/blackbird_biped.urdf'):
self.height = 1.2
self.base_height = self.height
# check parameters
if init_pos is None:
init_pos = (0., 0., self.height)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (self.height,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., self.height)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (self.height,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Blackbird, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Blackbird, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'blackbird'
# TODO: create constraints in pybullet
# From the user guide: "URDF, SDF and MJCF specify articulated bodies as a tree-structures without loops.
# The 'createConstraint' allows you to connect specific links of bodies to close those loops."
# self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
# self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
# for links in [['left_pelvis_rotation', 'left_hip', 'left_thigh', 'left_knee', 'left_shin',
# 'left_tarsus', 'left_toe'],
# ['right_pelvis_rotation', 'right_hip', 'right_thigh', 'right_knee', 'right_shin',
# 'right_tarsus', 'right_toe']]]
#
# self.feet = [self.getLinkIds(link) for link in ['left_toe', 'right_toe'] if link in self.link_names]
# self.feet = [self.get_link_ids(link) for link in ['left_toe', 'right_toe'] if link in self.link_names]
#
# # set joint angles to home position
# self.setJointHomePositions()
# self.set_joint_home_positions()
def getHomeJointPositions(self):
def get_home_joint_positions(self):
"""Return the joint positions for the home position"""
return np.array([0, 0, 1.0204, -1.97, -0.084, 2.06, -1.9, 0, 0, 1.0204, -1.97, -0.084, 2.06, -1.9])
@@ -77,13 +77,13 @@ if __name__ == "__main__":
robot = Blackbird(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.moveJointHomePositions()
# robot.update_joint_slider()
# robot.move_joint_home_positions()
world.step(sleep_dt=1./240)
+163 -159
View File
@@ -9,7 +9,7 @@ import sympy
import sympy.physics.mechanics as mechanics
from pyrobolearn.robots.robot import Robot
from pyrobolearn.utils.orientation import get_symbolic_matrix_from_axis_angle
from pyrobolearn.utils.orientation import get_symbolic_matrix_from_axis_angle, get_matrix_from_quaternion
class CartPole(Robot):
@@ -28,25 +28,25 @@ class CartPole(Robot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
scaling=1.,
useFixedBase=True,
urdf_path=os.path.join(pybullet_data.getDataPath(), "cartpole.urdf"),
fixed_base=True,
urdf=os.path.join(pybullet_data.getDataPath(), "cartpole.urdf"),
num_links=1,
inverted_pole=False,
pole_mass=1): # pole_mass=10
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(CartPole, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(CartPole, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'cartpole'
# create dynamically other links if necessary
@@ -55,7 +55,7 @@ class CartPole(Robot):
# 2. https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_utils/urdfEditor.py
# if num_links > 1:
# # get info about the link (dimensions, mass, etc).
# jointInfo = self.getJointInfo(self.joints[-1])
# jointInfo = self.get_joint_info(self.joints[-1])
# linkInfo = self.getLinkStates(self.joints[-1])
# dynamicInfo = self.sim.g
#
@@ -63,19 +63,19 @@ class CartPole(Robot):
#
# info =
# jointType = info[2]
# jointAxis, parent = info[-4]
# joint_axis, parent = info[-4]
# parentLinkIndex = info
#
# # create visual, collision shapes, and the body
# collision_shape = self.sim.createCollisionShape(self.sim.GEOM_BOX, halfExtents=dimensions)
# visual_shape = self.sim.createVisualShape(self.sim.GEOM_BOX, halfExtents=dimensions, rgbaColor=color)
# collision_shape = self.sim.create_collision_shape(self.sim.GEOM_BOX, half_extents=dimensions)
# visual_shape = self.sim.create_visual_shape(self.sim.GEOM_BOX, half_extents=dimensions, rgba_color=color)
#
# for i in range(num_links - 1):
# # create new link and attached it to the previous link
# linkId = self.sim.createMultiBody(baseMass=mass,
# baseCollisionShapeIndex=collision_shape,
# baseVisualShapeIndex=visual_shape,
# basePosition=position,
# linkId = self.sim.create_body(baseMass=mass,
# base_collision_shapeIndex=collision_shape,
# base_visual_shapeIndex=visual_shape,
# position=position,
# baseOrientation=orientation,
# linkParentIndices=[self.joints[-1]],
# linkJointTypes=[self.sim.JOINT_REVOLUTE])
@@ -85,7 +85,7 @@ class CartPole(Robot):
# The values are from the cartpole URDF: https://github.com/bulletphysics/bullet3/blob/master/data/cartpole.urdf
# remove body
self.sim.removeBody(self.id)
self.sim.remove_body(self.id)
# create slider
dims = (15, 0.025, 0.025)
@@ -93,74 +93,74 @@ class CartPole(Robot):
mass = 0
position = (0, 0, 0)
orientation = (0, 0, 0, 1)
collisionShape = self.sim.createCollisionShape(self.sim.GEOM_BOX, halfExtents=dims)
visualShape = self.sim.createVisualShape(self.sim.GEOM_BOX, halfExtents=dims, rgbaColor=color)
collision_shape = self.sim.create_collision_shape(self.sim.GEOM_BOX, half_extents=dims)
visual_shape = self.sim.create_visual_shape(self.sim.GEOM_BOX, half_extents=dims, rgba_color=color)
# create cart and pole
cartDims = (0.25, 0.25, 0.1)
cartCollisionShape = self.sim.createCollisionShape(self.sim.GEOM_BOX, halfExtents=cartDims)
cartVisualShape = self.sim.createVisualShape(self.sim.GEOM_BOX, halfExtents=cartDims, rgbaColor=(0,0,0.8,1))
poleDims = (0.025, 0.025, 0.5)
poleCollisionShape = self.sim.createCollisionShape(self.sim.GEOM_BOX, halfExtents=poleDims)
poleVisualShape = self.sim.createVisualShape(self.sim.GEOM_BOX, halfExtents=poleDims, rgbaColor=(1,1,1,1))
cart_dims = (0.25, 0.25, 0.1)
cart_collision_shape = self.sim.create_collision_shape(self.sim.GEOM_BOX, half_extents=cart_dims)
cart_visual_shape = self.sim.create_visual_shape(self.sim.GEOM_BOX, half_extents=cart_dims,
rgba_color=(0, 0, 0.8, 1))
pole_dims = (0.025, 0.025, 0.5)
pole_collision_shape = self.sim.create_collision_shape(self.sim.GEOM_BOX, half_extents=pole_dims)
pole_visual_shape = self.sim.create_visual_shape(self.sim.GEOM_BOX, half_extents=pole_dims,
rgba_color=(1, 1, 1, 1))
radius = 0.05
sphereCollisionShape = self.sim.createCollisionShape(self.sim.GEOM_SPHERE, radius=radius)
sphereVisualShape = self.sim.createVisualShape(self.sim.GEOM_SPHERE, radius=radius, rgbaColor=(1,0,0,1))
sphere_collision_shape = self.sim.create_collision_shape(self.sim.GEOM_SPHERE, radius=radius)
sphere_visual_shape = self.sim.create_visual_shape(self.sim.GEOM_SPHERE, radius=radius,
rgba_color=(1, 0, 0, 1))
linkMasses = [1]
linkCollisionShapeIds = [cartCollisionShape]
linkVisualShapeIds = [cartVisualShape]
link_masses = [1]
link_collision_shape_ids = [cart_collision_shape]
link_visual_shape_ids = [cart_visual_shape]
linkPositions = [[0, 0, 0]]
linkOrientations = [[0, 0, 0, 1]]
linkInertialFramePositions = [[0, 0, 0]]
linkInertialFrameOrientations = [[0, 0, 0, 1]]
link_positions = [[0, 0, 0]]
link_orientations = [[0, 0, 0, 1]]
link_inertial_frame_positions = [[0, 0, 0]]
link_inertial_frame_orientations = [[0, 0, 0, 1]]
parentIndices = [0]
parent_indices = [0]
jointTypes = [self.sim.JOINT_PRISMATIC]
jointAxis = [[1, 0, 0]]
joint_types = [self.sim.JOINT_PRISMATIC]
joint_axis = [[1, 0, 0]]
# for each new link
if num_links > 0:
linkMasses += [0.001, pole_mass] * num_links
linkCollisionShapeIds += [sphereCollisionShape, poleCollisionShape] * num_links
linkVisualShapeIds += [sphereVisualShape, poleVisualShape] * num_links
link_masses += [0.001, pole_mass] * num_links
link_collision_shape_ids += [sphere_collision_shape, pole_collision_shape] * num_links
link_visual_shape_ids += [sphere_visual_shape, pole_visual_shape] * num_links
if inverted_pole:
linkPositions += [[0, 0, 0], [0, 0, -0.5]]
linkPositions += [[0, 0, -0.5], [0, 0, -0.5]] * (num_links - 1)
link_positions += [[0, 0, 0], [0, 0, -0.5]]
link_positions += [[0, 0, -0.5], [0, 0, -0.5]] * (num_links - 1)
else:
linkPositions += [[0, 0, 0], [0, 0, 0.5]]
linkPositions += [[0, 0, 0.5], [0, 0, 0.5]] * (num_links - 1)
linkOrientations += [[0, 0, 0, 1]] * 2 * num_links
linkInertialFramePositions += [[0, 0, 0]] * 2 * num_links
linkInertialFrameOrientations += [[0, 0, 0, 1]] * 2 * num_links
parentIndices += range(1, 1 + 2 * num_links)
jointTypes += [self.sim.JOINT_REVOLUTE, self.sim.JOINT_FIXED] * num_links
jointAxis += [[0, 1, 0], [0, 1, 0]] * num_links
link_positions += [[0, 0, 0], [0, 0, 0.5]]
link_positions += [[0, 0, 0.5], [0, 0, 0.5]] * (num_links - 1)
link_orientations += [[0, 0, 0, 1]] * 2 * num_links
link_inertial_frame_positions += [[0, 0, 0]] * 2 * num_links
link_inertial_frame_orientations += [[0, 0, 0, 1]] * 2 * num_links
parent_indices += range(1, 1 + 2 * num_links)
joint_types += [self.sim.JOINT_REVOLUTE, self.sim.JOINT_FIXED] * num_links
joint_axis += [[0, 1, 0], [0, 1, 0]] * num_links
# create the whole body
self.id = self.sim.createMultiBody(baseMass=mass, baseCollisionShapeIndex=collisionShape,
baseVisualShapeIndex=visualShape, basePosition=position,
baseOrientation=orientation,
baseInertialFramePosition=[0, 0, 0],
baseInertialFrameOrientation=[0, 0, 0, 1],
linkMasses=linkMasses,
linkCollisionShapeIndices=linkCollisionShapeIds,
linkVisualShapeIndices=linkVisualShapeIds,
linkPositions=linkPositions, linkOrientations=linkOrientations,
linkInertialFramePositions=linkInertialFramePositions,
linkInertialFrameOrientations=linkInertialFrameOrientations,
linkParentIndices=parentIndices, linkJointTypes=jointTypes,
linkJointAxis=jointAxis)
self.id = self.sim.create_body(mass=mass, collision_shape_id=collision_shape, visual_shape_id=visual_shape,
position=position, orientation=orientation, baseInertialFramePosition=[0, 0, 0],
baseInertialFrameOrientation=[0, 0, 0, 1], linkMasses=link_masses,
linkCollisionShapeIndices=link_collision_shape_ids,
linkVisualShapeIndices=link_visual_shape_ids,
linkPositions=link_positions, linkOrientations=link_orientations,
linkInertialFramePositions=link_inertial_frame_positions,
linkInertialFrameOrientations=link_inertial_frame_orientations,
linkParentIndices=parent_indices, linkJointTypes=joint_types,
linkJointAxis=joint_axis)
# useful variables
self.joints = [] # non-fixed joint/link indices in the simulator
self.joint_names = {} # joint name to id in the simulator
self.link_names = {} # link name to id in the simulator
for joint in range(self.getNumberOfJoints()):
for joint in range(self.num_joints):
# Get joint info
jnt = self.sim.getJointInfo(self.id, joint)
jnt = self.sim.get_joint_info(self.id, joint)
self.joint_names[jnt[1]] = jnt[0]
self.link_names[jnt[12]] = jnt[0]
# remember actuated joints
@@ -168,10 +168,10 @@ class CartPole(Robot):
self.joints.append(jnt[0])
# disable the joints for the pole links
# self.disableMotor(self.joints[1:])
self.disableMotor(parentIndices[1::2])
# self.disable_motor(self.joints[1:])
self.disable_motor(parent_indices[1::2])
def getSymbolicEquationsOfMotion(self, verbose=False):
def get_symbolic_equations_of_motion(self, verbose=False):
"""
This returns the symbolic equation of motions of the robot (using the URDF). Internally, this used the
`sympy.mechanics` module.
@@ -180,105 +180,109 @@ class CartPole(Robot):
g, t = sympy.symbols('g t')
# create the world inertial frame of reference and its origin
worldFrame = mechanics.ReferenceFrame('Fw')
worldOrigin = mechanics.Point('Pw')
worldOrigin.set_vel(worldFrame, mechanics.Vector(0))
world_frame = mechanics.ReferenceFrame('Fw')
world_origin = mechanics.Point('Pw')
world_origin.set_vel(world_frame, mechanics.Vector(0))
# create the base frame (its position, orientation and velocities) + generalized coordinates and speeds
baseId = -1
base_id = -1
# Check if the robot has a fixed base and create the generalized coordinates and speeds based on that,
# as well the base position, orientation and velocities
if self.hasFixedBase():
if self.has_fixed_base():
# generalized coordinates q(t) and speeds dq(t)
q = mechanics.dynamicsymbols('q:{}'.format(len(self.joints)))
dq = mechanics.dynamicsymbols('dq:{}'.format(len(self.joints)))
pos, orn = self.getBasePositionAndOrientation(convert_to_numpy_quaternion=False)
linVel, angVel = [0,0,0], [0,0,0] # 0 because fixed base
jointId = 0
pos, orn = self.get_base_pose()
lin_vel, ang_vel = [0,0,0], [0,0,0] # 0 because fixed base
joint_id = 0
else:
# generalized coordinates q(t) and speeds dq(t)
q = mechanics.dynamicsymbols('q:{}'.format(7 + len(self.joints)))
dq = mechanics.dynamicsymbols('dq:{}'.format(6 + len(self.joints)))
pos, orn = q[:3], q[3:7]
linVel, angVel = dq[:3], dq[3:6]
jointId = 7
lin_vel, ang_vel = dq[:3], dq[3:6]
joint_id = 7
# set the position, orientation and velocities of the base
baseFrame = worldFrame.orientnew('Fb', 'Quaternion', [orn[3], orn[0], orn[1], orn[2]])
baseFrame.set_ang_vel(worldFrame, angVel[0] * worldFrame.x + angVel[1] * worldFrame.y + angVel[2] * worldFrame.z)
baseOrigin = worldOrigin.locatenew('Pb', pos[0] * worldFrame.x + pos[1] * worldFrame.y + pos[2] * worldFrame.z)
baseOrigin.set_vel(worldFrame, linVel[0] * worldFrame.x + linVel[1] * worldFrame.y + linVel[2] * worldFrame.z)
base_frame = world_frame.orientnew('Fb', 'Quaternion', [orn[3], orn[0], orn[1], orn[2]])
base_frame.set_ang_vel(world_frame, ang_vel[0] * world_frame.x + ang_vel[1] * world_frame.y + ang_vel[2] *
world_frame.z)
base_origin = world_origin.locatenew('Pb', pos[0] * world_frame.x + pos[1] * world_frame.y + pos[2] *
world_frame.z)
base_origin.set_vel(world_frame, lin_vel[0] * world_frame.x + lin_vel[1] * world_frame.y + lin_vel[2] *
world_frame.z)
# inputs u(t) (applied torques)
u = mechanics.dynamicsymbols('u:{}'.format(len(self.joints)))
jointIdU = 0
joint_id_u = 0
# kinematics differential equations
kd_eqs = [q[i].diff(t) - dq[i] for i in range(len(self.joints))]
# define useful lists/dicts for later
bodies, loads = [], []
frames = {baseId: (baseFrame, baseOrigin)}
# frames = {baseId: (worldFrame, worldOrigin)}
frames = {base_id: (base_frame, base_origin)}
# frames = {base_id: (worldFrame, worldOrigin)}
# go through each joint/link (each link is associated to a joint)
for linkId in range(self.getNumberOfLinks()):
for link_id in range(self.num_links):
# get useful information about joint/link kinematics and dynamics from simulator
info = self.sim.getDynamicsInfo(self.id, linkId)
mass, localInertiaDiagonal = info[0], np.array(info[2])
info = self.sim.getLinkState(self.id, linkId)
localInertialFramePosition, localInertialFrameOrientation = info[2], info[3]
info = self.sim.get_dynamics_info(self.id, link_id)
mass, local_inertia_diagonal = info[0], info[2]
info = self.sim.get_link_state(self.id, link_id)
local_inertial_frame_position, local_inertial_frame_orientation = info[2], info[3]
# worldLinkFramePosition, worldLinkFrameOrientation = info[4], info[5]
info = self.sim.getJointInfo(self.id, linkId)
jointName, jointType = info[1:3]
info = self.sim.get_joint_info(self.id, link_id)
joint_name, joint_type = info[1:3]
# jointDamping, jointFriction = info[6:8]
linkName, jointAxisInLocalFrame, parentFramePosition, parentFrameOrientation, parentIdx = info[-5:]
xl, yl, zl = jointAxisInLocalFrame
link_name, joint_axis_in_local_frame, parent_frame_position, parent_frame_orientation, \
parent_idx = info[-5:]
xl, yl, zl = joint_axis_in_local_frame
# get previous references
parentFrame, parentPoint = frames[parentIdx]
parent_frame, parent_point = frames[parent_idx]
# create a reference frame with its origin for each joint
# set frame orientation
if jointType == self.sim.JOINT_REVOLUTE:
R = np.array(self.sim.getMatrixFromQuaternion(parentFrameOrientation)).reshape(3,3)
R1 = getSymbolicMatrixFromAxisAngle(jointAxisInLocalFrame, q[jointId])
if joint_type == self.sim.JOINT_REVOLUTE:
R = get_matrix_from_quaternion(parent_frame_orientation)
R1 = get_symbolic_matrix_from_axis_angle(joint_axis_in_local_frame, q[joint_id])
R = R1.dot(R)
frame = parentFrame.orientnew('F' + str(linkId), 'DCM', sympy.Matrix(R))
frame = parent_frame.orientnew('F' + str(link_id), 'DCM', sympy.Matrix(R))
else:
x, y, z, w = parentFrameOrientation # orientation of the joint in parent CoM inertial frame
frame = parentFrame.orientnew('F' + str(linkId), 'Quaternion', [w, x, y, z])
x, y, z, w = parent_frame_orientation # orientation of the joint in parent CoM inertial frame
frame = parent_frame.orientnew('F' + str(link_id), 'Quaternion', [w, x, y, z])
# set frame angular velocity
angVel = 0
if jointType == self.sim.JOINT_REVOLUTE:
angVel = dq[jointId] * (xl * frame.x + yl * frame.y + zl * frame.z)
frame.set_ang_vel(parentFrame, angVel)
ang_vel = 0
if joint_type == self.sim.JOINT_REVOLUTE:
ang_vel = dq[joint_id] * (xl * frame.x + yl * frame.y + zl * frame.z)
frame.set_ang_vel(parent_frame, ang_vel)
# create origin of the reference frame
# set origin position
x, y, z = parentFramePosition # position of the joint in parent CoM inertial frame
pos = x * parentFrame.x + y * parentFrame.y + z * parentFrame.z
if jointType == self.sim.JOINT_PRISMATIC:
pos += q[jointId] * (xl * frame.x + yl * frame.y + zl * frame.z)
origin = parentPoint.locatenew('P' + str(linkId), pos)
x, y, z = parent_frame_position # position of the joint in parent CoM inertial frame
pos = x * parent_frame.x + y * parent_frame.y + z * parent_frame.z
if joint_type == self.sim.JOINT_PRISMATIC:
pos += q[joint_id] * (xl * frame.x + yl * frame.y + zl * frame.z)
origin = parent_point.locatenew('P' + str(link_id), pos)
# set origin velocity
if jointType == self.sim.JOINT_PRISMATIC:
vel = dq[jointId] * (xl * frame.x + yl * frame.y + zl * frame.z)
origin.set_vel(worldFrame, vel.express(worldFrame))
if joint_type == self.sim.JOINT_PRISMATIC:
vel = dq[joint_id] * (xl * frame.x + yl * frame.y + zl * frame.z)
origin.set_vel(world_frame, vel.express(world_frame))
else:
origin.v2pt_theory(parentPoint, worldFrame, parentFrame)
origin.v2pt_theory(parent_point, world_frame, parent_frame)
# define CoM frame and position (and velocities) wrt the local link frame
x, y, z, w = localInertialFrameOrientation
com_frame = frame.orientnew('Fc' + str(linkId), 'Quaternion', [w, x, y, z])
x, y, z, w = local_inertial_frame_orientation
com_frame = frame.orientnew('Fc' + str(link_id), 'Quaternion', [w, x, y, z])
com_frame.set_ang_vel(frame, mechanics.Vector(0))
x, y, z = localInertialFramePosition
com = origin.locatenew('C' + str(linkId), x * frame.x + y * frame.y + z * frame.z)
com.v2pt_theory(origin, worldFrame, frame)
x, y, z = local_inertial_frame_position
com = origin.locatenew('C' + str(link_id), x * frame.x + y * frame.y + z * frame.z)
com.v2pt_theory(origin, world_frame, frame)
# define com particle
# com_particle = mechanics.Particle('Pa' + str(linkId), com, mass)
@@ -287,62 +291,62 @@ class CartPole(Robot):
# save
# frames[linkId] = (frame, origin)
# frames[linkId] = (frame, origin, com_frame, com)
frames[linkId] = (com_frame, com)
frames[link_id] = (com_frame, com)
# define mass and inertia
ixx, iyy, izz = localInertiaDiagonal
ixx, iyy, izz = local_inertia_diagonal
inertia = mechanics.inertia(com_frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0)
inertia = (inertia, com)
# define rigid body associated to frame
body = mechanics.RigidBody(linkName, com, frame, mass, inertia)
body = mechanics.RigidBody(link_name, com, frame, mass, inertia)
bodies.append(body)
# define dynamical forces/torques acting on the body
# gravity force applied on the CoM
force = (com, - mass * g * worldFrame.z)
force = (com, - mass * g * world_frame.z)
loads.append(force)
# if prismatic joint, compute force
if jointType == self.sim.JOINT_PRISMATIC:
force = (origin, u[jointIdU] * (xl * frame.x + yl * frame.y + zl * frame.z))
if joint_type == self.sim.JOINT_PRISMATIC:
force = (origin, u[joint_id_u] * (xl * frame.x + yl * frame.y + zl * frame.z))
# force = (com, u[jointIdU] * (x * frame.x + y * frame.y + z * frame.z) - mass * g * worldFrame.z)
loads.append(force)
# if revolute joint, compute torque
if jointType == self.sim.JOINT_REVOLUTE:
if joint_type == self.sim.JOINT_REVOLUTE:
v = (xl * frame.x + yl * frame.y + zl * frame.z)
# torqueOnPrevBody = (parentFrame, - u[jointIdU] * v)
torqueOnPrevBody = (parentFrame, - u[jointIdU] * v)
torqueOnCurrBody = (frame, u[jointIdU] * v)
loads.append(torqueOnPrevBody)
loads.append(torqueOnCurrBody)
torque_on_prev_body = (parent_frame, - u[joint_id_u] * v)
torque_on_curr_body = (frame, u[joint_id_u] * v)
loads.append(torque_on_prev_body)
loads.append(torque_on_curr_body)
# if joint is not fixed increment the current joint id
if jointType != self.sim.JOINT_FIXED:
jointId += 1
jointIdU += 1
if joint_type != self.sim.JOINT_FIXED:
joint_id += 1
joint_id_u += 1
if verbose:
print("\nLink name with type: {} - {}".format(linkName, self.getJointTypes(jointId=linkId)))
print("\nLink name with type: {} - {}".format(link_name, self.get_joint_types(joint_ids=link_id)))
print("------------------------------------------------------")
print("Position of joint frame wrt parent frame: {}".format(origin.pos_from(parentPoint)))
print("Orientation of joint frame wrt parent frame: {}".format(frame.dcm(parentFrame)))
print("Linear velocity of joint frame wrt parent frame: {}".format(origin.vel(worldFrame).express(parentFrame)))
print("Angular velocity of joint frame wrt parent frame: {}".format(frame.ang_vel_in(parentFrame)))
print("Position of joint frame wrt parent frame: {}".format(origin.pos_from(parent_point)))
print("Orientation of joint frame wrt parent frame: {}".format(frame.dcm(parent_frame)))
print("Linear velocity of joint frame wrt parent frame: {}".format(origin.vel(world_frame).express(parent_frame)))
print("Angular velocity of joint frame wrt parent frame: {}".format(frame.ang_vel_in(parent_frame)))
print("------------------------------------------------------")
print("Position of joint frame wrt world frame: {}".format(origin.pos_from(worldOrigin)))
print("Orientation of joint frame wrt world frame: {}".format(frame.dcm(worldFrame).simplify()))
print("Linear velocity of joint frame wrt world frame: {}".format(origin.vel(worldFrame)))
print("Angular velocity of joint frame wrt parent frame: {}".format(frame.ang_vel_in(worldFrame)))
print("Position of joint frame wrt world frame: {}".format(origin.pos_from(world_origin)))
print("Orientation of joint frame wrt world frame: {}".format(frame.dcm(world_frame).simplify()))
print("Linear velocity of joint frame wrt world frame: {}".format(origin.vel(world_frame)))
print("Angular velocity of joint frame wrt parent frame: {}".format(frame.ang_vel_in(world_frame)))
print("------------------------------------------------------")
# print("Local position of CoM wrt joint frame: {}".format(com.pos_from(origin)))
# print("Local linear velocity of CoM wrt joint frame: {}".format(com.vel(worldFrame).express(frame)))
# print("Local angular velocity of CoM wrt joint frame: {}".format(com_frame.ang_vel_in(frame)))
# print("------------------------------------------------------")
if jointType == self.sim.JOINT_PRISMATIC:
if joint_type == self.sim.JOINT_PRISMATIC:
print("Input value (force): {}".format(loads[-1]))
elif jointType == self.sim.JOINT_REVOLUTE:
elif joint_type == self.sim.JOINT_REVOLUTE:
print("Input value (torque on previous and current bodies): {} and {}".format(loads[-2], loads[-1]))
print("")
@@ -360,7 +364,7 @@ class CartPole(Robot):
# TODO: 2. account for constraints (e.g. holonomic, non-holonomic, etc.)
# Get the Equation of Motion (EoM) using Kane's method
kane = mechanics.KanesMethod(worldFrame, q_ind=q, u_ind=dq, kd_eqs=kd_eqs)
kane = mechanics.KanesMethod(world_frame, q_ind=q, u_ind=dq, kd_eqs=kd_eqs)
kane.kanes_equations(bodies=bodies, loads=loads)
# get mass matrix and force vector (after simplifying) such that :math:`M(x,t) \dot{x} = f(x,t)`
@@ -387,7 +391,7 @@ class CartPole(Robot):
return M, f
def linearizeEquationOfMotion(self, point=None, verbose=False):
def linearize_equations_of_motion(self, point=None, verbose=False):
"""
Linearize the equation of motions around the given point (=state). That is, instead of having
:math:`\dot{x} = f(x,u)` where :math:`f` is in general a non-linear function, it linearizes it around
@@ -399,10 +403,10 @@ class CartPole(Robot):
the matrices.
"""
if self.symbols is None:
self.getSymbolicEquationsOfMotion()
self.get_symbolic_equations_of_motion()
if point is None: # take current state
point = list(self.getJointPositions()) + list(self.getJointVelocities())
point = list(self.get_joint_positions()) + list(self.get_joint_velocities())
point = dict(zip(self.symbols['q'] + self.symbols['dq'], point))
kane, parameters = self.symbols['kane'], self.symbols['parameters']
@@ -530,12 +534,12 @@ if __name__ == "__main__":
robot = CartPole(sim, num_links=num_links)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
robot.getSymbolicEquationsOfMotion()
robot.get_symbolic_equations_of_motion()
eq_point = np.zeros((num_links + 1) * 2) # state = [q, dq]
A, B = robot.linearizeEquationOfMotion(eq_point)
A, B = robot.linearize_equations_of_motion(eq_point)
# LQR controller
lqr = LQR(A, B)
@@ -543,9 +547,9 @@ if __name__ == "__main__":
for i in count():
# control
x = np.concatenate((robot.getJointPositions(), robot.getJointVelocities()))
x = np.concatenate((robot.get_joint_positions(), robot.get_joint_velocities()))
u = K.dot(eq_point - x)
robot.setJointTorques(u[0], 0)
robot.set_joint_torques(u[0], 0)
print("U[0] = {}".format(u[0]))
+21 -21
View File
@@ -25,40 +25,40 @@ class Cassie(BipedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, .8),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, .8),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/cassie/cassie.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/cassie/cassie.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.8)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.8,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.8)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.8,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Cassie, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Cassie, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'cassie'
# TODO: create constraints in pybullet
# From the user guide: "URDF, SDF and MJCF specify articulated bodies as a tree-structures without loops.
# The 'createConstraint' allows you to connect specific links of bodies to close those loops."
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['left_pelvis_rotation', 'left_hip', 'left_thigh', 'left_knee', 'left_shin',
'left_tarsus', 'left_toe'],
['right_pelvis_rotation', 'right_hip', 'right_thigh', 'right_knee', 'right_shin',
'right_tarsus', 'right_toe']]]
self.feet = [self.getLinkIds(link) for link in ['left_toe', 'right_toe'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['left_toe', 'right_toe'] if link in self.link_names]
# set joint angles to home position
self.setJointHomePositions()
self.set_joint_home_positions()
def getHomeJointPositions(self):
def get_home_joint_positions(self):
"""Return the joint positions for the home position"""
return np.array([0, 0, 1.0204, -1.97, -0.084, 2.06, -1.9, 0, 0, 1.0204, -1.97, -0.084, 2.06, -1.9])
@@ -78,13 +78,13 @@ if __name__ == "__main__":
robot = Cassie(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.moveJointHomePositions()
# robot.update_joint_slider()
robot.move_joint_home_positions()
world.step(sleep_dt=1./240)
+21 -21
View File
@@ -14,35 +14,35 @@ class Centauro(WheeledRobot, QuadrupedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 1.),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 1.),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/centauro/centauro_stick.urdf'
urdf=os.path.dirname(__file__) + '/urdfs/centauro/centauro_stick.urdf'
# centauro_stick.urdf, centauro_soft_hand.urdf, centauro_heri.urdf,
# centauro_schunk_handL.urdf, centauro_schunk_hand.urdf
):
# check parameters
if init_pos is None:
init_pos = (0., 0., 1.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (1.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 1.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (1.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Centauro, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase)
super(Centauro, self).__init__(simulator, urdf, position, orientation, fixed_base)
self.name = 'centauro'
self.necks = [self.getLinkIds(link) for link in ['neck_'+str(i) for i in range(1, 4)]]
self.necks = [self.get_link_ids(link) for link in ['neck_' + str(i) for i in range(1, 4)]]
# define wheels
self.wheels = [self.getLinkIds(link) for link in ['wheel_'+str(i) for i in range(1, 5)]]
self.wheels = [self.get_link_ids(link) for link in ['wheel_' + str(i) for i in range(1, 5)]]
self.wheel_directions = np.array([-1., 1., -1., 1])
# define legs and feet
self.legs = [[self.getLinkIds(link) for link in links]
self.legs = [[self.get_link_ids(link) for link in links]
for links in [['hip1_1', 'hip2_1', 'knee_1', 'ankle1_1', 'ankle2_1', 'wheel_1'],
['hip1_2', 'hip2_2', 'knee_2', 'ankle1_2', 'ankle2_2', 'wheel_2'],
['hip1_3', 'hip2_3', 'knee_3', 'ankle1_3', 'ankle2_3', 'wheel_3'],
@@ -51,11 +51,11 @@ class Centauro(WheeledRobot, QuadrupedRobot, BiManipulatorRobot):
self.feet = self.wheels
# define arms and hands
self.arms = [[self.getLinkIds(link) for link in links]
self.arms = [[self.get_link_ids(link) for link in links]
for links in [['arm1_1', 'arm1_2', 'arm1_3', 'arm1_4', 'arm1_5', 'arm1_6', 'arm1_7'],
['arm2_1', 'arm2_2', 'arm2_3', 'arm2_4', 'arm2_5', 'arm2_6', 'arm2_7']]]
self.hands = [self.getLinkIds(link) for link in ['arm1_8', 'arm2_8']]
self.hands = [self.get_link_ids(link) for link in ['arm1_8', 'arm2_8']]
# Test
@@ -74,14 +74,14 @@ if __name__ == "__main__":
robot = Centauro(sim) # , useFixedBase=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
print("Number of Legs: {}".format(robot.getNumberOfLegs()))
print("Number of Arms: {}".format(robot.getNumberOfArms()))
# robot.addJointSlider(robot.getRightFrontLegIds())
# robot.add_joint_slider(robot.getRightFrontLegIds())
robot.drive(speed=3)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+25 -25
View File
@@ -15,49 +15,49 @@ class Cogimon(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 1.),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 1.),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/cogimon/cogimon.urdf',
urdf=os.path.dirname(__file__) + '/urdfs/cogimon/cogimon.urdf',
lower_body=False): # cogimon_lower_body.urdf
# check parameters
if init_pos is None:
init_pos = (0., 0., 1.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (1.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 1.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (1.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
if lower_body:
urdf_path = os.path.dirname(__file__) + '/urdfs/cogimon/cogimon_lower_body.urdf'
urdf = os.path.dirname(__file__) + '/urdfs/cogimon/cogimon_lower_body.urdf'
super(Cogimon, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Cogimon, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'cogimon'
self.waist = self.getLinkIds('DWL') if 'DWL' in self.link_names else None
self.torso = self.getLinkIds('DWYTorso') if 'DWYTorso' in self.link_names else None
self.waist = self.get_link_ids('DWL') if 'DWL' in self.link_names else None
self.torso = self.get_link_ids('DWYTorso') if 'DWYTorso' in self.link_names else None
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['LHipMot', 'LThighUpLeg', 'LThighLowLeg', 'LLowLeg', 'LFootmot', 'LFoot'],
['RHipMot', 'RThighUpLeg', 'RThighLowLeg', 'RLowLeg', 'RFootmot', 'RFoot']]]
self.feet = [self.getLinkIds(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['LShp', 'LShr', 'LShy', 'LElb', 'LForearm', 'LWrMot2', 'LWrMot3'],
['RShp', 'RShr', 'RShy', 'RElb', 'RForearm', 'RWrMot2', 'RWrMot3']]]
self.hands = [self.getLinkIds(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
def CogimonLowerBody(simulator, init_pos=(0, 0, 1.), init_orient=(0, 0, 0, 1), useFixedBase=False, scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/cogimon/cogimon_lower_body.urdf'):
"""Load Cogimon Lower Body"""
return Cogimon(simulator=simulator, init_pos=init_pos, init_orient=init_orient, useFixedBase=useFixedBase,
scaling=scaling, urdf_path=urdf_path)
return Cogimon(simulator=simulator, position=init_pos, orientation=init_orient, fixed_base=useFixedBase,
scaling=scaling, urdf=urdf_path)
# Test
@@ -76,12 +76,12 @@ if __name__ == "__main__":
robot = Cogimon(sim, lower_body=False)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider(robot.left_leg)
robot.add_joint_slider(robot.left_leg)
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+31 -31
View File
@@ -16,42 +16,42 @@ class Coman(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.5),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.5),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/coman/coman.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/coman/coman.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.5)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.5,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.5)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.5,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Coman, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Coman, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'coman'
self.torso = [self.getLinkIds(link) for link in ['DWL', 'DWS', 'DWYTorso'] if link in self.link_names]
self.torso = [self.get_link_ids(link) for link in ['DWL', 'DWS', 'DWYTorso'] if link in self.link_names]
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['LHipMot', 'LThighUpLeg', 'LThighLowLeg', 'LLowLeg', 'LFootmot', 'LFoot'],
['RHipMot', 'RThighUpLeg', 'RThighLowLeg', 'RLowLeg', 'RFootmot', 'RFoot']]]
self.feet = [self.getLinkIds(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['LShp', 'LShr', 'LShy', 'LElb', 'LForearm', 'LWrMot2', 'LWrMot3'],
['RShp', 'RShr', 'RShy', 'RElb', 'RForearm', 'RWrMot2', 'RWrMot3']]]
self.hands = [self.getLinkIds(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
# move a little bit the arms
# self.setJointPositions([-np.pi/12, np.pi/12], [self.joints[i] for i in [4,11]]) # shoulder
# self.setJointPositions([-np.pi / 4, -np.pi / 4], [self.joints[i] for i in [6, 13]]) # elbow
# self.setJointPositions([-np.pi/4, -np.pi/4], [self.joints[i] for i in [17,23]])
# self.set_joint_positions([-np.pi/12, np.pi/12], [self.joints[i] for i in [4,11]]) # shoulder
# self.set_joint_positions([-np.pi / 4, -np.pi / 4], [self.joints[i] for i in [6, 13]]) # elbow
# self.set_joint_positions([-np.pi/4, -np.pi/4], [self.joints[i] for i in [17,23]])
# for _ in range(10):
# self.sim.stepSimulation()
@@ -69,23 +69,23 @@ if __name__ == "__main__":
world = BasicWorld(sim)
# create robot
robot = Coman(sim, useFixedBase=True)
robot = Coman(sim, fixed_base=True)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
print(robot.link_names)
# # Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
robot.changeTransparency()
# robot.drawLinkCoMs()
robot.drawLinkFrames()
# robot.drawBoundingBoxes(robot.right_leg[4])
robot.change_transparency()
# robot.draw_link_coms()
robot.draw_link_frames()
# robot.draw_bounding_boxes(robot.right_leg[4])
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.computeAndDrawCoMPosition()
# robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
# robot.compute_and_draw_com_position()
# robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+18 -18
View File
@@ -17,25 +17,25 @@ class Crab(HexapodRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.12),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.12),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/crab/crab.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/crab/crab.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.12)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.12,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.12)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.12,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Crab, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Crab, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'crab'
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['coxa_l1', 'femur_l1', 'tibia_l1'],
[ 'coxa_r1', 'femur_r1', 'tibia_r1'],
['coxa_l2', 'femur_l2', 'tibia_l2'],
@@ -43,7 +43,7 @@ class Crab(HexapodRobot):
['coxa_l3', 'femur_l3', 'tibia_l3'],
['coxa_r3', 'femur_r3', 'tibia_r3']]]
self.feet = [self.getLinkIds(link) for link in ['tibia_foot_l1', 'tibia_foot_r1', 'tibia_foot_l2',
self.feet = [self.get_link_ids(link) for link in ['tibia_foot_l1', 'tibia_foot_r1', 'tibia_foot_l2',
'tibia_foot_r2', 'tibia_foot_l3', 'tibia_foot_r3']
if link in self.link_names]
@@ -64,13 +64,13 @@ if __name__ == "__main__":
robot = Crab(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
robot.addJointSlider(robot.right_middle_leg)
robot.add_joint_slider(robot.right_middle_leg)
# run simulation
for i in count():
robot.updateJointSlider()
robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+19 -19
View File
@@ -24,26 +24,26 @@ class Cubli(Robot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.5),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.5),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/cubli/cubli.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/cubli/cubli.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.5)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.5,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.5)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.5,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Cubli, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Cubli, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'cubli'
# disable each motor joint
self.disableMotor()
self.disable_motor()
# Test
@@ -66,8 +66,8 @@ if __name__ == "__main__":
robot = Cubli(sim, position, orientation, scaling=scale)
# print information about the robot
robot.printRobotInfo()
H = robot.calculateMassMatrix(qIdx=slice(6, 6+len(robot.joints))) # floating base, thus keep only the last q
robot.print_info()
H = robot.get_mass_matrix(q_idx=slice(6, 6 + len(robot.joints))) # floating base, thus keep only the last q
print("Inertia matrix: H(q) = {}\n".format(H))
# PD control
@@ -77,13 +77,13 @@ if __name__ == "__main__":
for i in count():
# get state
quaternion = robot.getBaseOrientation(False)
w = robot.getBaseAngularVelocity()
quaternion = robot.get_base_orientation(False)
w = robot.get_base_angular_velocity()
euler = pybullet.getEulerFromQuaternion(quaternion.tolist())
# PD control
torques = [-Kp * (desired_roll - euler[0]) + Kd * w[0], 0., 0.]
robot.setJointTorques(torques)
robot.set_joint_torques(torques)
# step in simulation
world.step(sleep_dt=1./240)
+25 -25
View File
@@ -18,42 +18,42 @@ class Darwin(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.34),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.34),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/darwin/darwin.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/darwin/darwin.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.34)
if len(init_pos) == 2: # assume x, y are given
init_pos += (0.34,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.34)
if len(position) == 2: # assume x, y are given
position += (0.34,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Darwin, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Darwin, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'darwin'
# self.torso = [self.getLinkIds(link) for link in ['DWL', 'DWS', 'DWYTorso'] if link in self.link_names]
# self.torso = [self.get_link_ids(link) for link in ['DWL', 'DWS', 'DWYTorso'] if link in self.link_names]
#
# self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
# self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
# for links in [['LHipMot', 'LThighUpLeg', 'LThighLowLeg', 'LLowLeg', 'LFootmot', 'LFoot'],
# ['RHipMot', 'RThighUpLeg', 'RThighLowLeg', 'RLowLeg', 'RFootmot', 'RFoot']]]
#
# self.feet = [self.getLinkIds(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
# self.feet = [self.get_link_ids(link) for link in ['LFoot', 'RFoot'] if link in self.link_names]
#
# self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
# self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
# for links in [['LShp', 'LShr', 'LShy', 'LElb', 'LForearm', 'LWrMot2', 'LWrMot3'],
# ['RShp', 'RShr', 'RShy', 'RElb', 'RForearm', 'RWrMot2', 'RWrMot3']]]
#
# self.hands = [self.getLinkIds(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
# self.hands = [self.get_link_ids(link) for link in ['LSoftHand', 'RSoftHand'] if link in self.link_names]
# move a little bit the arms
# self.setJointPositions([-np.pi/12, np.pi/12], [self.joints[i] for i in [4,11]]) # shoulder
# self.setJointPositions([-np.pi / 4, -np.pi / 4], [self.joints[i] for i in [6, 13]]) # elbow
# self.setJointPositions([-np.pi/4, -np.pi/4], [self.joints[i] for i in [17,23]])
# self.set_joint_positions([-np.pi/12, np.pi/12], [self.joints[i] for i in [4,11]]) # shoulder
# self.set_joint_positions([-np.pi / 4, -np.pi / 4], [self.joints[i] for i in [6, 13]]) # elbow
# self.set_joint_positions([-np.pi/4, -np.pi/4], [self.joints[i] for i in [17,23]])
# for _ in range(10):
# self.sim.stepSimulation()
@@ -71,16 +71,16 @@ if __name__ == "__main__":
world = BasicWorld(sim)
# create robot
robot = Darwin(sim, useFixedBase=False)
robot = Darwin(sim, fixed_base=False)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
print(robot.link_names)
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+15 -15
View File
@@ -20,22 +20,22 @@ class Edo(ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
useFixedBase=True,
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
fixed_base=True,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/edo/edo.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/edo/edo.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(Edo, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Edo, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'edo'
@@ -55,8 +55,8 @@ if __name__ == "__main__":
robot = Edo(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
for i in count():
+18 -18
View File
@@ -19,25 +19,25 @@ class Epuck(DifferentialWheeledRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/epuck/epuck.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/epuck/epuck.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.0,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.0,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Epuck, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Epuck, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'epuck'
self.wheels = [self.getLinkIds(link) for link in ['left_wheel', 'right_wheel']
self.wheels = [self.get_link_ids(link) for link in ['left_wheel', 'right_wheel']
if link in self.link_names]
self.wheel_directions = np.ones(len(self.wheels))
@@ -58,18 +58,18 @@ if __name__ == "__main__":
robots = []
for _ in range(5):
x, y = np.random.uniform(low=-2, high=2, size=2)
robot = world.loadRobot(Epuck, position=(x, y, 0))
robot = world.load_robot(Epuck, position=(x, y, 0))
robots.append(robot)
# print information about the robot
robots[0].printRobotInfo()
robots[0].print_info()
# Position control using sliders
# robots[0].addJointSlider()
# robots[0].add_joint_slider()
# run simulator
for _ in count():
# robots[0].updateJointSlider()
# robots[0].update_joint_slider()
for robot in robots:
robot.drive(5)
world.step(sleep_dt=1./240)
+21 -21
View File
@@ -17,36 +17,36 @@ class F10Racecar(AckermannWheeledRobot):
def __init__(self,
simulator,
init_pos=(0, 0, .1),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, .1),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/f10_racecar/racecar.urdf'): # racecar_differential.urdf
urdf=os.path.dirname(__file__) + '/urdfs/f10_racecar/racecar.urdf'): # racecar_differential.urdf
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.1)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.1,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.1)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.1,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(F10Racecar, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(F10Racecar, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'racecar'
self.wheels = [self.getLinkIds(link) for link in ['left_front_wheel', 'right_front_wheel',
self.wheels = [self.get_link_ids(link) for link in ['left_front_wheel', 'right_front_wheel',
'left_rear_wheel', 'right_rear_wheel']
if link in self.link_names]
self.wheel_directions = np.ones(len(self.wheels))
self.steering = [self.getLinkIds(link) for link in ['left_steering_hinge', 'right_steering_hinge']
self.steering = [self.get_link_ids(link) for link in ['left_steering_hinge', 'right_steering_hinge']
if link in self.link_names]
def setSteering(self, angle):
def set_steering(self, angle):
"""Set steering angle"""
angle = angle * np.ones(len(self.steering))
self.setJointPositions(angle, jointId=self.steering)
self.set_joint_positions(angle, joint_ids=self.steering)
# Test
@@ -65,13 +65,13 @@ if __name__ == "__main__":
robot = F10Racecar(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.driveForward(10)
# robot.update_joint_slider()
robot.drive_forward(10)
world.step(sleep_dt=1./240)
+16 -16
View File
@@ -15,22 +15,22 @@ class Fetch(WheeledRobot, ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.1),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.1),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/fetch/fetch.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/fetch/fetch.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.1)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.1,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.1)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.1,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Fetch, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Fetch, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'fetch'
@@ -50,12 +50,12 @@ if __name__ == "__main__":
robot = Fetch(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
robot.addJointSlider()
robot.add_joint_slider()
# run simulator
for _ in count():
robot.updateJointSlider()
robot.update_joint_slider()
world.step(sleep_dt=1./240)
+18 -18
View File
@@ -21,25 +21,25 @@ class Franka(ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
scaling=1.,
useFixedBase=True,
urdf_path=os.path.dirname(__file__) + '/urdfs/franka/franka.urdf'):
fixed_base=True,
urdf=os.path.dirname(__file__) + '/urdfs/franka/franka.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.0,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.0,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(Franka, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Franka, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'franka'
# self.disableMotor()
# self.disable_motor()
# Test
@@ -58,14 +58,14 @@ if __name__ == "__main__":
robot = Franka(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+14 -14
View File
@@ -13,22 +13,22 @@ class HalfCheetah(Robot):
def __init__(self,
simulator,
init_pos=(-0.5, 0, 0.1),
init_orient=(0, 0.707, 0, 0.707),
useFixedBase=False,
position=(-0.5, 0, 0.1),
orientation=(0, 0.707, 0, 0.707),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/mjcfs/half_cheetah.xml'):
urdf=os.path.dirname(__file__) + '/mjcfs/half_cheetah.xml'):
# check parameters
if init_pos is None:
init_pos = (-0.5, 0., 0.1)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.1,)
if init_orient is None:
init_orient = (0, 0.707, 0, 0.707)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (-0.5, 0., 0.1)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.1,)
if orientation is None:
orientation = (0, 0.707, 0, 0.707)
if fixed_base is None:
fixed_base = False
super(HalfCheetah, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(HalfCheetah, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'halfCheetah'
@@ -48,7 +48,7 @@ if __name__ == "__main__":
robot = HalfCheetah(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+10 -10
View File
@@ -12,12 +12,12 @@ class Hand(Robot):
def __init__(self,
simulator,
urdf_path,
init_pos=(0, 0, 1.),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
urdf,
position=(0, 0, 1.),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.):
super(Hand, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Hand, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.fingers = [] # list of fingers where each finger is a list of links/joints
@@ -39,12 +39,12 @@ class TwoHand(Hand):
"""
def __init__(self,
simulator,
urdf_path,
init_pos=(0, 0, 1.),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
urdf,
position=(0, 0, 1.),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.):
super(TwoHand, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(TwoHand, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.left_fingers = [] # list of ids in self.fingers
self.right_fingers = [] # list of ids in self.fingers
+14 -14
View File
@@ -13,22 +13,22 @@ class Hopper(Robot):
def __init__(self,
simulator,
init_pos=(-0.5, 0, 0.1),
init_orient=(0, 0.707, 0, 0.707),
useFixedBase=False,
position=(-0.5, 0, 0.1),
orientation=(0, 0.707, 0, 0.707),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/mjcfs/hopper.xml'):
urdf=os.path.dirname(__file__) + '/mjcfs/hopper.xml'):
# check parameters
if init_pos is None:
init_pos = (-0.5, 0., 0.1)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.1,)
if init_orient is None:
init_orient = (0, 0.707, 0, 0.707)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (-0.5, 0., 0.1)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.1,)
if orientation is None:
orientation = (0, 0.707, 0, 0.707)
if fixed_base is None:
fixed_base = False
super(Hopper, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Hopper, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'hopper'
@@ -48,7 +48,7 @@ if __name__ == "__main__":
robot = Hopper(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+24 -24
View File
@@ -27,42 +27,42 @@ class Hubo(BipedRobot, BiManipulatorRobot, TwoHand):
def __init__(self,
simulator,
init_pos=(0, 0, 1),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 1),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/hubo/hubo.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/hubo/hubo.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 1.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (1.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 1.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (1.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Hubo, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Hubo, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'hubo'
self.neck = [self.getLinkIds(link) for link in ['Body_Neck', 'Body_Head_Empty', 'Body_Head']
self.neck = [self.get_link_ids(link) for link in ['Body_Neck', 'Body_Head_Empty', 'Body_Head']
if link in self.link_names]
self.head = self.getLinkIds('Body_Head') if 'Body_Head' in self.link_names else None
self.waist = self.getLinkIds('Body_Hip') if 'Body_Hip' in self.link_names else None
self.head = self.get_link_ids('Body_Head') if 'Body_Head' in self.link_names else None
self.waist = self.get_link_ids('Body_Hip') if 'Body_Hip' in self.link_names else None
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['Body_LHY', 'Body_LHR', 'Body_LHP', 'Body_LKN', 'Body_LAP', 'Body_LAR'],
['Body_RHY', 'Body_RHR', 'Body_RHP', 'Body_RKN', 'Body_RAP', 'Body_RAR']]]
self.feet = [self.getLinkIds(link) for link in ['Body_LAR', 'Body_RAR'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['Body_LAR', 'Body_RAR'] if link in self.link_names]
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['Body_LSP', 'Body_LSR', 'Body_LSY', 'Body_LEB', 'Body_LWY', 'Body_LWP'],
['Body_RSP', 'Body_RSR', 'Body_RSY', 'Body_REB', 'Body_RWY', 'Body_RWP']]]
self.hands = [self.getLinkIds(link) for link in ['Body_LWP', 'Body_RWP'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['Body_LWP', 'Body_RWP'] if link in self.link_names]
self.fingers = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.fingers = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['leftThumbProximal', 'leftThumbMedial', 'leftThumbDistal'],
['leftIndexProximal', 'leftIndexMedial', 'leftIndexDistal'],
['leftMiddleProximal', 'leftMiddleMedial', 'leftMiddleDistal'],
@@ -94,12 +94,12 @@ if __name__ == "__main__":
robot = Hubo(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+22 -22
View File
@@ -14,38 +14,38 @@ class Humanoid(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(-0.5, 0, 1.),
init_orient=(0, 0.707, 0, 0.707),
useFixedBase=False,
position=(-0.5, 0, 1.),
orientation=(0, 0.707, 0, 0.707),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/mjcfs/humanoid.xml'): # humanoid_symmetric.xml
urdf=os.path.dirname(__file__) + '/mjcfs/humanoid.xml'): # humanoid_symmetric.xml
# check parameters
if init_pos is None:
init_pos = (-0.5, 0., 1.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (1.,)
if init_orient is None:
init_orient = (0, 0.707, 0, 0.707)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (-0.5, 0., 1.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (1.,)
if orientation is None:
orientation = (0, 0.707, 0, 0.707)
if fixed_base is None:
fixed_base = False
super(Humanoid, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Humanoid, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'humanoid'
# self.waist = self.getLinkIds('DWL') if 'DWL' in self.link_names else None
# self.torso = self.getLinkIds('DWYTorso') if 'DWYTorso' in self.link_names else None
# self.waist = self.get_link_ids('DWL') if 'DWL' in self.link_names else None
# self.torso = self.get_link_ids('DWYTorso') if 'DWYTorso' in self.link_names else None
#
# self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
# self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
# for links in [['LHipMot', 'LThighUpLeg', 'LThighLowLeg', 'LLowLeg', 'LFootmot', 'LFoot'],
# ['RHipMot', 'RThighUpLeg', 'RThighLowLeg', 'RLowLeg', 'RFootmot', 'RFoot']]]
self.feet = [self.getLinkIds(link) for link in ['left_foot', 'right_foot'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['left_foot', 'right_foot'] if link in self.link_names]
# self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
# self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
# for links in [['LShp', 'LShr', 'LShy', 'LElb', 'LForearm', 'LWrMot2', 'LWrMot3'],
# ['RShp', 'RShr', 'RShy', 'RElb', 'RForearm', 'RWrMot2', 'RWrMot3']]]
self.hands = [self.getLinkIds(link) for link in ['left_lower_arm', 'right_lower_arm']
self.hands = [self.get_link_ids(link) for link in ['left_lower_arm', 'right_lower_arm']
if link in self.link_names]
@@ -65,13 +65,13 @@ if __name__ == "__main__":
robot = Humanoid(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulation
for i in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
# step in simulation
world.step(sleep_dt=1./240)
+18 -18
View File
@@ -21,25 +21,25 @@ class Husky(DifferentialWheeledRobot):
def __init__(self,
simulator,
init_pos=(0, 0, .14),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, .14),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/husky/husky.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/husky/husky.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.14)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.14,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.14)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.14,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(Husky, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Husky, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'husky'
self.wheels = [self.getLinkIds(link) for link in ['front_left_wheel_link', 'front_right_wheel_link',
self.wheels = [self.get_link_ids(link) for link in ['front_left_wheel_link', 'front_right_wheel_link',
'rear_left_wheel_link', 'rear_right_wheel_link']
if link in self.link_names]
self.wheel_directions = np.ones(len(self.wheels))
@@ -61,13 +61,13 @@ if __name__ == "__main__":
robot = Husky(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.driveForward(2)
# robot.update_joint_slider()
robot.drive_forward(2)
world.step(sleep_dt=1./240)
+20 -20
View File
@@ -18,31 +18,31 @@ class HyQ(QuadrupedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, .9),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, .9),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/hyq/hyq.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/hyq/hyq.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.9)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.9,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.9)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.9,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(HyQ, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(HyQ, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'hyq'
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['lf_hipassembly', 'lf_upperleg', 'lf_lowerleg'],
['rf_hipassembly', 'rf_upperleg', 'rf_lowerleg'],
['lh_hipassembly', 'lh_upperleg', 'lh_lowerleg'],
['rh_hipassembly', 'rh_upperleg', 'rh_lowerleg']]]
self.feet = [self.getLinkIds(link) for link in ['lf_foot', 'rf_foot', 'lh_foot', 'rh_foot']
self.feet = [self.get_link_ids(link) for link in ['lf_foot', 'rf_foot', 'lh_foot', 'rh_foot']
if link in self.link_names]
@@ -62,14 +62,14 @@ if __name__ == "__main__":
robot = HyQ(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# # Position control using sliders
robot.addJointSlider(robot.getLeftFrontLegIds())
robot.add_joint_slider(robot.getLeftFrontLegIds())
# run simulator
for _ in count():
robot.updateJointSlider()
robot.computeAndDrawCoMPosition()
robot.computeAndDrawProjectedCoMPosition()
robot.update_joint_slider()
robot.compute_and_draw_com_position()
robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+23 -23
View File
@@ -19,37 +19,37 @@ class HyQ2Max(QuadrupedRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.8),
init_orient=(0, 0, 0, 1),
useFixedBase=False,
position=(0, 0, 0.8),
orientation=(0, 0, 0, 1),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/hyq2max/hyq2max.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/hyq2max/hyq2max.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.8)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.8,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.8)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.8,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(HyQ2Max, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(HyQ2Max, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'hyq2max'
self.height = 0.9
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['lf_hipassembly', 'lf_upperleg', 'lf_lowerleg'],
['rf_hipassembly', 'rf_upperleg', 'rf_lowerleg'],
['lh_hipassembly', 'lh_upperleg', 'lh_lowerleg'],
['rh_hipassembly', 'rh_upperleg', 'rh_lowerleg']]]
self.feet = [self.getLinkIds(link) for link in ['lf_foot', 'rf_foot', 'lh_foot', 'rh_foot']
self.feet = [self.get_link_ids(link) for link in ['lf_foot', 'rf_foot', 'lh_foot', 'rh_foot']
if link in self.link_names]
for foot in self.feet:
self.sim.changeDynamics(self.id, foot, lateralFriction=.9, spinningFriction=1., rollingFriction=1.)
self.sim.changeDynamics(self.id, foot, restitution=0.)
self.sim.change_dynamics(self.id, foot, lateral_friction=.9, spinning_friction=1., rolling_friction=1.)
self.sim.change_dynamics(self.id, foot, restitution=0.)
# taken from "Learning agile and dynamic motor skills for legged robots", Hwangbo et al., 2019
self.kp = 50. * np.ones(12)
@@ -67,21 +67,21 @@ if __name__ == "__main__":
# create world
world = BasicWorld(sim)
world.loadJapaneseMonastery()
world.load_japanese_monastery()
# create robot
robot = HyQ2Max(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider(robot.getLeftFrontLegIds())
# robot.add_joint_slider(robot.getLeftFrontLegIds())
# run simulator
for _ in count():
# robot.updateJointSlider()
robot.computeAndDrawCoMPosition()
robot.computeAndDrawProjectedCoMPosition()
# robot.update_joint_slider()
robot.compute_and_draw_com_position()
robot.compute_and_draw_projected_com_position()
world.step(sleep_dt=1./240)
+23 -23
View File
@@ -16,41 +16,41 @@ class ICub(BipedRobot, BiManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0.7),
init_orient=(0, 0, 1, 0),
useFixedBase=False,
position=(0, 0, 0.7),
orientation=(0, 0, 1, 0),
fixed_base=False,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/icub/icub-v2.5+.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/icub/icub-v2.5+.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.7)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.7,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = False
if position is None:
position = (0., 0., 0.7)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.7,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = False
super(ICub, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase)
super(ICub, self).__init__(simulator, urdf, position, orientation, fixed_base)
self.name = 'icub'
self.head = self.getLinkIds('head') if 'head' in self.link_names else None
self.neck = [self.getLinkIds(link) for link in ['neck_1', 'neck_2'] if link in self.link_names]
self.torso = [self.getLinkIds(link) for link in ['torso_1', 'torso_2', 'chest'] if link in self.link_names]
self.head = self.get_link_ids('head') if 'head' in self.link_names else None
self.neck = [self.get_link_ids(link) for link in ['neck_1', 'neck_2'] if link in self.link_names]
self.torso = [self.get_link_ids(link) for link in ['torso_1', 'torso_2', 'chest'] if link in self.link_names]
self.legs = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.legs = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['l_hip_1', 'l_hip_2', 'l_upper_leg', 'l_lower_leg', 'l_ankle_1', 'l_ankle_2'],
['r_hip_1', 'r_hip_2', 'r_upper_leg', 'r_lower_leg', 'r_ankle_1', 'r_ankle_2']]]
self.feet = [self.getLinkIds(link) for link in ['l_sole', 'r_sole'] if link in self.link_names]
self.feet = [self.get_link_ids(link) for link in ['l_sole', 'r_sole'] if link in self.link_names]
self.arms = [[self.getLinkIds(link) for link in links if link in self.link_names]
self.arms = [[self.get_link_ids(link) for link in links if link in self.link_names]
for links in [['l_shoulder_1', 'l_shoulder_2', 'l_shoulder_3', 'l_elbow_1', 'l_forearm',
'l_wrist_1', 'l_hand'],
['r_shoulder_1', 'r_shoulder_2', 'r_shoulder_3', 'r_elbow_1', 'r_forearm',
'r_wrist_1', 'r_hand']]]
self.hands = [self.getLinkIds(link) for link in ['l_hand', 'r_hand'] if link in self.link_names]
self.hands = [self.get_link_ids(link) for link in ['l_hand', 'r_hand'] if link in self.link_names]
# Test
@@ -69,12 +69,12 @@ if __name__ == "__main__":
robot = ICub(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# Position control using sliders
# robot.addJointSlider()
# robot.add_joint_slider()
# run simulator
for _ in count():
# robot.updateJointSlider()
# robot.update_joint_slider()
world.step(sleep_dt=1./240)
+14 -14
View File
@@ -18,22 +18,22 @@ class Jaco(ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
useFixedBase=True,
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
fixed_base=True,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/jaco/jaco.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/jaco/jaco.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(Jaco, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(Jaco, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'jaco'
@@ -53,7 +53,7 @@ if __name__ == "__main__":
robot = Jaco(sim)
# print information about the robot
robot.printRobotInfo()
robot.print_info()
# run simulation
for i in count():
+15 -15
View File
@@ -20,22 +20,22 @@ class KR5(ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
useFixedBase=True,
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
fixed_base=True,
scaling=1.,
urdf_path=os.path.dirname(__file__) + '/urdfs/kuka/kr5/kr5.urdf'):
urdf=os.path.dirname(__file__) + '/urdfs/kuka/kr5/kr5.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(KR5, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(KR5, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'kr5'
@@ -55,8 +55,8 @@ if __name__ == "__main__":
robot = KR5(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
for i in count():
+25 -25
View File
@@ -21,25 +21,25 @@ class KukaIIWA(ManipulatorRobot):
def __init__(self,
simulator,
init_pos=(0, 0, 0),
init_orient=(0, 0, 0, 1),
position=(0, 0, 0),
orientation=(0, 0, 0, 1),
scaling=1.,
useFixedBase=True,
urdf_path=os.path.dirname(__file__) + '/urdfs/kuka/kuka_iiwa/iiwa14.urdf'):
fixed_base=True,
urdf=os.path.dirname(__file__) + '/urdfs/kuka/kuka_iiwa/iiwa14.urdf'):
# check parameters
if init_pos is None:
init_pos = (0., 0., 0.)
if len(init_pos) == 2: # assume x, y are given
init_pos = tuple(init_pos) + (0.,)
if init_orient is None:
init_orient = (0, 0, 0, 1)
if useFixedBase is None:
useFixedBase = True
if position is None:
position = (0., 0., 0.)
if len(position) == 2: # assume x, y are given
position = tuple(position) + (0.,)
if orientation is None:
orientation = (0, 0, 0, 1)
if fixed_base is None:
fixed_base = True
super(KukaIIWA, self).__init__(simulator, urdf_path, init_pos, init_orient, useFixedBase, scaling)
super(KukaIIWA, self).__init__(simulator, urdf, position, orientation, fixed_base, scaling)
self.name = 'kuka_iiwa'
# self.disableMotor()
# self.disable_motor()
# Test
@@ -59,11 +59,11 @@ if __name__ == "__main__":
robot = KukaIIWA(sim)
# print information about the robot
robot.printRobotInfo()
# H = robot.calculateMassMatrix()
robot.print_info()
# H = robot.get_mass_matrix()
# print("Inertia matrix: H(q) = {}".format(H))
# print(robot.getLinkWorldPositions(flatten=False))
# print(robot.get_link_world_positions(flatten=False))
K = 5000*np.identity(3)
# D = 2 * np.sqrt(K)
@@ -71,22 +71,22 @@ if __name__ == "__main__":
D = 100 * np.identity(3)
x_des = np.array([0.3, 0.0, 0.8])
x_des = np.array([0.52557296, 0.09732758, 0.80817658])
linkId = robot.getLinkIds('iiwa_link_ee')
linkId = robot.get_link_ids('iiwa_link_ee')
for i in count():
# print(robot.getLinkWorldPositions(flatten=False))
# print(robot.get_link_world_positions(flatten=False))
# get state
q = robot.getJointPositions()
dq = robot.getJointVelocities()
x = robot.getLinkWorldPositions(linkId)
dx = robot.getLinkWorldLinearVelocities(linkId)
q = robot.get_joint_positions()
dq = robot.get_joint_velocities()
x = robot.get_link_world_positions(linkId)
dx = robot.get_link_world_linear_velocities(linkId)
# get (linear) jacobian
J = robot.getLinearJacobian(linkId, q)
# get coriolis, gravity compensation torques
torques = robot.getCoriolisAndGravityCompensationTorques(q, dq)
torques = robot.get_coriolis_and_gravity_compensation_torques(q, dq)
# Impedance control: attractor point
F = K.dot(x_des - x) - D.dot(dx)
@@ -94,7 +94,7 @@ if __name__ == "__main__":
tau = J.T.dot(F)
print(tau)
torques += tau
robot.setJointTorques(torques)
robot.set_joint_torques(torques)
# step in simulation
world.step(sleep_dt=1./240)

Some files were not shown because too many files have changed in this diff Show More