file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareInterface.py | import odrive
from odrive.enums import *
from woofer.Config import RobotConfig
from woofer.HardwareConfig import (
ODRIVE_SERIAL_NUMBERS,
ACTUATOR_DIRECTIONS,
ANGLE_OFFSETS,
map_actuators_to_axes,
)
import time
import threading
import numpy as np
class HardwareInterface:
def __init__(self):
self.config = RobotConfig()
assert len(ODRIVE_SERIAL_NUMBERS) == self.config.NUM_ODRIVES
self.odrives = [None for _ in range(self.config.NUM_ODRIVES)]
threads = []
for i in range(self.config.NUM_ODRIVES):
t = threading.Thread(target=find_odrive, args=(i, self.odrives))
threads.append(t)
t.start()
for t in threads:
t.join()
input("Press enter to calibrate odrives...")
calibrate_odrives(self.odrives)
set_position_control(self.odrives)
self.axes = assign_axes(self.odrives)
def set_actuator_postions(self, joint_angles):
set_all_odrive_positions(self.axes, joint_angles, self.config)
def deactivate_actuators(self):
set_odrives_idle(self.odrives)
def find_odrive(i, odrives):
o = odrive.find_any(serial_number=ODRIVE_SERIAL_NUMBERS[i])
print("Found odrive: ", i)
odrives[i] = o
def calibrate_odrives(odrives):
for odrv in odrives:
odrv.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE
odrv.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE
for odrv in odrives:
while (
odrv.axis0.current_state != AXIS_STATE_IDLE
or odrv.axis1.current_state != AXIS_STATE_IDLE
):
time.sleep(0.1) # busy waiting - not ideal
def set_position_control(odrives):
for odrv in odrives:
for axis in [odrv.axis0, odrv.axis1]:
axis.controller.config.pos_gain = 60
axis.controller.config.vel_gain = 0.002
axis.controller.config.vel_limit_tolerance = 0
axis.controller.config.vel_integrator_gain = 0
axis.motor.config.current_lim = 15
print("Updated gains")
odrv.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL
odrv.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL
def set_odrives_idle(odrives):
for odrv in odrives:
odrv.axis0.requested_state = AXIS_STATE_IDLE
odrv.axis1.requested_state = AXIS_STATE_IDLE
def assign_axes(odrives):
return map_actuators_to_axes(odrives)
def set_all_odrive_positions(axes, joint_angles, config):
for i in range(joint_angles.shape[0]):
for j in range(joint_angles.shape[1]):
axes[i][j].controller.pos_setpoint = actuator_angle_to_odrive(
joint_angles, i, j, config
)
def radians_to_encoder_count(angle, config):
return (angle / (2 * np.pi)) * config.ENCODER_CPR * config.MOTOR_REDUCTION
def actuator_angle_to_odrive(joint_angles, i, j, config):
offset_angle = joint_angles[i][j] + ANGLE_OFFSETS[i][j]
odrive_radians = offset_angle * ACTUATOR_DIRECTIONS[i][j]
return radians_to_encoder_count(odrive_radians, config)
| 3,118 | Python | 30.82653 | 78 | 0.652341 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Kinematics.py | import numpy as np
def leg_forward_kinematics(alpha, leg_index, config):
"""Find the body-centric coordinates of a given foot given the joint angles.
Parameters
----------
alpha : Numpy array (3)
Joint angles ordered as (abduction, hip, knee)
leg_index : int
Leg index.
config : Config object
Robot parameters object
Returns
-------
Numpy array (3)
Body-centric coordinates of the specified foot
"""
pass
def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config):
"""Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration
Parameters
----------
r_body_foot : [type]
[description]
leg_index : [type]
[description]
config : [type]
[description]
Returns
-------
numpy array (3)
Array of corresponding joint angles.
"""
(x, y, z) = r_body_foot
# Distance from the leg origin to the foot, projected into the y-z plane
R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5
# Distance from the leg's forward/back point of rotation to the foot
R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5
# Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis
# For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative.
cos_param = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz
if abs(cos_param) > 0.9:
print("Clipping 1st cos param")
cos_param = np.clip(cos_param, -0.9, 0.9)
phi = np.arccos(cos_param)
# Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis
hip_foot_angle = np.arctan2(z, y)
# Ab/adduction angle, relative to the positive y-axis
abduction_angle = phi + hip_foot_angle
# theta: Angle between the tilted negative z-axis and the hip-to-foot vector
theta = np.arctan2(-x, R_hip_foot_yz)
# Distance between the hip and foot
R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5
# Using law of cosines to determine the angle between upper leg links
cos_param = (config.UPPER_LEG ** 2 + R_hip_foot ** 2 - config.LOWER_LEG ** 2) / (2.0*config.UPPER_LEG*R_hip_foot)
# Ensure that the leg isn't over or under extending
cos_param = np.clip(cos_param, -0.9, 0.9)
if abs(cos_param) > 0.9:
print("Clipping 2nd cos param")
# gamma: Angle between upper leg links and the center of the leg
gamma = np.arccos(cos_param)
return np.array([abduction_angle, theta - gamma, theta + gamma])
def four_legs_inverse_kinematics(r_body_foot, config):
"""Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions.
Parameters
----------
r_body_foot : numpy array (3,4)
Matrix of the body-frame foot positions. Each column corresponds to a separate foot.
config : Config object
Object of robot configuration parameters.
Returns
-------
numpy array (3,4)
Matrix of corresponding joint angles.
"""
alpha = np.zeros((3, 4))
for i in range(4):
body_offset = config.LEG_ORIGINS[:, i]
alpha[:, i] = leg_explicit_inverse_kinematics(
r_body_foot[:, i] - body_offset, i, config
)
return alpha | 3,449 | Python | 34.204081 | 136 | 0.636416 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareConfig.py | """
Per-robot configuration file that is particular to each individual robot, not just the type of robot.
"""
import numpy as np
ODRIVE_SERIAL_NUMBERS = [
"2065339F304B",
"208F3384304B",
"365833753037",
"207E35753748",
"208F3385304B",
"208E3387304B",
]
ACTUATOR_DIRECTIONS = np.array([[1, 1, -1, -1], [-1, -1, -1, -1], [1, 1, 1, 1]])
ANGLE_OFFSETS = np.array(
[
[0, 0, 0, 0],
[np.pi / 2, np.pi / 2, np.pi / 2, np.pi / 2],
[-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2],
]
)
def map_actuators_to_axes(odrives):
axes = [[None for _ in range(4)] for _ in range(3)]
axes[0][0] = odrives[1].axis1
axes[1][0] = odrives[0].axis0
axes[2][0] = odrives[0].axis1
axes[0][1] = odrives[1].axis0
axes[1][1] = odrives[2].axis1
axes[2][1] = odrives[2].axis0
axes[0][2] = odrives[4].axis1
axes[1][2] = odrives[5].axis0
axes[2][2] = odrives[5].axis1
axes[0][3] = odrives[4].axis0
axes[1][3] = odrives[3].axis1
axes[2][3] = odrives[3].axis0
return axes
| 1,057 | Python | 22.511111 | 101 | 0.553453 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Config.py | import numpy as np
from scipy.linalg import solve
class BehaviorState(Enum):
REST = 0
TROT = 1
HOP = 2
FINISHHOP = 3
class UserInputParams:
def __init__(self):
self.max_x_velocity = 0.5
self.max_y_velocity = 0.24
self.max_yaw_rate = 0.2
self.max_pitch = 30.0 * np.pi / 180.0
class MovementReference:
"""Stores movement reference
"""
def __init__(self):
self.v_xy_ref = np.array([0, 0])
self.wz_ref = 0.0
self.z_ref = -0.265
self.pitch = 0.0
self.roll = 0.0
class SwingParams:
"""Swing Parameters
"""
def __init__(self):
self.z_coeffs = None
self.z_clearance = 0.05
self.alpha = (
0.5
) # Ratio between touchdown distance and total horizontal stance movement
self.beta = (
0.5
) # Ratio between touchdown distance and total horizontal stance movement
@property
def z_clearance(self):
return self.__z_clearance
@z_clearance.setter
def z_clearance(self, z):
self.__z_clearance = z
b_z = np.array([0, 0, 0, 0, self.__z_clearance])
A_z = np.array(
[
[0, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 1, 0],
[4, 3, 2, 1, 0],
[0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0],
]
)
self.z_coeffs = solve(A_z, b_z)
class StanceParams:
"""Stance parameters
"""
def __init__(self):
self.z_time_constant = 0.02
self.z_speed = 0.03 # maximum speed [m/s]
self.pitch_deadband = 0.02
self.pitch_time_constant = 0.25
self.max_pitch_rate = 0.15
self.roll_speed = 0.16 # maximum roll rate [rad/s]
self.delta_x = 0.23
self.delta_y = 0.173
self.x_shift = -0.01
@property
def default_stance(self):
return np.array(
[
[
self.delta_x + self.x_shift,
self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
],
[-self.delta_y, self.delta_y, -self.delta_y, self.delta_y],
[0, 0, 0, 0],
]
)
class GaitParams:
"""Gait Parameters
"""
def __init__(self):
self.dt = 0.01
self.num_phases = 4
self.contact_phases = np.array(
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
)
self.overlap_time = (
0.5 # duration of the phase where all four feet are on the ground
)
self.swing_time = (
0.5 # duration of the phase when only two feet are on the ground
)
@property
def overlap_ticks(self):
return int(self.overlap_time / self.dt)
@property
def swing_ticks(self):
return int(self.swing_time / self.dt)
@property
def stance_ticks(self):
return 2 * self.overlap_ticks + self.swing_ticks
@property
def phase_times(self):
return np.array(
[self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks]
)
@property
def phase_length(self):
return 2 * self.overlap_ticks + 2 * self.swing_ticks
class RobotConfig:
"""Woofer hardware parameters
"""
def __init__(self):
# Robot geometry
self.LEG_FB = 0.23 # front-back distance from center line to leg axis
self.LEG_LR = 0.109 # left-right distance from center line to leg plane
self.ABDUCTION_OFFSET = 0.064 # distance from abduction axis to leg
self.FOOT_RADIUS = 0.02
self.UPPER_LEG = 0.18
self.LOWER_LEG = 0.32
# Update hip geometry
self.HIP_L = 0.0394
self.HIP_W = 0.0744
self.HIP_T = 0.0214
self.HIP_OFFSET = 0.0132
self.L = 0.66
self.W = 0.176
self.T = 0.092
self.LEG_ORIGINS = np.array(
[
[self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB],
[-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR],
[0, 0, 0, 0],
]
)
self.ABDUCTION_OFFSETS = np.array(
[
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
]
)
self.START_HEIGHT = 0.3
# Robot inertia params
self.FRAME_MASS = 3.0 # kg
self.MODULE_MASS = 1.033 # kg
self.LEG_MASS = 0.15 # kg
self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4
# Compensation factor of 3 because the inertia measurement was just
# of the carbon fiber and plastic parts of the frame and did not
# include the hip servos and electronics
self.FRAME_INERTIA = tuple(
map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3))
)
self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5)
leg_z = 1e-6
leg_mass = 0.010
leg_x = 1 / 12 * self.LOWER_LEG ** 2 * leg_mass
leg_y = leg_x
self.LEG_INERTIA = (leg_x, leg_y, leg_z)
# Joint params
G = 220 # Servo gear ratio
m_rotor = 0.016 # Servo rotor mass
r_rotor = 0.005 # Rotor radius
self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints
# print("Servo armature", self.ARMATURE)
NATURAL_DAMPING = 1.0 # Damping resulting from friction
ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF
self.REV_DAMPING = (
NATURAL_DAMPING + ELECTRICAL_DAMPING
) # Damping torque on the revolute joints
# Force limits
self.MAX_JOINT_TORQUE = 12.0
self.REVOLUTE_RANGE = 3
self.NUM_ODRIVES = 6
self.ENCODER_CPR = 2000
self.MOTOR_REDUCTION = 4
class EnvironmentConfig:
"""Environmental parameters
"""
def __init__(self):
self.MU = 1.5 # coeff friction
self.DT = 0.001 # seconds between simulation steps
class SolverConfig:
"""MuJoCo solver parameters
"""
def __init__(self):
self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints
self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters
self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts
self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters
| 6,661 | Python | 26.643153 | 88 | 0.523945 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/rover.py | #!/usr/bin/env python3
import sys
import argparse
import json
import time
import select
import pexpect
import UDPComms
import msgpack
def peek_func(port):
sub = UDPComms.Subscriber(port, timeout = 10)
while 1:
try:
data = sub.recv()
print( json.dumps(data) )
except UDPComms.timeout:
exit()
def poke_func(port, rate):
pub = UDPComms.Publisher(port)
data = None
while 1:
if select.select([sys.stdin], [], [], 0)[0]:
line = sys.stdin.readline()
# detailed behaviour
# reading from file: -ignores empty lines -repeats last line forever
# reading from terminal: -repeats last command
if line.rstrip():
data = line.rstrip()
elif len(line) == 0:
# exit() #uncomment to quit on end of file
pass
else:
continue
if data != None:
pub.send( json.loads(data) )
time.sleep( rate/1000 )
def call_func(command, ssh = True):
child = pexpect.spawn(command)
if ssh:
i = 1
while i == 1:
try:
i = child.expect(['password:',
'Are you sure you want to continue connecting',
'Welcome'], timeout=20)
except pexpect.EOF:
print("Can't connect to device")
exit()
except pexpect.TIMEOUT:
print("Interaction with device failed")
exit()
if i == 1:
child.sendline('yes')
if i == 0:
child.sendline('raspberry')
else:
try:
child.expect('robot:', timeout=1)
child.sendline('hello')
except pexpect.TIMEOUT:
pass
child.interact()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser')
peek = subparsers.add_parser("peek")
peek.add_argument('port', help="UDP port to subscribe to", type=int)
poke = subparsers.add_parser("poke")
poke.add_argument('port', help="UDP port to publish the data to", type=int)
poke.add_argument('rate', help="how often to republish (ms)", type=float)
peek = subparsers.add_parser("discover")
commands = ['status', 'log', 'start', 'stop', 'restart', 'enable', 'disable']
for command in commands:
status = subparsers.add_parser(command)
status.add_argument('host', help="Which device to look for this program on")
status.add_argument('unit', help="The unit whose status we want to know",
nargs='?', default=None)
connect = subparsers.add_parser('connect')
connect.add_argument('host', help="Which device to log into")
args = parser.parse_args()
if args.subparser == 'peek':
peek_func(args.port)
elif args.subparser == 'poke':
poke_func(args.port, args.rate)
elif args.subparser == 'connect':
call_func("ssh pi@"+args.host+".local")
elif args.subparser == 'discover':
call_func("nmap -sP 10.0.0.0/24", ssh=False)
elif args.subparser in commands:
if args.unit is None:
args.unit = args.host
if args.host == 'local':
prefix = ""
ssh = False
else:
prefix = "ssh pi@"+args.host+".local "
ssh = True
if args.subparser == 'status':
call_func(prefix + "sudo systemctl status "+args.unit, ssh)
elif args.subparser == 'log':
call_func(prefix + "sudo journalctl -f -u "+args.unit, ssh)
elif args.subparser == 'start':
call_func(prefix + "sudo systemctl start "+args.unit, ssh)
elif args.subparser == 'stop':
call_func(prefix + "sudo systemctl stop "+args.unit, ssh)
elif args.subparser == 'restart':
call_func(prefix + "sudo systemctl restart "+args.unit, ssh)
elif args.subparser == 'enable':
call_func(prefix + "sudo systemctl enable "+args.unit, ssh)
elif args.subparser == 'disable':
call_func(prefix + "sudo systemctl disable "+args.unit, ssh)
else:
parser.print_help()
| 4,329 | Python | 30.838235 | 84 | 0.546778 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/__init__.py | from .UDPComms import Publisher
from .UDPComms import Subscriber
from .UDPComms import timeout
| 95 | Python | 22.999994 | 32 | 0.842105 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='UDPComms',
version='1.1dev',
py_modules=['UDPComms'],
description='Simple library for sending messages over UDP',
author='Michal Adamkiewicz',
author_email='[email protected]',
url='https://github.com/stanfordroboticsclub/UDP-Comms',
)
| 349 | Python | 25.923075 | 65 | 0.673352 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/UDPComms.py |
import socket
import struct
from collections import namedtuple
from time import monotonic
import msgpack
import time
timeout = socket.timeout
MAX_SIZE = 65507
class Publisher:
def __init__(self, port_tx,port):
""" Create a Publisher Object
Arguments:
port -- the port to publish the messages on
"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.des_address = ("127.0.0.1",port_tx)
self.sock.bind(("127.0.0.1", port))
self.sock.settimeout(0.2)
def send(self, obj):
""" Publish a message. The obj can be any nesting of standard python types """
msg = msgpack.dumps(obj, use_bin_type=False)
assert len(msg) < MAX_SIZE, "Encoded message too big!"
self.sock.sendto(msg,self.des_address)
def __del__(self):
self.sock.close()
class Subscriber:
def __init__(self, port_rx, timeout=0.2):
""" Create a Subscriber Object
Arguments:
port -- the port to listen to messages on
timeout -- how long to wait before a message is considered out of date
"""
self.max_size = MAX_SIZE
self.timeout = timeout
self.last_data = None
self.last_time = float('-inf')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(timeout)
self.sock.bind(("127.0.0.1", port_rx))
def recv(self):
""" Receive a single message from the socket buffer. It blocks for up to timeout seconds.
If no message is received before timeout it raises a UDPComms.timeout exception"""
try:
self.last_data, address = self.sock.recvfrom(3)
except BlockingIOError:
raise socket.timeout("no messages in buffer and called with timeout = 0")
print(self.last_data)
self.last_time = monotonic()
return msgpack.loads(self.last_data, raw=False)
def get(self):
""" Returns the latest message it can without blocking. If the latest massage is
older then timeout seconds it raises a UDPComms.timeout exception"""
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
current_time = monotonic()
if (current_time - self.last_time) < self.timeout:
return msgpack.loads(self.last_data, raw=False)
else:
raise socket.timeout("timeout=" + str(self.timeout) + \
", last message time=" + str(self.last_time) + \
", current time=" + str(current_time))
def get_list(self):
""" Returns list of messages, in the order they were received"""
msg_bufer = []
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
msg = msgpack.loads(self.last_data, raw=False)
msg_bufer.append(msg)
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
return msg_bufer
def __del__(self):
self.sock.close()
class Subscriber:
def __init__(self, port, timeout=0.2):
""" Create a Subscriber Object
Arguments:
port -- the port to listen to messages on
timeout -- how long to wait before a message is considered out of date
"""
self.max_size = MAX_SIZE
self.port = port
self.timeout = timeout
self.last_data = None
self.last_time = float('-inf')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.settimeout(timeout)
self.sock.bind(("", port))
def recv(self):
""" Receive a single message from the socket buffer. It blocks for up to timeout seconds.
If no message is received before timeout it raises a UDPComms.timeout exception"""
try:
self.last_data, address = self.sock.recvfrom(self.max_size)
except BlockingIOError:
raise socket.timeout("no messages in buffer and called with timeout = 0")
self.last_time = monotonic()
return msgpack.loads(self.last_data, raw=False)
def get(self):
""" Returns the latest message it can without blocking. If the latest massage is
older then timeout seconds it raises a UDPComms.timeout exception"""
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
current_time = monotonic()
if (current_time - self.last_time) < self.timeout:
return msgpack.loads(self.last_data, raw=False)
else:
raise socket.timeout("timeout=" + str(self.timeout) + \
", last message time=" + str(self.last_time) + \
", current time=" + str(current_time))
def get_list(self):
""" Returns list of messages, in the order they were received"""
msg_bufer = []
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
msg = msgpack.loads(self.last_data, raw=False)
msg_bufer.append(msg)
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
return msg_bufer
def __del__(self):
self.sock.close()
if __name__ == "__main__":
msg = 'very important data'
a = Publisher(1000)
a.send( {"text": "magic", "number":5.5, "bool":False} )
| 6,463 | Python | 33.021052 | 97 | 0.573727 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Example/display/demo.py | import os
import sys
from PIL import Image
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang.LCD.ST7789 import ST7789
def main():
""" The demo for picture show
"""
# init st7789 device
disp = ST7789()
disp.begin()
disp.clear()
# show exaple picture
image=Image.open("./dog.png")
image.resize((320,240))
disp.display(image)
main()
| 527 | Python | 20.119999 | 129 | 0.671727 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/__init__.py | from __future__ import absolute_import
from Mangdang.Adafruit_GPIO.GPIO import *
| 82 | Python | 19.749995 | 41 | 0.780488 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/Platform.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
MINNOWBOARD = 3
JETSON_NANO = 4
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1:
return JETSON_NANO
# Handle Minnowboard
# Assumption is that mraa is installed
try:
import mraa
if mraa.getPlatformName()=='MinnowBoard MAX':
return MINNOWBOARD
except ImportError:
pass
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3 on 4.9.x kernel
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3 / Pi on 4.9.x kernel
return 3
else:
# Something else, not a pi.
return None
| 4,413 | Python | 37.719298 | 94 | 0.65375 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/GPIO.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import Adafruit_GPIO.Platform as Platform
OUT = 0
IN = 1
HIGH = True
LOW = False
RISING = 1
FALLING = 2
BOTH = 3
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
class BaseGPIO(object):
"""Base class for implementing simple digital IO for a platform.
Implementors are expected to subclass from this and provide an implementation
of the setup, output, and input functions."""
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
raise NotImplementedError
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
raise NotImplementedError
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
raise NotImplementedError
def set_high(self, pin):
"""Set the specified pin HIGH."""
self.output(pin, HIGH)
def set_low(self, pin):
"""Set the specified pin LOW."""
self.output(pin, LOW)
def is_high(self, pin):
"""Return true if the specified pin is pulled high."""
return self.input(pin) == HIGH
def is_low(self, pin):
"""Return true if the specified pin is pulled low."""
return self.input(pin) == LOW
# Basic implementation of multiple pin methods just loops through pins and
# processes each one individually. This is not optimal, but derived classes can
# provide a more optimal implementation that deals with groups of pins
# simultaneously.
# See MCP230xx or PCF8574 classes for examples of optimized implementations.
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
# General implementation just loops through pins and writes them out
# manually. This is not optimized, but subclasses can choose to implement
# a more optimal batch output implementation. See the MCP230xx class for
# example of optimized implementation.
for pin, value in iter(pins.items()):
self.output(pin, value)
def setup_pins(self, pins):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin type (IN or OUT).
"""
# General implementation that can be optimized by derived classes.
for pin, value in iter(pins.items()):
self.setup(pin, value)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# General implementation that can be optimized by derived classes.
return [self.input(pin) for pin in pins]
def add_event_detect(self, pin, edge):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH.
"""
raise NotImplementedError
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
raise NotImplementedError
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
raise NotImplementedError
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
raise NotImplementedError
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH."""
raise NotImplementedError
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
raise NotImplementedError
# helper functions useful to derived classes
def _validate_pin(self, pin):
# Raise an exception if pin is outside the range of allowed values.
if pin < 0 or pin >= self.NUM_GPIO:
raise ValueError('Invalid GPIO value, must be between 0 and {0}.'.format(self.NUM_GPIO))
def _bit2(self, src, bit, val):
bit = 1 << bit
return (src | bit) if val else (src & ~bit)
class RPiGPIOAdapter(BaseGPIO):
"""GPIO implementation for the Raspberry Pi using the RPi.GPIO library."""
def __init__(self, rpi_gpio, mode=None):
self.rpi_gpio = rpi_gpio
# Suppress warnings about GPIO in use.
rpi_gpio.setwarnings(False)
# Setup board pin mode.
if mode == rpi_gpio.BOARD or mode == rpi_gpio.BCM:
rpi_gpio.setmode(mode)
elif mode is not None:
raise ValueError('Unexpected value for mode. Must be BOARD or BCM.')
else:
# Default to BCM numbering if not told otherwise.
rpi_gpio.setmode(rpi_gpio.BCM)
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: rpi_gpio.OUT,
IN: rpi_gpio.IN }
self._pud_mapping = { PUD_OFF: rpi_gpio.PUD_OFF,
PUD_DOWN: rpi_gpio.PUD_DOWN,
PUD_UP: rpi_gpio.PUD_UP }
self._edge_mapping = { RISING: rpi_gpio.RISING,
FALLING: rpi_gpio.FALLING,
BOTH: rpi_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.rpi_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.rpi_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.rpi_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe rpi has a mass read... it would be more efficient to use it if it exists
return [self.rpi_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.rpi_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.rpi_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
self.rpi_gpio.add_event_callback(pin, callback)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.rpi_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.rpi_gpio.cleanup()
else:
self.rpi_gpio.cleanup(pin)
class AdafruitBBIOAdapter(BaseGPIO):
"""GPIO implementation for the Beaglebone Black using the Adafruit_BBIO
library.
"""
def __init__(self, bbio_gpio):
self.bbio_gpio = bbio_gpio
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: bbio_gpio.OUT,
IN: bbio_gpio.IN }
self._pud_mapping = { PUD_OFF: bbio_gpio.PUD_OFF,
PUD_DOWN: bbio_gpio.PUD_DOWN,
PUD_UP: bbio_gpio.PUD_UP }
self._edge_mapping = { RISING: bbio_gpio.RISING,
FALLING: bbio_gpio.FALLING,
BOTH: bbio_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.bbio_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.bbio_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.bbio_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe bbb has a mass read... it would be more efficient to use it if it exists
return [self.bbio_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.bbio_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback, bouncetime=-1):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_callback(pin, callback, **kwargs)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.bbio_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.bbio_gpio.cleanup()
else:
self.bbio_gpio.cleanup(pin)
class AdafruitMinnowAdapter(BaseGPIO):
"""GPIO implementation for the Minnowboard + MAX using the mraa library"""
def __init__(self,mraa_gpio):
self.mraa_gpio = mraa_gpio
# Define mapping of Adafruit GPIO library constants to mraa constants
self._dir_mapping = { OUT: self.mraa_gpio.DIR_OUT,
IN: self.mraa_gpio.DIR_IN }
self._pud_mapping = { PUD_OFF: self.mraa_gpio.MODE_STRONG,
PUD_UP: self.mraa_gpio.MODE_HIZ,
PUD_DOWN: self.mraa_gpio.MODE_PULLDOWN }
self._edge_mapping = { RISING: self.mraa_gpio.EDGE_RISING,
FALLING: self.mraa_gpio.EDGE_FALLING,
BOTH: self.mraa_gpio.EDGE_BOTH }
def setup(self,pin,mode):
"""Set the input or output mode for a specified pin. Mode should be
either DIR_IN or DIR_OUT.
"""
self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])
def output(self,pin,value):
"""Set the specified pin the provided high/low value. Value should be
either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean.
"""
self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)
def input(self,pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.mraa_gpio.Gpio.isr(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge])
def get_platform_gpio(**keywords):
"""Attempt to return a GPIO instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a GPIO instance can't be created for the current platform. The
returned GPIO object is an instance of BaseGPIO.
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
import RPi.GPIO
return RPiGPIOAdapter(RPi.GPIO, **keywords)
elif plat == Platform.BEAGLEBONE_BLACK:
import Adafruit_BBIO.GPIO
return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)
elif plat == Platform.MINNOWBOARD:
import mraa
return AdafruitMinnowAdapter(mraa, **keywords)
elif plat == Platform.JETSON_NANO:
import Jetson.GPIO
return RPiGPIOAdapter(Jetson.GPIO, **keywords)
elif plat == Platform.UNKNOWN:
raise RuntimeError('Could not determine platform.')
| 17,268 | Python | 39.160465 | 100 | 0.618253 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/SPI.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import operator
import time
import Mangdang.Adafruit_GPIO as GPIO
MSBFIRST = 0
LSBFIRST = 1
class SpiDev(object):
"""Hardware-based SPI implementation using the spidev interface."""
def __init__(self, port, device, max_speed_hz=500000):
"""Initialize an SPI device using the SPIdev interface. Port and device
identify the device, for example the device /dev/spidev1.0 would be port
1 and device 0.
"""
import spidev
self._device = spidev.SpiDev()
self._device.open(port, device)
self._device.max_speed_hz=max_speed_hz
# Default to mode 0, and make sure CS is active low.
self._device.mode = 0
#self._device.cshigh = False
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.max_speed_hz=hz
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode = mode
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbfirst = False
elif order == LSBFIRST:
self._device.lsbfirst = True
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.close()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.writebytes(data)
def read(self, length):
"""Half-duplex SPI read. The specified length of bytes will be clocked
in the MISO line and returned as a bytearray object.
"""
return bytearray(self._device.readbytes(length))
def transfer(self, data):
"""Full-duplex SPI read and write. The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line. Read bytes will be returned as a bytearray object.
"""
return bytearray(self._device.xfer2(data))
class SpiDevMraa(object):
"""Hardware SPI implementation with the mraa library on Minnowboard"""
def __init__(self, port, device, max_speed_hz=500000):
import mraa
self._device = mraa.Spi(0)
self._device.mode(0)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.frequency(hz)
def set_mode(self,mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode(mode)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbmode(False)
elif order == LSBFIRST:
self._device.lsbmode(True)
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.Spi()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.write(bytearray(data))
class BitBang(object):
"""Software-based implementation of the SPI protocol over GPIO pins."""
def __init__(self, gpio, sclk, mosi=None, miso=None, ss=None):
"""Initialize bit bang (or software) based SPI. Must provide a BaseGPIO
class, the SPI clock, and optionally MOSI, MISO, and SS (slave select)
pin numbers. If MOSI is set to None then writes will be disabled and fail
with an error, likewise for MISO reads will be disabled. If SS is set to
None then SS will not be asserted high/low by the library when
transfering data.
"""
self._gpio = gpio
self._sclk = sclk
self._mosi = mosi
self._miso = miso
self._ss = ss
# Set pins as outputs/inputs.
gpio.setup(sclk, GPIO.OUT)
if mosi is not None:
gpio.setup(mosi, GPIO.OUT)
if miso is not None:
gpio.setup(miso, GPIO.IN)
if ss is not None:
gpio.setup(ss, GPIO.OUT)
# Assert SS high to start with device communication off.
gpio.set_high(ss)
# Assume mode 0.
self.set_mode(0)
# Assume most significant bit first order.
self.set_bit_order(MSBFIRST)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock. This is unsupported with the bit
bang SPI class and will be ignored.
"""
pass
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
if mode & 0x02:
# Clock is normally high in mode 2 and 3.
self._clock_base = GPIO.HIGH
else:
# Clock is normally low in mode 0 and 1.
self._clock_base = GPIO.LOW
if mode & 0x01:
# Read on trailing edge in mode 1 and 3.
self._read_leading = False
else:
# Read on leading edge in mode 0 and 2.
self._read_leading = True
# Put clock into its base state.
self._gpio.output(self._sclk, self._clock_base)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
# Set self._mask to the bitmask which points at the appropriate bit to
# read or write, and appropriate left/right shift operator function for
# reading/writing.
if order == MSBFIRST:
self._mask = 0x80
self._write_shift = operator.lshift
self._read_shift = operator.rshift
elif order == LSBFIRST:
self._mask = 0x01
self._write_shift = operator.rshift
self._read_shift = operator.lshift
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close the SPI connection. Unused in the bit bang implementation."""
pass
def write(self, data, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high.
"""
# Fail MOSI is not specified.
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
for byte in data:
for i in range(8):
# Write bit to MOSI.
if self._write_shift(byte, i) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
def read(self, length, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI read. If assert_ss is true, the SS line will be
asserted low, the specified length of bytes will be clocked in the MISO
line, and if deassert_ss is true the SS line will be put back high.
Bytes which are read will be returned as a bytearray object.
"""
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(length)
for i in range(length):
for j in range(8):
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result
def transfer(self, data, assert_ss=True, deassert_ss=True):
"""Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS line will be put back high. Bytes which are
read will be returned as a bytearray object.
"""
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(len(data))
for i in range(len(data)):
for j in range(8):
# Write bit to MOSI.
if self._write_shift(data[i], j) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result
| 13,970 | Python | 41.465045 | 81 | 0.585827 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/ST7789.py | # ST7789 IPS LCD (320x240) driver
import numbers
import time
import numpy as np
import sys
import os
from PIL import Image
from PIL import ImageDraw
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
import Mangdang.Adafruit_GPIO as GPIO
import Mangdang.Adafruit_GPIO.SPI as SPI
from Mangdang.LCD.gif import AnimatedGif
SPI_CLOCK_HZ = 31200000 # 31.2 MHz
# Constants for interacting with display registers.
ST7789_TFTWIDTH = 320
ST7789_TFTHEIGHT = 240
ST7789_NOP = 0x00
ST7789_SWRESET = 0x01
ST7789_RDDID = 0x04
ST7789_RDDST = 0x09
ST7789_RDDPM = 0x0A
ST7789_RDDMADCTL = 0x0B
ST7789_RDDCOLMOD = 0x0C
ST7789_RDDIM = 0x0D
ST7789_RDDSM = 0x0E
ST7789_RDDSDR = 0x0F
ST7789_SLPIN = 0x10
ST7789_SLPOUT = 0x11
ST7789_PTLON = 0x12
ST7789_NORON = 0x13
ST7789_INVOFF = 0x20
ST7789_INVON = 0x21
ST7789_GAMSET = 0x26
ST7789_DISPOFF = 0x28
ST7789_DISPON = 0x29
ST7789_CASET = 0x2A
ST7789_RASET = 0x2B
ST7789_RAMWR = 0x2C
ST7789_RAMRD = 0x2E
ST7789_PTLAR = 0x30
ST7789_VSCRDEF = 0x33
ST7789_TEOFF = 0x34
ST7789_TEON = 0x35
ST7789_MADCTL = 0x36
ST7789_VSCRSADD = 0x37
ST7789_IDMOFF = 0x38
ST7789_IDMON = 0x39
ST7789_COLMOD = 0x3A
ST7789_RAMWRC = 0x3C
ST7789_RAMRDC = 0x3E
ST7789_TESCAN = 0x44
ST7789_RDTESCAN = 0x45
ST7789_WRDISBV = 0x51
ST7789_RDDISBV = 0x52
ST7789_WRCTRLD = 0x53
ST7789_RDCTRLD = 0x54
ST7789_WRCACE = 0x55
ST7789_RDCABC = 0x56
ST7789_WRCABCMB = 0x5E
ST7789_RDCABCMB = 0x5F
ST7789_RDABCSDR = 0x68
ST7789_RDID1 = 0xDA
ST7789_RDID2 = 0xDB
ST7789_RDID3 = 0xDC
ST7789_RAMCTRL = 0xB0
ST7789_RGBCTRL = 0xB1
ST7789_PORCTRL = 0xB2
ST7789_FRCTRL1 = 0xB3
ST7789_GCTRL = 0xB7
ST7789_DGMEN = 0xBA
ST7789_VCOMS = 0xBB
ST7789_LCMCTRL = 0xC0
ST7789_IDSET = 0xC1
ST7789_VDVVRHEN = 0xC2
ST7789_VRHS = 0xC3
ST7789_VDVSET = 0xC4
ST7789_VCMOFSET = 0xC5
ST7789_FRCTR2 = 0xC6
ST7789_CABCCTRL = 0xC7
ST7789_REGSEL1 = 0xC8
ST7789_REGSEL2 = 0xCA
ST7789_PWMFRSEL = 0xCC
ST7789_PWCTRL1 = 0xD0
ST7789_VAPVANEN = 0xD2
ST7789_CMD2EN = 0xDF5A6902
ST7789_PVGAMCTRL = 0xE0
ST7789_NVGAMCTRL = 0xE1
ST7789_DGMLUTR = 0xE2
ST7789_DGMLUTB = 0xE3
ST7789_GATECTRL = 0xE4
ST7789_PWCTRL2 = 0xE8
ST7789_EQCTRL = 0xE9
ST7789_PROMCTRL = 0xEC
ST7789_PROMEN = 0xFA
ST7789_NVMSET = 0xFC
ST7789_PROMACT = 0xFE
# Colours for convenience
ST7789_BLACK = 0x0000 # 0b 00000 000000 00000
ST7789_BLUE = 0x001F # 0b 00000 000000 11111
ST7789_GREEN = 0x07E0 # 0b 00000 111111 00000
ST7789_RED = 0xF800 # 0b 11111 000000 00000
ST7789_CYAN = 0x07FF # 0b 00000 111111 11111
ST7789_MAGENTA = 0xF81F # 0b 11111 000000 11111
ST7789_YELLOW = 0xFFE0 # 0b 11111 111111 00000
ST7789_WHITE = 0xFFFF # 0b 11111 111111 11111
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
def image_to_data(image):
"""Generator function to convert a PIL image to 16-bit 565 RGB bytes."""
# NumPy is much faster at doing this. NumPy code provided by:
# Keith (https://www.blogger.com/profile/02555547344016007163)
pb = np.array(image.convert('RGB')).astype('uint16')
color = ((pb[:,:,0] & 0xF8) << 8) | ((pb[:,:,1] & 0xFC) << 3) | (pb[:,:,2] >> 3)
return np.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()
class ST7789(object):
"""Representation of an ST7789 IPS LCD."""
def __init__(self, rst, dc, led):
"""Create an instance of the display using SPI communication. Must
provide the GPIO pin number for the D/C pin and the SPI driver. Can
optionally provide the GPIO pin number for the reset pin as the rst
parameter.
"""
SPI_PORT = 0
SPI_DEVICE = 0
SPI_MODE = 0b11
SPI_SPEED_HZ = 40000000
self._spi = SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=SPI_SPEED_HZ)
self._rst = rst
self._dc = dc
self._led = led
self._gpio = None
self.width = ST7789_TFTWIDTH
self.height = ST7789_TFTHEIGHT
if self._gpio is None:
self._gpio = GPIO.get_platform_gpio()
# Set DC as output.
self._gpio.setup(self._dc, GPIO.OUT)
# Setup reset as output (if provided).
if self._rst is not None:
self._gpio.setup(self._rst, GPIO.OUT)
# Turn on the backlight LED
self._gpio.setup(self._led, GPIO.OUT)
# Set SPI to mode 0, MSB first.
self._spi.set_mode(SPI_MODE)
self._spi.set_bit_order(SPI.MSBFIRST)
self._spi.set_clock_hz(SPI_CLOCK_HZ)
# Create an image buffer.
self.buffer = Image.new('RGB', (self.width, self.height))
def send(self, data, is_data=True, chunk_size=4096):
"""Write a byte or array of bytes to the display. Is_data parameter
controls if byte should be interpreted as display data (True) or command
data (False). Chunk_size is an optional size of bytes to write in a
single SPI transaction, with a default of 4096.
"""
# Set DC low for command, high for data.
self._gpio.output(self._dc, is_data)
# Convert scalar argument to list so either can be passed as parameter.
if isinstance(data, numbers.Number):
data = [data & 0xFF]
# Write data a chunk at a time.
for start in range(0, len(data), chunk_size):
end = min(start+chunk_size, len(data))
self._spi.write(data[start:end])
def command(self, data):
"""Write a byte or array of bytes to the display as command data."""
self.send(data, False)
def data(self, data):
"""Write a byte or array of bytes to the display as display data."""
self.send(data, True)
def reset(self):
"""Reset the display, if reset pin is connected."""
if self._rst is not None:
self._gpio.set_high(self._rst)
time.sleep(0.100)
self._gpio.set_low(self._rst)
time.sleep(0.100)
self._gpio.set_high(self._rst)
time.sleep(0.100)
def _init(self):
# Initialize the display. Broken out as a separate function so it can
# be overridden by other displays in the future.
time.sleep(0.012)
self.command(0x11)
time.sleep(0.150)
self.command(0x36)
self.data(0xA0)
self.data(0x00)
self.command(0x3A)
self.data(0x05)
self.command(0xB2)
self.data(0x0C)
self.data(0x0C)
self.data(0x00)
self.data(0x33)
self.data(0x33)
self.command(0xB7)
self.data(0x35)
## ---------------------------------ST7789S Power setting - ----------------------------
self.command(0xBB)
self.data(0x29)
# self.command(0xC0)
# self.data(0x2C)
self.command(0xC2)
self.data(0x01)
self.command(0xC3)
self.data(0x19)
self.command(0xC4)
self.data(0x20)
self.command(0xC5)
self.data(0x1A)
self.command(0xC6)
self.data(0x1F) ## 0x0F:60Hz
# self.command(0xCA)
# self.data(0x0F)
#
# self.command(0xC8)
# self.data(0x08)
#
# self.command(0x55)
# self.data(0x90)
self.command(0xD0)
self.data(0xA4)
self.data(0xA1)
## --------------------------------ST7789S gamma setting - -----------------------------
self.command(0xE0)
self.data(0xD0)
self.data(0x08)
self.data(0x0E)
self.data(0x09)
self.data(0x09)
self.data(0x05)
self.data(0x31)
self.data(0x33)
self.data(0x48)
self.data(0x17)
self.data(0x14)
self.data(0x15)
self.data(0x31)
self.data(0x34)
self.command(0xE1)
self.data(0xD0)
self.data(0x08)
self.data(0x0E)
self.data(0x09)
self.data(0x09)
self.data(0x15)
self.data(0x31)
self.data(0x33)
self.data(0x48)
self.data(0x17)
self.data(0x14)
self.data(0x15)
self.data(0x31)
self.data(0x34)
self.command(0x21)
self.command(0x29)
time.sleep(0.100) # 100 ms
self._gpio.set_high(self._led)
def begin(self):
"""Initialize the display. Should be called once before other calls that
interact with the display are called.
"""
self.reset()
self._init()
def set_window(self, x0=0, y0=0, x1=None, y1=None):
"""Set the pixel address window for proceeding drawing commands. x0 and
x1 should define the minimum and maximum x pixel bounds. y0 and y1
should define the minimum and maximum y pixel bound. If no parameters
are specified the default will be to update the entire display from 0,0
to width-1,height-1.
"""
if x1 is None:
x1 = self.width-1
if y1 is None:
y1 = self.height-1
self.command(ST7789_CASET) # Column addr set
self.data(x0 >> 8)
self.data(x0) # XSTART
self.data(x1 >> 8)
self.data(x1) # XEND
self.command(ST7789_RASET) # Row addr set
self.data(y0 >> 8)
self.data(y0) # YSTART
self.data(y1 >> 8)
self.data(y1) # YEND
self.command(ST7789_RAMWR) # write to RAM
#def display(self, image=None):
def display(self, image=None, x0=0, y0=0, x1=None, y1=None):
"""Write the display buffer or provided image to the hardware. If no
image parameter is provided the display buffer will be written to the
hardware. If an image is provided, it should be RGB format and the
same dimensions as the display hardware.
"""
# By default write the internal buffer to the display.
if image is None:
image = self.buffer
# Set address bounds to entire display.
#self.set_window()
if x1 is None:
x1 = self.width-1
if y1 is None:
y1 = self.height-1
self.set_window(x0, y0, x1, y1)
#image.thumbnail((x1-x0+1, y1-y0+1), Image.ANTIALIAS)
# Convert image to array of 16bit 565 RGB data bytes.
# Unfortunate that this copy has to occur, but the SPI byte writing
# function needs to take an array of bytes and PIL doesn't natively
# store images in 16-bit 565 RGB format.
pixelbytes = list(image_to_data(image))
# Write data to hardware.
self.data(pixelbytes)
def clear(self, color=(0,0,0)):
"""Clear the image buffer to the specified RGB color (default black)."""
width, height = self.buffer.size
self.buffer.putdata([color]*(width*height))
def draw(self):
"""Return a PIL ImageDraw instance for 2D drawing on the image buffer."""
return ImageDraw.Draw(self.buffer)
| 11,573 | Python | 29.781915 | 129 | 0.584723 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/gif.py | import os
import time
from PIL import Image
from PIL import ImageOps
class Frame:
def __init__(self, duration=0):
self.duration = duration
self.image = None
class AnimatedGif:
def __init__(self, display, width=None, height=None, folder=None):
self._frame_count = 0
self._loop = 0
self._index = 0
self._duration = 0
self._gif_files = []
self._frames = []
self._gif_folder = folder
if width is not None:
self._width = width
else:
self._width = display.width
if height is not None:
self._height = height
else:
self._height = display.height
self.display = display
if folder is not None:
self.load_files(folder)
self.preload()
def advance(self):
self._index = (self._index + 1) % len(self._gif_files)
def back(self):
self._index = (self._index - 1 + len(self._gif_files)) % len(self._gif_files)
def load_files(self, folder):
gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")]
for gif_file in gif_files:
image = Image.open(folder + gif_file)
# Only add animated Gifs
if image.is_animated:
self._gif_files.append(gif_file)
#print("Found", self._gif_files)
if not self._gif_files:
print("No Gif files found in current folder")
exit() # pylint: disable=consider-using-sys-exit
def preload(self):
image = Image.open(self._gif_folder + self._gif_files[self._index])
#print("Loading {}...".format(self._gif_files[self._index]))
if "duration" in image.info:
self._duration = image.info["duration"]
else:
self._duration = 0
if "loop" in image.info:
self._loop = image.info["loop"]
else:
self._loop = 1
self._frame_count = image.n_frames
del self._frames[:]
for frame in range(self._frame_count):
image.seek(frame)
# Create blank image for drawing.
# Make sure to create image with mode 'RGB' for full color.
frame_object = Frame(duration=self._duration)
if "duration" in image.info:
frame_object.duration = image.info["duration"]
frame_object.image = ImageOps.pad( # pylint: disable=no-member
image.convert("RGB"),
(self._width, self._height),
method=Image.NEAREST,
color=(0, 0, 0),
centering=(0.5, 0.5),
)
self._frames.append(frame_object)
def play(self):
# Check if we have loaded any files first
if not self._gif_files:
print("There are no Gif Images loaded to Play")
return False
#while True:
for frame_object in self._frames:
start_time = time.time()
self.display.display(frame_object.image)
while time.time() < (start_time + frame_object.duration / 1000):
pass
if self._loop == 1:
return True
if self._loop > 0:
self._loop -= 1
def run(self):
while True:
auto_advance = self.play()
if auto_advance:
self.advance()
| 3,404 | Python | 31.740384 | 85 | 0.529083 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PupperCommand/joystick.py | from UDPComms import Publisher, Subscriber, timeout
from PS4Joystick import Joystick
import time
## you need to git clone the PS4Joystick repo and run `sudo bash install.sh`
## Configurable ##
MESSAGE_RATE = 20
PUPPER_COLOR = {"red":0, "blue":0, "green":255}
joystick_pub = Publisher(8830,65530)
joystick_subcriber = Subscriber(8840, timeout=0.01)
joystick = Joystick()
joystick.led_color(**PUPPER_COLOR)
while True:
values = joystick.get_input()
left_y = -values["left_analog_y"]
right_y = -values["right_analog_y"]
right_x = values["right_analog_x"]
left_x = values["left_analog_x"]
L2 = values["l2_analog"]
R2 = values["r2_analog"]
R1 = values["button_r1"]
L1 = values["button_l1"]
square = values["button_square"]
x = values["button_cross"]
circle = values["button_circle"]
triangle = values["button_triangle"]
dpadx = values["dpad_right"] - values["dpad_left"]
dpady = values["dpad_up"] - values["dpad_down"]
msg = {
"ly": left_y,
"lx": left_x,
"rx": right_x,
"ry": right_y,
"L2": L2,
"R2": R2,
"R1": R1,
"L1": L1,
"dpady": dpady,
"dpadx": dpadx,
"x": x,
"square": square,
"circle": circle,
"triangle": triangle,
"message_rate": MESSAGE_RATE,
}
joystick_pub.send(msg)
try:
msg = joystick_subcriber.get()
joystick.led_color(**msg["ps4_color"])
except timeout:
pass
time.sleep(1 / MESSAGE_RATE)
| 1,539 | Python | 22.692307 | 76 | 0.581546 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Legacy/ImageOps.py | #
# The Python Imaging Library.
# $Id$
#
# standard image operations
#
# History:
# 2001-10-20 fl Created
# 2001-10-23 fl Added autocontrast operator
# 2001-12-18 fl Added Kevin's fit operator
# 2004-03-14 fl Fixed potential division by zero in equalize
# 2005-05-05 fl Fixed equalize for low number of values
#
# Copyright (c) 2001-2004 by Secret Labs AB
# Copyright (c) 2001-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from . import Image
import operator
import functools
import warnings
#
# helpers
def _border(border):
if isinstance(border, tuple):
if len(border) == 2:
left, top = right, bottom = border
elif len(border) == 4:
left, top, right, bottom = border
else:
left = top = right = bottom = border
return left, top, right, bottom
def _color(color, mode):
if isStringType(color):
from . import ImageColor
color = ImageColor.getcolor(color, mode)
return color
def _lut(image, lut):
if image.mode == "P":
# FIXME: apply to lookup table, not image data
raise NotImplementedError("mode P support coming soon")
elif image.mode in ("L", "RGB"):
if image.mode == "RGB" and len(lut) == 256:
lut = lut + lut + lut
return image.point(lut)
else:
raise IOError("not supported for this image mode")
#
# actions
def autocontrast(image, cutoff=0, ignore=None):
"""
Maximize (normalize) image contrast. This function calculates a
histogram of the input image, removes **cutoff** percent of the
lightest and darkest pixels from the histogram, and remaps the image
so that the darkest pixel becomes black (0), and the lightest
becomes white (255).
:param image: The image to process.
:param cutoff: How many percent to cut off from the histogram.
:param ignore: The background pixel value (use None for no background).
:return: An image.
"""
histogram = image.histogram()
lut = []
for layer in range(0, len(histogram), 256):
h = histogram[layer:layer+256]
if ignore is not None:
# get rid of outliers
try:
h[ignore] = 0
except TypeError:
# assume sequence
for ix in ignore:
h[ix] = 0
if cutoff:
# cut off pixels from both ends of the histogram
# get number of pixels
n = 0
for ix in range(256):
n = n + h[ix]
# remove cutoff% pixels from the low end
cut = n * cutoff // 100
for lo in range(256):
if cut > h[lo]:
cut = cut - h[lo]
h[lo] = 0
else:
h[lo] -= cut
cut = 0
if cut <= 0:
break
# remove cutoff% samples from the hi end
cut = n * cutoff // 100
for hi in range(255, -1, -1):
if cut > h[hi]:
cut = cut - h[hi]
h[hi] = 0
else:
h[hi] -= cut
cut = 0
if cut <= 0:
break
# find lowest/highest samples after preprocessing
for lo in range(256):
if h[lo]:
break
for hi in range(255, -1, -1):
if h[hi]:
break
if hi <= lo:
# don't bother
lut.extend(list(range(256)))
else:
scale = 255.0 / (hi - lo)
offset = -lo * scale
for ix in range(256):
ix = int(ix * scale + offset)
if ix < 0:
ix = 0
elif ix > 255:
ix = 255
lut.append(ix)
return _lut(image, lut)
def colorize(image, black, white, mid=None, blackpoint=0,
whitepoint=255, midpoint=127):
"""
Colorize grayscale image.
This function calculates a color wedge which maps all black pixels in
the source image to the first color and all white pixels to the
second color. If **mid** is specified, it uses three-color mapping.
The **black** and **white** arguments should be RGB tuples or color names;
optionally you can use three-color mapping by also specifying **mid**.
Mapping positions for any of the colors can be specified
(e.g. **blackpoint**), where these parameters are the integer
value corresponding to where the corresponding color should be mapped.
These parameters must have logical order, such that
**blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).
:param image: The image to colorize.
:param black: The color to use for black input pixels.
:param white: The color to use for white input pixels.
:param mid: The color to use for midtone input pixels.
:param blackpoint: an int value [0, 255] for the black mapping.
:param whitepoint: an int value [0, 255] for the white mapping.
:param midpoint: an int value [0, 255] for the midtone mapping.
:return: An image.
"""
# Initial asserts
assert image.mode == "L"
if mid is None:
assert 0 <= blackpoint <= whitepoint <= 255
else:
assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
# Define colors from arguments
black = _color(black, "RGB")
white = _color(white, "RGB")
if mid is not None:
mid = _color(mid, "RGB")
# Empty lists for the mapping
red = []
green = []
blue = []
# Create the low-end values
for i in range(0, blackpoint):
red.append(black[0])
green.append(black[1])
blue.append(black[2])
# Create the mapping (2-color)
if mid is None:
range_map = range(0, whitepoint - blackpoint)
for i in range_map:
red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))
# Create the mapping (3-color)
else:
range_map1 = range(0, midpoint - blackpoint)
range_map2 = range(0, whitepoint - midpoint)
for i in range_map1:
red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
for i in range_map2:
red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))
# Create the high-end values
for i in range(0, 256 - whitepoint):
red.append(white[0])
green.append(white[1])
blue.append(white[2])
# Return converted image
image = image.convert("RGB")
return _lut(image, red + green + blue)
def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):
"""
Returns a sized and padded version of the image, expanded to fill the
requested aspect ratio and size.
:param image: The image to size and crop.
:param size: The requested output size in pixels, given as a
(width, height) tuple.
:param method: What resampling method to use. Default is
:py:attr:`PIL.Image.NEAREST`.
:param color: The background color of the padded image.
:param centering: Control the position of the original image within the
padded version.
(0.5, 0.5) will keep the image centered
(0, 0) will keep the image aligned to the top left
(1, 1) will keep the image aligned to the bottom
right
:return: An image.
"""
im_ratio = image.width / image.height
dest_ratio = float(size[0]) / size[1]
if im_ratio == dest_ratio:
out = image.resize(size, resample=method)
else:
out = Image.new(image.mode, size, color)
if im_ratio > dest_ratio:
new_height = int(image.height / image.width * size[0])
if new_height != size[1]:
image = image.resize((size[0], new_height), resample=method)
y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
out.paste(image, (0, y))
else:
new_width = int(image.width / image.height * size[1])
if new_width != size[0]:
image = image.resize((new_width, size[1]), resample=method)
x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
out.paste(image, (x, 0))
return out
def crop(image, border=0):
"""
Remove border from image. The same amount of pixels are removed
from all four sides. This function works on all image modes.
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
:param image: The image to crop.
:param border: The number of pixels to remove.
:return: An image.
"""
left, top, right, bottom = _border(border)
return image.crop(
(left, top, image.size[0]-right, image.size[1]-bottom)
)
def scale(image, factor, resample=Image.NEAREST):
"""
Returns a rescaled image by a specific factor given in parameter.
A factor greater than 1 expands the image, between 0 and 1 contracts the
image.
:param image: The image to rescale.
:param factor: The expansion factor, as a float.
:param resample: An optional resampling filter. Same values possible as
in the PIL.Image.resize function.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if factor == 1:
return image.copy()
elif factor <= 0:
raise ValueError("the factor must be greater than 0")
else:
size = (int(round(factor * image.width)),
int(round(factor * image.height)))
return image.resize(size, resample)
def deform(image, deformer, resample=Image.BILINEAR):
"""
Deform the image.
:param image: The image to deform.
:param deformer: A deformer object. Any object that implements a
**getmesh** method can be used.
:param resample: An optional resampling filter. Same values possible as
in the PIL.Image.transform function.
:return: An image.
"""
return image.transform(
image.size, Image.MESH, deformer.getmesh(image), resample
)
def equalize(image, mask=None):
"""
Equalize the image histogram. This function applies a non-linear
mapping to the input image, in order to create a uniform
distribution of grayscale values in the output image.
:param image: The image to equalize.
:param mask: An optional mask. If given, only the pixels selected by
the mask are included in the analysis.
:return: An image.
"""
if image.mode == "P":
image = image.convert("RGB")
h = image.histogram(mask)
lut = []
for b in range(0, len(h), 256):
histo = [_f for _f in h[b:b+256] if _f]
if len(histo) <= 1:
lut.extend(list(range(256)))
else:
step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
if not step:
lut.extend(list(range(256)))
else:
n = step // 2
for i in range(256):
lut.append(n // step)
n = n + h[i+b]
return _lut(image, lut)
def expand(image, border=0, fill=0):
"""
Add border to the image
:param image: The image to expand.
:param border: Border width, in pixels.
:param fill: Pixel fill value (a color value). Default is 0 (black).
:return: An image.
"""
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
out = Image.new(image.mode, (width, height), _color(fill, image.mode))
out.paste(image, (left, top))
return out
def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
"""
Returns a sized and cropped version of the image, cropped to the
requested aspect ratio and size.
This function was contributed by Kevin Cazabon.
:param image: The image to size and crop.
:param size: The requested output size in pixels, given as a
(width, height) tuple.
:param method: What resampling method to use. Default is
:py:attr:`PIL.Image.NEAREST`.
:param bleed: Remove a border around the outside of the image from all
four edges. The value is a decimal percentage (use 0.01 for
one percent). The default value is 0 (no border).
Cannot be greater than or equal to 0.5.
:param centering: Control the cropping position. Use (0.5, 0.5) for
center cropping (e.g. if cropping the width, take 50% off
of the left side, and therefore 50% off the right side).
(0.0, 0.0) will crop from the top left corner (i.e. if
cropping the width, take all of the crop off of the right
side, and if cropping the height, take all of it off the
bottom). (1.0, 0.0) will crop from the bottom left
corner, etc. (i.e. if cropping the width, take all of the
crop off the left side, and if cropping the height take
none from the top, and therefore all off the bottom).
:return: An image.
"""
# by Kevin Cazabon, Feb 17/2000
# [email protected]
# http://www.cazabon.com
# ensure centering is mutable
centering = list(centering)
if not 0.0 <= centering[0] <= 1.0:
centering[0] = 0.5
if not 0.0 <= centering[1] <= 1.0:
centering[1] = 0.5
if not 0.0 <= bleed < 0.5:
bleed = 0.0
# calculate the area to use for resizing and cropping, subtracting
# the 'bleed' around the edges
# number of pixels to trim off on Top and Bottom, Left and Right
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
live_size = (image.size[0] - bleed_pixels[0] * 2,
image.size[1] - bleed_pixels[1] * 2)
# calculate the aspect ratio of the live_size
live_size_ratio = float(live_size[0]) / live_size[1]
# calculate the aspect ratio of the output image
output_ratio = float(size[0]) / size[1]
# figure out if the sides or top/bottom will be cropped off
if live_size_ratio >= output_ratio:
# live_size is wider than what's needed, crop the sides
crop_width = output_ratio * live_size[1]
crop_height = live_size[1]
else:
# live_size is taller than what's needed, crop the top and bottom
crop_width = live_size[0]
crop_height = live_size[0] / output_ratio
# make the crop
crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]
crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]
crop = (
crop_left, crop_top,
crop_left + crop_width, crop_top + crop_height
)
# resize the image and return it
return image.resize(size, method, box=crop)
def flip(image):
"""
Flip the image vertically (top to bottom).
:param image: The image to flip.
:return: An image.
"""
return image.transpose(Image.FLIP_TOP_BOTTOM)
def grayscale(image):
"""
Convert the image to grayscale.
:param image: The image to convert.
:return: An image.
"""
return image.convert("L")
def invert(image):
"""
Invert (negate) the image.
:param image: The image to invert.
:return: An image.
"""
lut = []
for i in range(256):
lut.append(255-i)
return _lut(image, lut)
def mirror(image):
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
def posterize(image, bits):
"""
Reduce the number of bits for each color channel.
:param image: The image to posterize.
:param bits: The number of bits to keep for each channel (1-8).
:return: An image.
"""
lut = []
mask = ~(2**(8-bits)-1)
for i in range(256):
lut.append(i & mask)
return _lut(image, lut)
def solarize(image, threshold=128):
"""
Invert all pixel values above a threshold.
:param image: The image to solarize.
:param threshold: All pixels above this greyscale level are inverted.
:return: An image.
"""
lut = []
for i in range(256):
if i < threshold:
lut.append(i)
else:
lut.append(255-i)
return _lut(image, lut)
# --------------------------------------------------------------------
# PIL USM components, from Kevin Cazabon.
def gaussian_blur(im, radius=None):
""" PIL_usm.gblur(im, [radius])"""
warnings.warn(
'PIL.ImageOps.gaussian_blur is deprecated. '
'Use PIL.ImageFilter.GaussianBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
if radius is None:
radius = 5.0
im.load()
return im.im.gaussian_blur(radius)
def gblur(im, radius=None):
""" PIL_usm.gblur(im, [radius])"""
warnings.warn(
'PIL.ImageOps.gblur is deprecated. '
'Use PIL.ImageFilter.GaussianBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
return gaussian_blur(im, radius)
def unsharp_mask(im, radius=None, percent=None, threshold=None):
""" PIL_usm.usm(im, [radius, percent, threshold])"""
warnings.warn(
'PIL.ImageOps.unsharp_mask is deprecated. '
'Use PIL.ImageFilter.UnsharpMask instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
if radius is None:
radius = 5.0
if percent is None:
percent = 150
if threshold is None:
threshold = 3
im.load()
return im.im.unsharp_mask(radius, percent, threshold)
def usm(im, radius=None, percent=None, threshold=None):
""" PIL_usm.usm(im, [radius, percent, threshold])"""
warnings.warn(
'PIL.ImageOps.usm is deprecated. '
'Use PIL.ImageFilter.UnsharpMask instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
return unsharp_mask(im, radius, percent, threshold)
def box_blur(image, radius):
"""
Blur the image by setting each pixel to the average value of the pixels
in a square box extending radius pixels in each direction.
Supports float radius of arbitrary size. Uses an optimized implementation
which runs in linear time relative to the size of the image
for any radius value.
:param image: The image to blur.
:param radius: Size of the box in one direction. Radius 0 does not blur,
returns an identical image. Radius 1 takes 1 pixel
in each direction, i.e. 9 pixels in total.
:return: An image.
"""
warnings.warn(
'PIL.ImageOps.box_blur is deprecated. '
'Use PIL.ImageFilter.BoxBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
image.load()
return image._new(image.im.box_blur(radius))
| 19,772 | Python | 30.891935 | 80 | 0.581732 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/calibrate_tool.py | import re
import tkinter as tk
import tkinter.messagebox
from tkinter import *
import _thread
import time
import os
import sys
import numpy as np
from pupper.HardwareInterface import HardwareInterface
###################################################################
OverLoadCurrentMax = 1500000
OverLoadHoldCounterMax = 100 # almost 3s
ServoCalibrationFilePath = '/sys/bus/i2c/devices/3-0050/eeprom'
servo1_en = 25
servo2_en = 21
hw_version=""
###################################################################
class LegPositionScale:
def __init__(self,root,location_x,location_y,leg_name):
self.LocationX = location_x
self.LocationY = location_y
delt_x = 40
delt_y = 45
self.Value1 = DoubleVar()
self.Value2 = DoubleVar()
self.Value3 = DoubleVar()
self.title = Label(root,text = leg_name,font = ('bold',16))
self.label1 = Label(root,text = 'Hip')
self.slider1 = Scale(root,from_=-100,to=100,variable = self.Value1,length = 120,orient = HORIZONTAL)
self.label2 = Label(root,text = 'Thigh')
self.slider2 = Scale(root,from_=-55,to=145,variable = self.Value2,length = 120,orient = HORIZONTAL)
self.label3 = Label(root,text = 'Calf')
self.slider3 = Scale(root,from_=-145,to=55,variable = self.Value3,length = 120,orient = HORIZONTAL)
self.label1.place(x=location_x, y=location_y + 20)
self.label2.place(x=location_x, y=location_y + delt_y*1+ 20)
self.label3.place(x=location_x, y=location_y + delt_y*2+ 20)
self.slider1.place(x=location_x + delt_x, y=location_y )
self.slider2.place(x=location_x + delt_x, y=location_y + delt_y*1)
self.slider3.place(x=location_x + delt_x, y=location_y + delt_y*2)
self.title.place(x=location_x + 70, y=location_y + delt_y*3)
def setValue(self,value):
self.slider1.set(value[0])
self.slider2.set(value[1])
self.slider3.set(value[2])
return True
def getValue(self):
value = []
value.append(self.Value1.get())
value.append(self.Value2.get())
value.append(self.Value3.get())
return value
class CalibrationTool:
def __init__(self,title, width, height):
self.Run = True
self.FileAllLines = []
#leg slider value
self.Leg1SlidersValue = [0,0,0]
self.Leg2SlidersValue = [0,0,0]
self.Leg3SlidersValue = [0,0,0]
self.Leg4SlidersValue = [0,0,0]
# calibration data
self.Matrix_EEPROM = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]])
self.ServoStandardLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.ServoNeutralLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.NocalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.CalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
#build main window
self.MainWindow = tk.Tk()
screenwidth = self.MainWindow.winfo_screenwidth()
screenheight = self.MainWindow.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
self.MainWindow.geometry(size)
self.MainWindow.title('MiniPupper') #Mini Pupper Calibration Tool
self.MainWindow.update()
#init title
self.Title = Label(self.MainWindow,text = title,font = ('bold',30))
self.Title.place(x=140,y=15)
#init robot image
self.photo = tk.PhotoImage(file= '/home/ubuntu/Robotics/QuadrupedRobot/Doc/imgs/MiniPupper.Calibration.png')
self.MainImg = Label(self.MainWindow,image = self.photo)
self.MainImg.place(x=230,y=60)
#init read update button
self.ResetButton = Button(self.MainWindow,text = ' Reset ',font = ('bold',20),command=self.ResetButtonEvent)
self.UpdateButton = Button(self.MainWindow,text = 'Update',font = ('bold',20),command=self.updateButtonEvent)
self.RestoreButton = Button(self.MainWindow,text = 'Restore',font = ('bold',7),command=self.RestoreButtonEvent)
self.ResetButton.place(x=600,y=100)
self.UpdateButton.place(x=600,y=200)
self.RestoreButton.place(x=160,y=80)
#build 4 legs sliders
self.Leg1Calibration = LegPositionScale(self.MainWindow,20,300, 'Leg 1')
self.Leg2Calibration = LegPositionScale(self.MainWindow,220,300,'Leg 2')
self.Leg3Calibration = LegPositionScale(self.MainWindow,420,300,'Leg 3')
self.Leg4Calibration = LegPositionScale(self.MainWindow,620,300,'Leg 4')
self.Leg1Calibration.setValue([self.ServoNeutralLAngle[0][0],self.ServoNeutralLAngle[1][0],self.ServoNeutralLAngle[2][0]])
self.Leg2Calibration.setValue([self.ServoNeutralLAngle[0][1],self.ServoNeutralLAngle[1][1],self.ServoNeutralLAngle[2][1]])
self.Leg3Calibration.setValue([self.ServoNeutralLAngle[0][2],self.ServoNeutralLAngle[1][2],self.ServoNeutralLAngle[2][2]])
self.Leg4Calibration.setValue([self.ServoNeutralLAngle[0][3],self.ServoNeutralLAngle[1][3],self.ServoNeutralLAngle[2][3]])
def setLegSlidersValue(self,value):
self.Leg1Calibration.setValue(value[0])
self.Leg2Calibration.setValue(value[1])
self.Leg3Calibration.setValue(value[2])
self.Leg4Calibration.setValue(value[3])
return value
def readCalibrationFile(self):
#read all lines text from EEPROM
try:
with open(ServoCalibrationFilePath, "rb") as nv_f:
arr1 = np.array(eval(nv_f.readline()))
arr2 = np.array(eval(nv_f.readline()))
matrix = np.append(arr1, arr2)
arr3 = np.array(eval(nv_f.readline()))
matrix = np.append(matrix, arr3)
matrix.resize(3,4)
self.Matrix_EEPROM = matrix
print("Get nv calibration params: \n" , self.Matrix_EEPROM)
except:
matrix = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]])
self.Matrix_EEPROM = matrix
#update
for i in range(3):
for j in range(4):
self.NocalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j]
self.CalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j]
return True
def updateCalibrationMatrix(self,angle):
for i in range(3):
for j in range(4):
self.Matrix_EEPROM[i,j] = angle[i][j]
return True
def writeCalibrationFile(self):
#write matrix to EEPROM
buf_matrix = np.zeros((3, 4))
for i in range(3):
for j in range(4):
buf_matrix[i,j]= self.Matrix_EEPROM[i,j]
# Format array object string for np.array
p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma
partially_formatted_matrix = p1.sub(r"\1,\2", str(buf_matrix))
p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines
formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix)
with open(ServoCalibrationFilePath, "w") as nv_f:
_tmp = str(buf_matrix)
_tmp = _tmp.replace('.' , ',')
_tmp = _tmp.replace('[' , '')
_tmp = _tmp.replace(']' , '')
print(_tmp, file = nv_f)
nv_f.close()
return True
def getLegSlidersValue(self):
value = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
self.Leg1SlidersValue = self.Leg1Calibration.getValue()
self.Leg2SlidersValue = self.Leg2Calibration.getValue()
self.Leg3SlidersValue = self.Leg3Calibration.getValue()
self.Leg4SlidersValue = self.Leg4Calibration.getValue()
value[0] = [self.Leg1SlidersValue[0],self.Leg2SlidersValue[0],self.Leg3SlidersValue[0],self.Leg4SlidersValue[0]]
value[1] = [self.Leg1SlidersValue[1],self.Leg2SlidersValue[1],self.Leg3SlidersValue[1],self.Leg4SlidersValue[1]]
value[2] = [self.Leg1SlidersValue[2],self.Leg2SlidersValue[2],self.Leg3SlidersValue[2],self.Leg4SlidersValue[2]]
self.ServoNeutralLAngle = value
return value
def ResetButtonEvent(self):
value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(4):
value[j][i] = self.ServoStandardLAngle[i][j]
self.setLegSlidersValue(value)
return True
def updateButtonEvent(self):
# update angle matrix
value = self.getLegSlidersValue()
angle = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in range(3):
for j in range(4):
angle[i][j] = self.ServoStandardLAngle[i][j] - value[i][j] +MainWindow.NocalibrationServoAngle[i][j]
# limit angle
for i in range(3):
for j in range(4):
if angle[i][j] > 90:
angle[i][j] = 90
elif angle[i][j] < -90:
angle[i][j] = -90
# popup message box
result = tk.messagebox.askquestion('Info:','****** Angle Matrix ******\n'
+str(angle[0])+'\n'
+str(angle[1])+'\n'
+str(angle[2])+'\n'
+'****************************\n'
+' Update Matrix?')
# update matrix
if result == 'yes':
self.updateCalibrationMatrix(angle)
self.writeCalibrationFile()
print('******** Angle Matrix ********')
print(angle[0])
print(angle[1])
print(angle[2])
print('******************************')
return True
def RestoreButtonEvent(self):
# update angle matrix
value = self.getLegSlidersValue()
angle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
# popup message box
result = tk.messagebox.askquestion('Warning','Are you sure you want to Restore Factory Setting!?')
# update matrix
if result == 'yes':
self.updateCalibrationMatrix(angle)
self.writeCalibrationFile()
print('******** Angle Matrix ********')
print(angle[0])
print(angle[1])
print(angle[2])
print('******************************')
sys.exit()
for i in range(3):
for j in range(4):
self.NocalibrationServoAngle[i][j] = angle[i][j]
#self.CalibrationServoAngle[i][j] = angle[i][j]
value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(4):
value[j][i] = self.ServoStandardLAngle[i][j]
self.setLegSlidersValue(value)
return True
def runMainWindow(self):
self.MainWindow.mainloop()
return True
def stopMainWindow(self):
self.Run = False
return True
OverLoadHoldCounter = 0
def OverLoadDetection():
overload = False
global OverLoadHoldCounter
r = os.popen("cat /sys/class/power_supply/max1720x_battery/current_now")
feedback = str(r.readlines())
current_now = int(feedback[3:len(feedback)-4])
if (current_now > OverLoadCurrentMax):
OverLoadHoldCounter = OverLoadHoldCounter + 1
if (OverLoadHoldCounter > OverLoadHoldCounterMax):
OverLoadHoldCounter = OverLoadHoldCounterMax
os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value")
os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value")
overload = True
else:
overload = False
else:
OverLoadHoldCounter = OverLoadHoldCounter - 10
if (OverLoadHoldCounter < 0):
OverLoadHoldCounter = 0
os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value")
os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value")
overload = False
return overload
def updateServoValue(MainWindow,servo):
while MainWindow.Run:
#update leg slider value
value = MainWindow.getLegSlidersValue()
# overload detection
overload = OverLoadDetection()
if overload == True:
tk.messagebox.showwarning('Warning','Servos overload, please check !!!')
else:
#control servo
joint_angles = np.zeros((3, 4))
joint_angles2 = np.zeros((3, 4))
for i in range(3):
for j in range(4):
joint_angles[i,j] = (value[i][j] - (MainWindow.NocalibrationServoAngle[i][j] - MainWindow.CalibrationServoAngle[i][j]))*0.01745
servo.set_actuator_postions(joint_angles)
time.sleep(0.01)
##############################################
with open("/home/ubuntu/.hw_version", "r") as hw_f:
hw_version = hw_f.readline()
if hw_version == 'P1\n':
ServoCalibrationFilePath = "/home/ubuntu/.nv_fle"
servo1_en = 19
servo2_en = 26
else:
servo1_en = 25
servo2_en = 21
os.system("sudo systemctl stop robot")
os.system("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value")
os.system("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value")
MainWindow = CalibrationTool('MiniPupper Calibration Tool',800,500)
MainWindow.readCalibrationFile()
hardware_interface = HardwareInterface()
try:
_thread.start_new_thread( updateServoValue, ( MainWindow, hardware_interface,) )
except:
print ('Thread Error')
MainWindow.runMainWindow()
MainWindow.stopMainWindow()
os.system("sudo systemctl start robot")
os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value")
os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value")
| 14,538 | Python | 34.987624 | 147 | 0.554684 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/run_robot.py | import os
import sys
import threading
import time
import numpy as np
from PIL import Image
from multiprocessing import Process
import multiprocessing
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang.LCD.ST7789 import ST7789
from Mangdang.LCD.gif import AnimatedGif
from src.Controller import Controller
from src.JoystickInterface import JoystickInterface
from src.State import State
from pupper.MovementGroup import MovementLib
from src.MovementScheme import MovementScheme
from pupper.HardwareInterface import HardwareInterface
from pupper.Config import Configuration
from pupper.Kinematics import four_legs_inverse_kinematics
quat_orientation = np.array([1, 0, 0, 0])
cartoons_folder = "/home/ubuntu/Robotics/QuadrupedRobot/Mangdang/LCD/cartoons/"
current_show = ""
with open("/home/ubuntu/.hw_version", "r") as hw_f:
hw_version = hw_f.readline()
if hw_version == 'P1\n':
disp = ST7789(14, 15, 47)
else :
disp = ST7789(27, 24, 26)
def pic_show(disp, pic_name, _lock):
""" Show the specify picture
Parameter:
disp : display instance
pic_name : picture name to show
Return : None
"""
if pic_name == "":
return
global current_show
if pic_name == current_show:
return
image=Image.open(cartoons_folder + pic_name)
image.resize((320,240))
_lock.acquire()
disp.display(image)
_lock.release()
current_show = pic_name
def animated_thr_fun(_disp, duration, is_connect, current_leg, _lock):
"""
The thread funcation to show sleep animated gif
Parameter: None
Returen: None
"""
try:
gif_player = AnimatedGif(_disp, width=320, height=240, folder=cartoons_folder)
last_time = time.time()
last_joint_angles = np.zeros(3)
while True:
if is_connect.value == 1 :
#if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1]) and (current_leg[2]==last_joint_angles[2])) == False :
if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1])) == False :
last_time = time.time()
last_joint_angles[0] = current_leg[0]
last_joint_angles[1] = current_leg[1]
#last_joint_angles[2] = current_leg[2]
if (time.time() - last_time) > duration :
_lock.acquire()
gif_player.play()
_lock.release()
time.sleep(0.5)
else :
last_time = time.time()
time.sleep(1.5)
except KeyboardInterrupt:
_lock.release()
pass
def cmd_dump(cmd):
"""
debug interface to show all info about PS4 command
Parameter: None
return : None
"""
print("\nGet PS4 command :")
print("horizontal_velocity: ", cmd.horizontal_velocity)
print("yaw_rate ", cmd.yaw_rate)
print("height", cmd.height)
print("pitch ", cmd.pitch)
print("roll ", cmd.roll)
print("activation ", cmd.activation)
print("hop_event ", cmd.hop_event)
print("trot_event ", cmd.trot_event)
print("activate_event ", cmd.activate_event)
def main():
"""Main program
"""
# Create config
config = Configuration()
hardware_interface = HardwareInterface()
# show logo
global disp
disp.begin()
disp.clear()
image=Image.open(cartoons_folder + "logo.png")
image.resize((320,240))
disp.display(image)
shutdown_counter = 0 # counter for shuudown cmd
# Start animated process
duration = 10
is_connect = multiprocessing.Value('l', 0)
current_leg = multiprocessing.Array('d', [0, 0, 0])
lock = multiprocessing.Lock()
animated_process = Process(target=animated_thr_fun, args=(disp, duration, is_connect, current_leg, lock))
#animated_process.start()
#Create movement group scheme
movement_ctl = MovementScheme(MovementLib)
# Create controller and user input handles
controller = Controller(
config,
four_legs_inverse_kinematics,
)
state = State()
print("Creating joystick listener...")
joystick_interface = JoystickInterface(config)
print("Done.")
last_loop = time.time()
print("Summary of gait parameters:")
print("overlap time: ", config.overlap_time)
print("swing time: ", config.swing_time)
print("z clearance: ", config.z_clearance)
print("x shift: ", config.x_shift)
# Wait until the activate button has been pressed
while True:
print("Waiting for L1 to activate robot.")
while True:
command = joystick_interface.get_command(state)
joystick_interface.set_color(config.ps4_deactivated_color)
if command.activate_event == 1:
break
time.sleep(0.1)
print("Robot activated.")
is_connect.value = 1
joystick_interface.set_color(config.ps4_color)
pic_show(disp, "walk.png", lock)
while True:
now = time.time()
if now - last_loop < config.dt:
continue
last_loop = time.time()
# Parse the udp joystick commands and then update the robot controller's parameters
command = joystick_interface.get_command(state)
#cmd_dump(command)
_pic = "walk.png" if command.yaw_rate ==0 else "turnaround.png"
if command.trot_event == True:
_pic = "walk_r1.png"
pic_show(disp, _pic, lock)
if command.activate_event == 1:
is_connect.value = 0
pic_show(disp, "notconnect.png", lock)
print("Deactivating Robot")
break
state.quat_orientation = quat_orientation
# movement scheme
movement_switch = command.dance_switch_event
gait_state = command.trot_event
dance_state = command.dance_activate_event
shutdown_signal = command.shutdown_signal
#shutdown counter
if shutdown_signal == True:
shutdown_counter = shutdown_counter + 1
# press shut dow button more 3s(0.015*200), shut down system
if shutdown_counter >= 200:
print('shutdown system now')
os.system('systemctl stop robot')
os.system('shutdown -h now')
# gait and movement control
if gait_state == True or dance_state == True: # if triger tort event, reset the movement number to 0
movement_ctl.resetMovementNumber()
movement_ctl.runMovementScheme(movement_switch)
food_location = movement_ctl.getMovemenLegsLocation()
attitude_location = movement_ctl.getMovemenAttitude()
robot_speed = movement_ctl.getMovemenSpeed()
controller.run(state,command,food_location,attitude_location,robot_speed)
# Update the pwm widths going to the servos
hardware_interface.set_actuator_postions(state.joint_angles)
current_leg[0]= state.joint_angles[0][0]
current_leg[1]= state.joint_angles[1][0]
#current_leg[2]= state.joint_angles[2][0]
try:
main()
except KeyboardInterrupt:
pass
| 7,553 | Python | 33.81106 | 158 | 0.60572 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/MovementScheme.py | from ActuatorControl import ActuatorControl
LocationStanding = [[ 0.06,0.06,-0.06,-0.06],[-0.05, 0.05,-0.05,0.05],[ -0.07,-0.07,-0.07,-0.07]]
DeltLocationMax = 0.001
AttitudeMinMax = [[-20,20],[-20,20],[-100,100]]
class SequenceInterpolation:
def __init__(self,name,dimension):
self.Name = name
self.Dimension = dimension
self.InterpolationNumber = 1
self.ExecuteTick = 0
self.SequenceExecuteCounter = 0
self.PhaseNumberMax = 1
self.SequencePoint = [[0,0,0]]
# interpolation point data
self.PointPhaseStart = 0
self.PointPhaseStop = 1
self.TnterpolationDelt = [0,0,0]
self.PointNow = [0,0,0]
self.PointPrevious = [0,0,0]
def setCycleType(self,cycle_type,cycle_index):
if cycle_type == 'Forever':
self.SequenceExecuteCounter = 9999
elif cycle_type == 'Multiple':
self.SequenceExecuteCounter = cycle_index
else:
self.SequenceExecuteCounter = 1
return True
def setInterpolationNumber(self,interpolation_number):
self.InterpolationNumber = interpolation_number
return True
def setSequencePoint(self,sequence):
self.SequencePoint = sequence
self.PhaseNumberMax = len(sequence)
# init now and pre point phase
for xyz in range(self.Dimension):
self.PointNow[xyz] = sequence[0][xyz]
self.PointPrevious[xyz] = sequence[0][xyz]
# init start point phase
self.PointPhaseStart = 0
# init stop point phase
self.PointPhaseStop = self.PointPhaseStart + 1
if self.PointPhaseStop >= len(sequence):
self.PointPhaseStop = self.PointPhaseStart
return True
def updatePointPhase(self):
# update start point phase
self.PointPhaseStart = self.PointPhaseStart + 1
if self.PointPhaseStart >= self.PhaseNumberMax:
if self.SequenceExecuteCounter >0:
self.PointPhaseStart = 0
else:
self.SequenceExecuteCounter = 0
self.PointPhaseStart = self.PointPhaseStart - 1
# update stop point phase
self.PointPhaseStop = self.PointPhaseStart + 1
if self.PointPhaseStop >= self.PhaseNumberMax:
self.SequenceExecuteCounter = self.SequenceExecuteCounter - 1
if self.SequenceExecuteCounter >0:
self.PointPhaseStop = 0
else:
self.SequenceExecuteCounter = 0
self.PointPhaseStop = self.PointPhaseStop - 1
self.PointPhaseStop = 0
return True
def updateInterpolationDelt(self):
#get start and stop point
point_start = self.SequencePoint[self.PointPhaseStart]
point_stop = self.SequencePoint[self.PointPhaseStop]
for xyz in range(self.Dimension):
diff = point_stop[xyz] - point_start[xyz]
self.TnterpolationDelt[xyz] = - diff/self.InterpolationNumber
return True
def getNewPoint(self):
#update movement tick
self.ExecuteTick = self.ExecuteTick + 1
if self.ExecuteTick >= self.InterpolationNumber:
self.ExecuteTick = 0
self.updatePointPhase()
self.updateInterpolationDelt()
self.PointNow[0] = self.PointPrevious[0] + self.TnterpolationDelt[0]
self.PointNow[1] = self.PointPrevious[1] + self.TnterpolationDelt[1]
self.PointNow[2] = self.PointPrevious[2] + self.TnterpolationDelt[2]
self.PointPrevious = self.PointNow
return self.PointNow
class Movements:
def __init__(self,name,speed_enable,attitude_enable,legs_enable,actuator_enable):
self.MovementName = name
self.SpeedEnable = speed_enable
self.AttitudeEnable = attitude_enable
self.LegsEnable = legs_enable
self.ActuatorEnable = actuator_enable
self.ExitToStand = True
self.SpeedMovements = SequenceInterpolation('speed',2)
self.AttitudeMovements = SequenceInterpolation('attitude',3)
self.LegsMovements = []
self.LegsMovements.append(SequenceInterpolation('leg1',3))
self.LegsMovements.append(SequenceInterpolation('leg2',3))
self.LegsMovements.append(SequenceInterpolation('leg3',3))
self.LegsMovements.append(SequenceInterpolation('leg4',3))
self.ActuatorsMovements = SequenceInterpolation('actuators',1)
# init state value
self.SpeedInit = [0,0,0] # x, y speed
self.AttitudeInit = [0,0,0] # roll pitch yaw rate
self.LegsLocationInit = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs
self.ActuatorsAngleInit = [0,0,0] # angle for 3 actuators
# output
self.SpeedOutput = [0,0,0] # x, y speed
self.AttitudeOutput = [0,0,0] # roll pitch yaw rate
self.LegsLocationOutput = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs
self.ActuatorsAngleOutput = [0,0,0] # angle for 3 actuators
def setInterpolationNumber(self,number):
self.ActuatorsMovements.setInterpolationNumber(number)
for leg in range(4):
self.LegsMovements[leg].setInterpolationNumber(number)
self.AttitudeMovements.setInterpolationNumber(number)
self.SpeedMovements.setInterpolationNumber(number)
return True
def setExitstate(self,state):
if state != 'Stand':
self.ExitToStand = False
return True
def setSpeedSequence(self,sequence,cycle_type,cycle_index):
self.SpeedMovements.setSequencePoint(sequence)
self.SpeedMovements.setCycleType(cycle_type,cycle_index)
self.SpeedInit = sequence[0]
def setAttitudeSequence(self,sequence,cycle_type,cycle_index):
self.AttitudeMovements.setSequencePoint(sequence)
self.AttitudeMovements.setCycleType(cycle_type,cycle_index)
self.AttitudeInit = sequence[0]
def setLegsSequence(self,sequence,cycle_type,cycle_index):
for leg in range(4):
self.LegsMovements[leg].setSequencePoint(sequence[leg])
self.LegsMovements[leg].setCycleType(cycle_type,cycle_index)
# init location
self.LegsLocationInit[0][leg] = sequence[leg][0][0]
self.LegsLocationInit[1][leg] = sequence[leg][0][1]
self.LegsLocationInit[2][leg] = sequence[leg][0][2]
def setActuatorsSequence(self,sequence,cycle_type,cycle_index):
self.ActuatorsMovements.setSequencePoint(sequence)
self.ActuatorsMovements.setCycleType(cycle_type,cycle_index)
self.ActuatorsAngleInit = sequence[0]
def runMovementSequence(self):
if self.SpeedEnable == 'SpeedEnable':
self.SpeedOutput = self.SpeedMovements.getNewPoint()
if self.AttitudeEnable == 'AttitudeEnable':
self.AttitudeOutput = self.AttitudeMovements.getNewPoint()
if self.LegsEnable == 'LegsEnable':
for leg in range(4):
leg_loaction = self.LegsMovements[leg].getNewPoint()
for xyz in range(3):
self.LegsLocationOutput[xyz][leg] = leg_loaction[xyz]
if self.ActuatorEnable == 'ActuatorEnable':
self.ActuatorsAngleOutput = self.ActuatorsMovements.getNewPoint()
def getSpeedOutput(self, state = 'Normal'):
if state == 'Init':
return self.SpeedInit
else:
return self.SpeedOutput
def getAttitudeOutput(self, state = 'Normal'):
if state == 'Init':
return self.AttitudeInit
else:
return self.AttitudeOutput
def getLegsLocationOutput(self, state = 'Normal'):
if state == 'Init':
return self.LegsLocationInit
else:
return self.LegsLocationOutput
def getActuatorsAngleOutput(self, state = 'Normal'):
if state == 'Init':
return self.ActuatorsAngleInit
else:
return self.ActuatorsAngleOutput
def getMovementName(self):
return self.MovementName
class MovementScheme:
def __init__(self,movements_lib):
self.movements_lib = movements_lib
self.movements_now = movements_lib[0]
self.movements_pre = movements_lib[0]
self.movement_now_name = movements_lib[0].getMovementName()
self.movement_now_number = 0
self.ststus = 'Movement' # 'Entry' 'Movement' 'Exit'
self.entry_down = False
self.exit_down = False
self.tick = 0
self.legs_location_pre = LocationStanding
self.legs_location_now = LocationStanding
self.attitude_pre = [0,0,0]
self.attitude_now = [0,0,0]
self.speed_pre = [0,0,0]
self.speed_now = [0,0,0]
self.actuators_pre = [0,0,0]
self.actuators_now = [0,0,0]
self.actuator = []
self.actuator.append(ActuatorControl(1))
self.actuator.append(ActuatorControl(2))
self.actuator.append(ActuatorControl(3))
def updateMovementType(self):
self.movements_pre = self.movements_lib[self.movement_now_number]
self.movement_now_number = self.movement_now_number + 1
if self.movement_now_number>= len(self.movements_lib):
self.movement_now_number = 0
self.entry_down = False
self.exit_down = False
self.movements_now = self.movements_lib[self.movement_now_number]
return self.movements_now.getMovementName()
def resetMovementNumber(self):
self.movements_pre = self.movements_lib[self.movement_now_number]
self.movement_now_number = 0
self.entry_down = False
self.exit_down = False
self.movements_now = self.movements_lib[0]
return True
def updateMovement(self,movement_type):
# movement state transition
if movement_type != self.movement_now_name:
self.ststus = 'Exit'
elif(self.entry_down):
self.ststus = 'Movement'
elif(self.exit_down):
self.ststus = 'Entry'
self.movement_now_name = movement_type
# update system tick
self.tick = self.tick+ 1
# movement execute
if self.ststus == 'Entry':
location_ready = self.movements_now.getLegsLocationOutput('Init')
self.legs_location_now,self.entry_down = self.updateMovementGradient(self.legs_location_pre,location_ready)
self.legs_location_pre = self.legs_location_now
if self.ststus == 'Exit':
if self.movements_pre.ExitToStand == False:
self.legs_location_now,self.exit_down = self.updateMovementGradient(self.location_pre,LocationStanding)
self.legs_location_pre = self.legs_location_now
else:
self.legs_location_now = self.legs_location_pre
self.exit_down = True
elif self.ststus == 'Movement':
self.updateMovemenScheme(self.tick)
self.legs_location_pre = self.legs_location_now
self.attitude_pre = self.attitude_now
return self.legs_location_now
def updateMovementGradient(self,location_now,location_target):
loaction_gradient = location_now
gradient_done = False
gradient_done_counter = 0
#legs gradient
for xyz_index in range(3):
for leg_index in range(4):
diff = location_now[xyz_index][leg_index] - location_target[xyz_index][leg_index]
if diff > DeltLocationMax:
loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] - DeltLocationMax
elif diff < -DeltLocationMax:
loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] + DeltLocationMax
else :
loaction_gradient[xyz_index][leg_index] = location_target[xyz_index][leg_index]
gradient_done_counter = gradient_done_counter + 1
# movement gradient is down
if gradient_done_counter == 12:
gradient_done = True
return loaction_gradient, gradient_done
def updateMovemenScheme(self,tick):
# run movement
self.movements_now.runMovementSequence()
# legs movement
self.legs_location_now = self.movements_now.getLegsLocationOutput('normal')
# speed movement
self.speed_now = self.movements_now.getSpeedOutput('normal')
# attitude movement
self.attitude_now = self.movements_now.getAttitudeOutput('normal')
# attitude movement
self.actuators_now = self.movements_now.getActuatorsAngleOutput('normal')
# attitude process
'''
for rpy in range(3):
#limite attitude angle
if attitude_now[rpy] < AttitudeMinMax[rpy][0]:
attitude_now[rpy] = AttitudeMinMax[rpy][0]
elif attitude_now[rpy] > AttitudeMinMax[rpy][1]:
attitude_now[rpy] = AttitudeMinMax[rpy][1]
'''
# speed process
return True
def runMovementScheme(self,transition):
# update movement
movement_name = ''
if transition == True:
movement_name = self.updateMovementType()
self.updateMovement(movement_name)
return True
def getMovemenSpeed(self):
speed_now = [0,0,0]
for xyz in range(3):
speed_now[xyz] = -self.speed_now[xyz]
return speed_now
def getMovemenLegsLocation(self):
return self.legs_location_now
def getMovemenAttitude(self):
attitude_now_rad = [0,0,0]
for rpy in range(3):
#angle to radin
attitude_now_rad[rpy] = -self.attitude_now[rpy] / 57.3
return attitude_now_rad
def getMovemenActuators(self):
return self.actuators_now
| 14,291 | Python | 31.930876 | 130 | 0.607865 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/ActuatorControl.py | import os
import sys
import time
class ActuatorControl:
def __init__(self,pwm_number):
self.pwm_number = pwm_number
def updateDutyCycle(self,angle):
duty_cycle = int((1.11*angle+50)*10000)
return duty_cycle
def updateActuatorAngle(self,angle):
if self.pwm_number == 1:
actuator_name = 'pwm1'
elif self.pwm_number == 2:
actuator_name = 'pwm2'
elif self.pwm_number == 3:
actuator_name = 'pwm3'
duty_cycle = self.updateDutyCycle(angle)
file_node = '/sys/class/pwm/pwmchip0/' + actuator_name+ '/duty_cycle'
f = open(file_node, "w")
f.write(str(duty_cycle))
#test = ActuatorControl(3)
#time.sleep(10)
#for index in range(30):
# test.updateActuatorAngle(index*3)
# time.sleep(0.1)
# test.updateActuatorAngle(0)
| 856 | Python | 22.162162 | 77 | 0.600467 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/ServoCalibration.py | # WARNING: This file is machine generated. Edit at your own risk.
import numpy as np
MICROS_PER_RAD = 11.111 * 180.0 / np.pi
| 128 | Python | 17.428569 | 65 | 0.703125 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/MovementGroup.py |
from src.MovementScheme import Movements
def appendDanceMovement():
'''
#demo 1
dance_scheme = Movements('stand','SpeedDisable','AttitudeDisable','LegsEnable','ActuatorDisable')
dance_scheme.setExitstate('Stand')
dance_all_legs = []
dance_all_legs.append([[ 0.06,-0.05,-0.065]]) # leg1
dance_all_legs.append([[ 0.06, 0.05,-0.065]]) # leg2
dance_all_legs.append([[-0.06,-0.05,-0.065]]) # leg3
dance_all_legs.append([[-0.06, 0.05,-0.065]]) # leg4
dance_scheme.setInterpolationNumber(50)
dance_scheme.setLegsSequence(dance_all_legs,'Forever',5)
MovementLib.append(dance_scheme) # append dance
'''
#demo 2
dance_scheme = Movements('push-up','SpeedEnable','AttitudeDisable','LegsEnable','ActuatorDisable')
dance_scheme.setExitstate('Stand')
dance_all_legs = []
dance_all_legs.append([[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.07],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04]]) # leg1
dance_all_legs.append([[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.07],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04]]) # leg2
dance_all_legs.append([[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.07],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04]]) # leg3
dance_all_legs.append([[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.07],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04]]) # leg4
dance_speed = [[0,0,0],[0,0,0],[0,0,0],[0.25,0,0,0],[0.25,0,0,0]] # speed_, speed_y, no_use
dance_attitude = [[0,0,0],[10,0,0],[0,0,0]] # roll, pitch, yaw rate
dance_scheme.setInterpolationNumber(70)
dance_scheme.setLegsSequence(dance_all_legs,'Forever',1)
dance_scheme.setSpeedSequence(dance_speed,'Forever',1)
dance_scheme.setAttitudeSequence(dance_attitude,'Forever',1)
MovementLib.append(dance_scheme) # append dance
MovementLib = []
appendDanceMovement()
| 1,955 | Python | 38.918367 | 137 | 0.588235 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/HardwareInterface.py | import os
import sys
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot/")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang import PWMController
from pupper.Config import ServoParams, PWMParams
#from __future__ import division
import numpy as np
class HardwareInterface:
def __init__(self):
self.pwm_params = PWMParams()
self.servo_params = ServoParams()
def set_actuator_postions(self, joint_angles):
send_servo_commands(self.pwm_params, self.servo_params, joint_angles)
def set_actuator_position(self, joint_angle, axis, leg):
send_servo_command(self.pwm_params, self.servo_params, joint_angle, axis, leg)
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams object
Returns
-------
float
PWM duty cycle corresponding to the pulse width
"""
pulsewidth_micros = int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range)
if np.isnan(pulsewidth_micros):
return 0
return int(np.clip(pulsewidth_micros, 0, 4096))
def angle_to_pwm(angle, servo_params, axis_index, leg_index):
"""Converts a desired servo angle into the corresponding PWM command
Parameters
----------
angle : float
Desired servo angle, relative to the vertical (z) axis
servo_params : ServoParams
ServoParams object
axis_index : int
Specifies which joint of leg to control. 0 is abduction servo, 1 is inner hip servo, 2 is outer hip servo.
leg_index : int
Specifies which leg to control. 0 is front-right, 1 is front-left, 2 is back-right, 3 is back-left.
Returns
-------
float
PWM width in microseconds
"""
angle_deviation = (
angle - servo_params.neutral_angles[axis_index, leg_index]
) * servo_params.servo_multipliers[axis_index, leg_index]
pulse_width_micros = (
servo_params.neutral_position_pwm
+ servo_params.micros_per_rad * angle_deviation
)
return pulse_width_micros
def angle_to_duty_cycle(angle, pwm_params, servo_params, axis_index, leg_index):
duty_cycle_f = angle_to_pwm(angle, servo_params, axis_index, leg_index) * 1e3
if np.isnan(duty_cycle_f):
return 0
return int(duty_cycle_f)
def initialize_pwm(pi, pwm_params):
pi.set_pwm_freq(pwm_params.freq)
def send_servo_commands(pwm_params, servo_params, joint_angles):
for leg_index in range(4):
for axis_index in range(3):
duty_cycle = angle_to_duty_cycle(
joint_angles[axis_index, leg_index],
pwm_params,
servo_params,
axis_index,
leg_index,
)
# write duty_cycle to pwm linux kernel node
file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis_index, leg_index]) + "/duty_cycle"
f = open(file_node, "w")
f.write(str(duty_cycle))
def send_servo_command(pwm_params, servo_params, joint_angle, axis, leg):
duty_cycle = angle_to_duty_cycle(joint_angle, pwm_params, servo_params, axis, leg)
file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis, leg]) + "/duty_cycle"
f = open(file_node, "w")
f.write(str(duty_cycle))
def deactivate_servos(pi, pwm_params):
for leg_index in range(4):
for axis_index in range(3):
pi.set_pwm(pwm_params.pins[axis_index, leg_index], 0, 0)
| 3,798 | Python | 33.225225 | 129 | 0.639547 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/PS4Joystick.py |
import sys
import time
import subprocess
import math
from threading import Thread
from collections import OrderedDict, deque
from ds4drv.actions import ActionRegistry
from ds4drv.backends import BluetoothBackend, HidrawBackend
from ds4drv.config import load_options
from ds4drv.daemon import Daemon
from ds4drv.eventloop import EventLoop
from ds4drv.exceptions import BackendError
from ds4drv.action import ReportAction
from ds4drv.__main__ import create_controller_thread
class ActionShim(ReportAction):
""" intercepts the joystick report"""
def __init__(self, *args, **kwargs):
super(ActionShim, self).__init__(*args, **kwargs)
self.timer = self.create_timer(0.02, self.intercept)
self.values = None
self.timestamps = deque(range(10), maxlen=10)
def enable(self):
self.timer.start()
def disable(self):
self.timer.stop()
self.values = None
def load_options(self, options):
pass
def deadzones(self,values):
deadzone = 0.14
if math.sqrt( values['left_analog_x'] ** 2 + values['left_analog_y'] ** 2) < deadzone:
values['left_analog_y'] = 0.0
values['left_analog_x'] = 0.0
if math.sqrt( values['right_analog_x'] ** 2 + values['right_analog_y'] ** 2) < deadzone:
values['right_analog_y'] = 0.0
values['right_analog_x'] = 0.0
return values
def intercept(self, report):
new_out = OrderedDict()
for key in report.__slots__:
value = getattr(report, key)
new_out[key] = value
for key in ["left_analog_x", "left_analog_y",
"right_analog_x", "right_analog_y",
"l2_analog", "r2_analog"]:
new_out[key] = 2*( new_out[key]/255 ) - 1
new_out = self.deadzones(new_out)
self.timestamps.append(new_out['timestamp'])
if len(set(self.timestamps)) <= 1:
self.values = None
else:
self.values = new_out
return True
class Joystick:
def __init__(self):
self.thread = None
options = load_options()
if options.hidraw:
raise ValueError("HID mode not supported")
backend = HidrawBackend(Daemon.logger)
else:
subprocess.run(["hciconfig", "hciX", "up"])
backend = BluetoothBackend(Daemon.logger)
backend.setup()
self.thread = create_controller_thread(1, options.controllers[0])
self.thread.controller.setup_device(next(backend.devices))
self.shim = ActionShim(self.thread.controller)
self.thread.controller.actions.append(self.shim)
self.shim.enable()
self._color = (None, None, None)
self._rumble = (None, None)
self._flash = (None, None)
# ensure we get a value before returning
while self.shim.values is None:
pass
def close(self):
if self.thread is None:
return
self.thread.controller.exit("Cleaning up...")
self.thread.controller.loop.stop()
def __del__(self):
self.close()
@staticmethod
def map(val, in_min, in_max, out_min, out_max):
""" helper static method that helps with rescaling """
in_span = in_max - in_min
out_span = out_max - out_min
value_scaled = float(val - in_min) / float(in_span)
value_mapped = (value_scaled * out_span) + out_min
if value_mapped < out_min:
value_mapped = out_min
if value_mapped > out_max:
value_mapped = out_max
return value_mapped
def get_input(self):
""" returns ordered dict with state of all inputs """
if self.thread.controller.error:
raise IOError("Encountered error with controller")
if self.shim.values is None:
raise TimeoutError("Joystick hasn't updated values in last 200ms")
return self.shim.values
def led_color(self, red=0, green=0, blue=0):
""" set RGB color in range 0-255"""
color = (int(red),int(green),int(blue))
if( self._color == color ):
return
self._color = color
self.thread.controller.device.set_led( *self._color )
def rumble(self, small=0, big=0):
""" rumble in range 0-255 """
rumble = (int(small),int(big))
if( self._rumble == rumble ):
return
self._rumble = rumble
self.thread.controller.device.rumble( *self._rumble )
def led_flash(self, on=0, off=0):
""" flash led: on and off times in range 0 - 255 """
flash = (int(on),int(off))
if( self._flash == flash ):
return
self._flash = flash
if( self._flash == (0,0) ):
self.thread.controller.device.stop_led_flash()
else:
self.thread.controller.device.start_led_flash( *self._flash )
if __name__ == "__main__":
j = Joystick()
while 1:
for key, value in j.get_input().items():
print(key,value)
print()
time.sleep(0.1)
| 5,123 | Python | 28.28 | 96 | 0.579934 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/mac_joystick.py | import os
import pygame
from UDPComms import Publisher
os.environ["SDL_VIDEODRIVER"] = "dummy"
drive_pub = Publisher(8830)
arm_pub = Publisher(8410)
pygame.display.init()
pygame.joystick.init()
# wait until joystick is connected
while 1:
try:
pygame.joystick.Joystick(0).init()
break
except pygame.error:
pygame.time.wait(500)
# Prints the joystick's name
JoyName = pygame.joystick.Joystick(0).get_name()
print("Name of the joystick:")
print(JoyName)
# Gets the number of axes
JoyAx = pygame.joystick.Joystick(0).get_numaxes()
print("Number of axis:")
print(JoyAx)
while True:
pygame.event.pump()
forward = (pygame.joystick.Joystick(0).get_axis(3))
twist = (pygame.joystick.Joystick(0).get_axis(2))
on = (pygame.joystick.Joystick(0).get_button(5))
if on:
print({'f':-150*forward,'t':-80*twist})
drive_pub.send({'f':-150*forward,'t':-80*twist})
else:
drive_pub.send({'f':0,'t':0})
pygame.time.wait(100)
| 994 | Python | 22.139534 | 56 | 0.662978 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='PS4Joystick',
version='2.0',
py_modules=['PS4Joystick'],
description='Interfaces with a PS4 joystick over Bluetooth',
author='Michal Adamkiewicz',
author_email='[email protected]',
url='https://github.com/stanfordroboticsclub/JoystickUDP',
)
| 356 | Python | 24.499998 | 66 | 0.679775 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/local_or_remote.py | import os
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while 1:
if not GPIO.input(21):
print("eanbling joystick")
os.system("sudo systemctl start ds4drv")
os.system("sudo systemctl start joystick")
#os.system("screen sudo python3 /home/pi/RoverCommand/joystick.py")
else:
os.system("sudo systemctl stop ds4drv")
os.system("sudo systemctl stop joystick")
print("not eanbling joystick")
time.sleep(5)
| 566 | Python | 27.349999 | 75 | 0.673145 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/rover_example.py | from UDPComms import Publisher
from PS4Joystick import Joystick
import time
from enum import Enum
drive_pub = Publisher(8830)
arm_pub = Publisher(8410)
j=Joystick()
MODES = Enum('MODES', 'SAFE DRIVE ARM')
mode = MODES.SAFE
while True:
values = j.get_input()
if( values['button_ps'] ):
if values['dpad_up']:
mode = MODES.DRIVE
j.led_color(red=255)
elif values['dpad_right']:
mode = MODES.ARM
j.led_color(blue=255)
elif values['dpad_down']:
mode = MODES.SAFE
j.led_color(green=255)
# overwrite when swiching modes to prevent phantom motions
values['dpad_down'] = 0
values['dpad_up'] = 0
values['dpad_right'] = 0
values['dpad_left'] = 0
if mode == MODES.DRIVE:
forward_left = - values['left_analog_y']
forward_right = - values['right_analog_y']
twist = values['right_analog_x']
on_right = values['button_r1']
on_left = values['button_l1']
l_trigger = values['l2_analog']
if on_left or on_right:
if on_right:
forward = forward_right
else:
forward = forward_left
slow = 150
fast = 500
max_speed = (fast+slow)/2 + l_trigger*(fast-slow)/2
out = {'f':(max_speed*forward),'t':-150*twist}
drive_pub.send(out)
print(out)
else:
drive_pub.send({'f':0,'t':0})
elif mode == MODES.ARM:
r_forward = - values['right_analog_y']
r_side = values['right_analog_x']
l_forward = - values['left_analog_y']
l_side = values['left_analog_x']
r_shoulder = values['button_r1']
l_shoulder = values['button_l1']
r_trigger = values['r2_analog']
l_trigger = values['l2_analog']
square = values['button_square']
cross = values['button_cross']
circle = values['button_circle']
triangle = values['button_triangle']
PS = values['button_ps']
# hat directions could be reversed from previous version
hat = [ values["dpad_up"] - values["dpad_down"],
values["dpad_right"] - values["dpad_left"] ]
reset = (PS == 1) and (triangle == 1)
reset_dock = (PS==1) and (square ==1)
target_vel = {"x": l_side,
"y": l_forward,
"z": (r_trigger - l_trigger)/2,
"yaw": r_side,
"pitch": r_forward,
"roll": (r_shoulder - l_shoulder),
"grip": cross - square,
"hat": hat,
"reset": reset,
"resetdock":reset_dock,
"trueXYZ": circle,
"dock": triangle}
print(target_vel)
arm_pub.send(target_vel)
elif mode == MODES.SAFE:
# random stuff to demo color features
triangle = values['button_triangle']
square = values['button_square']
j.rumble(small = 255*triangle, big = 255*square)
r2 = values['r2_analog']
r2 = j.map( r2, -1, 1, 0 ,255)
j.led_color( green = 255, blue = r2)
else:
pass
time.sleep(0.1)
| 3,285 | Python | 26.847457 | 66 | 0.506849 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/spot_ars.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../../')
from spotmicro.util.gui import GUI
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
import time
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
# Multiprocessing package for python
# Parallelization improvements based on:
# https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
import multiprocessing as mp
from multiprocessing import Pipe
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Trainer."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-nc",
"--NoContactSensing",
help="Disable Contact Sensing",
action='store_true')
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
parser.add_argument("-s", "--Seed", help="Seed (Default: 0).")
ARGS = parser.parse_args()
# Messages for Pipe
_RESET = 1
_CLOSE = 2
_EXPLORE = 3
def main():
""" The main() function. """
# Hold mp pipes
mp.freeze_support()
print("STARTING SPOT TRAINING ENV")
seed = 0
if ARGS.Seed:
seed = int(ARGS.Seed)
print("SEED: {}".format(seed))
max_timesteps = 4e6
eval_freq = 1e1
save_model = True
file_name = "spot_ars_"
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.NoContactSensing:
contacts = False
else:
contacts = True
if ARGS.DontRandomize:
env_randomizer = None
rand_name = "norand_"
else:
env_randomizer = SpotEnvRandomizer()
rand_name = "rand_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if contacts:
models_path = os.path.join(my_path, "../models/contact")
else:
models_path = os.path.join(my_path, "../models/no_contact")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=False,
on_rack=False,
height_field=height_field,
draw_foot_path=False,
contacts=contacts,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
env.reset()
g_u_i = GUI(env.spot.quadruped)
spot = SpotModel()
T_bf = spot.WorldToFoot
bz_step = BezierStepper(dt=env._time_step)
bzg = BezierGait(dt=env._time_step)
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim, seed=seed)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, bz_step, bzg, spot)
agent_num = 0
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
env.reset(agent.desired_velocity, agent.desired_rate)
episode_reward = 0
episode_timesteps = 0
episode_num = 0
# Create mp pipes
num_processes = policy.num_deltas
processes = []
childPipes = []
parentPipes = []
# Store mp pipes
for pr in range(num_processes):
parentPipe, childPipe = Pipe()
parentPipes.append(parentPipe)
childPipes.append(childPipe)
# Start multiprocessing
# Start multiprocessing
for proc_num in range(num_processes):
p = mp.Process(target=ParallelWorker,
args=(childPipes[proc_num], env, state_dim))
p.start()
processes.append(p)
print("STARTED SPOT TRAINING ENV")
t = 0
while t < (int(max_timesteps)):
# Maximum timesteps per rollout
episode_reward, episode_timesteps = agent.train_parallel(parentPipes)
t += episode_timesteps
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {:.2f} REWARD PER STEP: {:.2f}"
.format(t + 1, episode_num, episode_timesteps, episode_reward,
episode_reward / float(episode_timesteps)))
# Store Results (concat)
if episode_num == 0:
res = np.array(
[[episode_reward, episode_reward / float(episode_timesteps)]])
else:
new_res = np.array(
[[episode_reward, episode_reward / float(episode_timesteps)]])
res = np.concatenate((res, new_res))
# Also Save Results So Far (Overwrite)
# Results contain 2D numpy array of total reward for each ep
# and reward per timestep for each ep
np.save(
results_path + "/" + str(file_name) + rand_name + "seed" +
str(seed), res)
# Evaluate episode
if (episode_num + 1) % eval_freq == 0:
if save_model:
agent.save(models_path + "/" + str(file_name) +
str(episode_num))
episode_num += 1
# Close pipes and hence envs
for parentPipe in parentPipes:
parentPipe.send([_CLOSE, "pay2"])
for p in processes:
p.join()
if __name__ == '__main__':
main()
| 6,299 | Python | 28.166667 | 101 | 0.600572 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/env_tester.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import copy
import sys
sys.path.append('../../')
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.Kinematics.LieAlgebra import RPY
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
# TESTING
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import time
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini Environment Tester (No Joystick)."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-r",
"--DebugRack",
help="Put Spot on an Elevated Rack",
action='store_true')
parser.add_argument("-p",
"--DebugPath",
help="Draw Spot's Foot Path",
action='store_true')
parser.add_argument("-ay",
"--AutoYaw",
help="Automatically Adjust Spot's Yaw",
action='store_true')
parser.add_argument("-ar",
"--AutoReset",
help="Automatically Reset Environment When Spot Falls",
action='store_true')
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING SPOT TEST ENV")
seed = 0
max_timesteps = 4e6
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
env = spotBezierEnv(render=True,
on_rack=on_rack,
height_field=height_field,
draw_foot_path=draw_foot_path,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
state = env.reset()
g_u_i = GUI(env.spot.quadruped)
spot = SpotModel()
T_bf0 = spot.WorldToFoot
T_bf = copy.deepcopy(T_bf0)
bzg = BezierGait(dt=env._time_step)
bz_step = BezierStepper(dt=env._time_step, mode=0)
action = env.action_space.sample()
FL_phases = []
FR_phases = []
BL_phases = []
BR_phases = []
FL_Elbow = []
yaw = 0.0
print("STARTED SPOT TEST ENV")
t = 0
while t < (int(max_timesteps)):
bz_step.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = bz_step.StateMachine(
)
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod = g_u_i.UserInput(
)
# Update Swing Period
bzg.Tswing = SwingPeriod
yaw = env.return_yaw()
P_yaw = 5.0
if ARGS.AutoYaw:
YawRate += -yaw * P_yaw
# print("YAW RATE: {}".format(YawRate))
# TEMP
bz_step.StepLength = StepLength
bz_step.LateralFraction = LateralFraction
bz_step.YawRate = YawRate
bz_step.StepVelocity = StepVelocity
contacts = state[-4:]
FL_phases.append(env.spot.LegPhases[0])
FR_phases.append(env.spot.LegPhases[1])
BL_phases.append(env.spot.LegPhases[2])
BR_phases.append(env.spot.LegPhases[3])
# Get Desired Foot Poses
T_bf = bzg.GenerateTrajectory(StepLength, LateralFraction, YawRate,
StepVelocity, T_bf0, T_bf,
ClearanceHeight, PenetrationDepth,
contacts)
joint_angles = spot.IK(orn, pos, T_bf)
FL_Elbow.append(np.degrees(joint_angles[0][-1]))
# for i, (key, Tbf_in) in enumerate(T_bf.items()):
# print("{}: \t Angle: {}".format(key, np.degrees(joint_angles[i])))
# print("-------------------------")
env.pass_joint_angles(joint_angles.reshape(-1))
# Get External Observations
env.spot.GetExternalObservations(bzg, bz_step)
# Step
state, reward, done, _ = env.step(action)
# print("IMU Roll: {}".format(state[0]))
# print("IMU Pitch: {}".format(state[1]))
# print("IMU GX: {}".format(state[2]))
# print("IMU GY: {}".format(state[3]))
# print("IMU GZ: {}".format(state[4]))
# print("IMU AX: {}".format(state[5]))
# print("IMU AY: {}".format(state[6]))
# print("IMU AZ: {}".format(state[7]))
# print("-------------------------")
if done:
print("DONE")
if ARGS.AutoReset:
env.reset()
# plt.plot()
# # plt.plot(FL_phases, label="FL")
# # plt.plot(FR_phases, label="FR")
# # plt.plot(BL_phases, label="BL")
# # plt.plot(BR_phases, label="BR")
# plt.plot(FL_Elbow, label="FL ELbow (Deg)")
# plt.xlabel("dt")
# plt.ylabel("value")
# plt.title("Leg Phases")
# plt.legend()
# plt.show()
# time.sleep(1.0)
t += 1
env.close()
print(joint_angles)
if __name__ == '__main__':
main()
| 6,407 | Python | 27.864865 | 135 | 0.547214 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/spot_ars_eval.py | #!/usr/bin/env python
import numpy as np
import sys
sys.path.append('../../')
from ars_lib.ars import ARSAgent, Normalizer, Policy
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Evaluator."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-nr",
"--DontRender",
help="Don't Render environment",
action='store_true')
parser.add_argument("-r",
"--DebugRack",
help="Put Spot on an Elevated Rack",
action='store_true')
parser.add_argument("-p",
"--DebugPath",
help="Draw Spot's Foot Path",
action='store_true')
parser.add_argument("-gui",
"--GUI",
help="Control The Robot Yourself With a GUI",
action='store_true')
parser.add_argument("-nc",
"--NoContactSensing",
help="Disable Contact Sensing",
action='store_true')
parser.add_argument("-a", "--AgentNum", help="Agent Number To Load")
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
parser.add_argument("-pp",
"--PlotPolicy",
help="Plot Policy Output after each Episode.",
action='store_true')
parser.add_argument("-ta",
"--TrueAction",
help="Plot Action as seen by the Robot.",
action='store_true')
parser.add_argument(
"-save",
"--SaveData",
help="Save the Policy Output to a .npy file in the results folder.",
action='store_true')
parser.add_argument("-s", "--Seed", help="Seed (Default: 0).")
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
if ARGS.Seed:
seed = ARGS.Seed
max_timesteps = 4e6
file_name = "spot_ars_"
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.NoContactSensing:
contacts = False
else:
contacts = True
if ARGS.DontRender:
render = False
else:
render = True
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if contacts:
models_path = os.path.join(my_path, "../models/contact")
else:
models_path = os.path.join(my_path, "../models/no_contact")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=render,
on_rack=on_rack,
height_field=height_field,
draw_foot_path=draw_foot_path,
contacts=contacts,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
env.reset()
spot = SpotModel()
bz_step = BezierStepper(dt=env._time_step)
bzg = BezierGait(dt=env._time_step)
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# to GUI or not to GUI
if ARGS.GUI:
gui = True
else:
gui = False
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, bz_step, bzg, spot, gui)
agent_num = 0
if ARGS.AgentNum:
agent_num = ARGS.AgentNum
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = np.inf
policy = agent.policy
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
t = 0
while t < (int(max_timesteps)):
episode_reward, episode_timesteps = agent.deployTG()
t += episode_timesteps
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, episode_timesteps, episode_reward))
episode_num += 1
# Plot Policy Output
if ARGS.PlotPolicy or ARGS.TrueAction or ARGS.SaveData:
if ARGS.TrueAction:
action_name = "robot_act"
action = np.array(agent.true_action_history)
else:
action_name = "agent_act"
action = np.array(agent.action_history)
if ARGS.SaveData:
if height_field:
terrain_name = "rough_"
else:
terrain_name = "flat_"
np.save(
results_path + "/" + "policy_out_" + terrain_name + action_name, action)
print("SAVED DATA")
ClearHeight_act = action[:, 0]
BodyHeight_act = action[:, 1]
Residuals_act = action[:, 2:]
plt.plot(ClearHeight_act,
label='Clearance Height Mod',
color='black')
plt.plot(BodyHeight_act,
label='Body Height Mod',
color='darkviolet')
# FL
plt.plot(Residuals_act[:, 0],
label='Residual: FL (x)',
color='limegreen')
plt.plot(Residuals_act[:, 1],
label='Residual: FL (y)',
color='lime')
plt.plot(Residuals_act[:, 2],
label='Residual: FL (z)',
color='green')
# FR
plt.plot(Residuals_act[:, 3],
label='Residual: FR (x)',
color='lightskyblue')
plt.plot(Residuals_act[:, 4],
label='Residual: FR (y)',
color='dodgerblue')
plt.plot(Residuals_act[:, 5],
label='Residual: FR (z)',
color='blue')
# BL
plt.plot(Residuals_act[:, 6],
label='Residual: BL (x)',
color='firebrick')
plt.plot(Residuals_act[:, 7],
label='Residual: BL (y)',
color='crimson')
plt.plot(Residuals_act[:, 8],
label='Residual: BL (z)',
color='red')
# BR
plt.plot(Residuals_act[:, 9],
label='Residual: BR (x)',
color='gold')
plt.plot(Residuals_act[:, 10],
label='Residual: BR (y)',
color='orange')
plt.plot(Residuals_act[:, 11],
label='Residual: BR (z)',
color='coral')
plt.xlabel("Epoch Iteration")
plt.ylabel("Action Value")
plt.title("Policy Output")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main()
| 8,583 | Python | 29.119298 | 96 | 0.518467 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/sac_eval.py | #!/usr/bin/env python
import numpy as np
from sac_lib import SoftActorCritic, NormalizedActions, ReplayBuffer, PolicyNetwork
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import gym
import torch
import os
import time
def main():
""" The main() function. """
print("STARTING MINITAUR TD3")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
file_name = "mini_td3_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = NormalizedActions(MinitaurBulletEnv(render=True))
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
hidden_dim = 256
policy = PolicyNetwork(state_dim, action_dim, hidden_dim)
replay_buffer_size = 1000000
replay_buffer = ReplayBuffer(replay_buffer_size)
sac = SoftActorCritic(policy=policy,
state_dim=state_dim,
action_dim=action_dim,
replay_buffer=replay_buffer)
policy_num = 2239999
if os.path.exists(models_path + "/" + file_name + str(policy_num) +
"_critic"):
print("Loading Existing Policy")
sac.load(models_path + "/" + file_name + str(policy_num))
policy = sac.policy_net
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Deterministic Policy Action
action = np.clip(policy.get_action(np.array(state)),
-max_action, max_action)
# rospy.logdebug("Selected Acton: {}".format(action))
# Perform action
next_state, reward, done, _ = env.step(action)
state = next_state
episode_reward += reward
# print("DT REWARD: {}".format(reward))
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
if __name__ == '__main__':
main()
| 3,153 | Python | 26.911504 | 83 | 0.595623 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/ars_eval.py | #!/usr/bin/env python
import numpy as np
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
file_name = "mini_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 3000
policy = agent.policy
# Evaluate untrained agent and init list for storage
evaluations = []
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
t = 0
while t < (int(max_timesteps)):
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deploy()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
env.close()
if __name__ == '__main__':
main()
| 2,662 | Python | 25.63 | 76 | 0.622089 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/spot_sac_eval.py | #!/usr/bin/env python
import numpy as np
from sac_lib import SoftActorCritic, NormalizedActions, ReplayBuffer, PolicyNetwork
import copy
from gym import spaces
import sys
sys.path.append('../../')
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
# TESTING
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING SPOT SAC")
# TRAINING PARAMETERS
seed = 0
max_timesteps = 4e6
batch_size = 256
eval_freq = 1e4
save_model = True
file_name = "spot_sac_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=True,
on_rack=False,
height_field=False,
draw_foot_path=False)
env = NormalizedActions(env)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
hidden_dim = 256
policy = PolicyNetwork(state_dim, action_dim, hidden_dim)
replay_buffer_size = 1000000
replay_buffer = ReplayBuffer(replay_buffer_size)
sac = SoftActorCritic(policy=policy,
state_dim=state_dim,
action_dim=action_dim,
replay_buffer=replay_buffer)
policy_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(policy_num) +
"_policy_net"):
print("Loading Existing Policy")
sac.load(models_path + "/" + file_name + str(policy_num))
policy = sac.policy_net
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
max_t_per_ep = 5000
# State Machine for Random Controller Commands
bz_step = BezierStepper(dt=0.01, mode=0)
# Bezier Gait Generator
bzg = BezierGait(dt=0.01)
# Spot Model
spot = SpotModel()
T_bf0 = spot.WorldToFoot
T_bf = copy.deepcopy(T_bf0)
BaseClearanceHeight = bz_step.ClearanceHeight
BasePenetrationDepth = bz_step.PenetrationDepth
print("STARTED SPOT SAC")
for t in range(int(max_timesteps)):
contacts = state[-4:]
t += 1
episode_timesteps += 1
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = bz_step.StateMachine(
)
env.spot.GetExternalObservations(bzg, bz_step)
# Read UPDATED state based on controls and phase
state = env.return_state()
action = sac.policy_net.get_action(state)
# Bezier params specced by action
CD_SCALE = 0.002
SLV_SCALE = 0.01
StepLength += action[0] * CD_SCALE
StepVelocity += action[1] * SLV_SCALE
LateralFraction += action[2] * SLV_SCALE
YawRate = action[3]
ClearanceHeight += action[4] * CD_SCALE
PenetrationDepth += action[5] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, bz_step.StepLength_LIMITS[0],
bz_step.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity, bz_step.StepVelocity_LIMITS[0],
bz_step.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
bz_step.LateralFraction_LIMITS[0],
bz_step.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, bz_step.YawRate_LIMITS[0],
bz_step.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
bz_step.ClearanceHeight_LIMITS[0],
bz_step.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
bz_step.PenetrationDepth_LIMITS[0],
bz_step.PenetrationDepth_LIMITS[1])
contacts = state[-4:]
# Get Desired Foot Poses
T_bf = bzg.GenerateTrajectory(StepLength, LateralFraction, YawRate,
StepVelocity, T_bf0, T_bf,
ClearanceHeight, PenetrationDepth,
contacts)
# Add DELTA to XYZ Foot Poses
RESIDUALS_SCALE = 0.05
# T_bf["FL"][3, :3] += action[6:9] * RESIDUALS_SCALE
# T_bf["FR"][3, :3] += action[9:12] * RESIDUALS_SCALE
# T_bf["BL"][3, :3] += action[12:15] * RESIDUALS_SCALE
# T_bf["BR"][3, :3] += action[15:18] * RESIDUALS_SCALE
T_bf["FL"][3, 2] += action[6] * RESIDUALS_SCALE
T_bf["FR"][3, 2] += action[7] * RESIDUALS_SCALE
T_bf["BL"][3, 2] += action[8] * RESIDUALS_SCALE
T_bf["BR"][3, 2] += action[9] * RESIDUALS_SCALE
joint_angles = spot.IK(orn, pos, T_bf)
# Pass Joint Angles
env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
state, reward, done, _ = env.step(action)
episode_reward += reward
# print("DT REWARD: {}".format(reward))
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
env.close()
if __name__ == '__main__':
main() | 6,449 | Python | 31.089552 | 127 | 0.575748 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/tg_eval.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 1e6
file_name = "mini_tg_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True, on_rack=False)
dt = env._time_step
# TRAJECTORY GENERATOR
movetype = "walk"
# movetype = "trot"
# movetype = "bound"
# movetype = "pace"
# movetype = "pronk"
TG = TGPolicy(movetype=movetype,
center_swing=0.0,
amplitude_extension=0.2,
amplitude_lift=0.4)
TG_state_dim = len(TG.get_TG_state())
TG_action_dim = 5 # f_tg, Beta, alpha_tg, h_tg, intensity
state_dim = env.observation_space.shape[0] + TG_state_dim
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0] + TG_action_dim
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, TGP=TG)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 1000
policy = agent.policy
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
# Just to store correct action space
action = env.action_space.sample()
# Record extends for plot
# LF_ext = []
# LB_ext = []
# RF_ext = []
# RB_ext = []
LF_tp = []
LB_tp = []
RF_tp = []
RB_tp = []
t = 0
while t < (int(max_timesteps)):
action[:] = 0.0
# # Get Action from TG [no policies here]
# action = TG.get_utg(action, alpha_tg, h_tg, intensity,
# env.minitaur.num_motors)
# LF_ext.append(action[env.minitaur.num_motors / 2])
# LB_ext.append(action[1 + env.minitaur.num_motors / 2])
# RF_ext.append(action[2 + env.minitaur.num_motors / 2])
# RB_ext.append(action[3 + env.minitaur.num_motors / 2])
# # Perform action
# next_state, reward, done, _ = env.step(action)
obs = agent.TGP.get_TG_state()
# LF_tp.append(obs[0])
# LB_tp.append(obs[1])
# RF_tp.append(obs[2])
# RB_tp.append(obs[3])
# # Increment phase
# TG.increment(dt, f_tg, Beta)
# # time.sleep(1.0)
# t += 1
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deployTG()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
episode_reward = 0
episode_timesteps = 0
episode_num += 1
plt.plot(0)
plt.plot(LF_tp, label="LF")
plt.plot(LB_tp, label="LB")
plt.plot(RF_tp, label="RF")
plt.plot(RB_tp, label="RB")
plt.xlabel("t")
plt.ylabel("EXT")
plt.title("Leg Extensions")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main()
| 4,424 | Python | 25.981707 | 76 | 0.583635 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/td3_lib/td3.py | #!/usr/bin/env python
import copy
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import gym
import os
# Twin Delayed Deterministic Policy Gradient
# Algorithm Steps
# 1. Initiailize Networks
class Actor(nn.Module):
"""Initialize parameters and build model.
An nn.Module contains layers, and a method
forward(input)that returns the output.
Weights (learnable params) are inherently defined here.
Args:
state_dim (int): Dimension of each state
action_dim (int): Dimension of each action
max_action (float): highest action to take
Return:
action output of network with tanh activation
"""
def __init__(self, state_dim, action_dim, max_action):
# Super calls the nn.Module Constructor
super(Actor, self).__init__()
# input layer
self.fc1 = nn.Linear(state_dim, 256)
# hidden layer
self.fc2 = nn.Linear(256, 256)
# output layer
self.fc3 = nn.Linear(256, action_dim)
# wrap from -max to +max
self.max_action = max_action
def forward(self, state):
# You just have to define the forward function,
# and the backward function (where gradients are computed)
# is automatically defined for you using autograd.
# Learnable params can be accessed using Actor.parameters
# Here, we create the tensor architecture
# state into layer 1
a = F.relu(self.fc1(state))
# layer 1 output into layer 2
a = F.relu(self.fc2(a))
# layer 2 output into layer 3 into tanh activation
return self.max_action * torch.tanh(self.fc3(a))
class Critic(nn.Module):
"""Initialize parameters and build model.
Args:
state_dim (int): Dimension of each state
action_dim (int): Dimension of each action
Return:
value output of network
"""
def __init__(self, state_dim, action_dim):
# Super calls the nn.Module Constructor
super(Critic, self).__init__()
# Q1 architecture
self.fc1 = nn.Linear(state_dim + action_dim, 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
# Q2 architecture
self.fc4 = nn.Linear(state_dim + action_dim, 256)
self.fc5 = nn.Linear(256, 256)
self.fc6 = nn.Linear(256, 1)
def forward(self, state, action):
# concatenate state and actions by adding rows
# to form 1D input layer
sa = torch.cat([state, action], 1)
# s,a into input layer into relu activation
q1 = F.relu(self.fc1(sa))
# l1 output into l2 into relu activation
q1 = F.relu(self.fc2(q1))
# l2 output into l3
q1 = self.fc3(q1)
# s,a into input layer into relu activation
q2 = F.relu(self.fc4(sa))
# l4 output into l5 into relu activation
q2 = F.relu(self.fc5(q2))
# l5 output into l6
q2 = self.fc6(q2)
return q1, q2
def Q1(self, state, action):
# Return Q1 for gradient Ascent on Actor
# Note that only Q1 is used for Actor Update
# concatenate state and actions by adding rows
# to form 1D input layer
sa = torch.cat([state, action], 1)
# s,a into input layer into relu activation
q1 = F.relu(self.fc1(sa))
# l1 output into l2 into relu activation
q1 = F.relu(self.fc2(q1))
# l2 output into l3
q1 = self.fc3(q1)
return q1
# https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py
# Expects tuples of (state, next_state, action, reward, done)
class ReplayBuffer(object):
"""Buffer to store tuples of experience replay"""
def __init__(self, max_size=1000000):
"""
Args:
max_size (int): total amount of tuples to store
"""
self.storage = []
self.max_size = max_size
self.ptr = 0
my_path = os.path.abspath(os.path.dirname(__file__))
self.buffer_path = os.path.join(my_path, "../../replay_buffer")
def add(self, data):
"""Add experience tuples to buffer
Args:
data (tuple): experience replay tuple
"""
if len(self.storage) == self.max_size:
self.storage[int(self.ptr)] = data
self.ptr = (self.ptr + 1) % self.max_size
else:
self.storage.append(data)
def save(self, iterations):
if not os.path.exists(self.buffer_path):
os.makedirs(self.buffer_path)
with open(
self.buffer_path + '/' + 'replay_buffer_' + str(iterations) +
'.data', 'wb') as filehandle:
pickle.dump(self.storage, filehandle)
def load(self, iterations):
with open(
self.buffer_path + '/' + 'replay_buffer_' + str(iterations) +
'.data', 'rb') as filehandle:
self.storage = pickle.load(filehandle)
def sample(self, batch_size):
"""Samples a random amount of experiences from buffer of batch size
NOTE: We don't delete samples here, only overwrite when max_size
Args:
batch_size (int): size of sample
"""
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
ind = np.random.randint(0, len(self.storage), size=batch_size)
states, actions, next_states, rewards, dones = [], [], [], [], []
for i in ind:
s, a, s_, r, d = self.storage[i]
states.append(np.array(s, copy=False))
state = torch.FloatTensor(np.array(states)).to(device)
actions.append(np.array(a, copy=False))
action = torch.FloatTensor(np.array(actions)).to(device)
next_states.append(np.array(s_, copy=False))
next_state = torch.FloatTensor(np.array(next_states)).to(device)
rewards.append(np.array(r, copy=False))
reward = torch.FloatTensor(np.array(rewards).reshape(-1,
1)).to(device)
dones.append(np.array(d, copy=False))
not_done = torch.FloatTensor(
1. - (np.array(dones).reshape(-1, 1))).to(device)
return state, action, next_state, reward, not_done
class TD3Agent(object):
"""Agent class that handles the training of the networks and
provides outputs as actions
Args:
state_dim (int): state size
action_dim (int): action size
max_action (float): highest action to take
device (device): cuda or cpu to process tensors
env (env): gym environment to use
batch_size(int): batch size to sample from replay buffer
discount (float): discount factor
tau (float): soft update for main networks to target networks
"""
def __init__(self,
state_dim,
action_dim,
max_action,
discount=0.99,
tau=0.005,
policy_noise=0.2,
noise_clip=0.5,
policy_freq=2):
self.device = torch.device(
"cuda:1" if torch.cuda.is_available() else "cpu")
self.actor = Actor(state_dim, action_dim, max_action).to(self.device)
self.actor_target = copy.deepcopy(self.actor)
self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),
lr=3e-4)
self.critic = Critic(state_dim, action_dim).to(self.device)
self.critic_target = copy.deepcopy(self.critic)
self.critic_optimizer = torch.optim.Adam(self.critic.parameters(),
lr=3e-4)
self.max_action = max_action
self.discount = discount
self.tau = tau
self.policy_noise = policy_noise
self.noise_clip = noise_clip
self.policy_freq = policy_freq
self.total_it = 0
def select_action(self, state):
"""Select an appropriate action from the agent policy
Args:
state (array): current state of environment
Returns:
action (float): action clipped within action range
"""
# Turn float value into a CUDA Float Tensor
state = torch.FloatTensor(state.reshape(1, -1)).to(self.device)
action = self.actor(state).cpu().data.numpy().flatten()
return action
def train(self, replay_buffer, batch_size=100):
"""Train and update actor and critic networks
Args:
replay_buffer (ReplayBuffer): buffer for experience replay
batch_size(int): batch size to sample from replay buffer\
Return:
actor_loss (float): loss from actor network
critic_loss (float): loss from critic network
"""
self.total_it += 1
# Sample replay buffer
state, action, next_state, reward, not_done = replay_buffer.sample(
batch_size)
with torch.no_grad():
"""
Autograd: if you set its attribute .requires_gras as True,
(DEFAULT)
it tracks all operations on it. When you finish your
computation, call .backward() to have all gradients computed
automatically. The gradient for this tensor is then accumulated
into the .grad attribute.
To prevent tracking history and using memory, wrap the code block
in "with torch.no_grad()". This is heplful when evaluating a model
as it may have trainable params with requires_grad=True (DEFAULT),
but for which we don't need the gradients.
Here, we don't want to track the acyclic graph's history
when getting our next action because we DON'T want to train
our actor in this step. We train our actor ONLY when we perform
the periodic policy update. Could have done .detach() at
target_Q = reward + not_done * self.discount * target_Q
for the same effect
"""
# Select action according to policy and add clipped noise
noise = (torch.randn_like(action) * self.policy_noise).clamp(
-self.noise_clip, self.noise_clip)
next_action = (self.actor_target(next_state) + noise).clamp(
-self.max_action, self.max_action)
# Compute the target Q value
target_Q1, target_Q2 = self.critic_target(next_state, next_action)
target_Q = torch.min(target_Q1, target_Q2)
target_Q = reward + not_done * self.discount * target_Q
# Get current Q estimates
current_Q1, current_Q2 = self.critic(state, action)
# Compute critic loss
# A loss function takes the (output, target) pair of inputs,
# and computes a value that estimates how far away the output
# is from the target.
critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(
current_Q2, target_Q)
# Optimize the critic
# Zero the gradient buffers of all parameters
self.critic_optimizer.zero_grad()
# Backprops with random gradients
# When we call loss.backward(), the whole graph is differentiated
# w.r.t. the loss, and all Tensors in the graph that has
# requires_grad=True (DEFAULT) will have their .grad Tensor
# accumulated with the gradient.
critic_loss.backward()
# Does the update
self.critic_optimizer.step()
# Delayed policy updates
if self.total_it % self.policy_freq == 0:
# Compute actor losse
actor_loss = -self.critic.Q1(state, self.actor(state)).mean()
# Optimize the actor
# Zero the gradient buffers
self.actor_optimizer.zero_grad()
# Differentiate the whole graph wrt loss
actor_loss.backward()
# Does the update
self.actor_optimizer.step()
# Update target networks (Critic 1, Critic 2, Actor)
for param, target_param in zip(self.critic.parameters(),
self.critic_target.parameters()):
target_param.data.copy_(self.tau * param.data +
(1 - self.tau) * target_param.data)
for param, target_param in zip(self.actor.parameters(),
self.actor_target.parameters()):
target_param.data.copy_(self.tau * param.data +
(1 - self.tau) * target_param.data)
def save(self, filename):
torch.save(self.critic.state_dict(), filename + "_critic")
torch.save(self.critic_optimizer.state_dict(),
filename + "_critic_optimizer")
torch.save(self.actor.state_dict(), filename + "_actor")
torch.save(self.actor_optimizer.state_dict(),
filename + "_actor_optimizer")
def load(self, filename):
self.critic.load_state_dict(
torch.load(filename + "_critic", map_location=self.device))
self.critic_optimizer.load_state_dict(
torch.load(filename + "_critic_optimizer",
map_location=self.device))
self.actor.load_state_dict(
torch.load(filename + "_actor", map_location=self.device))
self.actor_optimizer.load_state_dict(
torch.load(filename + "_actor_optimizer",
map_location=self.device))
# Runs policy for X episodes and returns average reward
# A fixed seed is used for the eval environment
def evaluate_policy(policy, env_name, seed, eval_episodes=10, render=False):
"""run several episodes using the best agent policy
Args:
policy (agent): agent to evaluate
env (env): gym environment
eval_episodes (int): how many test episodes to run
render (bool): show training
Returns:
avg_reward (float): average reward over the number of evaluations
"""
eval_env = gym.make(env_name, render=render)
eval_env.seed(seed + 100)
avg_reward = 0.
for _ in range(eval_episodes):
state, done = eval_env.reset(), False
while not done:
# if render:
# eval_env.render()
# sleep(0.01)
action = policy.select_action(np.array(state))
state, reward, done, _ = eval_env.step(action)
avg_reward += reward
avg_reward /= eval_episodes
print("---------------------------------------")
print("Evaluation over {} episodes: {}".format(eval_episodes, avg_reward))
print("---------------------------------------")
if render:
eval_env.close()
return avg_reward
def trainer(env_name,
seed,
max_timesteps,
start_timesteps,
expl_noise,
batch_size,
eval_freq,
save_model,
file_name="best_avg"):
""" Test Script on stock OpenAI Gym Envs
"""
if not os.path.exists("../results"):
os.makedirs("../results")
if not os.path.exists("../models"):
os.makedirs("../models")
env = gym.make(env_name)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
action_dim = env.action_space.shape[0]
max_action = float(env.action_space.high[0])
policy = TD3Agent(state_dim, action_dim, max_action)
replay_buffer = ReplayBuffer()
# Evaluate untrained policy and init list for storage
evaluations = [evaluate_policy(policy, env_name, seed, 1)]
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Select action randomly or according to policy
# Random Action - no training yet, just storing in buffer
if t < start_timesteps:
action = env.action_space.sample()
else:
# According to policy + Exploraton Noise
action = (policy.select_action(np.array(state)) + np.random.normal(
0, max_action * expl_noise, size=action_dim)).clip(
-max_action, max_action)
# Perform action
next_state, reward, done, _ = env.step(action)
done_bool = float(
done) if episode_timesteps < env._max_episode_steps else 0
# Store data in replay buffer
replay_buffer.add((state, action, next_state, reward, done_bool))
state = next_state
episode_reward += reward
# Train agent after collecting sufficient data for buffer
if t >= start_timesteps:
policy.train(replay_buffer, batch_size)
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
episode_reward = 0
episode_timesteps = 0
episode_num += 1
# Evaluate episode
if (t + 1) % eval_freq == 0:
evaluations.append(evaluate_policy(policy, env_name, seed, 1))
np.save("../results/" + str(file_name) + str(t), evaluations)
if save_model:
policy.save("../models/" + str(file_name) + str(t))
if __name__ == "__main__":
""" The Main Function """
trainer("BipedalWalker-v2", 0, 1e6, 1e4, 0.1, 100, 15e3, True) | 18,049 | Python | 34.392157 | 82 | 0.57017 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/td3_lib/plot_reward.py | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
reward = np.load("../../results/plen_walk_gazebo_.npy")
plt.figure(0)
plt.autoscale(enable=True, axis='both', tight=None)
plt.title('Dominant Foot Trajectories - SS')
plt.ylabel('positon (mm)')
plt.xlabel('timestep')
plt.plot(reward, color='b', label="Reward")
plt.legend()
plt.show()
| 426 | Python | 21.473683 | 59 | 0.626761 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/ars_lib/ars.py | # from tg_lib.tg_policy import TGPolicy
import pickle
import numpy as np
from scipy.signal import butter, filtfilt
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.Kinematics.LieAlgebra import TransToRp
import copy
from spotmicro.util.gui import GUI
np.random.seed(0)
# Multiprocessing package for python
# Parallelization improvements based on:
# https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
# Messages for Pipes
_RESET = 1
_CLOSE = 2
_EXPLORE = 3
_EXPLORE_TG = 4
# Params for TG
CD_SCALE = 0.05
SLV_SCALE = 0.05
RESIDUALS_SCALE = 0.015
Z_SCALE = 0.05
# Filter actions
alpha = 0.7
# Added this to avoid filtering residuals
# -1 for all
actions_to_filter = 14
# For auto yaw control
P_yaw = 5.0
# Cummulative timestep exponential reward
# cum_dt_exp = 1.1
cum_dt_exp = 0.0
def butter_lowpass_filter(data, cutoff, fs, order=2):
""" Pass two subsequent datapoints in here to be filtered
"""
nyq = 0.5 * fs # Nyquist Frequency
normal_cutoff = cutoff / nyq
# Get the filter coefficients
b, a = butter(order, normal_cutoff, btype='low', analog=False)
y = filtfilt(b, a, data)
return y
def ParallelWorker(childPipe, env, nb_states):
""" Function to deploy multiple ARS agents in parallel
"""
# nb_states = env.observation_space.shape[0]
# common normalizer
normalizer = Normalizer(nb_states)
max_action = float(env.action_space.high[0])
_ = env.reset()
n = 0
while True:
n += 1
try:
# Only block for short times to have keyboard exceptions be raised.
if not childPipe.poll(0.001):
continue
message, payload = childPipe.recv()
except (EOFError, KeyboardInterrupt):
break
if message == _RESET:
_ = env.reset()
childPipe.send(["reset ok"])
continue
if message == _EXPLORE:
# Payloads received by parent in ARSAgent.train()
# [0]: normalizer, [1]: policy, [2]: direction, [3]: delta
# we use local normalizer so no need for [0] (optional)
# normalizer = payload[0]
policy = payload[1]
direction = payload[2]
delta = payload[3]
desired_velocity = payload[4]
desired_rate = payload[5]
state = env.reset(desired_velocity, desired_rate)
sum_rewards = 0.0
timesteps = 0
done = False
while not done and timesteps < policy.episode_steps:
normalizer.observe(state)
# Normalize State
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
# # Clip action between +-1 for execution in env
# for a in range(len(action)):
# action[a] = np.clip(action[a], -max_action, max_action)
state, reward, done, _ = env.step(action)
reward = max(min(reward, 1), -1)
sum_rewards += reward
timesteps += 1
childPipe.send([sum_rewards])
continue
if message == _EXPLORE_TG:
# Payloads received by parent in ARSAgent.train()
# [0]: normalizer, [1]: policy, [2]: direction, [3]: delta
# [4]: desired_velocity, [5]: desired_rate, [6]: Trajectory Gen
# we use local normalizer so no need for [0] (optional)
# normalizer = payload[0]
policy = payload[1]
direction = payload[2]
delta = payload[3]
desired_velocity = payload[4]
desired_rate = payload[5]
TGP = payload[6]
smach = payload[7]
spot = payload[8]
state = env.reset()
sum_rewards = 0.0
timesteps = 0
done = False
T_bf = copy.deepcopy(spot.WorldToFoot)
T_b0 = copy.deepcopy(spot.WorldToFoot)
action = env.action_space.sample()
action[:] = 0.0
old_act = action[:actions_to_filter]
# For auto yaw control
yaw = 0.0
while not done and timesteps < policy.episode_steps:
# smach.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = smach.StateMachine(
)
env.spot.GetExternalObservations(TGP, smach)
# Read UPDATED state based on controls and phase
state = env.return_state()
normalizer.observe(state)
# NOTE: Don't normalize contacts - must stay 0/1
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
contacts = state[-4:]
action = np.tanh(action)
# EXP FILTER
action[:actions_to_filter] = alpha * old_act + (
1.0 - alpha) * action[:actions_to_filter]
old_act = action[:actions_to_filter]
ClearanceHeight += action[0] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, smach.StepLength_LIMITS[0],
smach.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity,
smach.StepVelocity_LIMITS[0],
smach.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
smach.LateralFraction_LIMITS[0],
smach.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, smach.YawRate_LIMITS[0],
smach.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
smach.ClearanceHeight_LIMITS[0],
smach.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
smach.PenetrationDepth_LIMITS[0],
smach.PenetrationDepth_LIMITS[1])
# For auto yaw control
yaw = env.return_yaw()
YawRate += -yaw * P_yaw
# Get Desired Foot Poses
if timesteps > 20:
T_bf = TGP.GenerateTrajectory(StepLength, LateralFraction,
YawRate, StepVelocity, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
else:
T_bf = TGP.GenerateTrajectory(0.0, 0.0, 0.0, 0.1, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
action[:] = 0.0
action[2:] *= RESIDUALS_SCALE
# Add DELTA to XYZ Foot Poses
T_bf_copy = copy.deepcopy(T_bf)
T_bf_copy["FL"][:3, 3] += action[2:5]
T_bf_copy["FR"][:3, 3] += action[5:8]
T_bf_copy["BL"][:3, 3] += action[8:11]
T_bf_copy["BR"][:3, 3] += action[11:14]
# Adjust Body Height with action!
pos[2] += abs(action[1]) * Z_SCALE
joint_angles = spot.IK(orn, pos, T_bf_copy)
# Pass Joint Angles
env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
next_state, reward, done, _ = env.step(action)
sum_rewards += reward
timesteps += 1
# Divide reward by timesteps for normalized reward + add exponential surival reward
childPipe.send([(sum_rewards + timesteps**cum_dt_exp) / timesteps])
continue
if message == _CLOSE:
childPipe.send(["close ok"])
break
childPipe.close()
class Policy():
""" state --> action
"""
def __init__(
self,
state_dim,
action_dim,
# how much weights are changed each step
learning_rate=0.03,
# number of random expl_noise variations generated
# each step
# each one will be run for 2 epochs, + and -
num_deltas=16,
# used to update weights, sorted by highest rwrd
num_best_deltas=16,
# number of timesteps per episode per rollout
episode_steps=5000,
# weight of sampled exploration noise
expl_noise=0.05,
# for seed gen
seed=0):
# Tunable Hyperparameters
self.learning_rate = learning_rate
self.num_deltas = num_deltas
self.num_best_deltas = num_best_deltas
# there cannot be more best_deltas than there are deltas
assert self.num_best_deltas <= self.num_deltas
self.episode_steps = episode_steps
self.expl_noise = expl_noise
self.seed = seed
np.random.seed(seed)
self.state_dim = state_dim
self.action_dim = action_dim
# input/ouput matrix with weights set to zero
# this is the perception matrix (policy)
self.theta = np.zeros((action_dim, state_dim))
def evaluate(self, state, delta=None, direction=None):
""" state --> action
"""
# if direction is None, deployment mode: takes dot product
# to directly sample from (use) policy
if direction is None:
return self.theta.dot(state)
# otherwise, add (+-) directed expl_noise before taking dot product (policy)
# this is where the 2*num_deltas rollouts comes from
elif direction == "+":
return (self.theta + self.expl_noise * delta).dot(state)
elif direction == "-":
return (self.theta - self.expl_noise * delta).dot(state)
def sample_deltas(self):
""" generate array of random expl_noise matrices. Length of
array = num_deltas
matrix dimension: pxn where p=observation dim and
n=action dim
"""
deltas = []
# print("SHAPE THING with *: {}".format(*self.theta.shape))
# print("SHAPE THING NORMALLY: ({}, {})".format(self.theta.shape[0],
# self.theta.shape[1]))
# print("ACTUAL SHAPE: {}".format(self.theta.shape))
# print("SHAPE OF EXAMPLE DELTA WITH *: {}".format(
# np.random.randn(*self.theta.shape).shape))
# print("SHAPE OF EXAMPLE DELTA NOMRALLY: {}".format(
# np.random.randn(self.theta.shape[0], self.theta.shape[1]).shape))
for _ in range(self.num_deltas):
deltas.append(
np.random.randn(self.theta.shape[0], self.theta.shape[1]))
return deltas
def update(self, rollouts, std_dev_rewards):
""" Update policy weights (theta) based on rewards
from 2*num_deltas rollouts
"""
step = np.zeros(self.theta.shape)
for r_pos, r_neg, delta in rollouts:
# how much to deviate from policy
step += (r_pos - r_neg) * delta
self.theta += self.learning_rate / (self.num_best_deltas *
std_dev_rewards) * step
class Normalizer():
""" this ensures that the policy puts equal weight upon
each state component.
"""
# Normalizes the states
def __init__(self, state_dim):
""" Initialize state space (all zero)
"""
self.state = np.zeros(state_dim)
self.mean = np.zeros(state_dim)
self.mean_diff = np.zeros(state_dim)
self.var = np.zeros(state_dim)
def observe(self, x):
""" Compute running average and variance
clip variance >0 to avoid division by zero
"""
self.state += 1.0
last_mean = self.mean.copy()
# running avg
self.mean += (x - self.mean) / self.state
# used to compute variance
self.mean_diff += (x - last_mean) * (x - self.mean)
# variance
self.var = (self.mean_diff / self.state).clip(min=1e-2)
def normalize(self, states):
""" subtract mean state value from current state
and divide by standard deviation (sqrt(var))
to normalize
"""
state_mean = self.mean
state_std = np.sqrt(self.var)
return (states - state_mean) / state_std
class ARSAgent():
def __init__(self,
normalizer,
policy,
env,
smach=None,
TGP=None,
spot=None,
gui=False):
self.normalizer = normalizer
self.policy = policy
self.state_dim = self.policy.state_dim
self.action_dim = self.policy.action_dim
self.env = env
self.max_action = float(self.env.action_space.high[0])
self.successes = 0
self.phase = 0
self.desired_velocity = 0.5
self.desired_rate = 0.0
self.flip = 0
self.increment = 0
self.scaledown = True
self.type = "Stop"
self.smach = smach
if smach is not None:
self.BaseClearanceHeight = self.smach.ClearanceHeight
self.BasePenetrationDepth = self.smach.PenetrationDepth
self.TGP = TGP
self.spot = spot
if gui:
self.g_u_i = GUI(self.env.spot.quadruped)
else:
self.g_u_i = None
self.action_history = []
self.true_action_history = []
# Deploy Policy in one direction over one whole episode
# DO THIS ONCE PER ROLLOUT OR DURING DEPLOYMENT
def deploy(self, direction=None, delta=None):
state = self.env.reset(self.desired_velocity, self.desired_rate)
sum_rewards = 0.0
timesteps = 0
done = False
while not done and timesteps < self.policy.episode_steps:
# print("STATE: ", state)
# print("dt: {}".format(timesteps))
self.normalizer.observe(state)
# Normalize State
state = self.normalizer.normalize(state)
action = self.policy.evaluate(state, delta, direction)
# Clip action between +-1 for execution in env
for a in range(len(action)):
action[a] = np.clip(action[a], -self.max_action,
self.max_action)
# print("ACTION: ", action)
state, reward, done, _ = self.env.step(action)
# print("STATE: ", state)
# Clip reward between -1 and 1 to prevent outliers from
# distorting weights
reward = np.clip(reward, -self.max_action, self.max_action)
sum_rewards += reward
timesteps += 1
# Divide rewards by timesteps for reward-per-step + exp survive rwd
return (sum_rewards + timesteps**cum_dt_exp) / timesteps
# Deploy Policy in one direction over one whole episode
# DO THIS ONCE PER ROLLOUT OR DURING DEPLOYMENT
def deployTG(self, direction=None, delta=None):
state = self.env.reset()
sum_rewards = 0.0
timesteps = 0
done = False
# alpha = []
# h = []
# f = []
T_bf = copy.deepcopy(self.spot.WorldToFoot)
T_b0 = copy.deepcopy(self.spot.WorldToFoot)
self.action_history = []
self.true_action_history = []
action = self.env.action_space.sample()
action[:] = 0.0
old_act = action[:actions_to_filter]
# For auto yaw correction
yaw = 0.0
while not done and timesteps < self.policy.episode_steps:
# self.smach.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = self.smach.StateMachine(
)
if self.g_u_i:
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod = self.g_u_i.UserInput(
)
self.TGP.Tswing = SwingPeriod
self.env.spot.GetExternalObservations(self.TGP, self.smach)
# Read UPDATED state based on controls and phase
state = self.env.return_state()
self.normalizer.observe(state)
# Don't normalize contacts
state = self.normalizer.normalize(state)
action = self.policy.evaluate(state, delta, direction)
# Action History
self.action_history.append(np.tanh(action))
# Action History
true_action = copy.deepcopy(np.tanh(action))
true_action[0] *= CD_SCALE
true_action[1] = abs(true_action[1]) * Z_SCALE
true_action[2:] *= RESIDUALS_SCALE
self.true_action_history.append(true_action)
action = np.tanh(action)
# EXP FILTER
action[:actions_to_filter] = alpha * old_act + (
1.0 - alpha) * action[:actions_to_filter]
old_act = action[:actions_to_filter]
ClearanceHeight += action[0] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, self.smach.StepLength_LIMITS[0],
self.smach.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity,
self.smach.StepVelocity_LIMITS[0],
self.smach.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
self.smach.LateralFraction_LIMITS[0],
self.smach.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, self.smach.YawRate_LIMITS[0],
self.smach.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
self.smach.ClearanceHeight_LIMITS[0],
self.smach.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
self.smach.PenetrationDepth_LIMITS[0],
self.smach.PenetrationDepth_LIMITS[1])
contacts = copy.deepcopy(state[-4:])
# contacts = [0, 0, 0, 0]
# print("CONTACTS: {}".format(contacts))
yaw = self.env.return_yaw()
if not self.g_u_i:
YawRate += -yaw * P_yaw
# Get Desired Foot Poses
if timesteps > 20:
T_bf = self.TGP.GenerateTrajectory(StepLength, LateralFraction,
YawRate, StepVelocity, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
else:
T_bf = self.TGP.GenerateTrajectory(0.0, 0.0, 0.0, 0.1, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
action[:] = 0.0
action[2:] *= RESIDUALS_SCALE
# Add DELTA to XYZ Foot Poses
T_bf_copy = copy.deepcopy(T_bf)
T_bf_copy["FL"][:3, 3] += action[2:5]
T_bf_copy["FR"][:3, 3] += action[5:8]
T_bf_copy["BL"][:3, 3] += action[8:11]
T_bf_copy["BR"][:3, 3] += action[11:14]
# Adjust Height!
pos[2] += abs(action[1]) * Z_SCALE
joint_angles = self.spot.IK(orn, pos, T_bf_copy)
# Pass Joint Angles
self.env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
next_state, reward, done, _ = self.env.step(action)
sum_rewards += reward
timesteps += 1
self.TGP.reset()
self.smach.reshuffle()
self.smach.PenetrationDepth = self.BasePenetrationDepth
self.smach.ClearanceHeight = self.BaseClearanceHeight
return sum_rewards, timesteps
def returnPose(self):
return self.env.spot.GetBasePosition()
def train(self):
# Sample random expl_noise deltas
print("-------------------------------")
# print("Sampling Deltas")
deltas = self.policy.sample_deltas()
# Initialize +- reward list of size num_deltas
positive_rewards = [0] * self.policy.num_deltas
negative_rewards = [0] * self.policy.num_deltas
# Execute 2*num_deltas rollouts and store +- rewards
print("Deploying Rollouts")
for i in range(self.policy.num_deltas):
print("Rollout #{}".format(i + 1))
positive_rewards[i] = self.deploy(direction="+", delta=deltas[i])
negative_rewards[i] = self.deploy(direction="-", delta=deltas[i])
# Calculate std dev
std_dev_rewards = np.array(positive_rewards + negative_rewards).std()
# Order rollouts in decreasing list using cum reward as criterion
unsorted_rollouts = [(positive_rewards[i], negative_rewards[i],
deltas[i])
for i in range(self.policy.num_deltas)]
# When sorting, take the max between the reward for +- disturbance
sorted_rollouts = sorted(
unsorted_rollouts,
key=lambda x: max(unsorted_rollouts[0], unsorted_rollouts[1]),
reverse=True)
# Only take first best_num_deltas rollouts
rollouts = sorted_rollouts[:self.policy.num_best_deltas]
# Update Policy
self.policy.update(rollouts, std_dev_rewards)
# Execute Current Policy
eval_reward = self.deploy()
return eval_reward
def train_parallel(self, parentPipes):
""" Execute rollouts in parallel using multiprocessing library
based on: # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
"""
# USE VANILLA OR TG POLICY
if self.TGP is None:
exploration = _EXPLORE
else:
exploration = _EXPLORE_TG
# Initializing the perturbations deltas and the positive/negative rewards
deltas = self.policy.sample_deltas()
# Initialize +- reward list of size num_deltas
positive_rewards = [0] * self.policy.num_deltas
negative_rewards = [0] * self.policy.num_deltas
smach = copy.deepcopy(self.smach)
smach.ClearanceHeight = self.BaseClearanceHeight
smach.PenetrationDepth = self.BasePenetrationDepth
smach.reshuffle()
if parentPipes:
for i in range(self.policy.num_deltas):
# Execute each rollout on a separate thread
parentPipe = parentPipes[i]
# NOTE: target for parentPipe specified in main_ars.py
# (target is ParallelWorker fcn defined up top)
parentPipe.send([
exploration,
[
self.normalizer, self.policy, "+", deltas[i],
self.desired_velocity, self.desired_rate, self.TGP,
smach, self.spot
]
])
for i in range(self.policy.num_deltas):
# Receive cummulative reward from each rollout
positive_rewards[i] = parentPipes[i].recv()[0]
for i in range(self.policy.num_deltas):
# Execute each rollout on a separate thread
parentPipe = parentPipes[i]
parentPipe.send([
exploration,
[
self.normalizer, self.policy, "-", deltas[i],
self.desired_velocity, self.desired_rate, self.TGP,
smach, self.spot
]
])
for i in range(self.policy.num_deltas):
# Receive cummulative reward from each rollout
negative_rewards[i] = parentPipes[i].recv()[0]
else:
raise ValueError(
"Select 'train' method if you are not using multiprocessing!")
# Calculate std dev
std_dev_rewards = np.array(positive_rewards + negative_rewards).std()
# Order rollouts in decreasing list using cum reward as criterion
# take max between reward for +- disturbance as that rollout's reward
# Store max between positive and negative reward as key for sort
scores = {
k: max(r_pos, r_neg)
for k, (
r_pos,
r_neg) in enumerate(zip(positive_rewards, negative_rewards))
}
indeces = sorted(scores.keys(), key=lambda x: scores[x],
reverse=True)[:self.policy.num_deltas]
# print("INDECES: ", indeces)
rollouts = [(positive_rewards[k], negative_rewards[k], deltas[k])
for k in indeces]
# Update Policy
self.policy.update(rollouts, std_dev_rewards)
# Execute Current Policy USING VANILLA OR TG
if self.TGP is None:
return self.deploy()
else:
return self.deployTG()
def save(self, filename):
""" Save the Policy
:param filename: the name of the file where the policy is saved
"""
with open(filename + '_policy', 'wb') as filehandle:
pickle.dump(self.policy.theta, filehandle)
def load(self, filename):
""" Load the Policy
:param filename: the name of the file where the policy is saved
"""
with open(filename + '_policy', 'rb') as filehandle:
self.policy.theta = pickle.load(filehandle)
| 26,330 | Python | 37.836283 | 148 | 0.536308 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/terrain_env_randomizer.py | """Generates a random terrain at Minitaur gym environment reset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import os, inspect
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
parentdir = os.path.dirname(os.path.dirname(parentdir))
os.sys.path.insert(0, parentdir)
import itertools
import math
import enum
import numpy as np
from pybullet_envs.minitaur.envs import env_randomizer_base
_GRID_LENGTH = 15
_GRID_WIDTH = 10
_MAX_SAMPLE_SIZE = 30
_MIN_BLOCK_DISTANCE = 0.7
_MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE
_MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2
_MAX_BLOCK_HEIGHT = 0.05
_MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2
class PoissonDisc2D(object):
"""Generates 2D points using Poisson disk sampling method.
Implements the algorithm described in:
http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf
Unlike the uniform sampling method that creates small clusters of points,
Poisson disk method enforces the minimum distance between points and is more
suitable for generating a spatial distribution of non-overlapping objects.
"""
def __init__(self, grid_length, grid_width, min_radius, max_sample_size):
"""Initializes the algorithm.
Args:
grid_length: The length of the bounding square in which points are
sampled.
grid_width: The width of the bounding square in which points are
sampled.
min_radius: The minimum distance between any pair of points.
max_sample_size: The maximum number of sample points around a active site.
See details in the algorithm description.
"""
self._cell_length = min_radius / math.sqrt(2)
self._grid_length = grid_length
self._grid_width = grid_width
self._grid_size_x = int(grid_length / self._cell_length) + 1
self._grid_size_y = int(grid_width / self._cell_length) + 1
self._min_radius = min_radius
self._max_sample_size = max_sample_size
# Flattern the 2D grid as an 1D array. The grid is used for fast nearest
# point searching.
self._grid = [None] * self._grid_size_x * self._grid_size_y
# Generate the first sample point and set it as an active site.
first_sample = np.array(
np.random.random_sample(2)) * [grid_length, grid_width]
self._active_list = [first_sample]
# Also store the sample point in the grid.
self._grid[self._point_to_index_1d(first_sample)] = first_sample
def _point_to_index_1d(self, point):
"""Computes the index of a point in the grid array.
Args:
point: A 2D point described by its coordinates (x, y).
Returns:
The index of the point within the self._grid array.
"""
return self._index_2d_to_1d(self._point_to_index_2d(point))
def _point_to_index_2d(self, point):
"""Computes the 2D index (aka cell ID) of a point in the grid.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
x_index: The x index of the cell the point belongs to.
y_index: The y index of the cell the point belongs to.
"""
x_index = int(point[0] / self._cell_length)
y_index = int(point[1] / self._cell_length)
return x_index, y_index
def _index_2d_to_1d(self, index2d):
"""Converts the 2D index to the 1D position in the grid array.
Args:
index2d: The 2D index of a point (aka the cell ID) in the grid.
Returns:
The 1D position of the cell within the self._grid array.
"""
return index2d[0] + index2d[1] * self._grid_size_x
def _is_in_grid(self, point):
"""Checks if the point is inside the grid boundary.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
Whether the point is inside the grid.
"""
return (0 <= point[0] < self._grid_length) and (0 <= point[1] <
self._grid_width)
def _is_in_range(self, index2d):
"""Checks if the cell ID is within the grid.
Args:
index2d: The 2D index of a point (aka the cell ID) in the grid.
Returns:
Whether the cell (2D index) is inside the grid.
"""
return (0 <= index2d[0] < self._grid_size_x) and (0 <= index2d[1] <
self._grid_size_y)
def _is_close_to_existing_points(self, point):
"""Checks if the point is close to any already sampled (and stored) points.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
True iff the distance of the point to any existing points is smaller than
the min_radius
"""
px, py = self._point_to_index_2d(point)
# Now we can check nearby cells for existing points
for neighbor_cell in itertools.product(xrange(px - 1, px + 2),
xrange(py - 1, py + 2)):
if not self._is_in_range(neighbor_cell):
continue
maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)]
if maybe_a_point is not None and np.linalg.norm(
maybe_a_point - point) < self._min_radius:
return True
return False
def sample(self):
"""Samples new points around some existing point.
Removes the sampling base point and also stores the new jksampled points if
they are far enough from all existing points.
"""
active_point = self._active_list.pop()
for _ in xrange(self._max_sample_size):
# Generate random points near the current active_point between the radius
random_radius = np.random.uniform(self._min_radius,
2 * self._min_radius)
random_angle = np.random.uniform(0, 2 * math.pi)
# The sampled 2D points near the active point
sample = random_radius * np.array(
[np.cos(random_angle),
np.sin(random_angle)]) + active_point
if not self._is_in_grid(sample):
continue
if self._is_close_to_existing_points(sample):
continue
self._active_list.append(sample)
self._grid[self._point_to_index_1d(sample)] = sample
def generate(self):
"""Generates the Poisson disc distribution of 2D points.
Although the while loop looks scary, the algorithm is in fact O(N), where N
is the number of cells within the grid. When we sample around a base point
(in some base cell), new points will not be pushed into the base cell
because of the minimum distance constraint. Once the current base point is
removed, all future searches cannot start from within the same base cell.
Returns:
All sampled points. The points are inside the quare [0, grid_length] x [0,
grid_width]
"""
while self._active_list:
self.sample()
all_sites = []
for p in self._grid:
if p is not None:
all_sites.append(p)
return all_sites
class TerrainType(enum.Enum):
"""The randomzied terrain types we can use in the gym env."""
RANDOM_BLOCKS = 1
TRIANGLE_MESH = 2
class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase):
"""Generates an uneven terrain in the gym env."""
def __init__(self,
terrain_type=TerrainType.TRIANGLE_MESH,
mesh_filename="terrain9735.obj",
mesh_scale=None):
"""Initializes the randomizer.
Args:
terrain_type: Whether to generate random blocks or load a triangle mesh.
mesh_filename: The mesh file to be used. The mesh will only be loaded if
terrain_type is set to TerrainType.TRIANGLE_MESH.
mesh_scale: the scaling factor for the triangles in the mesh file.
"""
self._terrain_type = terrain_type
self._mesh_filename = mesh_filename
self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0, 0.3]
def randomize_env(self, env):
"""Generate a random terrain for the current env.
Args:
env: A minitaur gym environment.
"""
if self._terrain_type is TerrainType.TRIANGLE_MESH:
self._load_triangle_mesh(env)
if self._terrain_type is TerrainType.RANDOM_BLOCKS:
self._generate_convex_blocks(env)
def _load_triangle_mesh(self, env):
"""Represents the random terrain using a triangle mesh.
It is possible for Minitaur leg to stuck at the common edge of two triangle
pieces. To prevent this from happening, we recommend using hard contacts
(or high stiffness values) for Minitaur foot in sim.
Args:
env: A minitaur gym environment.
"""
env.pybullet_client.removeBody(env.ground_id)
terrain_collision_shape_id = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_MESH,
fileName=self._mesh_filename,
flags=1,
meshScale=self._mesh_scale)
env.ground_id = env.pybullet_client.createMultiBody(
baseMass=0,
baseCollisionShapeIndex=terrain_collision_shape_id,
basePosition=[0, 0, 0])
def _generate_convex_blocks(self, env):
"""Adds random convex blocks to the flat ground.
We use the Possion disk algorithm to add some random blocks on the ground.
Possion disk algorithm sets the minimum distance between two sampling
points, thus voiding the clustering effect in uniform N-D distribution.
Args:
env: A minitaur gym environment.
"""
poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH,
_MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE)
block_centers = poisson_disc.generate()
for center in block_centers:
# We want the blocks to be in front of the robot.
shifted_center = np.array(center) - [2, _GRID_WIDTH / 2]
# Do not place blocks near the point [0, 0], where the robot will start.
if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0:
continue
half_length = np.random.uniform(
_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2))
half_height = np.random.uniform(_MIN_BLOCK_HEIGHT,
_MAX_BLOCK_HEIGHT) / 2
box_id = env.pybullet_client.createCollisionShape(
env.pybullet_client.GEOM_BOX,
halfExtents=[half_length, half_length, half_height])
env.pybullet_client.createMultiBody(baseMass=0,
baseCollisionShapeIndex=box_id,
basePosition=[
shifted_center[0],
shifted_center[1],
half_height
])
def _generate_height_field(self, env):
random.seed(10)
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 0)
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.1, .1, 24],
fileName="heightmaps/wm_height_out.png")
textureId = env.pybullet_client.loadTexture("gimp_overlay_out.png")
terrain = env.pybullet_client.createMultiBody(0, terrainShape)
env.pybullet_client.changeVisualShape(terrain,
-1,
textureUniqueId=textureId)
env.pybullet_client.changeVisualShape(terrain,
-1,
rgbaColor=[1, 1, 1, 1]) | 12,192 | Python | 39.916107 | 85 | 0.602116 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/env_randomizer_base.py | """Abstract base class for environment randomizer."""
import abc
class EnvRandomizerBase(object):
"""Abstract base class for environment randomizer.
An EnvRandomizer is called in environment.reset(). It will
randomize physical parameters of the objects in the simulation.
The physical parameters will be fixed for that episode and be
randomized again in the next environment.reset().
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def randomize_env(self, env):
"""Randomize the simulated_objects in the environment.
Args:
env: The environment to be randomized.
"""
pass
| 622 | Python | 23.919999 | 65 | 0.726688 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/minitaur.py | """This file implements the functionalities of a minitaur using pybullet.
"""
import copy
import math
import numpy as np
from . import motor
import os
INIT_POSITION = [0, 0, .2]
INIT_ORIENTATION = [0, 0, 0, 1]
KNEE_CONSTRAINT_POINT_RIGHT = [0, 0.005, 0.2]
KNEE_CONSTRAINT_POINT_LEFT = [0, 0.01, 0.2]
OVERHEAT_SHUTDOWN_TORQUE = 2.45
OVERHEAT_SHUTDOWN_TIME = 1.0
LEG_POSITION = ["front_left", "back_left", "front_right", "back_right"]
MOTOR_NAMES = [
"motor_front_leftL_joint", "motor_front_leftR_joint",
"motor_back_leftL_joint", "motor_back_leftR_joint",
"motor_front_rightL_joint", "motor_front_rightR_joint",
"motor_back_rightL_joint", "motor_back_rightR_joint"
]
LEG_LINK_ID = [2, 3, 5, 6, 8, 9, 11, 12, 15, 16, 18, 19, 21, 22, 24, 25]
MOTOR_LINK_ID = [1, 4, 7, 10, 14, 17, 20, 23]
FOOT_LINK_ID = [3, 6, 9, 12, 16, 19, 22, 25]
BASE_LINK_ID = -1
class Minitaur(object):
"""The minitaur class that simulates a quadruped robot from Ghost Robotics.
"""
def __init__(self,
pybullet_client,
urdf_root=os.path.join(os.path.dirname(__file__), "../data"),
time_step=0.01,
self_collision_enabled=False,
motor_velocity_limit=np.inf,
pd_control_enabled=False,
accurate_motor_model_enabled=False,
motor_kp=0.7,
motor_kd=0.02,
torque_control_enabled=False,
motor_overheat_protection=False,
on_rack=False,
kd_for_pd_controllers=0.3,
desired_velocity=0.5,
desired_rate=0.0):
"""Constructs a minitaur and reset it to the initial states.
Args:
pybullet_client: The instance of BulletClient to manage different
simulations.
urdf_root: The path to the urdf folder.
time_step: The time step of the simulation.
self_collision_enabled: Whether to enable self collision.
motor_velocity_limit: The upper limit of the motor velocity.
pd_control_enabled: Whether to use PD control for the motors.
accurate_motor_model_enabled: Whether to use the accurate DC motor model.
motor_kp: proportional gain for the accurate motor model
motor_kd: derivative gain for the acurate motor model
torque_control_enabled: Whether to use the torque control, if set to
False, pose control will be used.
motor_overheat_protection: Whether to shutdown the motor that has exerted
large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
(OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
details.
on_rack: Whether to place the minitaur on rack. This is only used to debug
the walking gait. In this mode, the minitaur's base is hanged midair so
that its walking gait is clearer to visualize.
kd_for_pd_controllers: kd value for the pd controllers of the motors.
desired_velocity: additional observation space dimension for policy
desired_rate: additional observation space dimension for policy
"""
# used to calculate minitaur acceleration
self.prev_lin_twist = np.array([0, 0, 0])
self.prev_lin_acc = np.array([0, 0, 0])
self.num_motors = 8
self.num_legs = int(self.num_motors / 2)
self._pybullet_client = pybullet_client
self._urdf_root = urdf_root
self._self_collision_enabled = self_collision_enabled
self._motor_velocity_limit = motor_velocity_limit
self._pd_control_enabled = pd_control_enabled
self._motor_direction = [-1, -1, -1, -1, 1, 1, 1, 1]
self._observed_motor_torques = np.zeros(self.num_motors)
self._applied_motor_torques = np.zeros(self.num_motors)
self._max_force = 3.5
self._accurate_motor_model_enabled = accurate_motor_model_enabled
self._torque_control_enabled = torque_control_enabled
self._motor_overheat_protection = motor_overheat_protection
self._on_rack = on_rack
if self._accurate_motor_model_enabled:
self._kp = motor_kp
self._kd = motor_kd
self._motor_model = motor.MotorModel(
torque_control_enabled=self._torque_control_enabled,
kp=self._kp,
kd=self._kd)
elif self._pd_control_enabled:
self._kp = 8
self._kd = kd_for_pd_controllers
else:
self._kp = 1
self._kd = 1
self.time_step = time_step
self.desired_velocity = desired_velocity
self.desired_rate = desired_rate
self.Reset()
def _RecordMassInfoFromURDF(self):
self._base_mass_urdf = self._pybullet_client.getDynamicsInfo(
self.quadruped, BASE_LINK_ID)[0]
self._leg_masses_urdf = []
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
LEG_LINK_ID[0])[0])
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
MOTOR_LINK_ID[0])[0])
def _BuildJointNameToIdDict(self):
num_joints = self._pybullet_client.getNumJoints(self.quadruped)
self._joint_name_to_id = {}
for i in range(num_joints):
joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)
self._joint_name_to_id[joint_info[1].decode(
"UTF-8")] = joint_info[0]
def _BuildMotorIdList(self):
self._motor_id_list = [
self._joint_name_to_id[motor_name] for motor_name in MOTOR_NAMES
]
def Reset(self, reload_urdf=True, desired_velocity=None, desired_rate=None):
"""Reset the minitaur to its initial states.
Args:
reload_urdf: Whether to reload the urdf file. If not, Reset() just place
the minitaur back to its starting position.
"""
# UPDATE DESIRED VELOCITY AND RATE STATES
if desired_velocity is not None:
self.desired_velocity = desired_velocity
if desired_rate is not None:
self.desired_rate = desired_rate
if reload_urdf:
if self._self_collision_enabled:
self.quadruped = self._pybullet_client.loadURDF(
"%s/quadruped/minitaur.urdf" % self._urdf_root,
INIT_POSITION,
flags=self._pybullet_client.URDF_USE_SELF_COLLISION)
else:
self.quadruped = self._pybullet_client.loadURDF(
"%s/quadruped/minitaur.urdf" % self._urdf_root,
INIT_POSITION)
self._BuildJointNameToIdDict()
self._BuildMotorIdList()
self._RecordMassInfoFromURDF()
self.ResetPose(add_constraint=True)
if self._on_rack:
self._pybullet_client.createConstraint(
self.quadruped, -1, -1, -1,
self._pybullet_client.JOINT_FIXED, [0, 0, 0], [0, 0, 0],
[0, 0, 1])
else:
self._pybullet_client.resetBasePositionAndOrientation(
self.quadruped, INIT_POSITION, INIT_ORIENTATION)
self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0],
[0, 0, 0])
self.ResetPose(add_constraint=False)
self._overheat_counter = np.zeros(self.num_motors)
self._motor_enabled_list = [True] * self.num_motors\
def _SetMotorTorqueById(self, motor_id, torque):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.TORQUE_CONTROL,
force=torque)
def _SetDesiredMotorAngleById(self, motor_id, desired_angle):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.POSITION_CONTROL,
targetPosition=desired_angle,
positionGain=self._kp,
velocityGain=self._kd,
force=self._max_force)
def _SetDesiredMotorAngleByName(self, motor_name, desired_angle):
self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name],
desired_angle)
def ResetPose(self, add_constraint):
"""Reset the pose of the minitaur.
Args:
add_constraint: Whether to add a constraint at the joints of two feet.
"""
for i in range(self.num_legs):
self._ResetPoseForLeg(i, add_constraint)
def _ResetPoseForLeg(self, leg_id, add_constraint):
"""Reset the initial pose for the leg.
Args:
leg_id: It should be 0, 1, 2, or 3, which represents the leg at
front_left, back_left, front_right and back_right.
add_constraint: Whether to add a constraint at the joints of two feet.
"""
knee_friction_force = 0
half_pi = math.pi / 2.0
knee_angle = -2.1834
leg_position = LEG_POSITION[leg_id]
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "L_joint"],
self._motor_direction[2 * leg_id] * half_pi,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "L_link"],
self._motor_direction[2 * leg_id] * knee_angle,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "R_joint"],
self._motor_direction[2 * leg_id + 1] * half_pi,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "R_link"],
self._motor_direction[2 * leg_id + 1] * knee_angle,
targetVelocity=0)
if add_constraint:
self._pybullet_client.createConstraint(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "R_link"],
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "L_link"],
self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0],
KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
# Disable the default motor in pybullet.
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"L_joint"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"R_joint"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
else:
self._SetDesiredMotorAngleByName(
"motor_" + leg_position + "L_joint",
self._motor_direction[2 * leg_id] * half_pi)
self._SetDesiredMotorAngleByName(
"motor_" + leg_position + "R_joint",
self._motor_direction[2 * leg_id + 1] * half_pi)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["knee_" + leg_position +
"L_link"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["knee_" + leg_position +
"R_link"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
def GetBasePosition(self):
"""Get the position of minitaur's base.
Returns:
The position of minitaur's base.
"""
position, _ = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return position
def GetBaseOrientation(self):
"""Get the orientation of minitaur's base, represented as quaternion.
Returns:
The orientation of minitaur's base.
"""
_, orientation = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return orientation
def GetBaseTwitst(self):
"""Get the Twist of minitaur's base.
Returns:
The Twist of the minitaur's base.
"""
return self._pybullet_client.getBaseVelocity(self.quadruped)
def GetActionDimension(self):
"""Get the length of the action list.
Returns:
The length of the action list.
"""
return self.num_motors
def GetObservationUpperBound(self):
"""Get the upper bound of the observation.
Returns:
The upper bound of an observation. See GetObservation() for the details
of each element of an observation.
NOTE: Changed just like GetObservation()
"""
upper_bound = np.array([0.0] * self.GetObservationDimension())
# roll, pitch
upper_bound[0:2] = np.pi / 2.0
# acc, rate in x,y,z
upper_bound[2:8] = np.inf
# 8:10 are velocity and rate bounds, min and max are +-10
# upper_bound[8:10] = 10
# NOTE: ORIGINAL BELOW
# upper_bound[10:10 + self.num_motors] = math.pi # Joint angle.
# upper_bound[self.num_motors + 10:2 * self.num_motors + 10] = (
# motor.MOTOR_SPEED_LIMIT) # Joint velocity.
# upper_bound[2 * self.num_motors + 10:3 * self.num_motors + 10] = (
# motor.OBSERVED_TORQUE_LIMIT) # Joint torque.
# upper_bound[3 *
# self.num_motors:] = 1.0 # Quaternion of base orientation.
# print("UPPER BOUND{}".format(upper_bound))
return upper_bound
def GetObservationLowerBound(self):
"""Get the lower bound of the observation."""
return -self.GetObservationUpperBound()
def GetObservationDimension(self):
"""Get the length of the observation list.
Returns:
The length of the observation list.
"""
return len(self.GetObservation())
def GetObservation(self):
"""Get the observations of minitaur.
It includes the angles, velocities, torques and the orientation of the base.
Returns:
The observation list. observation[0:8] are motor angles. observation[8:16]
are motor velocities, observation[16:24] are motor torques.
observation[24:28] is the orientation of the base, in quaternion form.
NOTE: DIVERGES FROM STOCK MINITAUR ENV. WILL LEAVE ORIGINAL COMMENTED
For my purpose, the observation space includes Roll and Pitch, as well as
acceleration and gyroscopic rate along the x,y,z axes. All of this
information can be collected from an onboard IMU. The reward function
will contain a hidden velocity reward (fwd, bwd) which cannot be measured
and so is not included. For spinning, the gyroscopic z rate will be used
as the (explicit) velocity reward.
This version operates without motor torques, angles and velocities. Erwin
Coumans' paper suggests a sparse observation space leads to higher reward
"""
observation = []
ori = self.GetBaseOrientation()
# Get roll and pitch
roll, pitch, _ = self._pybullet_client.getEulerFromQuaternion(
[ori[0], ori[1], ori[2], ori[3]])
# Get linear accelerations and angular rates
lt, ang_twist = self.GetBaseTwitst()
lin_twist = np.array([lt[0], lt[1], lt[2]])
# Get linear accelerations
lin_acc = self.prev_lin_twist - lin_twist
# if lin_acc.all() == 0.0:
# lin_acc = self.prev_lin_acc
self.prev_lin_acc = lin_acc
# print("LIN ACC: ", lin_acc)
self.prev_lin_twist = lin_twist
# order: roll, pitch, acc(x,y,z), gyro(x,y,z)
observation.append(roll)
observation.append(pitch)
observation.extend(lin_acc.tolist())
observation.extend(list(ang_twist))
# velocity and rate
# observation.append(self.desired_velocity)
# observation.append(self.desired_rate)
# NOTE: ORIGINAL BELOW
# observation.extend(self.GetMotorAngles().tolist())
# observation.extend(self.GetMotorVelocities().tolist())
# observation.extend(self.GetMotorTorques().tolist())
# observation.extend(list(self.GetBaseOrientation()))
return observation
def ApplyAction(self, motor_commands):
"""Set the desired motor angles to the motors of the minitaur.
The desired motor angles are clipped based on the maximum allowed velocity.
If the pd_control_enabled is True, a torque is calculated according to
the difference between current and desired joint angle, as well as the joint
velocity. This torque is exerted to the motor. For more information about
PD control, please refer to: https://en.wikipedia.org/wiki/PID_controller.
Args:
motor_commands: The eight desired motor angles.
"""
if self._motor_velocity_limit < np.inf:
current_motor_angle = self.GetMotorAngles()
motor_commands_max = (current_motor_angle +
self.time_step * self._motor_velocity_limit)
motor_commands_min = (current_motor_angle -
self.time_step * self._motor_velocity_limit)
motor_commands = np.clip(motor_commands, motor_commands_min,
motor_commands_max)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
q = self.GetMotorAngles()
qdot = self.GetMotorVelocities()
if self._accurate_motor_model_enabled:
actual_torque, observed_torque = self._motor_model.convert_to_torque(
motor_commands, q, qdot)
if self._motor_overheat_protection:
for i in range(self.num_motors):
if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE:
self._overheat_counter[i] += 1
else:
self._overheat_counter[i] = 0
if (self._overheat_counter[i] >
OVERHEAT_SHUTDOWN_TIME / self.time_step):
self._motor_enabled_list[i] = False
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = observed_torque
# Transform into the motor space when applying the torque.
self._applied_motor_torque = np.multiply(
actual_torque, self._motor_direction)
for motor_id, motor_torque, motor_enabled in zip(
self._motor_id_list, self._applied_motor_torque,
self._motor_enabled_list):
if motor_enabled:
self._SetMotorTorqueById(motor_id, motor_torque)
else:
self._SetMotorTorqueById(motor_id, 0)
else:
torque_commands = -self._kp * (
q - motor_commands) - self._kd * qdot
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = torque_commands
# Transform into the motor space when applying the torque.
self._applied_motor_torques = np.multiply(
self._observed_motor_torques, self._motor_direction)
for motor_id, motor_torque in zip(self._motor_id_list,
self._applied_motor_torques):
self._SetMotorTorqueById(motor_id, motor_torque)
else:
motor_commands_with_direction = np.multiply(
motor_commands, self._motor_direction)
for motor_id, motor_command_with_direction in zip(
self._motor_id_list, motor_commands_with_direction):
self._SetDesiredMotorAngleById(motor_id,
motor_command_with_direction)
def GetMotorAngles(self):
"""Get the eight motor angles at the current moment.
Returns:
Motor angles.
"""
motor_angles = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[0]
for motor_id in self._motor_id_list
]
motor_angles = np.multiply(motor_angles, self._motor_direction)
return motor_angles
def GetMotorVelocities(self):
"""Get the velocity of all eight motors.
Returns:
Velocities of all eight motors.
"""
motor_velocities = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[1]
for motor_id in self._motor_id_list
]
motor_velocities = np.multiply(motor_velocities, self._motor_direction)
return motor_velocities
def GetMotorTorques(self):
"""Get the amount of torques the motors are exerting.
Returns:
Motor torques of all eight motors.
"""
if self._accurate_motor_model_enabled or self._pd_control_enabled:
return self._observed_motor_torques
else:
motor_torques = [
self._pybullet_client.getJointState(self.quadruped,
motor_id)[3]
for motor_id in self._motor_id_list
]
motor_torques = np.multiply(motor_torques, self._motor_direction)
return motor_torques
def ConvertFromLegModel(self, actions):
"""Convert the actions that use leg model to the real motor actions.
Args:
actions: The theta, phi of the leg model.
actions are of form = [phi, phi, phi, phi, theta, theta, theta, theta]
where phi = swing and theta = extension
Returns:
The eight desired motor angles that can be used in ApplyActions().
"""
motor_angle = copy.deepcopy(actions)
scale_for_singularity = 1
offset_for_singularity = 1.5
half_num_motors = int(self.num_motors / 2)
quater_pi = math.pi / 4
for i in range(self.num_motors):
action_idx = i // 2
forward_backward_component = (
-scale_for_singularity * quater_pi *
(actions[action_idx + half_num_motors] +
offset_for_singularity))
extension_component = (-1)**i * quater_pi * actions[action_idx]
if i >= half_num_motors:
extension_component = -extension_component
motor_angle[i] = (math.pi + forward_backward_component +
extension_component)
return motor_angle
def GetBaseMassFromURDF(self):
"""Get the mass of the base from the URDF file."""
return self._base_mass_urdf
def GetLegMassesFromURDF(self):
"""Get the mass of the legs from the URDF file."""
return self._leg_masses_urdf
def SetBaseMass(self, base_mass):
self._pybullet_client.changeDynamics(self.quadruped,
BASE_LINK_ID,
mass=base_mass)
def SetLegMasses(self, leg_masses):
"""Set the mass of the legs.
A leg includes leg_link and motor. All four leg_links have the same mass,
which is leg_masses[0]. All four motors have the same mass, which is
leg_mass[1].
Args:
leg_masses: The leg masses. leg_masses[0] is the mass of the leg link.
leg_masses[1] is the mass of the motor.
"""
for link_id in LEG_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
mass=leg_masses[0])
for link_id in MOTOR_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
mass=leg_masses[1])
def SetFootFriction(self, foot_friction):
"""Set the lateral friction of the feet.
Args:
foot_friction: The lateral friction coefficient of the foot. This value is
shared by all four feet.
"""
for link_id in FOOT_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
lateralFriction=foot_friction)
def SetBatteryVoltage(self, voltage):
if self._accurate_motor_model_enabled:
self._motor_model.set_voltage(voltage)
def SetMotorViscousDamping(self, viscous_damping):
if self._accurate_motor_model_enabled:
self._motor_model.set_viscous_damping(viscous_damping) | 25,949 | Python | 42.540268 | 85 | 0.582951 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/minitaur_gym_env.py | """This file implements the gym environment of minitaur.
"""
import os
import inspect
import math
import time
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import pybullet
import pybullet_utils.bullet_client as bc
from . import minitaur
import pybullet_data
from . import minitaur_env_randomizer
from pkg_resources import parse_version
from gym.envs.registration import register
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
NUM_SUBSTEPS = 5
NUM_MOTORS = 8
MOTOR_ANGLE_OBSERVATION_INDEX = 0
MOTOR_VELOCITY_OBSERVATION_INDEX = MOTOR_ANGLE_OBSERVATION_INDEX + NUM_MOTORS
MOTOR_TORQUE_OBSERVATION_INDEX = MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS
BASE_ORIENTATION_OBSERVATION_INDEX = MOTOR_TORQUE_OBSERVATION_INDEX + NUM_MOTORS
ACTION_EPS = 0.01
OBSERVATION_EPS = 0.01
RENDER_HEIGHT = 720
RENDER_WIDTH = 960
# Register as OpenAI Gym Environment
register(
id="MinitaurBulletEnv-v999",
entry_point='mini_bullet.minitaur_gym_env:MinitaurBulletEnv',
max_episode_steps=500,
)
class MinitaurBulletEnv(gym.Env):
"""The gym environment for the minitaur.
It simulates the locomotion of a minitaur, a quadruped robot. The state space
include the angles, velocities and torques for all the motors and the action
space is the desired motor angle for each motor. The reward function is based
on how far the minitaur walks in 1000 steps and penalizes the energy
expenditure.
"""
metadata = {
"render.modes": ["human", "rgb_array"],
"video.frames_per_second": 50
}
def __init__(
self,
urdf_root=pybullet_data.getDataPath(),
action_repeat=1,
# WEIGHTS
distance_weight=1.0,
rotation_weight=1.0,
energy_weight=0.0005,
shake_weight=0.005,
drift_weight=2.0,
rp_weight=0.1,
rate_weight=0.1,
distance_limit=float("inf"),
observation_noise_stdev=0.0,
self_collision_enabled=True,
motor_velocity_limit=np.inf,
pd_control_enabled=False, # not needed to be true if accurate motor model is enabled (has its own better PD)
leg_model_enabled=True,
accurate_motor_model_enabled=True,
motor_kp=0.7,
motor_kd=0.02,
torque_control_enabled=False,
motor_overheat_protection=True,
hard_reset=True,
on_rack=False,
render=False,
kd_for_pd_controllers=0.3,
env_randomizer=minitaur_env_randomizer.MinitaurEnvRandomizer(),
desired_velocity=0.5,
desired_rate=0.0,
lateral=False):
"""Initialize the minitaur gym environment.
Args:
urdf_root: The path to the urdf data folder.
action_repeat: The number of simulation steps before actions are applied.
distance_weight: The weight of the distance term in the reward.
energy_weight: The weight of the energy term in the reward.
shake_weight: The weight of the vertical shakiness term in the reward.
drift_weight: The weight of the sideways drift term in the reward.
distance_limit: The maximum distance to terminate the episode.
observation_noise_stdev: The standard deviation of observation noise.
self_collision_enabled: Whether to enable self collision in the sim.
motor_velocity_limit: The velocity limit of each motor.
pd_control_enabled: Whether to use PD controller for each motor.
leg_model_enabled: Whether to use a leg motor to reparameterize the action
space.
accurate_motor_model_enabled: Whether to use the accurate DC motor model.
motor_kp: proportional gain for the accurate motor model.
motor_kd: derivative gain for the accurate motor model.
torque_control_enabled: Whether to use the torque control, if set to
False, pose control will be used.
motor_overheat_protection: Whether to shutdown the motor that has exerted
large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
(OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
details.
hard_reset: Whether to wipe the simulation and load everything when reset
is called. If set to false, reset just place the minitaur back to start
position and set its pose to initial configuration.
on_rack: Whether to place the minitaur on rack. This is only used to debug
the walking gait. In this mode, the minitaur's base is hanged midair so
that its walking gait is clearer to visualize.
render: Whether to render the simulation.
kd_for_pd_controllers: kd value for the pd controllers of the motors
env_randomizer: An EnvRandomizer to randomize the physical properties
during reset().
"""
self._time_step = 0.01
self._action_repeat = action_repeat
self._num_bullet_solver_iterations = 300
self._urdf_root = urdf_root
self._self_collision_enabled = self_collision_enabled
self._motor_velocity_limit = motor_velocity_limit
self._observation = []
self._env_step_counter = 0
self._is_render = render
self._last_base_position = [0, 0, 0]
self._distance_weight = distance_weight
self._rotation_weight = rotation_weight
self._energy_weight = energy_weight
self._drift_weight = drift_weight
self._shake_weight = shake_weight
self._rp_weight = rp_weight
self._rate_weight = rate_weight
self._distance_limit = distance_limit
self._observation_noise_stdev = observation_noise_stdev
self._action_bound = 1
self._pd_control_enabled = pd_control_enabled
self._leg_model_enabled = leg_model_enabled
self._accurate_motor_model_enabled = accurate_motor_model_enabled
self._motor_kp = motor_kp
self._motor_kd = motor_kd
self._torque_control_enabled = torque_control_enabled
self._motor_overheat_protection = motor_overheat_protection
self._on_rack = on_rack
self._cam_dist = 1.0
self._cam_yaw = 0
self._cam_pitch = -30
self._hard_reset = True
self._kd_for_pd_controllers = kd_for_pd_controllers
self._last_frame_time = 0.0
print("urdf_root=" + self._urdf_root)
self._env_randomizer = env_randomizer
# PD control needs smaller time step for stability.
if pd_control_enabled or accurate_motor_model_enabled:
self._time_step /= NUM_SUBSTEPS
self._num_bullet_solver_iterations /= NUM_SUBSTEPS
self._action_repeat *= NUM_SUBSTEPS
if self._is_render:
self._pybullet_client = bc.BulletClient(
connection_mode=pybullet.GUI)
else:
self._pybullet_client = bc.BulletClient()
self.seed()
np.random.seed(0)
self.desired_velocity = desired_velocity
self.desired_rate = desired_rate
# Change fwd/bwd reward to side-side reward
self.lateral = lateral
self.reset()
observation_high = (self.minitaur.GetObservationUpperBound() +
OBSERVATION_EPS)
observation_low = (self.minitaur.GetObservationLowerBound() -
OBSERVATION_EPS)
action_dim = 8
action_high = np.array([self._action_bound] * action_dim)
self.action_space = spaces.Box(-action_high,
action_high,
dtype=np.float32)
self.observation_space = spaces.Box(observation_low,
observation_high,
dtype=np.float32)
self.viewer = None
self._hard_reset = hard_reset # This assignment need to be after reset()
def set_env_randomizer(self, env_randomizer):
self._env_randomizer = env_randomizer
def configure(self, args):
self._args = args
def reset(self, desired_velocity=None, desired_rate=None):
if desired_velocity is not None:
self.desired_velocity = desired_velocity
if desired_rate is not None:
self.desired_rate = desired_rate
if self._hard_reset:
self._pybullet_client.resetSimulation()
self._pybullet_client.setPhysicsEngineParameter(
numSolverIterations=int(self._num_bullet_solver_iterations))
self._pybullet_client.setTimeStep(self._time_step)
plane = self._pybullet_client.loadURDF("%s/plane.urdf" %
self._urdf_root)
self._pybullet_client.changeVisualShape(plane,
-1,
rgbaColor=[1, 1, 1, 0.9])
self._pybullet_client.configureDebugVisualizer(
self._pybullet_client.COV_ENABLE_PLANAR_REFLECTION, 0)
self._pybullet_client.setGravity(0, 0, -9.81)
acc_motor = self._accurate_motor_model_enabled
motor_protect = self._motor_overheat_protection
self.minitaur = (minitaur.Minitaur(
pybullet_client=self._pybullet_client,
urdf_root=self._urdf_root,
time_step=self._time_step,
self_collision_enabled=self._self_collision_enabled,
motor_velocity_limit=self._motor_velocity_limit,
pd_control_enabled=self._pd_control_enabled,
accurate_motor_model_enabled=acc_motor,
motor_kp=self._motor_kp,
motor_kd=self._motor_kd,
torque_control_enabled=self._torque_control_enabled,
motor_overheat_protection=motor_protect,
on_rack=self._on_rack,
kd_for_pd_controllers=self._kd_for_pd_controllers,
desired_velocity=self.desired_velocity,
desired_rate=self.desired_rate))
else:
self.minitaur.Reset(reload_urdf=False,
desired_velocity=self.desired_velocity,
desired_rate=self.desired_rate)
if self._env_randomizer is not None:
self._env_randomizer.randomize_env(self)
self._env_step_counter = 0
self._last_base_position = [0, 0, 0]
self._objectives = []
self._pybullet_client.resetDebugVisualizerCamera(
self._cam_dist, self._cam_yaw, self._cam_pitch, [0, 0, 0])
if not self._torque_control_enabled:
for _ in range(100):
if self._pd_control_enabled or self._accurate_motor_model_enabled:
self.minitaur.ApplyAction([math.pi / 2] * 8)
self._pybullet_client.stepSimulation()
return self._noisy_observation()
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def _transform_action_to_motor_command(self, action):
if self._leg_model_enabled:
for i, action_component in enumerate(action):
if not (-self._action_bound - ACTION_EPS <= action_component <=
self._action_bound + ACTION_EPS):
raise ValueError("{}th action {} out of bounds.".format(
i, action_component))
action = self.minitaur.ConvertFromLegModel(action)
return action
def step(self, action):
"""Step forward the simulation, given the action.
Args:
action: A list of desired motor angles for eight motors.
Returns:
observations: The angles, velocities and torques of all motors.
reward: The reward for the current state-action pair.
done: Whether the episode has ended.
info: A dictionary that stores diagnostic information.
Raises:
ValueError: The action dimension is not the same as the number of motors.
ValueError: The magnitude of actions is out of bounds.
"""
if self._is_render:
# Sleep, otherwise the computation takes less time than real time,
# which will make the visualization like a fast-forward video.
time_spent = time.time() - self._last_frame_time
self._last_frame_time = time.time()
time_to_sleep = self._action_repeat * self._time_step - time_spent
if time_to_sleep > 0:
time.sleep(time_to_sleep)
base_pos = self.minitaur.GetBasePosition()
camInfo = self._pybullet_client.getDebugVisualizerCamera()
curTargetPos = camInfo[11]
distance = camInfo[10]
yaw = camInfo[8]
pitch = camInfo[9]
targetPos = [
0.95 * curTargetPos[0] + 0.05 * base_pos[0],
0.95 * curTargetPos[1] + 0.05 * base_pos[1], curTargetPos[2]
]
self._pybullet_client.resetDebugVisualizerCamera(
distance, yaw, pitch, base_pos)
action = self._transform_action_to_motor_command(action)
for _ in range(self._action_repeat):
self.minitaur.ApplyAction(action)
self._pybullet_client.stepSimulation()
self._env_step_counter += 1
reward = self._reward()
done = self._termination()
return np.array(self._noisy_observation()), reward, done, {}
def render(self, mode="rgb_array", close=False):
if mode != "rgb_array":
return np.array([])
base_pos = self.minitaur.GetBasePosition()
view_matrix = self._pybullet_client.computeViewMatrixFromYawPitchRoll(
cameraTargetPosition=base_pos,
distance=self._cam_dist,
yaw=self._cam_yaw,
pitch=self._cam_pitch,
roll=0,
upAxisIndex=2)
proj_matrix = self._pybullet_client.computeProjectionMatrixFOV(
fov=60,
aspect=float(RENDER_WIDTH) / RENDER_HEIGHT,
nearVal=0.1,
farVal=100.0)
(_, _, px, _, _) = self._pybullet_client.getCameraImage(
width=RENDER_WIDTH,
height=RENDER_HEIGHT,
viewMatrix=view_matrix,
projectionMatrix=proj_matrix,
renderer=pybullet.ER_BULLET_HARDWARE_OPENGL)
rgb_array = np.array(px)
rgb_array = rgb_array[:, :, :3]
return rgb_array
def get_minitaur_motor_angles(self):
"""Get the minitaur's motor angles.
Returns:
A numpy array of motor angles.
"""
return np.array(
self._observation[MOTOR_ANGLE_OBSERVATION_INDEX:
MOTOR_ANGLE_OBSERVATION_INDEX + NUM_MOTORS])
def get_minitaur_motor_velocities(self):
"""Get the minitaur's motor velocities.
Returns:
A numpy array of motor velocities.
"""
return np.array(
self._observation[MOTOR_VELOCITY_OBSERVATION_INDEX:
MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS])
def get_minitaur_motor_torques(self):
"""Get the minitaur's motor torques.
Returns:
A numpy array of motor torques.
"""
return np.array(
self._observation[MOTOR_TORQUE_OBSERVATION_INDEX:
MOTOR_TORQUE_OBSERVATION_INDEX + NUM_MOTORS])
def get_minitaur_base_orientation(self):
"""Get the minitaur's base orientation, represented by a quaternion.
Returns:
A numpy array of minitaur's orientation.
"""
return np.array(self._observation[BASE_ORIENTATION_OBSERVATION_INDEX:])
def is_fallen(self):
"""Decide whether the minitaur has fallen.
If the up directions between the base and the world is larger (the dot
product is smaller than 0.85) or the base is very low on the ground
(the height is smaller than 0.13 meter), the minitaur is considered fallen.
Returns:
Boolean value that indicates whether the minitaur has fallen.
"""
orientation = self.minitaur.GetBaseOrientation()
rot_mat = self._pybullet_client.getMatrixFromQuaternion(orientation)
local_up = rot_mat[6:]
pos = self.minitaur.GetBasePosition()
return (np.dot(np.asarray([0, 0, 1]), np.asarray(local_up)) < 0.85
or pos[2] < 0.10)
def _termination(self):
position = self.minitaur.GetBasePosition()
distance = math.sqrt(position[0]**2 + position[1]**2)
return self.is_fallen() or distance > self._distance_limit
def _reward(self):
""" NOTE: reward now consists of:
roll, pitch at desired 0
acc (y,z) = 0
FORWARD-BACKWARD: rate(x,y,z) = 0
--> HIDDEN REWARD: x(+-) velocity reference, not incl. in obs
SPIN: acc(x) = 0, rate(x,y) = 0, rate (z) = rate reference
Also include drift, energy vanilla rewards
"""
current_base_position = self.minitaur.GetBasePosition()
# get observation
obs = self._get_observation()
# forward_reward = current_base_position[0] - self._last_base_position[0]
# POSITIVE FOR FORWARD, NEGATIVE FOR BACKWARD | NOTE: HIDDEN
fwd_speed = self.minitaur.prev_lin_twist[0]
lat_speed = self.minitaur.prev_lin_twist[1]
# print("FORWARD SPEED: {} \t STATE SPEED: {}".format(
# fwd_speed, self.desired_velocity))
# self.desired_velocity = 0.4
# Modification for lateral/fwd rewards
# FORWARD
if not self.lateral:
# f(x)=-(x-desired))^(2)*((1/desired)^2)+1
# to make sure that at 0vel there is 0 reawrd.
# also squishes allowable tolerance
reward_max = 1.0
forward_reward = reward_max * np.exp(
-(fwd_speed - self.desired_velocity)**2 / (0.1))
# LATERAL
else:
reward_max = 1.0
forward_reward = reward_max * np.exp(
-(lat_speed - self.desired_rate)**2 / (0.1))
if forward_reward < 0.0:
forward_reward = 0.0
yaw_rate = obs[7]
if self.desired_rate != 0:
rot_reward = (-(yaw_rate - (self.desired_rate))**2) * (
(1.0 / self.desired_rate)**2) + 1.0
else:
rot_reward = (-(yaw_rate -
(self.desired_rate))**2) * ((1.0 / 0.1)**2) + 1.0
# Make sure that for forward-policy there is the appropriate rotation penalty
if self.desired_velocity != 0:
self._rotation_weight = self._rate_weight
rot_reward = -abs(obs[7])
elif self.desired_rate != 0:
forward_reward = 0.0
# penalty for nonzero roll, pitch
rp_reward = -(abs(obs[0]) + abs(obs[1]))
# print("ROLL: {} \t PITCH: {}".format(obs[0], obs[1]))
# penalty for nonzero acc(z)
shake_reward = -abs(obs[4])
# penalty for nonzero rate (x,y,z)
rate_reward = -(abs(obs[5]) + abs(obs[6]))
# drift_reward = -abs(current_base_position[1] -
# self._last_base_position[1])
# this penalizes absolute error, and does not penalize correction
# NOTE: for side-side, drift reward becomes in x instead
drift_reward = -abs(current_base_position[1])
# If Lateral, change drift reward
if self.lateral:
drift_reward = -abs(current_base_position[0])
# shake_reward = -abs(current_base_position[2] -
# self._last_base_position[2])
self._last_base_position = current_base_position
energy_reward = -np.abs(
np.dot(self.minitaur.GetMotorTorques(),
self.minitaur.GetMotorVelocities())) * self._time_step
reward = (self._distance_weight * forward_reward +
self._rotation_weight * rot_reward +
self._energy_weight * energy_reward +
self._drift_weight * drift_reward +
self._shake_weight * shake_reward +
self._rp_weight * rp_reward +
self._rate_weight * rate_reward)
self._objectives.append(
[forward_reward, energy_reward, drift_reward, shake_reward])
return reward
def get_objectives(self):
return self._objectives
def _get_observation(self):
self._observation = self.minitaur.GetObservation()
return self._observation
def _noisy_observation(self):
self._get_observation()
observation = np.array(self._observation)
if self._observation_noise_stdev > 0:
observation += (self.np_random.normal(
scale=self._observation_noise_stdev, size=observation.shape) *
self.minitaur.GetObservationUpperBound())
return observation
if parse_version(gym.__version__) < parse_version('0.9.6'):
_render = render
_reset = reset
_seed = seed
_step = step | 21,275 | Python | 40.554687 | 121 | 0.600188 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/minitaur_env_randomizer.py | """Randomize the minitaur_gym_env when reset() is called."""
import numpy as np
from . import env_randomizer_base
# Relative range.
MINITAUR_BASE_MASS_ERROR_RANGE = (-0.2, 0.2) # 0.2 means 20%
MINITAUR_LEG_MASS_ERROR_RANGE = (-0.2, 0.2) # 0.2 means 20%
# Absolute range.
BATTERY_VOLTAGE_RANGE = (14.8, 16.8) # Unit: Volt
MOTOR_VISCOUS_DAMPING_RANGE = (0, 0.01) # Unit: N*m*s/rad (torque/angular vel)
MINITAUR_LEG_FRICTION = (0.8, 1.5) # Unit: dimensionless
class MinitaurEnvRandomizer(env_randomizer_base.EnvRandomizerBase):
"""A randomizer that change the minitaur_gym_env during every reset."""
def __init__(self,
minitaur_base_mass_err_range=MINITAUR_BASE_MASS_ERROR_RANGE,
minitaur_leg_mass_err_range=MINITAUR_LEG_MASS_ERROR_RANGE,
battery_voltage_range=BATTERY_VOLTAGE_RANGE,
motor_viscous_damping_range=MOTOR_VISCOUS_DAMPING_RANGE):
self._minitaur_base_mass_err_range = minitaur_base_mass_err_range
self._minitaur_leg_mass_err_range = minitaur_leg_mass_err_range
self._battery_voltage_range = battery_voltage_range
self._motor_viscous_damping_range = motor_viscous_damping_range
np.random.seed(0)
def randomize_env(self, env):
self._randomize_minitaur(env.minitaur)
def _randomize_minitaur(self, minitaur):
"""Randomize various physical properties of minitaur.
It randomizes the mass/inertia of the base, mass/inertia of the legs,
friction coefficient of the feet, the battery voltage and the motor damping
at each reset() of the environment.
Args:
minitaur: the Minitaur instance in minitaur_gym_env environment.
"""
base_mass = minitaur.GetBaseMassFromURDF()
randomized_base_mass = np.random.uniform(
base_mass * (1.0 + self._minitaur_base_mass_err_range[0]),
base_mass * (1.0 + self._minitaur_base_mass_err_range[1]))
minitaur.SetBaseMass(randomized_base_mass)
leg_masses = minitaur.GetLegMassesFromURDF()
leg_masses_lower_bound = np.array(leg_masses) * (
1.0 + self._minitaur_leg_mass_err_range[0])
leg_masses_upper_bound = np.array(leg_masses) * (
1.0 + self._minitaur_leg_mass_err_range[1])
randomized_leg_masses = [
np.random.uniform(leg_masses_lower_bound[i],
leg_masses_upper_bound[i])
for i in range(len(leg_masses))
]
minitaur.SetLegMasses(randomized_leg_masses)
randomized_battery_voltage = np.random.uniform(
BATTERY_VOLTAGE_RANGE[0], BATTERY_VOLTAGE_RANGE[1])
minitaur.SetBatteryVoltage(randomized_battery_voltage)
randomized_motor_damping = np.random.uniform(
MOTOR_VISCOUS_DAMPING_RANGE[0], MOTOR_VISCOUS_DAMPING_RANGE[1])
minitaur.SetMotorViscousDamping(randomized_motor_damping)
randomized_foot_friction = np.random.uniform(MINITAUR_LEG_FRICTION[0],
MINITAUR_LEG_FRICTION[1])
minitaur.SetFootFriction(randomized_foot_friction)
| 3,133 | Python | 43.771428 | 79 | 0.651452 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/motor.py | """This file implements an accurate motor model."""
import numpy as np
VOLTAGE_CLIPPING = 50
OBSERVED_TORQUE_LIMIT = 5.7
MOTOR_VOLTAGE = 16.0
MOTOR_RESISTANCE = 0.186
MOTOR_TORQUE_CONSTANT = 0.0954
MOTOR_VISCOUS_DAMPING = 0
MOTOR_SPEED_LIMIT = MOTOR_VOLTAGE / (MOTOR_VISCOUS_DAMPING +
MOTOR_TORQUE_CONSTANT)
class MotorModel(object):
"""The accurate motor model, which is based on the physics of DC motors.
The motor model support two types of control: position control and torque
control. In position control mode, a desired motor angle is specified, and a
torque is computed based on the internal motor model. When the torque control
is specified, a pwm signal in the range of [-1.0, 1.0] is converted to the
torque.
The internal motor model takes the following factors into consideration:
pd gains, viscous friction, back-EMF voltage and current-torque profile.
"""
def __init__(self, torque_control_enabled=False, kp=1.2, kd=0):
self._torque_control_enabled = torque_control_enabled
self._kp = kp
self._kd = kd
self._resistance = MOTOR_RESISTANCE
self._voltage = MOTOR_VOLTAGE
self._torque_constant = MOTOR_TORQUE_CONSTANT
self._viscous_damping = MOTOR_VISCOUS_DAMPING
self._current_table = [0, 10, 20, 30, 40, 50, 60]
self._torque_table = [0, 1, 1.9, 2.45, 3.0, 3.25, 3.5]
def set_voltage(self, voltage):
self._voltage = voltage
def get_voltage(self):
return self._voltage
def set_viscous_damping(self, viscous_damping):
self._viscous_damping = viscous_damping
def get_viscous_dampling(self):
return self._viscous_damping
def convert_to_torque(self, motor_commands, current_motor_angle,
current_motor_velocity):
"""Convert the commands (position control or torque control) to torque.
Args:
motor_commands: The desired motor angle if the motor is in position
control mode. The pwm signal if the motor is in torque control mode.
current_motor_angle: The motor angle at the current time step.
current_motor_velocity: The motor velocity at the current time step.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
if self._torque_control_enabled:
pwm = motor_commands
else:
pwm = (-self._kp * (current_motor_angle - motor_commands) -
self._kd * current_motor_velocity)
pwm = np.clip(pwm, -1.0, 1.0)
return self._convert_to_torque_from_pwm(pwm, current_motor_velocity)
def _convert_to_torque_from_pwm(self, pwm, current_motor_velocity):
"""Convert the pwm signal to torque.
Args:
pwm: The pulse width modulation.
current_motor_velocity: The motor velocity at the current time step.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
observed_torque = np.clip(
self._torque_constant * (pwm * self._voltage / self._resistance),
-OBSERVED_TORQUE_LIMIT, OBSERVED_TORQUE_LIMIT)
# Net voltage is clipped at 50V by diodes on the motor controller.
voltage_net = np.clip(
pwm * self._voltage -
(self._torque_constant + self._viscous_damping) *
current_motor_velocity, -VOLTAGE_CLIPPING, VOLTAGE_CLIPPING)
current = voltage_net / self._resistance
current_sign = np.sign(current)
current_magnitude = np.absolute(current)
# Saturate torque based on empirical current relation.
actual_torque = np.interp(current_magnitude, self._current_table,
self._torque_table)
actual_torque = np.multiply(current_sign, actual_torque)
return actual_torque, observed_torque
| 3,985 | Python | 39.673469 | 79 | 0.652698 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/heightfield.py | import pybullet as p
import pybullet_data as pd
import math
import time
textureId = -1
useProgrammatic = 0
useTerrainFromPNG = 1
useDeepLocoCSV = 2
updateHeightfield = False
heightfieldSource = useProgrammatic
import random
random.seed(10)
class HeightField():
def __init__(self):
self.hf_id = 0
def _generate_field(self, env, heightPerturbationRange=0.08):
env.pybullet_client.setAdditionalSearchPath(pd.getDataPath())
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 0)
heightPerturbationRange = heightPerturbationRange
if heightfieldSource == useProgrammatic:
numHeightfieldRows = 256
numHeightfieldColumns = 256
heightfieldData = [0] * numHeightfieldRows * numHeightfieldColumns
for j in range(int(numHeightfieldColumns / 2)):
for i in range(int(numHeightfieldRows / 2)):
height = random.uniform(0, heightPerturbationRange)
heightfieldData[2 * i +
2 * j * numHeightfieldRows] = height
heightfieldData[2 * i + 1 +
2 * j * numHeightfieldRows] = height
heightfieldData[2 * i +
(2 * j + 1) * numHeightfieldRows] = height
heightfieldData[2 * i + 1 +
(2 * j + 1) * numHeightfieldRows] = height
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.05, .05, 1],
heightfieldTextureScaling=(numHeightfieldRows - 1) / 2,
heightfieldData=heightfieldData,
numHeightfieldRows=numHeightfieldRows,
numHeightfieldColumns=numHeightfieldColumns)
terrain = env.pybullet_client.createMultiBody(
0, terrainShape)
env.pybullet_client.resetBasePositionAndOrientation(
terrain, [0, 0, 0], [0, 0, 0, 1])
if heightfieldSource == useDeepLocoCSV:
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.5, .5, 2.5],
fileName="heightmaps/ground0.txt",
heightfieldTextureScaling=128)
terrain = env.pybullet_client.createMultiBody(
0, terrainShape)
env.pybullet_client.resetBasePositionAndOrientation(
terrain, [0, 0, 0], [0, 0, 0, 1])
if heightfieldSource == useTerrainFromPNG:
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.05, .05, 5],
fileName="heightmaps/wm_height_out.png")
textureId = env.pybullet_client.loadTexture(
"heightmaps/gimp_overlay_out.png")
terrain = env.pybullet_client.createMultiBody(
0, terrainShape)
env.pybullet_client.changeVisualShape(terrain,
-1,
textureUniqueId=textureId)
self.hf_id = terrainShape
print("TERRAIN SHAPE: {}".format(terrainShape))
env.pybullet_client.changeVisualShape(terrain,
-1,
rgbaColor=[1, 1, 1, 1])
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 1)
| 3,706 | Python | 40.188888 | 78 | 0.565839 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/softQnetwork.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
class SoftQNetwork(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size, init_w=3e-3):
super(SoftQNetwork, self).__init__()
self.q1 = nn.Sequential(
nn.Linear(num_inputs + num_actions, hidden_size), nn.ReLU(),
nn.Linear(hidden_size, hidden_size), nn.ReLU(),
nn.Linear(hidden_size, 1)
)
self.q2 = nn.Sequential(
nn.Linear(num_inputs + num_actions, hidden_size), nn.ReLU(),
nn.Linear(hidden_size, hidden_size), nn.ReLU(),
nn.Linear(hidden_size, 1)
)
def forward(self, state, action):
state_action = torch.cat([state, action], 1)
return self.q1(state_action), self.q2(state_action)
| 866 | Python | 35.124999 | 74 | 0.615473 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/policynetwork.py | import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
class PolicyNetwork(nn.Module):
def __init__(self,
num_inputs,
num_actions,
hidden_size,
init_w=3e-3,
log_std_min=-20,
log_std_max=2):
super(PolicyNetwork, self).__init__()
self.log_std_min = log_std_min
self.log_std_max = log_std_max
self.linear1 = nn.Linear(num_inputs, hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.mean_linear = nn.Linear(hidden_size, num_actions)
self.mean_linear.weight.data.uniform_(-init_w, init_w)
self.mean_linear.bias.data.uniform_(-init_w, init_w)
self.log_std_linear1 = nn.Linear(hidden_size, hidden_size)
self.log_std_linear2 = nn.Linear(hidden_size, num_actions)
self.log_std_linear2.weight.data.uniform_(-init_w, init_w)
self.log_std_linear2.bias.data.uniform_(-init_w, init_w)
# self.log_std_linear.weight.data.zero_()
# self.log_std_linear.bias.data.zero_()
def forward(self, state):
x = F.relu(self.linear1(state))
x = F.relu(self.linear2(x))
mean = self.mean_linear(x)
log_std = self.log_std_linear2(F.relu(self.log_std_linear1(x)))
log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)
return mean, log_std
def evaluate(self, state, epsilon=1e-6):
mean, log_std = self.forward(state)
std = log_std.exp()
normal = Normal(mean, std)
z = normal.rsample()
action = torch.tanh(z)
log_prob = normal.log_prob(z) - torch.log(1 - action.pow(2) + epsilon)
log_prob = log_prob.sum(-1, keepdim=True)
return action, log_prob, z, mean, log_std
def get_action(self, state):
state = torch.FloatTensor(state).unsqueeze(0).to(device)
mean, log_std = self.forward(state)
std = log_std.exp()
normal = Normal(mean, std)
z = normal.sample()
action = torch.tanh(z)
action = action.detach().cpu().numpy()
return action[0]
| 2,319 | Python | 31.222222 | 78 | 0.593359 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/replay_buffer.py | import numpy as np
import random
class ReplayBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = []
self.position = 0
def push(self, state, action, reward, next_state, done):
if len(self.buffer) < self.capacity:
self.buffer.append(None)
self.buffer[self.position] = (state, action, reward, next_state, done)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
batch = random.sample(self.buffer, batch_size)
state, action, reward, next_state, done = map(np.stack, zip(*batch))
return state, action, reward, next_state, done
def __len__(self):
return len(self.buffer)
| 733 | Python | 30.913042 | 78 | 0.619372 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/__init__.py | from .sac import SoftActorCritic
from .policynetwork import PolicyNetwork
from .replay_buffer import ReplayBuffer
from .normalized_actions import NormalizedActions
| 164 | Python | 31.999994 | 49 | 0.865854 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/normalized_actions.py | import gym
import numpy as np
class NormalizedActions(gym.ActionWrapper):
def action(self, action):
low_bound = self.action_space.low
upper_bound = self.action_space.high
action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound)
action = np.clip(action, low_bound, upper_bound)
return action
def reverse_action(self, action):
low_bound = self.action_space.low
upper_bound = self.action_space.high
action = 2 * (action - low_bound) / (upper_bound - low_bound) - 1
action = np.clip(action, low_bound, upper_bound)
return actions
| 638 | Python | 26.782608 | 77 | 0.62069 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/sac.py | import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
# alg specific imports
from .softQnetwork import SoftQNetwork
from .valuenetwork import ValueNetwork
class SoftActorCritic(object):
def __init__(self,
policy,
state_dim,
action_dim,
replay_buffer,
hidden_dim=256,
soft_q_lr=3e-3,
policy_lr=3e-3,
device=torch.device(
"cuda:1" if torch.cuda.is_available() else "cpu")):
self.device = device
# set up the networks
self.policy_net = policy.to(device)
self.soft_q_net = SoftQNetwork(state_dim, action_dim,
hidden_dim).to(device)
self.target_soft_q_net = SoftQNetwork(state_dim, action_dim,
hidden_dim).to(device)
# ent coeff
self.target_entropy = -action_dim
self.log_ent_coef = torch.FloatTensor(np.log(np.array([.1
]))).to(device)
self.log_ent_coef.requires_grad = True
# copy the target params over
for target_param, param in zip(self.target_soft_q_net.parameters(),
self.soft_q_net.parameters()):
target_param.data.copy_(param.data)
# set the losses
self.soft_q_criterion = nn.MSELoss()
# set the optimizers
self.soft_q_optimizer = optim.Adam(self.soft_q_net.parameters(),
lr=soft_q_lr)
self.policy_optimizer = optim.Adam(self.policy_net.parameters(),
lr=policy_lr)
self.ent_coef_optimizer = optim.Adam([self.log_ent_coef], lr=3e-3)
# reference the replay buffer
self.replay_buffer = replay_buffer
self.log = {'entropy_loss': [], 'q_value_loss': [], 'policy_loss': []}
def soft_q_update(self, batch_size, gamma=0.99, soft_tau=0.01):
state, action, reward, next_state, done = self.replay_buffer.sample(
batch_size)
state = torch.FloatTensor(state).to(self.device)
next_state = torch.FloatTensor(next_state).to(self.device)
action = torch.FloatTensor(action).to(self.device)
reward = torch.FloatTensor(reward).unsqueeze(1).to(self.device)
done = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(self.device)
ent_coef = torch.exp(self.log_ent_coef.detach())
new_action, log_prob, z, mean, log_std = self.policy_net.evaluate(
next_state)
target_q1_value, target_q2_value = self.target_soft_q_net(
next_state, new_action)
target_value = reward + (1 - done) * gamma * (
torch.min(target_q2_value, target_q2_value) - ent_coef * log_prob)
expected_q1_value, expected_q2_value = self.soft_q_net(state, action)
q_value_loss = self.soft_q_criterion(expected_q1_value, target_value.detach()) \
+ self.soft_q_criterion(expected_q2_value, target_value.detach())
self.soft_q_optimizer.zero_grad()
q_value_loss.backward()
self.soft_q_optimizer.step()
new_action, log_prob, z, mean, log_std = self.policy_net.evaluate(
state)
expected_new_q1_value, expected_new_q2_value = self.soft_q_net(
state, new_action)
expected_new_q_value = torch.min(expected_new_q1_value,
expected_new_q2_value)
policy_loss = (ent_coef * log_prob - expected_new_q_value).mean()
self.policy_optimizer.zero_grad()
policy_loss.backward()
self.policy_optimizer.step()
self.ent_coef_optimizer.zero_grad()
ent_loss = torch.mean(
torch.exp(self.log_ent_coef) *
(-log_prob - self.target_entropy).detach())
ent_loss.backward()
self.ent_coef_optimizer.step()
for target_param, param in zip(self.target_soft_q_net.parameters(),
self.soft_q_net.parameters()):
target_param.data.copy_(target_param.data * (1.0 - soft_tau) +
param.data * soft_tau)
self.log['q_value_loss'].append(q_value_loss.item())
self.log['entropy_loss'].append(ent_loss.item())
self.log['policy_loss'].append(policy_loss.item())
def save(self, filename):
torch.save(self.policy_net.state_dict(), filename + "_policy_net")
torch.save(self.policy_optimizer.state_dict(),
filename + "_policy_optimizer")
torch.save(self.soft_q_net.state_dict(), filename + "_soft_q_net")
torch.save(self.soft_q_optimizer.state_dict(),
filename + "_soft_q_optimizer")
def load(self, filename):
self.policy_net.load_state_dict(
torch.load(filename + "_policy_net", map_location=self.device))
self.policy_optimizer.load_state_dict(
torch.load(filename + "_policy_optimizer",
map_location=self.device))
# self.soft_q_net.load_state_dict(
# torch.load(filename + "_soft_q_net", map_location=self.device))
# self.soft_q_optimizer.load_state_dict(
# torch.load(filename + "_soft_q_optimizer",
# map_location=self.device))
# self.target_soft_q_net = copy.deepcopy(self.soft_q_net)
| 5,614 | Python | 40.286764 | 93 | 0.563591 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/sac_lib/valuenetwork.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
class ValueNetwork(nn.Module):
def __init__(self, state_dim, hidden_dim, init_w=3e-3):
super(ValueNetwork, self).__init__()
self.linear1 = nn.Linear(state_dim, hidden_dim)
self.linear2 = nn.Linear(hidden_dim, hidden_dim)
self.linear3 = nn.Linear(hidden_dim, 1)
self.linear3.weight.data.uniform_(-init_w, init_w)
self.linear3.bias.data.uniform_(-init_w, init_w)
def forward(self, state):
x = F.relu(self.linear1(state))
x = F.relu(self.linear2(x))
x = self.linear3(x)
return x
| 726 | Python | 30.608694 | 59 | 0.62259 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/tg_lib/traj_gen.py | import numpy as np
PHASE_PERIOD = 2.0 * np.pi
class CyclicIntegrator():
def __init__(self, dphi_leg=0.0):
# Phase starts with offset
self.tprime = PHASE_PERIOD * dphi_leg
def progress_tprime(self, dt, f_tg, swing_stance_speed_ratio):
""" swing_stance_speed_ratio is Beta in the paper
set by policy at each step, but default is 1/3
delta_period is just dt
This moves the phase based on delta
(which is one parameter * delta_time_step).
The speed of the phase depends on swing vs stance phase
(phase > np.pi or phase < np.pi) which has different speeds.
"""
time_mult = dt * f_tg
stance_speed_coef = (swing_stance_speed_ratio +
1) * 0.5 / swing_stance_speed_ratio
swing_speed_coef = (swing_stance_speed_ratio + 1) * 0.5
if self.tprime < PHASE_PERIOD / 2.0: # Swing
delta_phase_multiplier = stance_speed_coef * PHASE_PERIOD
self.tprime += np.fmod(time_mult * delta_phase_multiplier,
PHASE_PERIOD)
else: # Stance
delta_phase_multiplier = swing_speed_coef * PHASE_PERIOD
self.tprime += np.fmod(time_mult * delta_phase_multiplier,
PHASE_PERIOD)
self.tprime = np.fmod(self.tprime, PHASE_PERIOD)
class TrajectoryGenerator():
def __init__(self,
center_swing=0.0,
amplitude_extension=0.2,
amplitude_lift=0.4,
dphi_leg=0.0):
# Cyclic Integrator
self.CI = CyclicIntegrator(dphi_leg)
self.center_swing = center_swing
self.amplitude_extension = amplitude_extension
self.amplitude_lift = amplitude_lift
def get_state_based_on_phase(self):
return np.array([(np.cos(self.CI.tprime) + 1) / 2.0,
(np.sin(self.CI.tprime) + 1) / 2.0])
def get_swing_extend_based_on_phase(self,
amplitude_swing=0.0,
center_extension=0.0,
intensity=1.0,
theta=0.0):
""" Eqn 2 in paper appendix
Cs: center_swing
Ae: amplitude_extension
theta: extention difference between end of swing and stance (good for climbing)
POLICY PARAMS:
h_tg = center_extension --> walking height (+short/-tall)
alpha_th = amplitude_swing --> swing fwd (-) or bwd (+)
"""
# Set amplitude_extension
amplitude_extension = self.amplitude_extension
if self.CI.tprime > PHASE_PERIOD / 2.0:
amplitude_extension = self.amplitude_lift
# E(t)
extend = center_extension + (amplitude_extension * np.sin(
self.CI.tprime)) * intensity + theta * np.cos(self.CI.tprime)
# S(t)
swing = self.center_swing + amplitude_swing * np.cos(
self.CI.tprime) * intensity
return swing, extend
| 3,133 | Python | 38.175 | 91 | 0.5391 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/tg_lib/tg_policy.py | import numpy as np
from tg_lib.traj_gen import TrajectoryGenerator
class TGPolicy():
""" state --> action
"""
def __init__(
self,
movetype="walk",
# offset for leg swing.
# mostly useless except walking up/down hill
# Might be good to make it a policy param
center_swing=0.0,
# push legs towards body
amplitude_extension=0.0,
# push legs away from body
amplitude_lift=0.0,
):
""" movetype decides which type of
TG we are training for
OPTIONS:
walk: one leg at a time LF, LB, RF, RB
trot: LF|RB together followed by
bound
pace
pronk
"""
# Trajectory Generators
self.TG_dict = {}
movetype_dict = {
"walk": [0, 0.25, 0.5, 0.75], # ORDER: RF | LF | RB | LB
"trot": [0, 0.5, 0.5, 0], # ORDER: LF + RB | LB + RF
"bound": [0, 0.5, 0, 0.5], # ORDER: LF + LB | RF + RB
"pace": [0, 0, 0.5, 0.5], # ORDER: LF + RF | LB + RB
"pronk": [0, 0, 0, 0] # LF + LB + RF + RB
}
TG_LF = TrajectoryGenerator(center_swing, amplitude_extension,
amplitude_lift, movetype_dict[movetype][0])
TG_LB = TrajectoryGenerator(center_swing, amplitude_extension,
amplitude_lift, movetype_dict[movetype][1])
TG_RF = TrajectoryGenerator(center_swing, amplitude_extension,
amplitude_lift, movetype_dict[movetype][2])
TG_RB = TrajectoryGenerator(center_swing, amplitude_extension,
amplitude_lift, movetype_dict[movetype][3])
self.TG_dict["LF"] = TG_LF
self.TG_dict["LB"] = TG_LB
self.TG_dict["RF"] = TG_RF
self.TG_dict["RB"] = TG_RB
def increment(self, dt, f_tg, Beta):
# Increment phase
for (key, tg) in self.TG_dict.items():
tg.CI.progress_tprime(dt, f_tg, Beta)
def get_TG_state(self):
# NOTE: MAYBE RETURN ONLY tprime for TG1 since that's
# the 'master' phase
# We get two observations per TG
# obs = np.array([])
# for i, (key, tg) in enumerate(self.TG_dict.items()):
# obs = np.append(obs, tg.get_state_based_on_phase[0])
# obs = np.append(obs, tg.get_state_based_on_phase[1])
# return obs
# OR just return phase, not sure why sin and cos is relevant...
# obs = np.array([])
# for i, (key, tg) in enumerate(self.TG_dict.items()):
# obs = np.append(obs, tg.CI.tprime)
# Return MASTER phase
obs = self.TG_dict["LF"].get_state_based_on_phase()
return obs
def get_utg(self, action, alpha_tg, h_tg, intensity, num_motors,
theta=0.0):
""" INPUTS:
action: residuals for each motor
from Policy
alpha_tg: swing amplitude from Policy
h_tg: center extension from Policy
ie walking height
num_motors: number of motors on minitaur
OUTPUTS:
action: residuals + TG
"""
# Get Action from TG [no policies here]
half_num_motors = int(num_motors / 2)
for i, (key, tg) in enumerate(self.TG_dict.items()):
action_idx = i
swing, extend = tg.get_swing_extend_based_on_phase(
alpha_tg, h_tg, intensity, theta)
# NOTE: ADDING to residuals
action[action_idx] += swing
action[action_idx + half_num_motors] += extend
return action
| 3,806 | Python | 35.257143 | 79 | 0.505255 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/debug_scripts/loader.py | #!/usr/bin/env python
import pybullet as p
import time
import pybullet_data
import numpy as np
import sys
sys.path.append('../../../')
from spotmicro.util import pybullet_data as pd
physicsClient = p.connect(p.GUI) # or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath()) # optionally
p.setGravity(0, 0, -9.81)
# p.setTimeStep(1./240.) # slow, accurate
p.setRealTimeSimulation(0) # we want to be faster than real time :)
planeId = p.loadURDF("plane.urdf")
StartPos = [0, 0, 0.3]
StartOrientation = p.getQuaternionFromEuler([0, 0, 0])
p.resetDebugVisualizerCamera(cameraDistance=0.8,
cameraYaw=45,
cameraPitch=-30,
cameraTargetPosition=[0, 0, 0])
boxId = p.loadURDF(pd.getDataPath() + "/assets/urdf/spot.urdf",
StartPos,
StartOrientation,
flags=p.URDF_USE_SELF_COLLISION_EXCLUDE_PARENT)
numj = p.getNumJoints(boxId)
numb = p.getNumBodies()
Pos, Orn = p.getBasePositionAndOrientation(boxId)
print(Pos, Orn)
print("Number of joints {}".format(numj))
print("Number of links {}".format(numb))
joint = []
movingJoints = [
6,
7,
8, # FL
10,
11,
12, # FR
15,
16,
17, # BL
19,
20,
21 # BR
]
maxVelocity = 100
mode = p.POSITION_CONTROL
p.setJointMotorControlArray(bodyUniqueId=boxId,
jointIndices=movingJoints,
controlMode=p.POSITION_CONTROL,
targetPositions=np.zeros(12),
targetVelocities=np.zeros(12),
forces=np.ones(12) * np.inf)
counter = 0
angle1 = -np.pi / 2.0
angle2 = 0.0
angle = angle1
for i in range(100000000):
counter += 1
if counter % 1000 == 0:
p.setJointMotorControlArray(
bodyUniqueId=boxId,
jointIndices=[8, 12, 17, 21], # FWrists
controlMode=p.POSITION_CONTROL,
targetPositions=np.ones(4) * angle,
targetVelocities=np.zeros(4),
forces=np.ones(4) * 0.15)
counter = 0
if angle == angle1:
angle = angle2
else:
angle = angle1
p.stepSimulation()
p.disconnect() | 2,296 | Python | 26.674698 | 73 | 0.578397 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_training_scripts/mini_td3.py | #!/usr/bin/env python
import numpy as np
from td3_lib.td3 import ReplayBuffer, TD3Agent, evaluate_policy
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR TD3")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
start_timesteps = 1e4 # 1e3 for testing purposes, use 1e4 for real
expl_noise = 0.1
batch_size = 100
eval_freq = 1e4
save_model = True
file_name = "mini_td3_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=False)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
policy = TD3Agent(state_dim, action_dim, max_action)
policy_num = 0
if os.path.exists(models_path + "/" + file_name +
str(policy_num) + "_critic"):
print("Loading Existing Policy")
policy.load(models_path + "/" + file_name + str(policy_num))
replay_buffer = ReplayBuffer()
# Optionally load existing policy, replace 9999 with num
buffer_number = 0 # BY DEFAULT WILL LOAD NOTHING, CHANGE THIS
if os.path.exists(replay_buffer.buffer_path + "/" + "replay_buffer_" +
str(buffer_number) + '.data'):
print("Loading Replay Buffer " + str(buffer_number))
replay_buffer.load(buffer_number)
# print(replay_buffer.storage)
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TD3")
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Select action randomly or according to policy
# Random Action - no training yet, just storing in buffer
if t < start_timesteps:
action = env.action_space.sample()
# rospy.logdebug("Sampled Action")
else:
# According to policy + Exploraton Noise
# print("POLICY Action")
""" Note we clip at +-0.99.... because Gazebo
has problems executing actions at the
position limit (breaks model)
"""
action = np.clip(
(policy.select_action(np.array(state)) + np.random.normal(
0, max_action * expl_noise, size=action_dim)),
-max_action, max_action)
# rospy.logdebug("Selected Acton: {}".format(action))
# Perform action
next_state, reward, done, _ = env.step(action)
done_bool = float(done)
# Store data in replay buffer
replay_buffer.add((state, action, next_state, reward, done_bool))
state = next_state
episode_reward += reward
# Train agent after collecting sufficient data for buffer
if t >= start_timesteps:
policy.train(replay_buffer, batch_size)
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
# Evaluate episode
if (t + 1) % eval_freq == 0:
# evaluate_policy(policy, env_name, seed,
np.save(results_path + "/" + str(file_name), evaluations)
if save_model:
policy.save(models_path + "/" + str(file_name) + str(t))
# replay_buffer.save(t)
env.close()
if __name__ == '__main__':
main() | 4,520 | Python | 30.615384 | 78 | 0.584735 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_training_scripts/mini_ars.py | #!/usr/bin/env python
import numpy as np
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import torch
import os
# Multiprocessing package for python
# Parallelization improvements based on:
# https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
import multiprocessing as mp
from multiprocessing import Pipe
# Messages for Pipe
_RESET = 1
_CLOSE = 2
_EXPLORE = 3
def main():
""" The main() function. """
# Hold mp pipes
mp.freeze_support()
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
eval_freq = 1e1
save_model = True
file_name = "mini_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=False)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env)
agent_num = 0
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
# Evaluate untrained agent and init list for storage
evaluations = []
env.reset(agent.desired_velocity, agent.desired_rate)
episode_reward = 0
episode_timesteps = 0
episode_num = 0
# MULTIPROCESSING
# Create mp pipes
num_processes = policy.num_deltas
processes = []
childPipes = []
parentPipes = []
# Store mp pipes
for pr in range(num_processes):
parentPipe, childPipe = Pipe()
parentPipes.append(parentPipe)
childPipes.append(childPipe)
# Start multiprocessing
for proc_num in range(num_processes):
p = mp.Process(target=ParallelWorker, args=(childPipes[proc_num], env))
p.start()
processes.append(p)
print("STARTED MINITAUR ARS")
t = 0
while t < (int(max_timesteps)):
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.train_parallel(parentPipes)
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}, >400: {}".
format(t, episode_num, policy.episode_steps, episode_reward,
agent.successes))
# Reset environment
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
# Evaluate episode
if (episode_num + 1) % eval_freq == 0:
# evaluate_agent(agent, env_name, seed,
np.save(results_path + "/" + str(file_name), evaluations)
if save_model:
agent.save(models_path + "/" + str(file_name) +
str(episode_num))
# replay_buffer.save(t)
episode_num += 1
# Close pipes and hence envs
for parentPipe in parentPipes:
parentPipe.send([_CLOSE, "pay2"])
for p in processes:
p.join()
if __name__ == '__main__':
main()
| 4,077 | Python | 26.186666 | 101 | 0.619328 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/paper/GMBC_data_collector.py | #!/usr/bin/env python
import numpy as np
import sys
sys.path.append('../../')
from ars_lib.ars import ARSAgent, Normalizer, Policy
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
import os
import argparse
import pickle
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set()
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Evaluator."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-a", "--AgentNum", help="Agent Number To Load")
parser.add_argument("-nep",
"--NumberOfEpisodes",
help="Number of Episodes to Collect Data For")
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
parser.add_argument("-nc",
"--NoContactSensing",
help="Disable Contact Sensing",
action='store_true')
parser.add_argument("-s",
"--Seed",
help="Seed (Default: 0).")
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
if ARGS.Seed:
seed = ARGS.Seed
max_episodes = 1000
if ARGS.NumberOfEpisodes:
max_episodes = ARGS.NumberOfEpisodes
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.NoContactSensing:
contacts = False
else:
contacts = True
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
file_name = "spot_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if contacts:
models_path = os.path.join(my_path, "../models/contact")
else:
models_path = os.path.join(my_path, "../models/no_contact")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
if ARGS.HeightField:
height_field = True
else:
height_field = False
env = spotBezierEnv(render=False,
on_rack=False,
height_field=height_field,
draw_foot_path=False,
contacts=contacts,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
env.reset()
spot = SpotModel()
bz_step = BezierStepper(dt=env._time_step)
bzg = BezierGait(dt=env._time_step)
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim, episode_steps=np.inf)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, bz_step, bzg, spot, False)
use_agent = False
agent_num = 0
if ARGS.AgentNum:
agent_num = ARGS.AgentNum
use_agent = True
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 50000
policy = agent.policy
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
# Used to create gaussian distribution of survival distance
surv_pos = []
# Store results
if use_agent:
# Store _agent
agt = "agent_" + str(agent_num)
else:
# Store _vanilla
agt = "vanilla"
while episode_num < (int(max_episodes)):
episode_reward, episode_timesteps = agent.deployTG()
# We only care about x/y pos
travelled_pos = list(agent.returnPose())
# NOTE: FORMAT: X, Y, TIMESTEPS -
# tells us if robobt was just stuck forever. didn't actually fall.
travelled_pos[-1] = episode_timesteps
episode_num += 1
# Store dt and frequency for prob distribution
surv_pos.append(travelled_pos)
print("Episode Num: {} Episode T: {} Reward: {}".format(
episode_num, episode_timesteps, episode_reward))
print("Survival Pos: {}".format(surv_pos[-1]))
# Save/Overwrite each time
with open(
results_path + "/" + str(file_name) + agt + '_survival_' +
str(max_episodes), 'wb') as filehandle:
pickle.dump(surv_pos, filehandle)
env.close()
print("---------------------------------------")
if __name__ == '__main__':
main()
| 5,460 | Python | 27.442708 | 74 | 0.59359 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/paper/GMBC_data_plotter.py | #!/usr/bin/env python
import numpy as np
import sys
import os
import argparse
import pickle
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import copy
from scipy.stats import norm
sns.set()
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Evaluator."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-nep",
"--NumberOfEpisodes",
help="Number of Episodes to Plot Data For")
parser.add_argument("-maw",
"--MovingAverageWindow",
help="Moving Average Window for Plotting (Default: 50)")
parser.add_argument("-surv",
"--Survival",
help="Plot Survival Curve",
action='store_true')
parser.add_argument("-tr",
"--TrainingData",
help="Plot Training Curve",
action='store_true')
parser.add_argument("-tot",
"--TotalReward",
help="Show Total Reward instead of Reward Per Timestep",
action='store_true')
parser.add_argument("-ar",
"--RandAgentNum",
help="Randomized Agent Number To Load")
parser.add_argument("-anor",
"--NoRandAgentNum",
help="Non-Randomized Agent Number To Load")
parser.add_argument("-raw",
"--Raw",
help="Plot Raw Data in addition to Moving Averaged Data",
action='store_true')
parser.add_argument(
"-s",
"--Seed",
help="Seed [UP TO, e.g. 0 | 0, 1 | 0, 1, 2 ...] (Default: 0).")
parser.add_argument("-pout",
"--PolicyOut",
help="Plot Policy Output Data",
action='store_true')
parser.add_argument("-rough",
"--Rough",
help="Plot Policy Output Data for Rough Terrain",
action='store_true')
parser.add_argument(
"-tru",
"--TrueAct",
help="Plot the Agent Action instead of what the robot sees",
action='store_true')
ARGS = parser.parse_args()
MA_WINDOW = 50
if ARGS.MovingAverageWindow:
MA_WINDOW = int(ARGS.MovingAverageWindow)
def moving_average(a, n=MA_WINDOW):
MA = np.cumsum(a, dtype=float)
MA[n:] = MA[n:] - MA[:-n]
return MA[n - 1:] / n
def extract_data_bounds(min=0, max=5, dist_data=None, dt_data=None):
""" 3 bounds: lower, mid, highest
"""
if dist_data is not None:
# Get Survival Data, dt
# Lowest Bound: x <= max
bound = np.array([0])
if min == 0:
less_max_cond = dist_data <= max
bound = np.where(less_max_cond)
else:
# Highest Bound: min <= x
if max == np.inf:
gtr_min_cond = dist_data >= min
bound = np.where(gtr_min_cond)
# Mid Bound: min < x < max
else:
less_max_gtr_min_cond = np.logical_and(dist_data > min,
dist_data < max)
bound = np.where(less_max_gtr_min_cond)
if dt_data is not None:
dt_bounded = dt_data[bound]
num_surv = np.array(np.where(dt_bounded == 50000))[0].shape[0]
else:
num_surv = None
return dist_data[bound], num_surv
else:
return None
def main():
""" The main() function. """
file_name = "spot_ars_"
seed = 0
if ARGS.Seed:
seed = ARGS.Seed
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if not os.path.exists(results_path):
os.makedirs(results_path)
vanilla_surv = np.random.randn(1000)
agent_surv = np.random.randn(1000)
nep = 1000
if ARGS.NumberOfEpisodes:
nep = ARGS.NumberOfEpisodes
if ARGS.TrainingData:
training = True
else:
training = False
if ARGS.Survival:
surv = True
else:
surv = False
if ARGS.PolicyOut or ARGS.Rough or ARGS.TrueAct:
pout = True
else:
pout = False
if not pout and not surv and not training:
print(
"Please Select which Data you would like to plot (-pout | -surv | -tr)"
)
rand_agt = 579
norand_agt = 569
if ARGS.RandAgentNum:
rand_agt = ARGS.RandAgentNum
if ARGS.NoRandAgentNum:
norand_agt = ARGS.NoRandAgentNum
if surv:
# Vanilla Data
if os.path.exists(results_path + "/" + file_name + "vanilla" +
'_survival_{}'.format(nep)):
with open(
results_path + "/" + file_name + "vanilla" +
'_survival_{}'.format(nep), 'rb') as filehandle:
vanilla_surv = np.array(pickle.load(filehandle))
# Rand Agent Data
if os.path.exists(results_path + "/" + file_name +
"agent_{}".format(rand_agt) +
'_survival_{}'.format(nep)):
with open(
results_path + "/" + file_name +
"agent_{}".format(rand_agt) + '_survival_{}'.format(nep),
'rb') as filehandle:
d2gmbc_surv = np.array(pickle.load(filehandle))
# NoRand Agent Data
if os.path.exists(results_path + "/" + file_name +
"agent_{}".format(norand_agt) +
'_survival_{}'.format(nep)):
with open(
results_path + "/" + file_name +
"agent_{}".format(norand_agt) + '_survival_{}'.format(nep),
'rb') as filehandle:
gmbc_surv = np.array(pickle.load(filehandle))
# print(gmbc_surv[:, 0])
# Extract useful values
vanilla_surv_x = vanilla_surv[:1000, 0]
d2gmbc_surv_x = d2gmbc_surv[:, 0]
gmbc_surv_x = gmbc_surv[:, 0]
# convert the lists to series
data = {
'Open Loop': vanilla_surv_x,
'GMBC': d2gmbc_surv_x,
'D^2-GMBC': gmbc_surv_x
}
colors = ['r', 'g', 'b']
# get dataframe
df = pd.DataFrame(data)
print(df)
# get dataframe2
# Extract useful values
vanilla_surv_dt = vanilla_surv[:1000, -1]
d2gmbc_surv_dt = d2gmbc_surv[:, -1]
gmbc_surv_dt = gmbc_surv[:, -1]
# convert the lists to series
data2 = {
'Open Loop': vanilla_surv_dt,
'GMBC': d2gmbc_surv_dt,
'D^2-GMBC': gmbc_surv_dt
}
df2 = pd.DataFrame(data2)
# Plot
for i, col in enumerate(df.columns):
sns.distplot(df[[col]], color=colors[i])
plt.legend(labels=['D^2-GMBC', 'GMBC', 'Open Loop'])
plt.xlabel("Forward Survived Distance (m)")
plt.ylabel("Kernel Density Estimate")
plt.show()
# Print AVG and STDEV
norand_avg = np.average(copy.deepcopy(gmbc_surv_x))
norand_std = np.std(copy.deepcopy(gmbc_surv_x))
rand_avg = np.average(copy.deepcopy(d2gmbc_surv_x))
rand_std = np.std(copy.deepcopy(d2gmbc_surv_x))
vanilla_avg = np.average(copy.deepcopy(vanilla_surv_x))
vanilla_std = np.std(copy.deepcopy(vanilla_surv_x))
print("Open Loop: AVG [{}] | STD [{}] | AMOUNT [{}]".format(
vanilla_avg, vanilla_std, gmbc_surv_x.shape[0]))
print("D^2-GMBC: AVG [{}] | STD [{}] AMOUNT [{}]".format(
rand_avg, rand_std, d2gmbc_surv_x.shape[0]))
print("GMBC: AVG [{}] | STD [{}] AMOUNT [{}]".format(
norand_avg, norand_std, vanilla_surv_x.shape[0]))
# collect data
gmbc_surv_x_less_5, gmbc_surv_num_less_5 = extract_data_bounds(
0, 5, gmbc_surv_x, gmbc_surv_dt)
d2gmbc_surv_x_less_5, d2gmbc_surv_num_less_5 = extract_data_bounds(
0, 5, d2gmbc_surv_x, d2gmbc_surv_dt)
vanilla_surv_x_less_5, vanilla_surv_num_less_5 = extract_data_bounds(
0, 5, vanilla_surv_x, vanilla_surv_dt)
# <=5
# Make sure all arrays filled
if gmbc_surv_x_less_5.size == 0:
gmbc_surv_x_less_5 = np.array([0])
if d2gmbc_surv_x_less_5.size == 0:
d2gmbc_surv_x_less_5 = np.array([0])
if vanilla_surv_x_less_5.size == 0:
vanilla_surv_x_less_5 = np.array([0])
norand_avg = np.average(gmbc_surv_x_less_5)
norand_std = np.std(gmbc_surv_x_less_5)
rand_avg = np.average(d2gmbc_surv_x_less_5)
rand_std = np.std(d2gmbc_surv_x_less_5)
vanilla_avg = np.average(vanilla_surv_x_less_5)
vanilla_std = np.std(vanilla_surv_x_less_5)
print("<= 5m")
print(
"Open Loop: AVG [{}] | STD [{}] | AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(vanilla_avg, vanilla_std,
vanilla_surv_x_less_5.shape[0] - vanilla_surv_num_less_5,
vanilla_surv_num_less_5))
print(
"D^2-GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(rand_avg, rand_std,
d2gmbc_surv_x_less_5.shape[0] - d2gmbc_surv_num_less_5,
d2gmbc_surv_num_less_5))
print("GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]".
format(norand_avg, norand_std,
gmbc_surv_x_less_5.shape[0] - gmbc_surv_num_less_5,
gmbc_surv_num_less_5))
# collect data
gmbc_surv_x_gtr_5, gmbc_surv_num_gtr_5 = extract_data_bounds(
5, 90, gmbc_surv_x, gmbc_surv_dt)
d2gmbc_surv_x_gtr_5, d2gmbc_surv_num_gtr_5 = extract_data_bounds(
5, 90, d2gmbc_surv_x, d2gmbc_surv_dt)
vanilla_surv_x_gtr_5, vanilla_surv_num_gtr_5 = extract_data_bounds(
5, 90, vanilla_surv_x, vanilla_surv_dt)
# >5 <90
# Make sure all arrays filled
if gmbc_surv_x_gtr_5.size == 0:
gmbc_surv_x_gtr_5 = np.array([0])
if d2gmbc_surv_x_gtr_5.size == 0:
d2gmbc_surv_x_gtr_5 = np.array([0])
if vanilla_surv_x_gtr_5.size == 0:
vanilla_surv_x_gtr_5 = np.array([0])
norand_avg = np.average(gmbc_surv_x_gtr_5)
norand_std = np.std(gmbc_surv_x_gtr_5)
rand_avg = np.average(d2gmbc_surv_x_gtr_5)
rand_std = np.std(d2gmbc_surv_x_gtr_5)
vanilla_avg = np.average(vanilla_surv_x_gtr_5)
vanilla_std = np.std(vanilla_surv_x_gtr_5)
print("> 5m and <90m")
print(
"Open Loop: AVG [{}] | STD [{}] | AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(vanilla_avg, vanilla_std,
vanilla_surv_x_gtr_5.shape[0] - vanilla_surv_num_gtr_5,
vanilla_surv_num_gtr_5))
print(
"D^2-GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(rand_avg, rand_std,
d2gmbc_surv_x_gtr_5.shape[0] - d2gmbc_surv_num_gtr_5,
d2gmbc_surv_num_gtr_5))
print("GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]".
format(norand_avg, norand_std,
gmbc_surv_x_gtr_5.shape[0] - gmbc_surv_num_gtr_5,
gmbc_surv_num_gtr_5))
# collect data
gmbc_surv_x_gtr_90, gmbc_surv_num_gtr_90 = extract_data_bounds(
90, np.inf, gmbc_surv_x, gmbc_surv_dt)
d2gmbc_surv_x_gtr_90, d2gmbc_surv_num_gtr_90 = extract_data_bounds(
90, np.inf, d2gmbc_surv_x, d2gmbc_surv_dt)
vanilla_surv_x_gtr_90, vanilla_surv_num_gtr_90 = extract_data_bounds(
90, np.inf, vanilla_surv_x, vanilla_surv_dt)
# >90
# Make sure all arrays filled
if gmbc_surv_x_gtr_90.size == 0:
gmbc_surv_x_gtr_90 = np.array([0])
if d2gmbc_surv_x_gtr_90.size == 0:
d2gmbc_surv_x_gtr_90 = np.array([0])
if vanilla_surv_x_gtr_90.size == 0:
vanilla_surv_x_gtr_90 = np.array([0])
norand_avg = np.average(gmbc_surv_x_gtr_90)
norand_std = np.std(gmbc_surv_x_gtr_90)
rand_avg = np.average(d2gmbc_surv_x_gtr_90)
rand_std = np.std(d2gmbc_surv_x_gtr_90)
vanilla_avg = np.average(vanilla_surv_x_gtr_90)
vanilla_std = np.std(vanilla_surv_x_gtr_90)
print(">= 90m")
print(
"Open Loop: AVG [{}] | STD [{}] | AAMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(vanilla_avg, vanilla_std,
vanilla_surv_x_gtr_90.shape[0] - vanilla_surv_num_gtr_90,
vanilla_surv_num_gtr_90))
print(
"D^2-GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]"
.format(rand_avg, rand_std,
d2gmbc_surv_x_gtr_90.shape[0] - d2gmbc_surv_num_gtr_90,
d2gmbc_surv_num_gtr_90))
print("GMBC: AVG [{}] | STD [{}] AMOUNT DEAD [{}] | AMOUNT ALIVE [{}]".
format(norand_avg, norand_std,
gmbc_surv_x_gtr_90.shape[0] - gmbc_surv_num_gtr_90,
gmbc_surv_num_gtr_90))
# Save to excel
df.to_excel(results_path + "/SurvDist.xlsx", index=False)
df2.to_excel(results_path + "/SurvDT.xlsx", index=False)
elif training:
rand_data_list = []
norand_data_list = []
rand_shortest_length = np.inf
norand_shortest_length = np.inf
for i in range(int(seed) + 1):
# Training Data Plotter
rand_data_temp = np.load(results_path + "/spot_ars_rand_" +
"seed" + str(i) + ".npy")
norand_data_temp = np.load(results_path + "/spot_ars_norand_" +
"seed" + str(i) + ".npy")
rand_shortest_length = min(
np.shape(rand_data_temp[:, 1])[0], rand_shortest_length)
norand_shortest_length = min(
np.shape(norand_data_temp[:, 1])[0], norand_shortest_length)
rand_data_list.append(rand_data_temp)
norand_data_list.append(norand_data_temp)
tot_rand_data = []
tot_norand_data = []
norm_rand_data = []
norm_norand_data = []
for i in range(int(seed) + 1):
tot_rand_data.append(
moving_average(rand_data_list[i][:rand_shortest_length, 0]))
tot_norand_data.append(
moving_average(
norand_data_list[i][:norand_shortest_length, 0]))
norm_rand_data.append(
moving_average(rand_data_list[i][:rand_shortest_length, 1]))
norm_norand_data.append(
moving_average(
norand_data_list[i][:norand_shortest_length, 1]))
tot_rand_data = np.array(tot_rand_data)
tot_norand_data = np.array(tot_norand_data)
norm_rand_data = np.array(norm_rand_data)
norm_norand_data = np.array(norm_norand_data)
# column-wise
axis = 0
# MEAN
tot_rand_mean = tot_rand_data.mean(axis=axis)
tot_norand_mean = tot_norand_data.mean(axis=axis)
norm_rand_mean = norm_rand_data.mean(axis=axis)
norm_norand_mean = norm_norand_data.mean(axis=axis)
# STD
tot_rand_std = tot_rand_data.std(axis=axis)
tot_norand_std = tot_norand_data.std(axis=axis)
norm_rand_std = norm_rand_data.std(axis=axis)
norm_norand_std = norm_norand_data.std(axis=axis)
aranged_rand = np.arange(np.shape(tot_rand_mean)[0])
aranged_norand = np.arange(np.shape(tot_norand_mean)[0])
if ARGS.TotalReward:
if ARGS.Raw:
plt.plot(rand_data_list[0][:, 0],
label="Randomized (Total Reward)",
color='g')
plt.plot(norand_data_list[0][:, 0],
label="Non-Randomized (Total Reward)",
color='r')
plt.plot(aranged_norand,
tot_norand_mean,
label="MA: Non-Randomized (Total Reward)",
color='r')
plt.fill_between(aranged_norand,
tot_norand_mean - tot_norand_std,
tot_norand_mean + tot_norand_std,
color='r',
alpha=0.2)
plt.plot(aranged_rand,
tot_rand_mean,
label="MA: Randomized (Total Reward)",
color='g')
plt.fill_between(aranged_rand,
tot_rand_mean - tot_rand_std,
tot_rand_mean + tot_rand_std,
color='g',
alpha=0.2)
else:
if ARGS.Raw:
plt.plot(rand_data_list[0][:, 1],
label="Randomized (Reward/dt)",
color='g')
plt.plot(norand_data_list[0][:, 1],
label="Non-Randomized (Reward/dt)",
color='r')
plt.plot(aranged_norand,
norm_norand_mean,
label="MA: Non-Randomized (Reward/dt)",
color='r')
plt.fill_between(aranged_norand,
norm_norand_mean - norm_norand_std,
norm_norand_mean + norm_norand_std,
color='r',
alpha=0.2)
plt.plot(aranged_rand,
norm_rand_mean,
label="MA: Randomized (Reward/dt)",
color='g')
plt.fill_between(aranged_rand,
norm_rand_mean - norm_rand_std,
norm_rand_mean + norm_rand_std,
color='g',
alpha=0.2)
plt.xlabel("Epoch #")
plt.ylabel("Reward")
plt.title(
"Training Performance with {} seed samples".format(int(seed) + 1))
plt.legend()
plt.show()
elif pout:
if ARGS.Rough:
terrain_name = "rough_"
else:
terrain_name = "flat_"
if ARGS.TrueAct:
action_name = "agent_act"
else:
action_name = "robot_act"
action = np.load(results_path + "/" + "policy_out_" + terrain_name +
action_name + ".npy")
ClearHeight_act = action[:, 0]
BodyHeight_act = action[:, 1]
Residuals_act = action[:, 2:]
plt.plot(ClearHeight_act, label='Clearance Height Mod', color='black')
plt.plot(BodyHeight_act, label='Body Height Mod', color='darkviolet')
# FL
plt.plot(Residuals_act[:, 0],
label='Residual: FL (x)',
color='limegreen')
plt.plot(Residuals_act[:, 1], label='Residual: FL (y)', color='lime')
plt.plot(Residuals_act[:, 2], label='Residual: FL (z)', color='green')
# FR
plt.plot(Residuals_act[:, 3],
label='Residual: FR (x)',
color='lightskyblue')
plt.plot(Residuals_act[:, 4],
label='Residual: FR (y)',
color='dodgerblue')
plt.plot(Residuals_act[:, 5], label='Residual: FR (z)', color='blue')
# BL
plt.plot(Residuals_act[:, 6],
label='Residual: BL (x)',
color='firebrick')
plt.plot(Residuals_act[:, 7],
label='Residual: BL (y)',
color='crimson')
plt.plot(Residuals_act[:, 8], label='Residual: BL (z)', color='red')
# BR
plt.plot(Residuals_act[:, 9], label='Residual: BR (x)', color='gold')
plt.plot(Residuals_act[:, 10],
label='Residual: BR (y)',
color='orange')
plt.plot(Residuals_act[:, 11], label='Residual: BR (z)', color='coral')
plt.xlabel("Epoch Iteration")
plt.ylabel("Action Value")
plt.title("Policy Output")
plt.legend()
plt.show()
if __name__ == '__main__':
main()
| 20,353 | Python | 36.484346 | 84 | 0.5014 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_real/Control/RPi/lib/servo_model.py | #!/usr/bin/env python
import numpy as np
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
import time
from adafruit_servokit import ServoKit
class ServoJoint:
def __init__(self,
name,
effort=0.15,
speed=8.76,
gpio=22,
fb_chan=0,
pwm_chan=0,
pwm_min=600,
pwm_max=2800,
servo_horn_bias=0,
actuation_range=270):
self.name = name
self.effort = effort # Nm
self.speed = speed # rad/s
# offset in mechanical design
self.servo_horn_bias = servo_horn_bias
# create the spi bus
self.spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
# create the cs (chip select)
if gpio == 22:
self.cs = digitalio.DigitalInOut(board.D22)
elif gpio == 27:
self.cs = digitalio.DigitalInOut(board.D27)
# create the mcp object
self.mcp = MCP.MCP3008(self.spi, self.cs)
# fb_chan from 0 to 7 for each MCP ADC
if fb_chan == 0:
self.chan = AnalogIn(self.mcp, MCP.P0)
elif fb_chan == 1:
self.chan = AnalogIn(self.mcp, MCP.P1)
elif fb_chan == 2:
self.chan = AnalogIn(self.mcp, MCP.P2)
elif fb_chan == 3:
self.chan = AnalogIn(self.mcp, MCP.P3)
elif fb_chan == 4:
self.chan = AnalogIn(self.mcp, MCP.P4)
elif fb_chan == 5:
self.chan = AnalogIn(self.mcp, MCP.P5)
elif fb_chan == 6:
self.chan = AnalogIn(self.mcp, MCP.P6)
elif fb_chan == 7:
self.chan = AnalogIn(self.mcp, MCP.P7)
self.kit = ServoKit(channels=16)
self.pwm_chan = pwm_chan
self.kit.servo[self.pwm_chan].set_pulse_width_range(pwm_min, pwm_max)
self.kit.servo[self.pwm_chan].actuation_range = actuation_range
self.bias = self.rad2deg(self.servo_horn_bias) # degrees
def forward_propagate(self, current_pos, desired_pos, dt):
""" Predict the new position of the actuated servo
motor joint
"""
pos_change = desired_pos - current_pos
percent_of_pos_reached = (self.speed * dt) / np.abs(pos_change)
# Cap at 100%
if percent_of_pos_reached > 100.0:
percent_of_pos_reached = 100.0
return current_pos + (pos_change * percent_of_pos_reached)
def calibrate(self, min_val, max_val, num_iters=22):
# Send to min value and record digital sig
# Send to max value and record digital sig
# OR INCREMENT TO GET MORE DATA
commands = np.array([])
measurements = np.array([])
# Number of data points to collect
num_iters = num_iters
for i in range(num_iters):
# commanded_value = (-np.pi / 2.0) + (i *
# (np.pi) / float(num_iters - 1))
range_val = max_val - min_val
commanded_value = (min_val) + (i *
(range_val) / float(num_iters - 1))
commands = np.append(commands, commanded_value)
self.actuate(commanded_value)
time.sleep(.5) # according to rated speed 0.1sec/60deg
measurements = np.append(measurements, self.chan.value)
time.sleep(1.0) # according to rated speed 0.1sec/60deg
# Perform fit
print("COMMANDS: {}".format(commands))
print("MEASUREMENTS: {}".format(measurements))
polynomial = 4
# We want to input measurements and receive equivalent commanded angles in radians
self.fit = np.poly1d(np.polyfit(measurements, commands, polynomial))
# Test Fit
print("TESTING FIT: 90 DEG; RESULT IS {}".format(
self.fit(self.chan.value)))
print("RETURNING TO -90")
self.actuate(-np.pi / 2)
# Save fit
np.save(self.name + "_fit", self.fit)
def load_calibration(self):
# Load fit
self.fit = np.load(self.name + "_fit.npy")
def remap(self, value):
# Use calibraton value to remap from Digital Sig to Angle
p = np.poly1d(self.fit)
return p(value)
def measure(self):
return self.remap(self.chan.value)
def rad2deg(self, rad):
deg = rad * 180.0 / np.pi
if deg > 90:
deg = 90
elif deg < -90:
deg = -90
return deg
def deg2rad(self, deg):
return deg * np.pi / 180.0
def actuate(self, desired_pos):
self.kit.servo[
self.pwm_chan].angle = self.bias + self.rad2deg(desired_pos)
def actuate_deg(self, desired_pos):
self.kit.servo[
self.pwm_chan].angle = desired_pos
| 4,877 | Python | 31.092105 | 90 | 0.555464 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_real/Control/RPi/lib/serial_test.py | import time
from Teensy_Interface import TeensyInterface
ti = TeensyInterface()
while True:
s = input("Send? [y/n]")
if s == "y":
ti.add_to_buffer(4, 0, 135, 60)
ti.send_buffer()
r = input("Read? [y/n]")
if r == "y":
print(ti.read_buffer())
| 284 | Python | 17.999999 | 44 | 0.552817 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_real/Control/RPi/lib/motor_calibrate.py | #!/usr/bin/env python
import time
import numpy as np
from servo_model import ServoJoint
joint_names = [
'rb_servo_r_hip', 'r_hip_r_thigh', 'r_thigh_r_knee', 'r_knee_r_shin',
'r_shin_r_ankle', 'r_ankle_r_foot', 'lb_servo_l_hip', 'l_hip_l_thigh',
'l_thigh_l_knee', 'l_knee_l_shin', 'l_shin_l_ankle', 'l_ankle_l_foot',
'torso_r_shoulder', 'r_shoulder_rs_servo', 're_servo_r_elbow',
'torso_l_shoulder', 'l_shoulder_ls_servo', 'le_servo_l_elbow'
]
loop = True
pwm_min = int(input("Enter Min PWM: ")) # 500
pwm_max = int(input("Enter Max PWM: ")) # 2400
actuation_range = int(input("Enter Actuation Range: "))
while loop:
channel = int(
input("Which channel is your servo connected to? [0-11]: "))
servo = ServoJoint(name=joint_names[channel],
pwm_chan=channel,
pwm_min=pwm_min,
pwm_max=pwm_max,
actuation_range=actuation_range)
inner_loop = True
while inner_loop:
val = float(input("Select an angle value (deg): [q to quit]"))
if val == "q" or val == "Q":
inner_loop = False
else:
servo.actuate_deg(val)
cont = input("Test another motor [y] or quit [n]? ")
if cont == "n":
loop = False
| 1,292 | Python | 29.069767 | 74 | 0.563467 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_real/Control/RPi/lib/Teensy_Interface.py | import serial
class TeensyInterface:
def __init__(self, port='/dev/ttyS0', baud=500000, timeout=0.2):
self.ser = serial.Serial(port, baud)
self.ser.flush()
self.buffer = []
def __construct_string(self, i, x, y, z):
return "{},{},{},{}\n".format(i, x, y, z)
def add_to_buffer(self, i, x, y, z):
self.buffer.append(self.__construct_string(i, x, y, z))
def add_raw(self, val):
self.buffer.append("{}\n".format(val))
def send_buffer(self):
for message in self.buffer:
self.ser.write(message.encode('utf-8'))
self.buffer = []
def read_buffer(self):
return self.ser.read_until(b'\n')
| 694 | Python | 24.74074 | 68 | 0.559078 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_real/Control/RPi/lib/imu.py | import time
import board
import busio
import adafruit_lsm9ds1
import numpy as np
import math
# i2c permission: sudo usermod -a -G i2c <user>
# https://www.raspberrypi.org/forums/viewtopic.php?t=58782
# use ROS with python3: https://medium.com/@beta_b0t/how-to-setup-ros-with-python-3-44a69ca36674
class IMU:
def __init__(self, rp_flip=True, r_neg=False, p_neg=True, y_neg=True):
# I2C connection:
# SPI connection:
# from digitalio import DigitalInOut, Direction
# spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
# csag = DigitalInOut(board.D5)
# csag.direction = Direction.OUTPUT
# csag.value = True
# csm = DigitalInOut(board.D6)
# csm.direction = Direction.OUTPUT
# csm.value = True
# sensor = adafruit_lsm9ds1.LSM9DS1_SPI(spi, csag, csm)
self.i2c = busio.I2C(board.SCL, board.SDA)
self.sensor = adafruit_lsm9ds1.LSM9DS1_I2C(self.i2c)
# Calibration Parameters
self.x_gyro_calibration = 0
self.y_gyro_calibration = 0
self.z_gyro_calibration = 0
self.roll_calibration = 0
self.pitch_calibration = 0
self.yaw_calibration = 0
# IMU Parameters: acc (x,y,z), gyro(x,y,z)
self.imu_data = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
# Time in seconds
self.prev_time = time.time()
# IMU timer
self.imu_diff = 0
# Gyroscope integrals for filtering
self.roll_int = 0
self.pitch_int = 0
self.yaw_int = 0
# Complementary Filter Coefficient
self.comp_filter = 0.02
# Filtered RPY
self.roll = 0
self.pitch = 0
self.yaw = 0
# Used to turn the IMU into right-hand coordinate system
self.rp_flip = rp_flip
self.r_neg = r_neg
self.p_neg = p_neg
self.y_neg = y_neg
# Magnemometer Calibration Values
self.scale_x = 1
self.scale_y = 1
self.scale_z = 1
self.mag_x_bias = 0
self.mag_y_bias = 0
self.mag_z_bias = 0
self.yaw_bias = 0
# CALIBRATE
self.calibrate_imu()
print("IMU Calibrated!\n")
def calibrate_imu(self):
"""
"""
# Reset calibration params
self.x_gyro_calibration = 0
self.y_gyro_calibration = 0
self.z_gyro_calibration = 0
self.roll_calibration = 0
self.pitch_calibration = 0
self.yaw_calibration = 0
sum_xg = 0
sum_yg = 0
sum_zg = 0
sum_xa = 0
sum_ya = 0
sum_za = 0
sum_roll = 0
sum_pitch = 0
sum_yaw = 0
num_calibrations = 1000
print("Calibrating Gyroscope and Accelerometer...\n")
for i in range(num_calibrations):
""" GYRO/ACC CALIBRATION
"""
self.read_imu()
sum_xg += self.imu_data[0]
sum_yg += self.imu_data[1]
sum_zg += self.imu_data[2]
sum_xa += self.imu_data[3]
sum_ya += self.imu_data[4]
sum_za += self.imu_data[5]
# Y,Z accelerations make up roll
sum_roll += (math.atan2(self.imu_data[3],
self.imu_data[5])) * 180.0 / np.pi
# X,Z accelerations make up pitch
sum_pitch += (math.atan2(self.imu_data[4],
self.imu_data[5])) * 180.0 / np.pi
# # Y, X accelerations make up yaw
# sum_yaw += (math.atan2(self.imu_data[7], self.imu_data[6]) *
# 180.0 / np.pi)
# Average values for calibration
self.x_gyro_calibration = sum_xg / float(num_calibrations)
self.y_gyro_calibration = sum_yg / float(num_calibrations)
self.z_gyro_calibration = sum_zg / float(num_calibrations)
self.roll_calibration = sum_roll / float(num_calibrations)
self.pitch_calibration = sum_pitch / float(num_calibrations)
# self.yaw_calibration = sum_yaw / float(num_calibrations)
print("Gyroscope and Accelerometer calibrated!\n")
# magne_cal = input(
# "Calibrate Magnemometer [c] or Load Existing Calibration [l] ?")
# if magne_cal == "c":
# print("Calibrating Magnetometer...")
# self.calibrate_magnemometer()
# else:
# print("Loading Magnetometer Calibration...")
# self.load_magnemometer_calibration()
# input(
# "Put the robot at its zero-yaw position and press Enter to calibrate Yaw"
# )
# self.read_imu()
# self.yaw_bias = (math.atan2(self.imu_data[7], self.imu_data[6]) *
# 180.0 / np.pi)
# print("Recorded Bias: {}".format(self.yaw_bias))
# input("Enter To Start")
def load_magnemometer_calibration(self):
return True
def calibrate_magnemometer(self):
# Get 10 seconds of magnemometer data
collection_time = 10.0
# Hard Iron Offset
mag_x_max = -32767
mag_x_min = 32767
mag_y_max = -32767
mag_y_min = 32767
mag_z_max = -32767
mag_z_min = 32767
input("Press Enter to start data collection for " +
str(collection_time) + " seconds:")
start_time = time.time()
elapsed_time = time.time() - start_time
while elapsed_time < collection_time:
elapsed_time = time.time() - start_time
self.read_imu()
# Set Max/Min for x
if self.imu_data[6] > mag_x_max:
mag_x_max = self.imu_data[6]
if self.imu_data[6] < mag_x_min:
mag_x_min = self.imu_data[6]
# Set Max/Min for y
if self.imu_data[7] > mag_y_max:
mag_y_max = self.imu_data[7]
if self.imu_data[7] < mag_y_min:
mag_y_min = self.imu_data[6]
# Set Max/Min for z
if self.imu_data[8] > mag_z_max:
mag_z_max = self.imu_data[8]
if self.imu_data[8] < mag_z_min:
mag_z_min = self.imu_data[8]
# Get Hard Iron Correction
self.mag_x_bias = (mag_x_max + mag_x_min) / 2.0
self.mag_y_bias = (mag_y_max + mag_y_min) / 2.0
self.mag_z_bias = (mag_z_max + mag_z_min) / 2.0
# Soft Iron Distortion - SCALE BIASES METHOD
# https://appelsiini.net/2018/calibrate-magnetometer/
# NOTE: Can also do Matrix Method
mag_x_delta = (mag_x_max - mag_x_min) / 2.0
mag_y_delta = (mag_y_max - mag_y_min) / 2.0
mag_z_delta = (mag_z_max - mag_z_min) / 2.0
avg_delta = (mag_x_delta + mag_y_delta + mag_z_delta) / 3.0
self.scale_x = avg_delta / mag_x_delta
self.scale_y = avg_delta / mag_y_delta
self.scale_y = avg_delta / mag_z_delta
# NOW, FOR EACH AXIS: corrected_reading = (reading - bias) * scale
input("Press Enter to save results")
def read_imu(self):
"""
"""
accel_x, accel_y, accel_z = self.sensor.acceleration
mag_x, mag_y, mag_z = self.sensor.magnetic
gyro_x, gyro_y, gyro_z = self.sensor.gyro
# temp = self.sensor.temperature
# Populate imu data list
# Gyroscope Values (Degrees/sec)
self.imu_data[0] = gyro_x - self.x_gyro_calibration
self.imu_data[1] = gyro_y - self.y_gyro_calibration
self.imu_data[2] = gyro_z - self.z_gyro_calibration
# Accelerometer Values (m/s^2)
self.imu_data[3] = accel_x
self.imu_data[4] = accel_y
self.imu_data[5] = accel_z
# Magnemometer Values
self.imu_data[6] = (mag_x - self.mag_x_bias) * self.scale_x
self.imu_data[7] = (mag_y - self.mag_y_bias) * self.scale_y
self.imu_data[8] = (mag_z - self.mag_z_bias) * self.scale_z
def filter_rpy(self):
"""
"""
# Get Readings
self.read_imu()
# Get Current Time in seconds
current_time = time.time()
self.imu_diff = current_time - self.prev_time
# Set new previous time
self.prev_time = current_time
# Catch rollovers
if self.imu_diff < 0:
self.imu_diff = 0
# Complementary filter for RPY
# TODO: DOUBLE CHECK THIS!!!!!!!
roll_gyro_delta = self.imu_data[1] * self.imu_diff
pitch_gyro_delta = self.imu_data[0] * self.imu_diff
yaw_gyro_delta = self.imu_data[2] * self.imu_diff
self.roll_int += roll_gyro_delta
self.pitch_int += pitch_gyro_delta
self.yaw_int += yaw_gyro_delta
# RPY from Accelerometer
# Y,Z accelerations make up roll
roll_a = (math.atan2(self.imu_data[3], self.imu_data[5])
) * 180.0 / np.pi - self.roll_calibration
# X,Z accelerations make up pitch
pitch_a = (math.atan2(self.imu_data[4], self.imu_data[5])
) * 180.0 / np.pi - self.pitch_calibration
# Y, X Magnetometer data makes up yaw
yaw_m = (math.atan2(self.imu_data[7], self.imu_data[6]) * 180.0 /
np.pi)
# Calculate Filtered RPY
self.roll = roll_a * self.comp_filter + (1 - self.comp_filter) * (
roll_gyro_delta + self.roll)
self.pitch = pitch_a * self.comp_filter + (1 - self.comp_filter) * (
pitch_gyro_delta + self.pitch)
self.yaw = math.atan2(self.imu_data[7],
self.imu_data[6]) * 180.0 / np.pi
self.yaw = yaw_m - self.yaw_bias
# Wrap from -PI to PI
self.yaw -= 360.0 * math.floor((self.yaw + 180) / 360.0)
# self.yaw = yaw_m * self.comp_filter + (1 - self.comp_filter) * (
# pitch_gyro_delta + self.yaw)
# self.roll = roll_a
# self.pitch = pitch_a
# self.yaw = yaw_a
# Recenter Roll and Pitch for Right Handed Frame
self.recenter_rp()
def recenter_rp(self):
""" LSM9DS1 IMU does not adhere to right hand rule.
this function allows the user to specify which coordinate
frame standards to use by deciding when to flip and/or negate
Roll and Pitch in the class constructor.
"""
if self.rp_flip:
if self.r_neg:
self.true_roll = -self.pitch
else:
self.true_roll = self.pitch
if self.p_neg:
self.true_pitch = -self.roll
else:
self.true_pitch = self.roll
else:
if self.r_neg:
self.true_roll = -self.roll
else:
self.true_roll = self.roll
if self.p_neg:
self.true_pitch = -self.pitch
else:
self.true_pitch = self.pitch
if self.y_neg:
self.yaw = -self.yaw
if __name__ == "__main__":
imu = IMU()
while True:
imu.filter_rpy()
print("ROLL: {} \t PICH: {} \t YAW: {} \n".format(
imu.true_roll, imu.true_pitch, imu.yaw)) | 11,139 | Python | 33.596273 | 96 | 0.534429 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/mini_ros/setup.py | ## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
## Copies from http://docs.ros.org/melodic/api/catkin/html/howto/format2/installing_python.html and edited for our package
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['mini_bullet', 'ars_lib'],
package_dir={'../mini_bullet/src': ''})
setup(**setup_args)
| 457 | Python | 37.166664 | 122 | 0.746171 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/spot.py | """
CODE BASED ON EXAMPLE FROM:
@misc{coumans2017pybullet,
title={Pybullet, a python module for physics simulation in robotics, games and machine learning},
author={Coumans, Erwin and Bai, Yunfei},
url={www.pybullet.org},
year={2017},
}
Example: minitaur.py
https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/bullet/minitaur.py
"""
import collections
import copy
import math
import re
import numpy as np
from . import motor
from spotmicro.util import pybullet_data
print(pybullet_data.getDataPath())
from spotmicro.Kinematics.SpotKinematics import SpotModel
import spotmicro.Kinematics.LieAlgebra as LA
INIT_POSITION = [0, 0, 0.25]
INIT_RACK_POSITION = [0, 0, 1]
# NOTE: URDF IS FACING THE WRONG WAY
# TEMP FIX
INIT_ORIENTATION = [0, 0, 0, 1]
OVERHEAT_SHUTDOWN_TORQUE = 2.45
OVERHEAT_SHUTDOWN_TIME = 1.0
# -math.pi / 5
INIT_LEG_POS = -0.658319
# math.pi / 3
INIT_FOOT_POS = 1.0472
OLD_LEG_POSITION = ["front_left", "front_right", "rear_left", "rear_right"]
OLD_MOTOR_NAMES = [
"motor_front_left_shoulder", "motor_front_left_leg",
"foot_motor_front_left", "motor_front_right_shoulder",
"motor_front_right_leg", "foot_motor_front_right",
"motor_rear_left_shoulder", "motor_rear_left_leg", "foot_motor_rear_left",
"motor_rear_right_shoulder", "motor_rear_right_leg",
"foot_motor_rear_right"
]
OLD_MOTOR_LIMITS_BY_NAME = {}
for name in OLD_MOTOR_NAMES:
if "shoulder" in name:
OLD_MOTOR_LIMITS_BY_NAME[name] = [-1.04, 1.04]
elif "leg" in name:
OLD_MOTOR_LIMITS_BY_NAME[name] = [-2.59, 1.571]
elif "foot" in name:
OLD_MOTOR_LIMITS_BY_NAME[name] = [-1.571, 2.9]
OLD_FOOT_NAMES = [
"front_left_toe", "front_right_toe", "rear_left_toe", "rear_right_toe"
]
LEG_POSITION = ["front_left", "front_right", "back_left", "back_right"]
MOTOR_NAMES = [
"motor_front_left_hip", "motor_front_left_upper_leg",
"motor_front_left_lower_leg", "motor_front_right_hip",
"motor_front_right_upper_leg", "motor_front_right_lower_leg",
"motor_back_left_hip", "motor_back_left_upper_leg",
"motor_back_left_lower_leg", "motor_back_right_hip",
"motor_back_right_upper_leg", "motor_back_right_lower_leg"
]
MOTOR_LIMITS_BY_NAME = {}
for name in MOTOR_NAMES:
if "hip" in name:
MOTOR_LIMITS_BY_NAME[name] = [-1.04, 1.04]
elif "upper_leg" in name:
MOTOR_LIMITS_BY_NAME[name] = [-1.571, 2.59]
elif "lower_leg" in name:
MOTOR_LIMITS_BY_NAME[name] = [-2.9, 1.671]
FOOT_NAMES = [
"front_left_leg_foot", "front_right_leg_foot", "back_left_leg_foot",
"back_right_leg_foot"
]
_CHASSIS_NAME_PATTERN = re.compile(r"chassis\D*")
_MOTOR_NAME_PATTERN = re.compile(r"motor\D*")
_FOOT_NAME_PATTERN = re.compile(r"foot\D*")
SENSOR_NOISE_STDDEV = (0.0, 0.0, 0.0, 0.0, 0.0)
TWO_PI = 2 * math.pi
def MapToMinusPiToPi(angles):
"""Maps a list of angles to [-pi, pi].
Args:
angles: A list of angles in rad.
Returns:
A list of angle mapped to [-pi, pi].
"""
mapped_angles = copy.deepcopy(angles)
for i in range(len(angles)):
mapped_angles[i] = math.fmod(angles[i], TWO_PI)
if mapped_angles[i] >= math.pi:
mapped_angles[i] -= TWO_PI
elif mapped_angles[i] < -math.pi:
mapped_angles[i] += TWO_PI
return mapped_angles
class Spot(object):
"""The spot class that simulates a quadruped robot.
"""
INIT_POSES = {
'stand':
np.array([
0.15192765, 0.7552236, -1.5104472, -0.15192765, 0.7552236,
-1.5104472, 0.15192765, 0.7552236, -1.5104472, -0.15192765,
0.7552236, -1.5104472
]),
'liedown':
np.array([-0.4, -1.5, 6, 0.4, -1.5, 6, -0.4, -1.5, 6, 0.4, -1.5, 6]),
'zero':
np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
}
def __init__(self,
pybullet_client,
urdf_root=pybullet_data.getDataPath(),
time_step=0.01,
action_repeat=1,
self_collision_enabled=False,
motor_velocity_limit=9.7,
pd_control_enabled=False,
accurate_motor_model_enabled=False,
remove_default_joint_damping=False,
max_force=100.0,
motor_kp=1.0,
motor_kd=0.02,
pd_latency=0.0,
control_latency=0.0,
observation_noise_stdev=SENSOR_NOISE_STDDEV,
torque_control_enabled=False,
motor_overheat_protection=False,
on_rack=False,
kd_for_pd_controllers=0.3,
pose_id='stand',
np_random=np.random,
contacts=True):
"""Constructs a spot and reset it to the initial states.
Args:
pybullet_client: The instance of BulletClient to manage different
simulations.
urdf_root: The path to the urdf folder.
time_step: The time step of the simulation.
action_repeat: The number of ApplyAction() for each control step.
self_collision_enabled: Whether to enable self collision.
motor_velocity_limit: The upper limit of the motor velocity.
pd_control_enabled: Whether to use PD control for the motors.
accurate_motor_model_enabled: Whether to use the accurate DC motor model.
remove_default_joint_damping: Whether to remove the default joint damping.
motor_kp: proportional gain for the accurate motor model.
motor_kd: derivative gain for the accurate motor model.
pd_latency: The latency of the observations (in seconds) used to calculate
PD control. On the real hardware, it is the latency between the
microcontroller and the motor controller.
control_latency: The latency of the observations (in second) used to
calculate action. On the real hardware, it is the latency from the motor
controller, the microcontroller to the host (Nvidia TX2).
observation_noise_stdev: The standard deviation of a Gaussian noise model
for the sensor. It should be an array for separate sensors in the
following order [motor_angle, motor_velocity, motor_torque,
base_roll_pitch_yaw, base_angular_velocity]
torque_control_enabled: Whether to use the torque control, if set to
False, pose control will be used.
motor_overheat_protection: Whether to shutdown the motor that has exerted
large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
(OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in spot.py for more
details.
on_rack: Whether to place the spot on rack. This is only used to debug
the walking gait. In this mode, the spot's base is hanged midair so
that its walking gait is clearer to visualize.
"""
# SPOT MODEL
self.spot = SpotModel()
# Whether to include contact sensing
self.contacts = contacts
# Control Inputs
self.StepLength = 0.0
self.StepVelocity = 0.0
self.LateralFraction = 0.0
self.YawRate = 0.0
# Leg Phases
self.LegPhases = [0.0, 0.0, 0.0, 0.0]
# used to calculate minitaur acceleration
self.init_leg = INIT_LEG_POS
self.init_foot = INIT_FOOT_POS
self.prev_ang_twist = np.array([0, 0, 0])
self.prev_lin_twist = np.array([0, 0, 0])
self.prev_lin_acc = np.array([0, 0, 0])
self.num_motors = 12
self.num_legs = int(self.num_motors / 3)
self._pybullet_client = pybullet_client
self._action_repeat = action_repeat
self._urdf_root = urdf_root
self._self_collision_enabled = self_collision_enabled
self._motor_velocity_limit = motor_velocity_limit
self._pd_control_enabled = pd_control_enabled
self._motor_direction = np.ones(self.num_motors)
self._observed_motor_torques = np.zeros(self.num_motors)
self._applied_motor_torques = np.zeros(self.num_motors)
self._max_force = max_force
self._pd_latency = pd_latency
self._control_latency = control_latency
self._observation_noise_stdev = observation_noise_stdev
self._accurate_motor_model_enabled = accurate_motor_model_enabled
self._remove_default_joint_damping = remove_default_joint_damping
self._observation_history = collections.deque(maxlen=100)
self._control_observation = []
self._chassis_link_ids = [-1]
self._leg_link_ids = []
self._motor_link_ids = []
self._foot_link_ids = []
self._torque_control_enabled = torque_control_enabled
self._motor_overheat_protection = motor_overheat_protection
self._on_rack = on_rack
self._pose_id = pose_id
self.np_random = np_random
if self._accurate_motor_model_enabled:
self._kp = motor_kp
self._kd = motor_kd
self._motor_model = motor.MotorModel(
torque_control_enabled=self._torque_control_enabled,
kp=self._kp,
kd=self._kd)
elif self._pd_control_enabled:
self._kp = 8
self._kd = kd_for_pd_controllers
else:
self._kp = 1
self._kd = 1
self.time_step = time_step
self._step_counter = 0
# reset_time=-1.0 means skipping the reset motion.
# See Reset for more details.
self.Reset(reset_time=-1)
self.init_on_rack_position = INIT_RACK_POSITION
self.init_position = INIT_POSITION
self.initial_pose = self.INIT_POSES[pose_id]
def _RecordMassInfoFromURDF(self):
self._base_mass_urdf = []
for chassis_id in self._chassis_link_ids:
self._base_mass_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
chassis_id)[0])
self._leg_masses_urdf = []
for leg_id in self._leg_link_ids:
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
leg_id)[0])
for motor_id in self._motor_link_ids:
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
motor_id)[0])
def GetBaseMassFromURDF(self):
"""Get the mass of the base from the URDF file."""
return self._base_mass_urdf
def SetBaseMass(self, base_mass):
for i in range(len(self._chassis_link_ids)):
self._pybullet_client.changeDynamics(self.quadruped,
self._chassis_link_ids[i],
mass=base_mass[i])
def _RecordInertiaInfoFromURDF(self):
"""Record the inertia of each body from URDF file."""
self._link_urdf = []
num_bodies = self._pybullet_client.getNumJoints(self.quadruped)
for body_id in range(-1, num_bodies): # -1 is for the base link.
inertia = self._pybullet_client.getDynamicsInfo(
self.quadruped, body_id)[2]
self._link_urdf.append(inertia)
# We need to use id+1 to index self._link_urdf because it has the base
# (index = -1) at the first element.
self._base_inertia_urdf = [
self._link_urdf[chassis_id + 1]
for chassis_id in self._chassis_link_ids
]
self._leg_inertia_urdf = [
self._link_urdf[leg_id + 1] for leg_id in self._leg_link_ids
]
self._leg_inertia_urdf.extend([
self._link_urdf[motor_id + 1] for motor_id in self._motor_link_ids
])
def _BuildJointNameToIdDict(self):
num_joints = self._pybullet_client.getNumJoints(self.quadruped)
self._joint_name_to_id = {}
for i in range(num_joints):
joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)
self._joint_name_to_id[joint_info[1].decode(
"UTF-8")] = joint_info[0]
def _BuildMotorIdList(self):
self._motor_id_list = [
self._joint_name_to_id[motor_name] for motor_name in MOTOR_NAMES
]
def _BuildFootIdList(self):
self._foot_id_list = [
self._joint_name_to_id[foot_name] for foot_name in FOOT_NAMES
]
print(self._foot_id_list)
def _BuildUrdfIds(self):
"""Build the link Ids from its name in the URDF file."""
c = []
m = []
f = []
lg = []
num_joints = self._pybullet_client.getNumJoints(self.quadruped)
self._chassis_link_ids = [-1]
# the self._leg_link_ids include both the upper and lower links of the leg.
self._leg_link_ids = []
self._motor_link_ids = []
self._foot_link_ids = []
for i in range(num_joints):
joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)
joint_name = joint_info[1].decode("UTF-8")
joint_id = self._joint_name_to_id[joint_name]
if _CHASSIS_NAME_PATTERN.match(joint_name):
c.append(joint_name)
self._chassis_link_ids.append(joint_id)
elif _MOTOR_NAME_PATTERN.match(joint_name):
m.append(joint_name)
self._motor_link_ids.append(joint_id)
elif _FOOT_NAME_PATTERN.match(joint_name):
f.append(joint_name)
self._foot_link_ids.append(joint_id)
else:
lg.append(joint_name)
self._leg_link_ids.append(joint_id)
self._leg_link_ids.extend(self._foot_link_ids)
self._chassis_link_ids.sort()
self._motor_link_ids.sort()
self._foot_link_ids.sort()
self._leg_link_ids.sort()
def Reset(self,
reload_urdf=True,
default_motor_angles=None,
reset_time=3.0):
"""Reset the spot to its initial states.
Args:
reload_urdf: Whether to reload the urdf file. If not, Reset() just place
the spot back to its starting position.
default_motor_angles: The default motor angles. If it is None, spot
will hold a default pose for 100 steps. In
torque control mode, the phase of holding the default pose is skipped.
reset_time: The duration (in seconds) to hold the default motor angles. If
reset_time <= 0 or in torque control mode, the phase of holding the
default pose is skipped.
"""
if self._on_rack:
init_position = INIT_RACK_POSITION
else:
init_position = INIT_POSITION
if reload_urdf:
if self._self_collision_enabled:
self.quadruped = self._pybullet_client.loadURDF(
pybullet_data.getDataPath() + "/assets/urdf/spot.urdf",
init_position,
useFixedBase=self._on_rack,
flags=self._pybullet_client.URDF_USE_SELF_COLLISION_EXCLUDE_PARENT)
else:
self.quadruped = self._pybullet_client.loadURDF(
pybullet_data.getDataPath() + "/assets/urdf/spot.urdf",
init_position,
INIT_ORIENTATION,
useFixedBase=self._on_rack)
self._BuildJointNameToIdDict()
self._BuildUrdfIds()
if self._remove_default_joint_damping:
self._RemoveDefaultJointDamping()
self._BuildMotorIdList()
self._BuildFootIdList()
self._RecordMassInfoFromURDF()
self._RecordInertiaInfoFromURDF()
self.ResetPose(add_constraint=True)
else:
self._pybullet_client.resetBasePositionAndOrientation(
self.quadruped, init_position, INIT_ORIENTATION)
self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0],
[0, 0, 0])
# self._pybullet_client.changeDynamics(self.quadruped, -1, lateralFriction=0.8)
self.ResetPose(add_constraint=False)
self._overheat_counter = np.zeros(self.num_motors)
self._motor_enabled_list = [True] * self.num_motors
self._step_counter = 0
# Perform reset motion within reset_duration if in position control mode.
# Nothing is performed if in torque control mode for now.
self._observation_history.clear()
if reset_time > 0.0 and default_motor_angles is not None:
self.RealisticObservation()
for _ in range(100):
self.ApplyAction(self.initial_pose)
self._pybullet_client.stepSimulation()
self.RealisticObservation()
num_steps_to_reset = int(reset_time / self.time_step)
for _ in range(num_steps_to_reset):
self.ApplyAction(default_motor_angles)
self._pybullet_client.stepSimulation()
self.RealisticObservation()
self.RealisticObservation()
# Set Foot Friction
self.SetFootFriction()
def _RemoveDefaultJointDamping(self):
num_joints = self._pybullet_client.getNumJoints(self.quadruped)
for i in range(num_joints):
joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)
self._pybullet_client.changeDynamics(joint_info[0],
-1,
linearDamping=0,
angularDamping=0)
def _SetMotorTorqueById(self, motor_id, torque):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.TORQUE_CONTROL,
force=torque)
def _SetDesiredMotorAngleById(self, motor_id, desired_angle):
if self._pd_control_enabled or self._accurate_motor_model_enabled:
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.POSITION_CONTROL,
targetPosition=desired_angle,
positionGain=self._kp,
velocityGain=self._kd,
force=self._max_force)
# Pybullet has a 'perfect' joint controller with its default p,d
else:
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.POSITION_CONTROL,
targetPosition=desired_angle)
def _SetDesiredMotorAngleByName(self, motor_name, desired_angle):
self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name],
desired_angle)
def ResetPose(self, add_constraint):
"""Reset the pose of the spot.
Args:
add_constraint: Whether to add a constraint at the joints of two feet.
"""
for i in range(self.num_legs):
self._ResetPoseForLeg(i, add_constraint)
def _ResetPoseForLeg(self, leg_id, add_constraint):
"""Reset the initial pose for the leg.
Args:
leg_id: It should be 0, 1, 2, or 3, which represents the leg at
front_left, back_left, front_right and back_right.
add_constraint: Whether to add a constraint at the joints of two feet.
"""
knee_friction_force = 0
pi = math.pi
leg_position = LEG_POSITION[leg_id]
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "_hip"],
self.INIT_POSES[self._pose_id][3 * leg_id],
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "_upper_leg"],
self.INIT_POSES[self._pose_id][3 * leg_id + 1],
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "_lower_leg"],
self.INIT_POSES[self._pose_id][3 * leg_id + 2],
targetVelocity=0)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
# Disable the default motor in pybullet.
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"_hip"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"_upper_leg"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"_lower_leg"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
def GetBasePosition(self):
"""Get the position of spot's base.
Returns:
The position of spot's base.
"""
position, _ = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return position
def GetBaseOrientation(self):
"""Get the orientation of spot's base, represented as quaternion.
Returns:
The orientation of spot's base.
"""
_, orientation = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return orientation
def GetBaseRollPitchYaw(self):
"""Get the rate of orientation change of the spot's base in euler angle.
Returns:
rate of (roll, pitch, yaw) change of the spot's base.
"""
vel = self._pybullet_client.getBaseVelocity(self.quadruped)
return np.asarray([vel[1][0], vel[1][1], vel[1][2]])
def GetBaseRollPitchYawRate(self):
"""Get the rate of orientation change of the spot's base in euler angle.
This function mimicks the noisy sensor reading and adds latency.
Returns:
rate of (roll, pitch, yaw) change of the spot's base polluted by noise
and latency.
"""
return self._AddSensorNoise(
np.array(self._control_observation[3 * self.num_motors +
4:3 * self.num_motors + 7]),
self._observation_noise_stdev[4])
def GetBaseTwist(self):
"""Get the Twist of minitaur's base.
Returns:
The Twist of the minitaur's base.
"""
return self._pybullet_client.getBaseVelocity(self.quadruped)
def GetActionDimension(self):
"""Get the length of the action list.
Returns:
The length of the action list.
"""
return self.num_motors
def GetObservationUpperBound(self):
"""Get the upper bound of the observation.
Returns:
The upper bound of an observation. See GetObservation() for the details
of each element of an observation.
NOTE: Changed just like GetObservation()
"""
upper_bound = np.array([0.0] * self.GetObservationDimension())
# roll, pitch
upper_bound[0:2] = 2.0 * np.pi
# acc, rate in x,y,z
upper_bound[2:8] = np.inf
# Leg Phases
upper_bound[8:12] = 2.0
# Contacts
if self.contacts:
upper_bound[12:] = 1.0
return upper_bound
def GetObservationLowerBound(self):
"""Get the lower bound of the observation."""
return -self.GetObservationUpperBound()
def GetObservationDimension(self):
"""Get the length of the observation list.
Returns:
The length of the observation list.
"""
return len(self.GetObservation())
def GetObservation(self):
"""Get the observations of minitaur.
It includes the angles, velocities, torques and the orientation of the base.
Returns:
The observation list. observation[0:8] are motor angles. observation[8:16]
are motor velocities, observation[16:24] are motor torques.
observation[24:28] is the orientation of the base, in quaternion form.
NOTE: DIVERGES FROM STOCK MINITAUR ENV. WILL LEAVE ORIGINAL COMMENTED
For my purpose, the observation space includes Roll and Pitch, as well as
acceleration and gyroscopic rate along the x,y,z axes. All of this
information can be collected from an onboard IMU. The reward function
will contain a hidden velocity reward (fwd, bwd) which cannot be measured
and so is not included. For spinning, the gyroscopic z rate will be used
as the (explicit) velocity reward.
This version operates without motor torques, angles and velocities. Erwin
Coumans' paper suggests a sparse observation space leads to higher reward
# NOTE: use True version for perfect data, or other for realistic data
"""
observation = []
# GETTING TWIST IN BODY FRAME
pos = self.GetBasePosition()
orn = self.GetBaseOrientation()
roll, pitch, yaw = self._pybullet_client.getEulerFromQuaternion(
[orn[0], orn[1], orn[2], orn[3]])
# rpy = LA.RPY(roll, pitch, yaw)
# R, _ = LA.TransToRp(rpy)
# T_wb = LA.RpToTrans(R, np.array([pos[0], pos[1], pos[2]]))
# T_bw = LA.TransInv(T_wb)
# Adj_Tbw = LA.Adjoint(T_bw)
# Get Linear and Angular Twist in WORLD FRAME
lin_twist, ang_twist = self.GetBaseTwist()
lin_twist = np.array([lin_twist[0], lin_twist[1], lin_twist[2]])
ang_twist = np.array([ang_twist[0], ang_twist[1], ang_twist[2]])
# Vw = np.concatenate((ang_twist, lin_twist))
# Vb = np.dot(Adj_Tbw, Vw)
# roll, pitch, _ = self._pybullet_client.getEulerFromQuaternion(
# [orn[0], orn[1], orn[2], orn[3]])
# # Get linear accelerations
# lin_twist = -Vb[3:]
# ang_twist = Vb[:3]
lin_acc = lin_twist - self.prev_lin_twist
if lin_acc.all() == 0.0:
lin_acc = self.prev_lin_acc
self.prev_lin_acc = lin_acc
# print("LIN TWIST: ", lin_twist)
self.prev_lin_twist = lin_twist
self.prev_ang_twist = ang_twist
# Get Contacts
CONTACT = list(self._pybullet_client.getContactPoints(self.quadruped))
FLC = 0
FRC = 0
BLC = 0
BRC = 0
if len(CONTACT) > 0:
for i in range(len(CONTACT)):
Contact_Link_Index = CONTACT[i][3]
if Contact_Link_Index == self._foot_id_list[0]:
FLC = 1
# print("FL CONTACT")
if Contact_Link_Index == self._foot_id_list[1]:
FRC = 1
# print("FR CONTACT")
if Contact_Link_Index == self._foot_id_list[2]:
BLC = 1
# print("BL CONTACT")
if Contact_Link_Index == self._foot_id_list[3]:
BRC = 1
# print("BR CONTACT")
# order: roll, pitch, gyro(x,y,z), acc(x, y, z)
observation.append(roll)
observation.append(pitch)
observation.extend(list(ang_twist))
observation.extend(list(lin_acc))
# Control Input
# observation.append(self.StepLength)
# observation.append(self.StepVelocity)
# observation.append(self.LateralFraction)
# observation.append(self.YawRate)
observation.extend(self.LegPhases)
if self.contacts:
observation.append(FLC)
observation.append(FRC)
observation.append(BLC)
observation.append(BRC)
# print("CONTACTS: {} {} {} {}".format(FLC, FRC, BLC, BRC))
return observation
def GetControlInput(self, controller):
""" Store Control Input as Observation
"""
_, _, StepLength, LateralFraction, YawRate, StepVelocity, _, _ = controller.return_bezier_params(
)
self.StepLength = StepLength
self.StepVelocity = StepVelocity
self.LateralFraction = LateralFraction
self.YawRate = YawRate
def GetLegPhases(self, TrajectoryGenerator):
""" Leg phases according to TG from 0->2
0->1: Stance
1->2 Swing
"""
self.LegPhases = TrajectoryGenerator.Phases
def GetExternalObservations(self, TrajectoryGenerator, controller):
""" Augment State Space
"""
self.GetControlInput(controller)
self.GetLegPhases(TrajectoryGenerator)
def ConvertFromLegModel(self, action):
# TODO
joint_angles = action
return joint_angles
def ApplyMotorLimits(self, joint_angles):
eps = 0.001
for i in range(len(joint_angles)):
LIM = MOTOR_LIMITS_BY_NAME[MOTOR_NAMES[i]]
joint_angles[i] = np.clip(joint_angles[i], LIM[0] + eps,
LIM[1] - eps)
return joint_angles
def ApplyAction(self, motor_commands):
"""Set the desired motor angles to the motors of the minitaur.
The desired motor angles are clipped based on the maximum allowed velocity.
If the pd_control_enabled is True, a torque is calculated according to
the difference between current and desired joint angle, as well as the joint
velocity. This torque is exerted to the motor. For more information about
PD control, please refer to: https://en.wikipedia.org/wiki/PID_controller.
Args:
motor_commands: The eight desired motor angles.
"""
# FIRST, APPLY MOTOR LIMITS:
motor_commands = self.ApplyMotorLimits(motor_commands)
if self._motor_velocity_limit < np.inf:
current_motor_angle = self.GetMotorAngles()
motor_commands_max = (current_motor_angle +
self.time_step * self._motor_velocity_limit)
motor_commands_min = (current_motor_angle -
self.time_step * self._motor_velocity_limit)
motor_commands = np.clip(motor_commands, motor_commands_min,
motor_commands_max)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
q = self.GetMotorAngles()
qdot = self.GetMotorVelocities()
if self._accurate_motor_model_enabled:
actual_torque, observed_torque = self._motor_model.convert_to_torque(
motor_commands, q, qdot)
if self._motor_overheat_protection:
for i in range(self.num_motors):
if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE:
self._overheat_counter[i] += 1
else:
self._overheat_counter[i] = 0
if (self._overheat_counter[i] >
OVERHEAT_SHUTDOWN_TIME / self.time_step):
self._motor_enabled_list[i] = False
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = observed_torque
# Transform into the motor space when applying the torque.
self._applied_motor_torque = np.multiply(
actual_torque, self._motor_direction)
for motor_id, motor_torque, motor_enabled in zip(
self._motor_id_list, self._applied_motor_torque,
self._motor_enabled_list):
if motor_enabled:
self._SetMotorTorqueById(motor_id, motor_torque)
else:
self._SetMotorTorqueById(motor_id, 0)
else:
torque_commands = -self._kp * (
q - motor_commands) - self._kd * qdot
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = torque_commands
# Transform into the motor space when applying the torque.
self._applied_motor_torques = np.multiply(
self._observed_motor_torques, self._motor_direction)
for motor_id, motor_torque in zip(self._motor_id_list,
self._applied_motor_torques):
self._SetMotorTorqueById(motor_id, motor_torque)
else:
motor_commands_with_direction = np.multiply(
motor_commands, self._motor_direction)
for motor_id, motor_command_with_direction in zip(
self._motor_id_list, motor_commands_with_direction):
self._SetDesiredMotorAngleById(motor_id,
motor_command_with_direction)
def Step(self, action):
for _ in range(self._action_repeat):
self.ApplyAction(action)
self._pybullet_client.stepSimulation()
self.RealisticObservation()
self._step_counter += 1
def GetTimeSinceReset(self):
return self._step_counter * self.time_step
def GetMotorAngles(self):
"""Gets the eight motor angles at the current moment, mapped to [-pi, pi].
Returns:
Motor angles, mapped to [-pi, pi].
"""
motor_angles = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[0]
for motor_id in self._motor_id_list
]
motor_angles = np.multiply(motor_angles, self._motor_direction)
return MapToMinusPiToPi(motor_angles)
def GetMotorVelocities(self):
"""Get the velocity of all eight motors.
Returns:
Velocities of all eight motors.
"""
motor_velocities = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[1]
for motor_id in self._motor_id_list
]
motor_velocities = np.multiply(motor_velocities, self._motor_direction)
return motor_velocities
def GetMotorTorques(self):
"""Get the amount of torque the motors are exerting.
Returns:
Motor torques of all eight motors.
"""
if self._accurate_motor_model_enabled or self._pd_control_enabled:
return self._observed_motor_torques
else:
motor_torques = [
self._pybullet_client.getJointState(self.quadruped,
motor_id)[3]
for motor_id in self._motor_id_list
]
motor_torques = np.multiply(motor_torques, self._motor_direction)
return motor_torques
def GetBaseMassesFromURDF(self):
"""Get the mass of the base from the URDF file."""
return self._base_mass_urdf
def GetBaseInertiasFromURDF(self):
"""Get the inertia of the base from the URDF file."""
return self._base_inertia_urdf
def GetLegMassesFromURDF(self):
"""Get the mass of the legs from the URDF file."""
return self._leg_masses_urdf
def GetLegInertiasFromURDF(self):
"""Get the inertia of the legs from the URDF file."""
return self._leg_inertia_urdf
def SetBaseMasses(self, base_mass):
"""Set the mass of spot's base.
Args:
base_mass: A list of masses of each body link in CHASIS_LINK_IDS. The
length of this list should be the same as the length of CHASIS_LINK_IDS.
Raises:
ValueError: It is raised when the length of base_mass is not the same as
the length of self._chassis_link_ids.
"""
if len(base_mass) != len(self._chassis_link_ids):
raise ValueError(
"The length of base_mass {} and self._chassis_link_ids {} are not "
"the same.".format(len(base_mass),
len(self._chassis_link_ids)))
for chassis_id, chassis_mass in zip(self._chassis_link_ids, base_mass):
self._pybullet_client.changeDynamics(self.quadruped,
chassis_id,
mass=chassis_mass)
def SetLegMasses(self, leg_masses):
"""Set the mass of the legs.
Args:
leg_masses: The leg and motor masses for all the leg links and motors.
Raises:
ValueError: It is raised when the length of masses is not equal to number
of links + motors.
"""
if len(leg_masses) != len(self._leg_link_ids) + len(
self._motor_link_ids):
raise ValueError("The number of values passed to SetLegMasses are "
"different than number of leg links and motors.")
for leg_id, leg_mass in zip(self._leg_link_ids, leg_masses):
self._pybullet_client.changeDynamics(self.quadruped,
leg_id,
mass=leg_mass)
motor_masses = leg_masses[len(self._leg_link_ids):]
for link_id, motor_mass in zip(self._motor_link_ids, motor_masses):
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
mass=motor_mass)
def SetBaseInertias(self, base_inertias):
"""Set the inertias of spot's base.
Args:
base_inertias: A list of inertias of each body link in CHASIS_LINK_IDS.
The length of this list should be the same as the length of
CHASIS_LINK_IDS.
Raises:
ValueError: It is raised when the length of base_inertias is not the same
as the length of self._chassis_link_ids and base_inertias contains
negative values.
"""
if len(base_inertias) != len(self._chassis_link_ids):
raise ValueError(
"The length of base_inertias {} and self._chassis_link_ids {} are "
"not the same.".format(len(base_inertias),
len(self._chassis_link_ids)))
for chassis_id, chassis_inertia in zip(self._chassis_link_ids,
base_inertias):
for inertia_value in chassis_inertia:
if (np.asarray(inertia_value) < 0).any():
raise ValueError(
"Values in inertia matrix should be non-negative.")
self._pybullet_client.changeDynamics(
self.quadruped,
chassis_id,
localInertiaDiagonal=chassis_inertia)
def SetLegInertias(self, leg_inertias):
"""Set the inertias of the legs.
Args:
leg_inertias: The leg and motor inertias for all the leg links and motors.
Raises:
ValueError: It is raised when the length of inertias is not equal to
the number of links + motors or leg_inertias contains negative values.
"""
if len(leg_inertias) != len(self._leg_link_ids) + len(
self._motor_link_ids):
raise ValueError("The number of values passed to SetLegMasses are "
"different than number of leg links and motors.")
for leg_id, leg_inertia in zip(self._leg_link_ids, leg_inertias):
for inertia_value in leg_inertias:
if (np.asarray(inertia_value) < 0).any():
raise ValueError(
"Values in inertia matrix should be non-negative.")
self._pybullet_client.changeDynamics(
self.quadruped, leg_id, localInertiaDiagonal=leg_inertia)
motor_inertias = leg_inertias[len(self._leg_link_ids):]
for link_id, motor_inertia in zip(self._motor_link_ids,
motor_inertias):
for inertia_value in motor_inertias:
if (np.asarray(inertia_value) < 0).any():
raise ValueError(
"Values in inertia matrix should be non-negative.")
self._pybullet_client.changeDynamics(
self.quadruped, link_id, localInertiaDiagonal=motor_inertia)
def SetFootFriction(self, foot_friction=100.0):
"""Set the lateral friction of the feet.
Args:
foot_friction: The lateral friction coefficient of the foot. This value is
shared by all four feet.
"""
for link_id in self._foot_link_ids:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
lateralFriction=foot_friction)
# TODO(b/73748980): Add more API's to set other contact parameters.
def SetFootRestitution(self, link_id, foot_restitution=1.0):
"""Set the coefficient of restitution at the feet.
Args:
foot_restitution: The coefficient of restitution (bounciness) of the feet.
This value is shared by all four feet.
"""
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
restitution=foot_restitution)
def SetJointFriction(self, joint_frictions):
for knee_joint_id, friction in zip(self._foot_link_ids,
joint_frictions):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=knee_joint_id,
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=friction)
def GetNumKneeJoints(self):
return len(self._foot_link_ids)
def SetBatteryVoltage(self, voltage):
if self._accurate_motor_model_enabled:
self._motor_model.set_voltage(voltage)
def SetMotorViscousDamping(self, viscous_damping):
if self._accurate_motor_model_enabled:
self._motor_model.set_viscous_damping(viscous_damping)
def RealisticObservation(self):
"""Receive the observation from sensors.
This function is called once per step. The observations are only updated
when this function is called.
"""
self._observation_history.appendleft(self.GetObservation())
self._control_observation = self._GetDelayedObservation(
self._control_latency)
self._control_observation = self._AddSensorNoise(
self._control_observation, self._observation_noise_stdev)
return self._control_observation
def _GetDelayedObservation(self, latency):
"""Get observation that is delayed by the amount specified in latency.
Args:
latency: The latency (in seconds) of the delayed observation.
Returns:
observation: The observation which was actually latency seconds ago.
"""
if latency <= 0 or len(self._observation_history) == 1:
observation = self._observation_history[0]
else:
n_steps_ago = int(latency / self.time_step)
if n_steps_ago + 1 >= len(self._observation_history):
return self._observation_history[-1]
remaining_latency = latency - n_steps_ago * self.time_step
blend_alpha = remaining_latency / self.time_step
observation = (
(1.0 - blend_alpha) *
np.array(self._observation_history[n_steps_ago]) +
blend_alpha *
np.array(self._observation_history[n_steps_ago + 1]))
return observation
def _GetPDObservation(self):
pd_delayed_observation = self._GetDelayedObservation(self._pd_latency)
q = pd_delayed_observation[0:self.num_motors]
qdot = pd_delayed_observation[self.num_motors:2 * self.num_motors]
return (np.array(q), np.array(qdot))
def _AddSensorNoise(self, observation, noise_stdev):
# if self._observation_noise_stdev > 0:
# observation += (self.np_random.normal(scale=noise_stdev,
# size=observation.shape) *
# self.GetObservationUpperBound())
return observation
def SetControlLatency(self, latency):
"""Set the latency of the control loop.
It measures the duration between sending an action from Nvidia TX2 and
receiving the observation from microcontroller.
Args:
latency: The latency (in seconds) of the control loop.
"""
self._control_latency = latency
def GetControlLatency(self):
"""Get the control latency.
Returns:
The latency (in seconds) between when the motor command is sent and when
the sensor measurements are reported back to the controller.
"""
return self._control_latency
def SetMotorGains(self, kp, kd):
"""Set the gains of all motors.
These gains are PD gains for motor positional control. kp is the
proportional gain and kd is the derivative gain.
Args:
kp: proportional gain of the motors.
kd: derivative gain of the motors.
"""
self._kp = kp
self._kd = kd
if self._accurate_motor_model_enabled:
self._motor_model.set_motor_gains(kp, kd)
def GetMotorGains(self):
"""Get the gains of the motor.
Returns:
The proportional gain.
The derivative gain.
"""
return self._kp, self._kd
def SetMotorStrengthRatio(self, ratio):
"""Set the strength of all motors relative to the default value.
Args:
ratio: The relative strength. A scalar range from 0.0 to 1.0.
"""
if self._accurate_motor_model_enabled:
self._motor_model.set_strength_ratios([ratio] * self.num_motors)
def SetMotorStrengthRatios(self, ratios):
"""Set the strength of each motor relative to the default value.
Args:
ratios: The relative strength. A numpy array ranging from 0.0 to 1.0.
"""
if self._accurate_motor_model_enabled:
self._motor_model.set_strength_ratios(ratios)
def SetTimeSteps(self, action_repeat, simulation_step):
"""Set the time steps of the control and simulation.
Args:
action_repeat: The number of simulation steps that the same action is
repeated.
simulation_step: The simulation time step.
"""
self.time_step = simulation_step
self._action_repeat = action_repeat
@property
def chassis_link_ids(self):
return self._chassis_link_ids
| 47,996 | Python | 40.269991 | 107 | 0.578777 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/spot_gym_env.py | """
CODE BASED ON EXAMPLE FROM:
@misc{coumans2017pybullet,
title={Pybullet, a python module for physics simulation in robotics, games and machine learning},
author={Coumans, Erwin and Bai, Yunfei},
url={www.pybullet.org},
year={2017},
}
Example: minitaur_gym_env.py
https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_gym_env.py
"""
import math
import time
import gym
import numpy as np
import pybullet
import pybullet_data
from gym import spaces
from gym.utils import seeding
from pkg_resources import parse_version
from spotmicro import spot
import pybullet_utils.bullet_client as bullet_client
from gym.envs.registration import register
from spotmicro.heightfield import HeightField
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import spotmicro.Kinematics.LieAlgebra as LA
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
NUM_SUBSTEPS = 5
NUM_MOTORS = 12
MOTOR_ANGLE_OBSERVATION_INDEX = 0
MOTOR_VELOCITY_OBSERVATION_INDEX = MOTOR_ANGLE_OBSERVATION_INDEX + NUM_MOTORS
MOTOR_TORQUE_OBSERVATION_INDEX = MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS
BASE_ORIENTATION_OBSERVATION_INDEX = MOTOR_TORQUE_OBSERVATION_INDEX + NUM_MOTORS
ACTION_EPS = 0.01
OBSERVATION_EPS = 0.01
RENDER_HEIGHT = 720
RENDER_WIDTH = 960
SENSOR_NOISE_STDDEV = spot.SENSOR_NOISE_STDDEV
DEFAULT_URDF_VERSION = "default"
NUM_SIMULATION_ITERATION_STEPS = 1000
spot_URDF_VERSION_MAP = {DEFAULT_URDF_VERSION: spot.Spot}
# Register as OpenAI Gym Environment
register(
id="SpotMicroEnv-v0",
entry_point='spotmicro.spot_gym_env:spotGymEnv',
max_episode_steps=1000,
)
def convert_to_list(obj):
try:
iter(obj)
return obj
except TypeError:
return [obj]
class spotGymEnv(gym.Env):
"""The gym environment for spot.
It simulates the locomotion of spot, a quadruped robot. The state space
include the angles, velocities and torques for all the motors and the action
space is the desired motor angle for each motor. The reward function is based
on how far spot walks in 1000 steps and penalizes the energy
expenditure.
"""
metadata = {
"render.modes": ["human", "rgb_array"],
"video.frames_per_second": 50
}
def __init__(self,
distance_weight=1.0,
rotation_weight=1.0,
energy_weight=0.0005,
shake_weight=0.005,
drift_weight=2.0,
rp_weight=0.1,
rate_weight=0.1,
urdf_root=pybullet_data.getDataPath(),
urdf_version=None,
distance_limit=float("inf"),
observation_noise_stdev=SENSOR_NOISE_STDDEV,
self_collision_enabled=True,
motor_velocity_limit=np.inf,
pd_control_enabled=False,
leg_model_enabled=False,
accurate_motor_model_enabled=False,
remove_default_joint_damping=False,
motor_kp=2.0,
motor_kd=0.03,
control_latency=0.0,
pd_latency=0.0,
torque_control_enabled=False,
motor_overheat_protection=False,
hard_reset=False,
on_rack=False,
render=True,
num_steps_to_log=1000,
action_repeat=1,
control_time_step=None,
env_randomizer=SpotEnvRandomizer(),
forward_reward_cap=float("inf"),
reflection=True,
log_path=None,
desired_velocity=0.5,
desired_rate=0.0,
lateral=False,
draw_foot_path=False,
height_field=False,
height_field_iters=2,
AutoStepper=False,
contacts=True):
"""Initialize the spot gym environment.
Args:
urdf_root: The path to the urdf data folder.
urdf_version: [DEFAULT_URDF_VERSION] are allowable
versions. If None, DEFAULT_URDF_VERSION is used.
distance_weight: The weight of the distance term in the reward.
energy_weight: The weight of the energy term in the reward.
shake_weight: The weight of the vertical shakiness term in the reward.
drift_weight: The weight of the sideways drift term in the reward.
distance_limit: The maximum distance to terminate the episode.
observation_noise_stdev: The standard deviation of observation noise.
self_collision_enabled: Whether to enable self collision in the sim.
motor_velocity_limit: The velocity limit of each motor.
pd_control_enabled: Whether to use PD controller for each motor.
leg_model_enabled: Whether to use a leg motor to reparameterize the action
space.
accurate_motor_model_enabled: Whether to use the accurate DC motor model.
remove_default_joint_damping: Whether to remove the default joint damping.
motor_kp: proportional gain for the accurate motor model.
motor_kd: derivative gain for the accurate motor model.
control_latency: It is the delay in the controller between when an
observation is made at some point, and when that reading is reported
back to the Neural Network.
pd_latency: latency of the PD controller loop. PD calculates PWM based on
the motor angle and velocity. The latency measures the time between when
the motor angle and velocity are observed on the microcontroller and
when the true state happens on the motor. It is typically (0.001-
0.002s).
torque_control_enabled: Whether to use the torque control, if set to
False, pose control will be used.
motor_overheat_protection: Whether to shutdown the motor that has exerted
large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
(OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in spot.py for more
details.
hard_reset: Whether to wipe the simulation and load everything when reset
is called. If set to false, reset just place spot back to start
position and set its pose to initial configuration.
on_rack: Whether to place spot on rack. This is only used to debug
the walking gait. In this mode, spot's base is hanged midair so
that its walking gait is clearer to visualize.
render: Whether to render the simulation.
num_steps_to_log: The max number of control steps in one episode that will
be logged. If the number of steps is more than num_steps_to_log, the
environment will still be running, but only first num_steps_to_log will
be recorded in logging.
action_repeat: The number of simulation steps before actions are applied.
control_time_step: The time step between two successive control signals.
env_randomizer: An instance (or a list) of EnvRandomizer(s). An
EnvRandomizer may randomize the physical property of spot, change
the terrrain during reset(), or add perturbation forces during step().
forward_reward_cap: The maximum value that forward reward is capped at.
Disabled (Inf) by default.
log_path: The path to write out logs. For the details of logging, refer to
spot_logging.proto.
Raises:
ValueError: If the urdf_version is not supported.
"""
# Sense Contacts
self.contacts = contacts
# Enable Auto Stepper State Machine
self.AutoStepper = AutoStepper
# Enable Rough Terrain or Not
self.height_field = height_field
self.draw_foot_path = draw_foot_path
# DRAWING FEET PATH
self.prev_feet_path = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
# CONTROL METRICS
self.desired_velocity = desired_velocity
self.desired_rate = desired_rate
self.lateral = lateral
# Set up logging.
self._log_path = log_path
# @TODO fix logging
# NUM ITERS
self._time_step = 0.01
self._action_repeat = action_repeat
self._num_bullet_solver_iterations = 300
self.logging = None
if pd_control_enabled or accurate_motor_model_enabled:
self._time_step /= NUM_SUBSTEPS
self._num_bullet_solver_iterations /= NUM_SUBSTEPS
self._action_repeat *= NUM_SUBSTEPS
# PD control needs smaller time step for stability.
if control_time_step is not None:
self.control_time_step = control_time_step
else:
# Get Control Timestep
self.control_time_step = self._time_step * self._action_repeat
# TODO: Fix the value of self._num_bullet_solver_iterations.
self._num_bullet_solver_iterations = int(
NUM_SIMULATION_ITERATION_STEPS / self._action_repeat)
# URDF
self._urdf_root = urdf_root
self._self_collision_enabled = self_collision_enabled
self._motor_velocity_limit = motor_velocity_limit
self._observation = []
self._true_observation = []
self._objectives = []
self._objective_weights = [
distance_weight, energy_weight, drift_weight, shake_weight
]
self._env_step_counter = 0
self._num_steps_to_log = num_steps_to_log
self._is_render = render
self._last_base_position = [0, 0, 0]
self._last_base_orientation = [0, 0, 0, 1]
self._distance_weight = distance_weight
self._rotation_weight = rotation_weight
self._energy_weight = energy_weight
self._drift_weight = drift_weight
self._shake_weight = shake_weight
self._rp_weight = rp_weight
self._rate_weight = rate_weight
self._distance_limit = distance_limit
self._observation_noise_stdev = observation_noise_stdev
self._action_bound = 1
self._pd_control_enabled = pd_control_enabled
self._leg_model_enabled = leg_model_enabled
self._accurate_motor_model_enabled = accurate_motor_model_enabled
self._remove_default_joint_damping = remove_default_joint_damping
self._motor_kp = motor_kp
self._motor_kd = motor_kd
self._torque_control_enabled = torque_control_enabled
self._motor_overheat_protection = motor_overheat_protection
self._on_rack = on_rack
self._cam_dist = 1.0
self._cam_yaw = 0
self._cam_pitch = -30
self._forward_reward_cap = forward_reward_cap
self._hard_reset = True
self._last_frame_time = 0.0
self._control_latency = control_latency
self._pd_latency = pd_latency
self._urdf_version = urdf_version
self._ground_id = None
self._reflection = reflection
self._env_randomizer = env_randomizer
# @TODO fix logging
self._episode_proto = None
if self._is_render:
self._pybullet_client = bullet_client.BulletClient(
connection_mode=pybullet.GUI)
else:
self._pybullet_client = bullet_client.BulletClient()
if self._urdf_version is None:
self._urdf_version = DEFAULT_URDF_VERSION
self._pybullet_client.setPhysicsEngineParameter(enableConeFriction=0)
self.seed()
# Only update after HF has been generated
self.height_field = False
self.reset()
observation_high = (self.spot.GetObservationUpperBound() +
OBSERVATION_EPS)
observation_low = (self.spot.GetObservationLowerBound() -
OBSERVATION_EPS)
action_dim = NUM_MOTORS
action_high = np.array([self._action_bound] * action_dim)
self.action_space = spaces.Box(-action_high, action_high)
self.observation_space = spaces.Box(observation_low, observation_high)
self.viewer = None
self._hard_reset = hard_reset # This assignment need to be after reset()
self.goal_reached = False
# Generate HeightField or not
self.height_field = height_field
self.hf = HeightField()
if self.height_field:
# Do 3x for extra roughness
for i in range(height_field_iters):
self.hf._generate_field(self)
def set_env_randomizer(self, env_randomizer):
self._env_randomizer = env_randomizer
def configure(self, args):
self._args = args
def reset(self,
initial_motor_angles=None,
reset_duration=1.0,
desired_velocity=None,
desired_rate=None):
# Use Autostepper
if self.AutoStepper:
self.StateMachine = BezierStepper(dt=self._time_step)
# Shuffle order of states
self.StateMachine.reshuffle()
self._pybullet_client.configureDebugVisualizer(
self._pybullet_client.COV_ENABLE_RENDERING, 0)
if self._hard_reset:
self._pybullet_client.resetSimulation()
self._pybullet_client.setPhysicsEngineParameter(
numSolverIterations=int(self._num_bullet_solver_iterations))
self._pybullet_client.setTimeStep(self._time_step)
self._ground_id = self._pybullet_client.loadURDF("%s/plane.urdf" %
self._urdf_root)
if self._reflection:
self._pybullet_client.changeVisualShape(
self._ground_id, -1, rgbaColor=[1, 1, 1, 0.8])
self._pybullet_client.configureDebugVisualizer(
self._pybullet_client.COV_ENABLE_PLANAR_REFLECTION,
self._ground_id)
self._pybullet_client.setGravity(0, 0, -9.81)
acc_motor = self._accurate_motor_model_enabled
motor_protect = self._motor_overheat_protection
if self._urdf_version not in spot_URDF_VERSION_MAP:
raise ValueError("%s is not a supported urdf_version." %
self._urdf_version)
else:
self.spot = (spot_URDF_VERSION_MAP[self._urdf_version](
pybullet_client=self._pybullet_client,
action_repeat=self._action_repeat,
urdf_root=self._urdf_root,
time_step=self._time_step,
self_collision_enabled=self._self_collision_enabled,
motor_velocity_limit=self._motor_velocity_limit,
pd_control_enabled=self._pd_control_enabled,
accurate_motor_model_enabled=acc_motor,
remove_default_joint_damping=self.
_remove_default_joint_damping,
motor_kp=self._motor_kp,
motor_kd=self._motor_kd,
control_latency=self._control_latency,
pd_latency=self._pd_latency,
observation_noise_stdev=self._observation_noise_stdev,
torque_control_enabled=self._torque_control_enabled,
motor_overheat_protection=motor_protect,
on_rack=self._on_rack,
np_random=self.np_random,
contacts=self.contacts))
self.spot.Reset(reload_urdf=False,
default_motor_angles=initial_motor_angles,
reset_time=reset_duration)
if self._env_randomizer is not None:
self._env_randomizer.randomize_env(self)
# Also update heightfield if wr are wholly randomizing
if self.height_field:
self.hf.UpdateHeightField()
if desired_velocity is not None:
self.desired_velocity = desired_velocity
if desired_rate is not None:
self.desired_rate = desired_rate
self._pybullet_client.setPhysicsEngineParameter(enableConeFriction=0)
self._env_step_counter = 0
self._last_base_position = [0, 0, 0]
self._last_base_orientation = [0, 0, 0, 1]
self._objectives = []
self._pybullet_client.resetDebugVisualizerCamera(
self._cam_dist, self._cam_yaw, self._cam_pitch, [0, 0, 0])
self._pybullet_client.configureDebugVisualizer(
self._pybullet_client.COV_ENABLE_RENDERING, 1)
return self._get_observation()
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def _transform_action_to_motor_command(self, action):
if self._leg_model_enabled:
for i, action_component in enumerate(action):
if not (-self._action_bound - ACTION_EPS <= action_component <=
self._action_bound + ACTION_EPS):
raise ValueError("{}th action {} out of bounds.".format(
i, action_component))
action = self.spot.ConvertFromLegModel(action)
return action
def step(self, action):
"""Step forward the simulation, given the action.
Args:
action: A list of desired motor angles for eight motors.
Returns:
observations: The angles, velocities and torques of all motors.
reward: The reward for the current state-action pair.
done: Whether the episode has ended.
info: A dictionary that stores diagnostic information.
Raises:
ValueError: The action dimension is not the same as the number of motors.
ValueError: The magnitude of actions is out of bounds.
"""
self._last_base_position = self.spot.GetBasePosition()
self._last_base_orientation = self.spot.GetBaseOrientation()
# print("ACTION:")
# print(action)
if self._is_render:
# Sleep, otherwise the computation takes less time than real time,
# which will make the visualization like a fast-forward video.
time_spent = time.time() - self._last_frame_time
self._last_frame_time = time.time()
time_to_sleep = self.control_time_step - time_spent
if time_to_sleep > 0:
time.sleep(time_to_sleep)
base_pos = self.spot.GetBasePosition()
# Keep the previous orientation of the camera set by the user.
[yaw, pitch,
dist] = self._pybullet_client.getDebugVisualizerCamera()[8:11]
self._pybullet_client.resetDebugVisualizerCamera(
dist, yaw, pitch, base_pos)
action = self._transform_action_to_motor_command(action)
self.spot.Step(action)
reward = self._reward()
done = self._termination()
self._env_step_counter += 1
# DRAW FOOT PATH
if self.draw_foot_path:
self.DrawFootPath()
return np.array(self._get_observation()), reward, done, {}
def render(self, mode="rgb_array", close=False):
if mode != "rgb_array":
return np.array([])
base_pos = self.spot.GetBasePosition()
view_matrix = self._pybullet_client.computeViewMatrixFromYawPitchRoll(
cameraTargetPosition=base_pos,
distance=self._cam_dist,
yaw=self._cam_yaw,
pitch=self._cam_pitch,
roll=0,
upAxisIndex=2)
proj_matrix = self._pybullet_client.computeProjectionMatrixFOV(
fov=60,
aspect=float(RENDER_WIDTH) / RENDER_HEIGHT,
nearVal=0.1,
farVal=100.0)
(_, _, px, _, _) = self._pybullet_client.getCameraImage(
width=RENDER_WIDTH,
height=RENDER_HEIGHT,
renderer=self._pybullet_client.ER_BULLET_HARDWARE_OPENGL,
viewMatrix=view_matrix,
projectionMatrix=proj_matrix)
rgb_array = np.array(px)
rgb_array = rgb_array[:, :, :3]
return rgb_array
def DrawFootPath(self):
# Get Foot Positions
FL = self._pybullet_client.getLinkState(self.spot.quadruped,
self.spot._foot_id_list[0])[0]
FR = self._pybullet_client.getLinkState(self.spot.quadruped,
self.spot._foot_id_list[1])[0]
BL = self._pybullet_client.getLinkState(self.spot.quadruped,
self.spot._foot_id_list[2])[0]
BR = self._pybullet_client.getLinkState(self.spot.quadruped,
self.spot._foot_id_list[3])[0]
lifetime = 3.0 # sec
self._pybullet_client.addUserDebugLine(self.prev_feet_path[0],
FL, [1, 0, 0],
lifeTime=lifetime)
self._pybullet_client.addUserDebugLine(self.prev_feet_path[1],
FR, [0, 1, 0],
lifeTime=lifetime)
self._pybullet_client.addUserDebugLine(self.prev_feet_path[2],
BL, [0, 0, 1],
lifeTime=lifetime)
self._pybullet_client.addUserDebugLine(self.prev_feet_path[3],
BR, [1, 1, 0],
lifeTime=lifetime)
self.prev_feet_path[0] = FL
self.prev_feet_path[1] = FR
self.prev_feet_path[2] = BL
self.prev_feet_path[3] = BR
def get_spot_motor_angles(self):
"""Get the spot's motor angles.
Returns:
A numpy array of motor angles.
"""
return np.array(
self._observation[MOTOR_ANGLE_OBSERVATION_INDEX:
MOTOR_ANGLE_OBSERVATION_INDEX + NUM_MOTORS])
def get_spot_motor_velocities(self):
"""Get the spot's motor velocities.
Returns:
A numpy array of motor velocities.
"""
return np.array(
self._observation[MOTOR_VELOCITY_OBSERVATION_INDEX:
MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS])
def get_spot_motor_torques(self):
"""Get the spot's motor torques.
Returns:
A numpy array of motor torques.
"""
return np.array(
self._observation[MOTOR_TORQUE_OBSERVATION_INDEX:
MOTOR_TORQUE_OBSERVATION_INDEX + NUM_MOTORS])
def get_spot_base_orientation(self):
"""Get the spot's base orientation, represented by a quaternion.
Returns:
A numpy array of spot's orientation.
"""
return np.array(self._observation[BASE_ORIENTATION_OBSERVATION_INDEX:])
def is_fallen(self):
"""Decide whether spot has fallen.
If the up directions between the base and the world is larger (the dot
product is smaller than 0.85) or the base is very low on the ground
(the height is smaller than 0.13 meter), spot is considered fallen.
Returns:
Boolean value that indicates whether spot has fallen.
"""
orientation = self.spot.GetBaseOrientation()
rot_mat = self._pybullet_client.getMatrixFromQuaternion(orientation)
local_up = rot_mat[6:]
pos = self.spot.GetBasePosition()
# or pos[2] < 0.13
return (np.dot(np.asarray([0, 0, 1]), np.asarray(local_up)) < 0.55)
def _termination(self):
position = self.spot.GetBasePosition()
distance = math.sqrt(position[0]**2 + position[1]**2)
return self.is_fallen() or distance > self._distance_limit
def _reward(self):
""" NOTE: reward now consists of:
roll, pitch at desired 0
acc (y,z) = 0
FORWARD-BACKWARD: rate(x,y,z) = 0
--> HIDDEN REWARD: x(+-) velocity reference, not incl. in obs
SPIN: acc(x) = 0, rate(x,y) = 0, rate (z) = rate reference
Also include drift, energy vanilla rewards
"""
current_base_position = self.spot.GetBasePosition()
# get observation
obs = self._get_observation()
# forward_reward = current_base_position[0] - self._last_base_position[0]
# # POSITIVE FOR FORWARD, NEGATIVE FOR BACKWARD | NOTE: HIDDEN
# GETTING TWIST IN BODY FRAME
pos = self.spot.GetBasePosition()
orn = self.spot.GetBaseOrientation()
roll, pitch, yaw = self._pybullet_client.getEulerFromQuaternion(
[orn[0], orn[1], orn[2], orn[3]])
rpy = LA.RPY(roll, pitch, yaw)
R, _ = LA.TransToRp(rpy)
T_wb = LA.RpToTrans(R, np.array([pos[0], pos[1], pos[2]]))
T_bw = LA.TransInv(T_wb)
Adj_Tbw = LA.Adjoint(T_bw)
Vw = np.concatenate(
(self.spot.prev_ang_twist, self.spot.prev_lin_twist))
Vb = np.dot(Adj_Tbw, Vw)
# New Twist in Body Frame
# POSITIVE FOR FORWARD, NEGATIVE FOR BACKWARD | NOTE: HIDDEN
fwd_speed = -Vb[3] # vx
lat_speed = -Vb[4] # vy
# fwd_speed = self.spot.prev_lin_twist[0]
# lat_speed = self.spot.prev_lin_twist[1]
# print("FORWARD SPEED: {} \t STATE SPEED: {}".format(
# fwd_speed, self.desired_velocity))
# self.desired_velocity = 0.4
# Modification for lateral/fwd rewards
reward_max = 1.0
# FORWARD
if not self.lateral:
# f(x)=-(x-desired))^(2)*((1/desired)^2)+1
# to make sure that at 0vel there is 0 reawrd.
# also squishes allowable tolerance
forward_reward = reward_max * np.exp(
-(fwd_speed - self.desired_velocity)**2 / (0.1))
# LATERAL
else:
forward_reward = reward_max * np.exp(
-(lat_speed - self.desired_velocity)**2 / (0.1))
yaw_rate = obs[4]
rot_reward = reward_max * np.exp(-(yaw_rate - self.desired_rate)**2 /
(0.1))
# Make sure that for forward-policy there is the appropriate rotation penalty
if self.desired_velocity != 0:
self._rotation_weight = self._rate_weight
rot_reward = -abs(obs[4])
elif self.desired_rate != 0:
forward_reward = 0.0
# penalty for nonzero roll, pitch
rp_reward = -(abs(obs[0]) + abs(obs[1]))
# print("ROLL: {} \t PITCH: {}".format(obs[0], obs[1]))
# penalty for nonzero acc(z)
shake_reward = -abs(obs[4])
# penalty for nonzero rate (x,y,z)
rate_reward = -(abs(obs[2]) + abs(obs[3]))
# drift_reward = -abs(current_base_position[1] -
# self._last_base_position[1])
# this penalizes absolute error, and does not penalize correction
# NOTE: for side-side, drift reward becomes in x instead
drift_reward = -abs(current_base_position[1])
# If Lateral, change drift reward
if self.lateral:
drift_reward = -abs(current_base_position[0])
# shake_reward = -abs(current_base_position[2] -
# self._last_base_position[2])
self._last_base_position = current_base_position
energy_reward = -np.abs(
np.dot(self.spot.GetMotorTorques(),
self.spot.GetMotorVelocities())) * self._time_step
reward = (self._distance_weight * forward_reward +
self._rotation_weight * rot_reward +
self._energy_weight * energy_reward +
self._drift_weight * drift_reward +
self._shake_weight * shake_reward +
self._rp_weight * rp_reward +
self._rate_weight * rate_reward)
self._objectives.append(
[forward_reward, energy_reward, drift_reward, shake_reward])
# print("REWARD: ", reward)
return reward
def get_objectives(self):
return self._objectives
@property
def objective_weights(self):
"""Accessor for the weights for all the objectives.
Returns:
List of floating points that corresponds to weights for the objectives in
the order that objectives are stored.
"""
return self._objective_weights
def _get_observation(self):
"""Get observation of this environment, including noise and latency.
spot class maintains a history of true observations. Based on the
latency, this function will find the observation at the right time,
interpolate if necessary. Then Gaussian noise is added to this observation
based on self.observation_noise_stdev.
Returns:
The noisy observation with latency.
"""
self._observation = self.spot.GetObservation()
return self._observation
def _get_realistic_observation(self):
"""Get the observations of this environment.
It includes the angles, velocities, torques and the orientation of the base.
Returns:
The observation list. observation[0:8] are motor angles. observation[8:16]
are motor velocities, observation[16:24] are motor torques.
observation[24:28] is the orientation of the base, in quaternion form.
"""
self._observation = self.spot.RealisticObservation()
return self._observation
if parse_version(gym.__version__) < parse_version('0.9.6'):
_render = render
_reset = reset
_seed = seed
_step = step
def set_time_step(self, control_step, simulation_step=0.001):
"""Sets the time step of the environment.
Args:
control_step: The time period (in seconds) between two adjacent control
actions are applied.
simulation_step: The simulation time step in PyBullet. By default, the
simulation step is 0.001s, which is a good trade-off between simulation
speed and accuracy.
Raises:
ValueError: If the control step is smaller than the simulation step.
"""
if control_step < simulation_step:
raise ValueError(
"Control step should be larger than or equal to simulation step."
)
self.control_time_step = control_step
self._time_step = simulation_step
self._action_repeat = int(round(control_step / simulation_step))
self._num_bullet_solver_iterations = (NUM_SIMULATION_ITERATION_STEPS /
self._action_repeat)
self._pybullet_client.setPhysicsEngineParameter(
numSolverIterations=self._num_bullet_solver_iterations)
self._pybullet_client.setTimeStep(self._time_step)
self.spot.SetTimeSteps(action_repeat=self._action_repeat,
simulation_step=self._time_step)
@property
def pybullet_client(self):
return self._pybullet_client
@property
def ground_id(self):
return self._ground_id
@ground_id.setter
def ground_id(self, new_ground_id):
self._ground_id = new_ground_id
@property
def env_step_counter(self):
return self._env_step_counter
| 31,142 | Python | 40.358566 | 122 | 0.598452 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/spot_env_randomizer.py | """
CODE BASED ON EXAMPLE FROM:
@misc{coumans2017pybullet,
title={Pybullet, a python module for physics simulation in robotics, games and machine learning},
author={Coumans, Erwin and Bai, Yunfei},
url={www.pybullet.org},
year={2017},
}
Example: minitaur_env_randomizer.py
https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/minitaur/envs/env_randomizers/minitaur_env_randomizer.py
"""
import numpy as np
from . import env_randomizer_base
# Relative range.
spot_BASE_MASS_ERROR_RANGE = (-0.2, 0.2) # 0.2 means 20%
spot_LEG_MASS_ERROR_RANGE = (-0.2, 0.2) # 0.2 means 20%
# Absolute range.
BATTERY_VOLTAGE_RANGE = (7.0, 8.4) # Unit: Volt
MOTOR_VISCOUS_DAMPING_RANGE = (0, 0.01) # Unit: N*m*s/rad (torque/angular vel)
spot_LEG_FRICTION = (0.8, 1.5) # Unit: dimensionless
class SpotEnvRandomizer(env_randomizer_base.EnvRandomizerBase):
"""A randomizer that change the spot_gym_env during every reset."""
def __init__(self,
spot_base_mass_err_range=spot_BASE_MASS_ERROR_RANGE,
spot_leg_mass_err_range=spot_LEG_MASS_ERROR_RANGE,
battery_voltage_range=BATTERY_VOLTAGE_RANGE,
motor_viscous_damping_range=MOTOR_VISCOUS_DAMPING_RANGE):
self._spot_base_mass_err_range = spot_base_mass_err_range
self._spot_leg_mass_err_range = spot_leg_mass_err_range
self._battery_voltage_range = battery_voltage_range
self._motor_viscous_damping_range = motor_viscous_damping_range
np.random.seed(0)
def randomize_env(self, env):
self._randomize_spot(env.spot)
def _randomize_spot(self, spot):
"""Randomize various physical properties of spot.
It randomizes the mass/inertia of the base, mass/inertia of the legs,
friction coefficient of the feet, the battery voltage and the motor damping
at each reset() of the environment.
Args:
spot: the spot instance in spot_gym_env environment.
"""
base_mass = spot.GetBaseMassFromURDF()
# print("BM: ", base_mass)
randomized_base_mass = np.random.uniform(
np.array([base_mass]) * (1.0 + self._spot_base_mass_err_range[0]),
np.array([base_mass]) * (1.0 + self._spot_base_mass_err_range[1]))
spot.SetBaseMass(randomized_base_mass[0])
leg_masses = spot.GetLegMassesFromURDF()
leg_masses_lower_bound = np.array(leg_masses) * (
1.0 + self._spot_leg_mass_err_range[0])
leg_masses_upper_bound = np.array(leg_masses) * (
1.0 + self._spot_leg_mass_err_range[1])
randomized_leg_masses = [
np.random.uniform(leg_masses_lower_bound[i],
leg_masses_upper_bound[i])
for i in range(len(leg_masses))
]
spot.SetLegMasses(randomized_leg_masses)
randomized_battery_voltage = np.random.uniform(
BATTERY_VOLTAGE_RANGE[0], BATTERY_VOLTAGE_RANGE[1])
spot.SetBatteryVoltage(randomized_battery_voltage)
randomized_motor_damping = np.random.uniform(
MOTOR_VISCOUS_DAMPING_RANGE[0], MOTOR_VISCOUS_DAMPING_RANGE[1])
spot.SetMotorViscousDamping(randomized_motor_damping)
randomized_foot_friction = np.random.uniform(spot_LEG_FRICTION[0],
spot_LEG_FRICTION[1])
spot.SetFootFriction(randomized_foot_friction)
| 3,428 | Python | 40.817073 | 145 | 0.648483 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/heightfield.py | """
CODE BASED ON EXAMPLE FROM:
@misc{coumans2017pybullet,
title={Pybullet, a python module for physics simulation in robotics, games and machine learning},
author={Coumans, Erwin and Bai, Yunfei},
url={www.pybullet.org},
year={2017},
}
Example: heightfield.py
https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/heightfield.py
"""
import pybullet as p
import pybullet_data as pd
import math
import time
textureId = -1
useProgrammatic = 0
useTerrainFromPNG = 1
useDeepLocoCSV = 2
updateHeightfield = False
heightfieldSource = useProgrammatic
numHeightfieldRows = 256
numHeightfieldColumns = 256
import random
random.seed(10)
class HeightField():
def __init__(self):
self.hf_id = 0
self.terrainShape = 0
self.heightfieldData = [0] * numHeightfieldRows * numHeightfieldColumns
def _generate_field(self, env, heightPerturbationRange=0.08):
env.pybullet_client.setAdditionalSearchPath(pd.getDataPath())
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 0)
heightPerturbationRange = heightPerturbationRange
if heightfieldSource == useProgrammatic:
for j in range(int(numHeightfieldColumns / 2)):
for i in range(int(numHeightfieldRows / 2)):
height = random.uniform(0, heightPerturbationRange)
self.heightfieldData[2 * i +
2 * j * numHeightfieldRows] = height
self.heightfieldData[2 * i + 1 +
2 * j * numHeightfieldRows] = height
self.heightfieldData[2 * i + (2 * j + 1) *
numHeightfieldRows] = height
self.heightfieldData[2 * i + 1 + (2 * j + 1) *
numHeightfieldRows] = height
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.07, .07, 1.6],
heightfieldTextureScaling=(numHeightfieldRows - 1) / 2,
heightfieldData=self.heightfieldData,
numHeightfieldRows=numHeightfieldRows,
numHeightfieldColumns=numHeightfieldColumns)
terrain = env.pybullet_client.createMultiBody(0, terrainShape)
env.pybullet_client.resetBasePositionAndOrientation(
terrain, [0, 0, 0.0], [0, 0, 0, 1])
env.pybullet_client.changeDynamics(terrain,
-1,
lateralFriction=1.0)
if heightfieldSource == useDeepLocoCSV:
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.5, .5, 2.5],
fileName="heightmaps/ground0.txt",
heightfieldTextureScaling=128)
terrain = env.pybullet_client.createMultiBody(0, terrainShape)
env.pybullet_client.resetBasePositionAndOrientation(
terrain, [0, 0, 0], [0, 0, 0, 1])
env.pybullet_client.changeDynamics(terrain,
-1,
lateralFriction=1.0)
if heightfieldSource == useTerrainFromPNG:
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.05, .05, 1.8],
fileName="heightmaps/wm_height_out.png")
textureId = env.pybullet_client.loadTexture(
"heightmaps/gimp_overlay_out.png")
terrain = env.pybullet_client.createMultiBody(0, terrainShape)
env.pybullet_client.changeVisualShape(terrain,
-1,
textureUniqueId=textureId)
env.pybullet_client.resetBasePositionAndOrientation(
terrain, [0, 0, 0.1], [0, 0, 0, 1])
env.pybullet_client.changeDynamics(terrain,
-1,
lateralFriction=1.0)
self.hf_id = terrainShape
self.terrainShape = terrainShape
print("TERRAIN SHAPE: {}".format(terrainShape))
env.pybullet_client.changeVisualShape(terrain,
-1,
rgbaColor=[1, 1, 1, 1])
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 1)
def UpdateHeightField(self, heightPerturbationRange=0.08):
if heightfieldSource == useProgrammatic:
for j in range(int(numHeightfieldColumns / 2)):
for i in range(int(numHeightfieldRows / 2)):
height = random.uniform(
0, heightPerturbationRange) # +math.sin(time.time())
self.heightfieldData[2 * i +
2 * j * numHeightfieldRows] = height
self.heightfieldData[2 * i + 1 +
2 * j * numHeightfieldRows] = height
self.heightfieldData[2 * i + (2 * j + 1) *
numHeightfieldRows] = height
self.heightfieldData[2 * i + 1 + (2 * j + 1) *
numHeightfieldRows] = height
#GEOM_CONCAVE_INTERNAL_EDGE may help avoid getting stuck at an internal (shared) edge of the triangle/heightfield.
#GEOM_CONCAVE_INTERNAL_EDGE is a bit slower to build though.
#flags = p.GEOM_CONCAVE_INTERNAL_EDGE
flags = 0
self.terrainShape = p.createCollisionShape(
shapeType=p.GEOM_HEIGHTFIELD,
flags=flags,
meshScale=[.05, .05, 1],
heightfieldTextureScaling=(numHeightfieldRows - 1) / 2,
heightfieldData=self.heightfieldData,
numHeightfieldRows=numHeightfieldRows,
numHeightfieldColumns=numHeightfieldColumns,
replaceHeightfieldIndex=self.terrainShape)
| 6,396 | Python | 44.368794 | 126 | 0.553627 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/Kinematics/SpotKinematics.py | #!/usr/bin/env python
import numpy as np
from spotmicro.Kinematics.LegKinematics import LegIK
from spotmicro.Kinematics.LieAlgebra import RpToTrans, TransToRp, TransInv, RPY, TransformVector
from collections import OrderedDict
class SpotModel:
def __init__(self,
shoulder_length=0.055,
elbow_length=0.10652,
wrist_length=0.145,
hip_x=0.23,
hip_y=0.075,
foot_x=0.23,
foot_y=0.185,
height=0.20,
com_offset=0.016,
shoulder_lim=[-0.548, 0.548],
elbow_lim=[-2.17, 0.97],
wrist_lim=[-0.1, 2.59]):
"""
Spot Micro Kinematics
"""
# COM offset in x direction
self.com_offset = com_offset
# Leg Parameters
self.shoulder_length = shoulder_length
self.elbow_length = elbow_length
self.wrist_length = wrist_length
# Leg Vector desired_positions
# Distance Between Hips
# Length
self.hip_x = hip_x
# Width
self.hip_y = hip_y
# Distance Between Feet
# Length
self.foot_x = foot_x
# Width
self.foot_y = foot_y
# Body Height
self.height = height
# Joint Parameters
self.shoulder_lim = shoulder_lim
self.elbow_lim = elbow_lim
self.wrist_lim = wrist_lim
# Dictionary to store Leg IK Solvers
self.Legs = OrderedDict()
self.Legs["FL"] = LegIK("LEFT", self.shoulder_length,
self.elbow_length, self.wrist_length,
self.shoulder_lim, self.elbow_lim,
self.wrist_lim)
self.Legs["FR"] = LegIK("RIGHT", self.shoulder_length,
self.elbow_length, self.wrist_length,
self.shoulder_lim, self.elbow_lim,
self.wrist_lim)
self.Legs["BL"] = LegIK("LEFT", self.shoulder_length,
self.elbow_length, self.wrist_length,
self.shoulder_lim, self.elbow_lim,
self.wrist_lim)
self.Legs["BR"] = LegIK("RIGHT", self.shoulder_length,
self.elbow_length, self.wrist_length,
self.shoulder_lim, self.elbow_lim,
self.wrist_lim)
# Dictionary to store Hip and Foot Transforms
# Transform of Hip relative to world frame
# With Body Centroid also in world frame
Rwb = np.eye(3)
self.WorldToHip = OrderedDict()
self.ph_FL = np.array([self.hip_x / 2.0, self.hip_y / 2.0, 0])
self.WorldToHip["FL"] = RpToTrans(Rwb, self.ph_FL)
self.ph_FR = np.array([self.hip_x / 2.0, -self.hip_y / 2.0, 0])
self.WorldToHip["FR"] = RpToTrans(Rwb, self.ph_FR)
self.ph_BL = np.array([-self.hip_x / 2.0, self.hip_y / 2.0, 0])
self.WorldToHip["BL"] = RpToTrans(Rwb, self.ph_BL)
self.ph_BR = np.array([-self.hip_x / 2.0, -self.hip_y / 2.0, 0])
self.WorldToHip["BR"] = RpToTrans(Rwb, self.ph_BR)
# Transform of Foot relative to world frame
# With Body Centroid also in world frame
self.WorldToFoot = OrderedDict()
self.pf_FL = np.array(
[self.foot_x / 2.0, self.foot_y / 2.0, -self.height])
self.WorldToFoot["FL"] = RpToTrans(Rwb, self.pf_FL)
self.pf_FR = np.array(
[self.foot_x / 2.0, -self.foot_y / 2.0, -self.height])
self.WorldToFoot["FR"] = RpToTrans(Rwb, self.pf_FR)
self.pf_BL = np.array(
[-self.foot_x / 2.0, self.foot_y / 2.0, -self.height])
self.WorldToFoot["BL"] = RpToTrans(Rwb, self.pf_BL)
self.pf_BR = np.array(
[-self.foot_x / 2.0, -self.foot_y / 2.0, -self.height])
self.WorldToFoot["BR"] = RpToTrans(Rwb, self.pf_BR)
def HipToFoot(self, orn, pos, T_bf):
"""
Converts a desired position and orientation wrt Spot's
home position, with a desired body-to-foot Transform
into a body-to-hip Transform, which is used to extract
and return the Hip To Foot Vector.
:param orn: A 3x1 np.array([]) with Spot's Roll, Pitch, Yaw angles
:param pos: A 3x1 np.array([]) with Spot's X, Y, Z coordinates
:param T_bf: Dictionary of desired body-to-foot Transforms.
:return: Hip To Foot Vector for each of Spot's Legs.
"""
# Following steps in attached document: SpotBodyIK.
# TODO: LINK DOC
# Only get Rot component
Rb, _ = TransToRp(RPY(orn[0], orn[1], orn[2]))
pb = pos
T_wb = RpToTrans(Rb, pb)
# Dictionary to store vectors
HipToFoot_List = OrderedDict()
for i, (key, T_wh) in enumerate(self.WorldToHip.items()):
# ORDER: FL, FR, FR, BL, BR
# Extract vector component
_, p_bf = TransToRp(T_bf[key])
# Step 1, get T_bh for each leg
T_bh = np.dot(TransInv(T_wb), T_wh)
# Step 2, get T_hf for each leg
# VECTOR ADDITION METHOD
_, p_bh = TransToRp(T_bh)
p_hf0 = p_bf - p_bh
# TRANSFORM METHOD
T_hf = np.dot(TransInv(T_bh), T_bf[key])
_, p_hf1 = TransToRp(T_hf)
# They should yield the same result
if p_hf1.all() != p_hf0.all():
print("NOT EQUAL")
p_hf = p_hf1
HipToFoot_List[key] = p_hf
return HipToFoot_List
def IK(self, orn, pos, T_bf):
"""
Uses HipToFoot() to convert a desired position
and orientation wrt Spot's home position into a
Hip To Foot Vector, which is fed into the LegIK solver.
Finally, the resultant joint angles are returned
from the LegIK solver for each leg.
:param orn: A 3x1 np.array([]) with Spot's Roll, Pitch, Yaw angles
:param pos: A 3x1 np.array([]) with Spot's X, Y, Z coordinates
:param T_bf: Dictionary of desired body-to-foot Transforms.
:return: Joint angles for each of Spot's joints.
"""
# Following steps in attached document: SpotBodyIK.
# TODO: LINK DOC
# Modify x by com offset
pos[0] += self.com_offset
# 4 legs, 3 joints per leg
joint_angles = np.zeros((4, 3))
# print("T_bf: {}".format(T_bf))
# Steps 1 and 2 of pipeline here
HipToFoot = self.HipToFoot(orn, pos, T_bf)
for i, (key, p_hf) in enumerate(HipToFoot.items()):
# ORDER: FL, FR, FR, BL, BR
# print("LEG: {} \t HipToFoot: {}".format(key, p_hf))
# Step 3, compute joint angles from T_hf for each leg
joint_angles[i, :] = self.Legs[key].solve(p_hf)
# print("-----------------------------")
return joint_angles
| 7,062 | Python | 33.120773 | 96 | 0.528887 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/Kinematics/LegKinematics.py | #!/usr/bin/env python
# https://www.researchgate.net/publication/320307716_Inverse_Kinematic_Analysis_Of_A_Quadruped_Robot
import numpy as np
class LegIK():
def __init__(self,
legtype="RIGHT",
shoulder_length=0.04,
elbow_length=0.1,
wrist_length=0.125,
hip_lim=[-0.548, 0.548],
shoulder_lim=[-2.17, 0.97],
leg_lim=[-0.1, 2.59]):
self.legtype = legtype
self.shoulder_length = shoulder_length
self.elbow_length = elbow_length
self.wrist_length = wrist_length
self.hip_lim = hip_lim
self.shoulder_lim = shoulder_lim
self.leg_lim = leg_lim
def get_domain(self, x, y, z):
"""
Calculates the leg's Domain and caps it in case of a breach
:param x,y,z: hip-to-foot distances in each dimension
:return: Leg Domain D
"""
D = (y**2 + (-z)**2 - self.shoulder_length**2 +
(-x)**2 - self.elbow_length**2 - self.wrist_length**2) / (
2 * self.wrist_length * self.elbow_length)
if D > 1 or D < -1:
# DOMAIN BREACHED
# print("---------DOMAIN BREACH---------")
D = np.clip(D, -1.0, 1.0)
return D
else:
return D
def solve(self, xyz_coord):
"""
Generic Leg Inverse Kinematics Solver
:param xyz_coord: hip-to-foot distances in each dimension
:return: Joint Angles required for desired position
"""
x = xyz_coord[0]
y = xyz_coord[1]
z = xyz_coord[2]
D = self.get_domain(x, y, z)
if self.legtype == "RIGHT":
return self.RightIK(x, y, z, D)
else:
return self.LeftIK(x, y, z, D)
def RightIK(self, x, y, z, D):
"""
Right Leg Inverse Kinematics Solver
:param x,y,z: hip-to-foot distances in each dimension
:param D: leg domain
:return: Joint Angles required for desired position
"""
wrist_angle = np.arctan2(-np.sqrt(1 - D**2), D)
sqrt_component = y**2 + (-z)**2 - self.shoulder_length**2
if sqrt_component < 0.0:
# print("NEGATIVE SQRT")
sqrt_component = 0.0
shoulder_angle = -np.arctan2(z, y) - np.arctan2(
np.sqrt(sqrt_component), -self.shoulder_length)
elbow_angle = np.arctan2(-x, np.sqrt(sqrt_component)) - np.arctan2(
self.wrist_length * np.sin(wrist_angle),
self.elbow_length + self.wrist_length * np.cos(wrist_angle))
joint_angles = np.array([-shoulder_angle, elbow_angle, wrist_angle])
return joint_angles
def LeftIK(self, x, y, z, D):
"""
Left Leg Inverse Kinematics Solver
:param x,y,z: hip-to-foot distances in each dimension
:param D: leg domain
:return: Joint Angles required for desired position
"""
wrist_angle = np.arctan2(-np.sqrt(1 - D**2), D)
sqrt_component = y**2 + (-z)**2 - self.shoulder_length**2
if sqrt_component < 0.0:
print("NEGATIVE SQRT")
sqrt_component = 0.0
shoulder_angle = -np.arctan2(z, y) - np.arctan2(
np.sqrt(sqrt_component), self.shoulder_length)
elbow_angle = np.arctan2(-x, np.sqrt(sqrt_component)) - np.arctan2(
self.wrist_length * np.sin(wrist_angle),
self.elbow_length + self.wrist_length * np.cos(wrist_angle))
joint_angles = np.array([-shoulder_angle, elbow_angle, wrist_angle])
return joint_angles
| 3,617 | Python | 35.918367 | 100 | 0.544927 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/Kinematics/LieAlgebra.py | #!/usr/bin/env python
import numpy as np
# NOTE: Code snippets from Modern Robotics at Northwestern University:
# See https://github.com/NxRLab/ModernRobotics
def RpToTrans(R, p):
"""
Converts a rotation matrix and a position vector into homogeneous
transformation matrix
:param R: A 3x3 rotation matrix
:param p: A 3-vector
:return: A homogeneous transformation matrix corresponding to the inputs
Example Input:
R = np.array([[1, 0, 0],
[0, 0, -1],
[0, 1, 0]])
p = np.array([1, 2, 5])
Output:
np.array([[1, 0, 0, 1],
[0, 0, -1, 2],
[0, 1, 0, 5],
[0, 0, 0, 1]])
"""
return np.r_[np.c_[R, p], [[0, 0, 0, 1]]]
def TransToRp(T):
"""
Converts a homogeneous transformation matrix into a rotation matrix
and position vector
:param T: A homogeneous transformation matrix
:return R: The corresponding rotation matrix,
:return p: The corresponding position vector.
Example Input:
T = np.array([[1, 0, 0, 0],
[0, 0, -1, 0],
[0, 1, 0, 3],
[0, 0, 0, 1]])
Output:
(np.array([[1, 0, 0],
[0, 0, -1],
[0, 1, 0]]),
np.array([0, 0, 3]))
"""
T = np.array(T)
return T[0:3, 0:3], T[0:3, 3]
def TransInv(T):
"""
Inverts a homogeneous transformation matrix
:param T: A homogeneous transformation matrix
:return: The inverse of T
Uses the structure of transformation matrices to avoid taking a matrix
inverse, for efficiency.
Example input:
T = np.array([[1, 0, 0, 0],
[0, 0, -1, 0],
[0, 1, 0, 3],
[0, 0, 0, 1]])
Output:
np.array([[1, 0, 0, 0],
[0, 0, 1, -3],
[0, -1, 0, 0],
[0, 0, 0, 1]])
"""
R, p = TransToRp(T)
Rt = np.array(R).T
return np.r_[np.c_[Rt, -np.dot(Rt, p)], [[0, 0, 0, 1]]]
def Adjoint(T):
"""
Computes the adjoint representation of a homogeneous transformation
matrix
:param T: A homogeneous transformation matrix
:return: The 6x6 adjoint representation [AdT] of T
Example Input:
T = np.array([[1, 0, 0, 0],
[0, 0, -1, 0],
[0, 1, 0, 3],
[0, 0, 0, 1]])
Output:
np.array([[1, 0, 0, 0, 0, 0],
[0, 0, -1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 3, 1, 0, 0],
[3, 0, 0, 0, 0, -1],
[0, 0, 0, 0, 1, 0]])
"""
R, p = TransToRp(T)
return np.r_[np.c_[R, np.zeros((3, 3))], np.c_[np.dot(VecToso3(p), R), R]]
def VecToso3(omg):
"""
Converts a 3-vector to an so(3) representation
:param omg: A 3-vector
:return: The skew symmetric representation of omg
Example Input:
omg = np.array([1, 2, 3])
Output:
np.array([[ 0, -3, 2],
[ 3, 0, -1],
[-2, 1, 0]])
"""
return np.array([[0, -omg[2], omg[1]], [omg[2], 0, -omg[0]],
[-omg[1], omg[0], 0]])
def RPY(roll, pitch, yaw):
"""
Creates a Roll, Pitch, Yaw Transformation Matrix
:param roll: roll component of matrix
:param pitch: pitch component of matrix
:param yaw: yaw component of matrix
:return: The transformation matrix
Example Input:
roll = 0.0
pitch = 0.0
yaw = 0.0
Output:
np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
"""
Roll = np.array([[1, 0, 0, 0], [0, np.cos(roll), -np.sin(roll), 0],
[0, np.sin(roll), np.cos(roll), 0], [0, 0, 0, 1]])
Pitch = np.array([[np.cos(pitch), 0, np.sin(pitch), 0], [0, 1, 0, 0],
[-np.sin(pitch), 0, np.cos(pitch), 0], [0, 0, 0, 1]])
Yaw = np.array([[np.cos(yaw), -np.sin(yaw), 0, 0],
[np.sin(yaw), np.cos(yaw), 0, 0], [0, 0, 1, 0],
[0, 0, 0, 1]])
return np.matmul(np.matmul(Roll, Pitch), Yaw)
def RotateTranslate(rotation, position):
"""
Creates a Transformation Matrix from a Rotation, THEN, a Translation
:param rotation: pure rotation matrix
:param translation: pure translation matrix
:return: The transformation matrix
"""
trans = np.eye(4)
trans[0, 3] = position[0]
trans[1, 3] = position[1]
trans[2, 3] = position[2]
return np.dot(rotation, trans)
def TransformVector(xyz_coord, rotation, translation):
"""
Transforms a vector by a specified Rotation THEN Translation Matrix
:param xyz_coord: the vector to transform
:param rotation: pure rotation matrix
:param translation: pure translation matrix
:return: The transformed vector
"""
xyz_vec = np.append(xyz_coord, 1.0)
Transformed = np.dot(RotateTranslate(rotation, translation), xyz_vec)
return Transformed[:3]
| 5,162 | Python | 27.213115 | 78 | 0.49012 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/util/gui.py | #!/usr/bin/env python
import pybullet as pb
import time
import numpy as np
import sys
class GUI:
def __init__(self, quadruped):
time.sleep(0.5)
self.cyaw = 0
self.cpitch = -7
self.cdist = 0.66
self.xId = pb.addUserDebugParameter("x", -0.10, 0.10, 0.)
self.yId = pb.addUserDebugParameter("y", -0.10, 0.10, 0.)
self.zId = pb.addUserDebugParameter("z", -0.055, 0.17, 0.)
self.rollId = pb.addUserDebugParameter("roll", -np.pi / 4, np.pi / 4,
0.)
self.pitchId = pb.addUserDebugParameter("pitch", -np.pi / 4, np.pi / 4,
0.)
self.yawId = pb.addUserDebugParameter("yaw", -np.pi / 4, np.pi / 4, 0.)
self.StepLengthID = pb.addUserDebugParameter("Step Length", -0.1, 0.1,
0.0)
self.YawRateId = pb.addUserDebugParameter("Yaw Rate", -2.0, 2.0, 0.)
self.LateralFractionId = pb.addUserDebugParameter(
"Lateral Fraction", -np.pi / 2.0, np.pi / 2.0, 0.)
self.StepVelocityId = pb.addUserDebugParameter("Step Velocity", 0.001,
3., 0.001)
self.SwingPeriodId = pb.addUserDebugParameter("Swing Period", 0.1, 0.4,
0.2)
self.ClearanceHeightId = pb.addUserDebugParameter(
"Clearance Height", 0.0, 0.1, 0.045)
self.PenetrationDepthId = pb.addUserDebugParameter(
"Penetration Depth", 0.0, 0.05, 0.003)
self.quadruped = quadruped
def UserInput(self):
quadruped_pos, _ = pb.getBasePositionAndOrientation(self.quadruped)
pb.resetDebugVisualizerCamera(cameraDistance=self.cdist,
cameraYaw=self.cyaw,
cameraPitch=self.cpitch,
cameraTargetPosition=quadruped_pos)
keys = pb.getKeyboardEvents()
# Keys to change camera
if keys.get(100): # D
self.cyaw += 1
if keys.get(97): # A
self.cyaw -= 1
if keys.get(99): # C
self.cpitch += 1
if keys.get(102): # F
self.cpitch -= 1
if keys.get(122): # Z
self.cdist += .01
if keys.get(120): # X
self.cdist -= .01
if keys.get(27): # ESC
pb.disconnect()
sys.exit()
# Read Robot Transform from GUI
pos = np.array([
pb.readUserDebugParameter(self.xId),
pb.readUserDebugParameter(self.yId),
pb.readUserDebugParameter(self.zId)
])
orn = np.array([
pb.readUserDebugParameter(self.rollId),
pb.readUserDebugParameter(self.pitchId),
pb.readUserDebugParameter(self.yawId)
])
StepLength = pb.readUserDebugParameter(self.StepLengthID)
YawRate = pb.readUserDebugParameter(self.YawRateId)
LateralFraction = pb.readUserDebugParameter(self.LateralFractionId)
StepVelocity = pb.readUserDebugParameter(self.StepVelocityId)
ClearanceHeight = pb.readUserDebugParameter(self.ClearanceHeightId)
PenetrationDepth = pb.readUserDebugParameter(self.PenetrationDepthId)
SwingPeriod = pb.readUserDebugParameter(self.SwingPeriodId)
return pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod
| 3,557 | Python | 39.431818 | 123 | 0.555243 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/util/action_mapper.py | STATIC_ACTIONS_MAP = {
'gallop': ('rex_gym/policies/galloping/balanced', 'model.ckpt-20000000'),
'walk': ('rex_gym/policies/walking/alternating_legs', 'model.ckpt-16000000'),
'standup': ('rex_gym/policies/standup', 'model.ckpt-10000000')
}
DYNAMIC_ACTIONS_MAP = {
'turn': ('rex_gym/policies/turn', 'model.ckpt-16000000')
}
ACTIONS_TO_ENV_NAMES = {
'gallop': 'RexReactiveEnv',
'walk': 'RexWalkEnv',
'turn': 'RexTurnEnv',
'standup': 'RexStandupEnv'
}
| 483 | Python | 27.470587 | 81 | 0.648033 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/util/bullet_client.py | """A wrapper for pybullet to manage different clients."""
from __future__ import absolute_import
from __future__ import division
import functools
import inspect
import pybullet
class BulletClient(object):
"""A wrapper for pybullet to manage different clients."""
def __init__(self, connection_mode=None):
"""Creates a Bullet client and connects to a simulation.
Args:
connection_mode:
`None` connects to an existing simulation or, if fails, creates a
new headless simulation,
`pybullet.GUI` creates a new simulation with a GUI,
`pybullet.DIRECT` creates a headless simulation,
`pybullet.SHARED_MEMORY` connects to an existing simulation.
"""
self._shapes = {}
if connection_mode is None:
self._client = pybullet.connect(pybullet.SHARED_MEMORY)
if self._client >= 0:
return
else:
connection_mode = pybullet.DIRECT
self._client = pybullet.connect(connection_mode)
def __del__(self):
"""Clean up connection if not already done."""
try:
pybullet.disconnect(physicsClientId=self._client)
except pybullet.error:
pass
def __getattr__(self, name):
"""Inject the client id into Bullet functions."""
attribute = getattr(pybullet, name)
if inspect.isbuiltin(attribute):
if name not in [
"invertTransform",
"multiplyTransforms",
"getMatrixFromQuaternion",
"getEulerFromQuaternion",
"computeViewMatrixFromYawPitchRoll",
"computeProjectionMatrixFOV",
"getQuaternionFromEuler",
]: # A temporary hack for now.
attribute = functools.partial(attribute, physicsClientId=self._client)
return attribute
| 1,894 | Python | 33.454545 | 86 | 0.607181 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/util/pybullet_data/__init__.py | import os
def getDataPath():
resdir = os.path.join(os.path.dirname(__file__))
return resdir
| 98 | Python | 13.142855 | 50 | 0.683673 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/OpenLoopSM/SpotOL.py | """ Open Loop Controller for Spot Micro. Takes GUI params or uses default
"""
import numpy as np
from random import shuffle
import copy
# Ensuring totally random seed every step!
np.random.seed()
FB = 0
LAT = 1
ROT = 2
COMBI = 3
FWD = 0
ALL = 1
class BezierStepper():
def __init__(self,
pos=np.array([0.0, 0.0, 0.0]),
orn=np.array([0.0, 0.0, 0.0]),
StepLength=0.04,
LateralFraction=0.0,
YawRate=0.0,
StepVelocity=0.001,
ClearanceHeight=0.045,
PenetrationDepth=0.003,
episode_length=5000,
dt=0.01,
num_shuffles=2,
mode=FWD):
self.pos = pos
self.orn = orn
self.desired_StepLength = StepLength
self.StepLength = StepLength
self.StepLength_LIMITS = [-0.05, 0.05]
self.LateralFraction = LateralFraction
self.LateralFraction_LIMITS = [-np.pi / 2.0, np.pi / 2.0]
self.YawRate = YawRate
self.YawRate_LIMITS = [-1.0, 1.0]
self.StepVelocity = StepVelocity
self.StepVelocity_LIMITS = [0.1, 1.5]
self.ClearanceHeight = ClearanceHeight
self.ClearanceHeight_LIMITS = [0.0, 0.04]
self.PenetrationDepth = PenetrationDepth
self.PenetrationDepth_LIMITS = [0.0, 0.02]
self.mode = mode
self.dt = dt
# Keep track of state machine
self.time = 0
# Decide how long to stay in each phase based on maxtime
self.max_time = episode_length
""" States
1: FWD/BWD
2: Lat
3: Rot
4: Combined
"""
self.order = [FB, LAT, ROT, COMBI]
# Shuffles list in place so the order of states is unpredictable
# NOTE: increment num_shuffles by episode num (cap at 10
# and reset or someting) for some forced randomness
for _ in range(num_shuffles):
shuffle(self.order)
# Forward/Backward always needs to be first!
self.reshuffle()
# Current State
self.current_state = self.order[0]
# Divide by number of states (see RL_SM())
self.time_per_episode = int(self.max_time / len(self.order))
def ramp_up(self):
if self.StepLength < self.desired_StepLength:
self.StepLength += self.desired_StepLength * self.dt
def reshuffle(self):
self.time = 0
# Make sure FWD/BWD is always first state
FB_index = self.order.index(FB)
if FB_index != 0:
what_was_in_zero = self.order[0]
self.order[0] = FB
self.order[FB_index] = what_was_in_zero
def which_state(self):
# Ensuring totally random seed every step!
np.random.seed()
if self.time > self.max_time:
# Combined
self.current_state = COMBI
self.time = 0
else:
index = int(self.time / self.time_per_episode)
if index > len(self.order) - 1:
index = len(self.order) - 1
self.current_state = self.order[index]
def StateMachine(self):
"""
State Machined used for training robust RL on top of OL gait.
STATES:
Forward/Backward: All Default Values.
Can have slow changes to
StepLength(+-) and Velocity
Lateral: As above (fwd or bwd random) with added random
slow changing LateralFraction param
Rotating: As above except with YawRate
Combined: ALL changeable values may change!
StepLength
StepVelocity
LateralFraction
YawRate
NOTE: the RL is solely responsible for modulating Clearance Height
and Penetration Depth
"""
if self.mode is ALL:
self.which_state()
if self.current_state == FB:
# print("FORWARD/BACKWARD")
self.FB()
elif self.current_state == LAT:
# print("LATERAL")
self.LAT()
elif self.current_state == ROT:
# print("ROTATION")
self.ROT()
elif self.current_state == COMBI:
# print("COMBINED")
self.COMBI()
return self.return_bezier_params()
def return_bezier_params(self):
# First, Clip Everything
self.StepLength = np.clip(self.StepLength, self.StepLength_LIMITS[0],
self.StepLength_LIMITS[1])
self.StepVelocity = np.clip(self.StepVelocity,
self.StepVelocity_LIMITS[0],
self.StepVelocity_LIMITS[1])
self.LateralFraction = np.clip(self.LateralFraction,
self.LateralFraction_LIMITS[0],
self.LateralFraction_LIMITS[1])
self.YawRate = np.clip(self.YawRate, self.YawRate_LIMITS[0],
self.YawRate_LIMITS[1])
self.ClearanceHeight = np.clip(self.ClearanceHeight,
self.ClearanceHeight_LIMITS[0],
self.ClearanceHeight_LIMITS[1])
self.PenetrationDepth = np.clip(self.PenetrationDepth,
self.PenetrationDepth_LIMITS[0],
self.PenetrationDepth_LIMITS[1])
# Then, return
# FIRST COPY TO AVOID OVERWRITING
pos = copy.deepcopy(self.pos)
orn = copy.deepcopy(self.orn)
StepLength = copy.deepcopy(self.StepLength)
LateralFraction = copy.deepcopy(self.LateralFraction)
YawRate = copy.deepcopy(self.YawRate)
StepVelocity = copy.deepcopy(self.StepVelocity)
ClearanceHeight = copy.deepcopy(self.ClearanceHeight)
PenetrationDepth = copy.deepcopy(self.PenetrationDepth)
return pos, orn, StepLength, LateralFraction,\
YawRate, StepVelocity,\
ClearanceHeight, PenetrationDepth
def FB(self):
"""
Here, we can modulate StepLength and StepVelocity
"""
# The maximum update amount for these element
StepLength_DELTA = self.dt * (self.StepLength_LIMITS[1] -
self.StepLength_LIMITS[0]) / (6.0)
StepVelocity_DELTA = self.dt * (self.StepVelocity_LIMITS[1] -
self.StepVelocity_LIMITS[0]) / (2.0)
# Add either positive or negative or zero delta for each
# NOTE: 'High' is open bracket ) so the max is 1
if self.StepLength < -self.StepLength_LIMITS[0] / 2.0:
StepLength_DIRECTION = np.random.randint(-1, 3, 1)[0]
elif self.StepLength > self.StepLength_LIMITS[1] / 2.0:
StepLength_DIRECTION = np.random.randint(-2, 2, 1)[0]
else:
StepLength_DIRECTION = np.random.randint(-1, 2, 1)[0]
StepVelocity_DIRECTION = np.random.randint(-1, 2, 1)[0]
# Now, modify modifiable params AND CLIP
self.StepLength += StepLength_DIRECTION * StepLength_DELTA
self.StepLength = np.clip(self.StepLength, self.StepLength_LIMITS[0],
self.StepLength_LIMITS[1])
self.StepVelocity += StepVelocity_DIRECTION * StepVelocity_DELTA
self.StepVelocity = np.clip(self.StepVelocity,
self.StepVelocity_LIMITS[0],
self.StepVelocity_LIMITS[1])
def LAT(self):
"""
Here, we can modulate StepLength and LateralFraction
"""
# The maximum update amount for these element
LateralFraction_DELTA = self.dt * (self.LateralFraction_LIMITS[1] -
self.LateralFraction_LIMITS[0]) / (
2.0)
# Add either positive or negative or zero delta for each
# NOTE: 'High' is open bracket ) so the max is 1
LateralFraction_DIRECTION = np.random.randint(-1, 2, 1)[0]
# Now, modify modifiable params AND CLIP
self.LateralFraction += LateralFraction_DIRECTION * LateralFraction_DELTA
self.LateralFraction = np.clip(self.LateralFraction,
self.LateralFraction_LIMITS[0],
self.LateralFraction_LIMITS[1])
def ROT(self):
"""
Here, we can modulate StepLength and YawRate
"""
# The maximum update amount for these element
# no dt since YawRate is already mult by dt
YawRate_DELTA = (self.YawRate_LIMITS[1] -
self.YawRate_LIMITS[0]) / (2.0)
# Add either positive or negative or zero delta for each
# NOTE: 'High' is open bracket ) so the max is 1
YawRate_DIRECTION = np.random.randint(-1, 2, 1)[0]
# Now, modify modifiable params AND CLIP
self.YawRate += YawRate_DIRECTION * YawRate_DELTA
self.YawRate = np.clip(self.YawRate, self.YawRate_LIMITS[0],
self.YawRate_LIMITS[1])
def COMBI(self):
"""
Here, we can modify all the parameters
"""
self.FB()
self.LAT()
self.ROT()
| 9,534 | Python | 36.53937 | 81 | 0.540696 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/GymEnvs/spot_bezier_env.py | """ This file implements the gym environment of SpotMicro with Bezier Curve.
"""
import math
import time
import gym
import numpy as np
import pybullet
import pybullet_data
from gym import spaces
from gym.utils import seeding
from pkg_resources import parse_version
from spotmicro import spot
import pybullet_utils.bullet_client as bullet_client
from gym.envs.registration import register
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.spot_gym_env import spotGymEnv
import spotmicro.Kinematics.LieAlgebra as LA
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
SENSOR_NOISE_STDDEV = spot.SENSOR_NOISE_STDDEV
# Register as OpenAI Gym Environment
register(
id="SpotMicroEnv-v1",
entry_point='spotmicro.GymEnvs.spot_bezier_env:spotBezierEnv',
max_episode_steps=1000,
)
class spotBezierEnv(spotGymEnv):
"""The gym environment for spot.
It simulates the locomotion of spot, a quadruped robot. The state space
include the angles, velocities and torques for all the motors and the action
space is the desired motor angle for each motor. The reward function is based
on how far spot walks in 1000 steps and penalizes the energy
expenditure.
"""
metadata = {
"render.modes": ["human", "rgb_array"],
"video.frames_per_second": 50
}
def __init__(self,
distance_weight=1.0,
rotation_weight=0.0,
energy_weight=0.000,
shake_weight=0.00,
drift_weight=0.0,
rp_weight=10.0,
rate_weight=.03,
urdf_root=pybullet_data.getDataPath(),
urdf_version=None,
distance_limit=float("inf"),
observation_noise_stdev=SENSOR_NOISE_STDDEV,
self_collision_enabled=True,
motor_velocity_limit=np.inf,
pd_control_enabled=False,
leg_model_enabled=False,
accurate_motor_model_enabled=False,
remove_default_joint_damping=False,
motor_kp=2.0,
motor_kd=0.03,
control_latency=0.0,
pd_latency=0.0,
torque_control_enabled=False,
motor_overheat_protection=False,
hard_reset=False,
on_rack=False,
render=True,
num_steps_to_log=1000,
action_repeat=1,
control_time_step=None,
env_randomizer=SpotEnvRandomizer(),
forward_reward_cap=float("inf"),
reflection=True,
log_path=None,
desired_velocity=0.5,
desired_rate=0.0,
lateral=False,
draw_foot_path=False,
height_field=False,
AutoStepper=True,
action_dim=14,
contacts=True):
super(spotBezierEnv, self).__init__(
distance_weight=distance_weight,
rotation_weight=rotation_weight,
energy_weight=energy_weight,
shake_weight=shake_weight,
drift_weight=drift_weight,
rp_weight=rp_weight,
rate_weight=rate_weight,
urdf_root=urdf_root,
urdf_version=urdf_version,
distance_limit=distance_limit,
observation_noise_stdev=observation_noise_stdev,
self_collision_enabled=self_collision_enabled,
motor_velocity_limit=motor_velocity_limit,
pd_control_enabled=pd_control_enabled,
leg_model_enabled=leg_model_enabled,
accurate_motor_model_enabled=accurate_motor_model_enabled,
remove_default_joint_damping=remove_default_joint_damping,
motor_kp=motor_kp,
motor_kd=motor_kd,
control_latency=control_latency,
pd_latency=pd_latency,
torque_control_enabled=torque_control_enabled,
motor_overheat_protection=motor_overheat_protection,
hard_reset=hard_reset,
on_rack=on_rack,
render=render,
num_steps_to_log=num_steps_to_log,
action_repeat=action_repeat,
control_time_step=control_time_step,
env_randomizer=env_randomizer,
forward_reward_cap=forward_reward_cap,
reflection=reflection,
log_path=log_path,
desired_velocity=desired_velocity,
desired_rate=desired_rate,
lateral=lateral,
draw_foot_path=draw_foot_path,
height_field=height_field,
AutoStepper=AutoStepper,
contacts=contacts)
# Residuals + Clearance Height + Penetration Depth
action_high = np.array([self._action_bound] * action_dim)
self.action_space = spaces.Box(-action_high, action_high)
print("Action SPACE: {}".format(self.action_space))
self.prev_pos = np.array([0.0, 0.0, 0.0])
self.yaw = 0.0
def pass_joint_angles(self, ja):
""" For executing joint angles
"""
self.ja = ja
def step(self, action):
"""Step forward the simulation, given the action.
Args:
action: A list of desired motor angles for eight motors.
smach: the bezier state machine containing simulated
random controll inputs
Returns:
observations: The angles, velocities and torques of all motors.
reward: The reward for the current state-action pair.
done: Whether the episode has ended.
info: A dictionary that stores diagnostic information.
Raises:
ValueError: The action dimension is not the same as the number of motors.
ValueError: The magnitude of actions is out of bounds.
"""
# Discard all but joint angles
action = self.ja
self._last_base_position = self.spot.GetBasePosition()
self._last_base_orientation = self.spot.GetBaseOrientation()
# print("ACTION:")
# print(action)
if self._is_render:
# Sleep, otherwise the computation takes less time than real time,
# which will make the visualization like a fast-forward video.
time_spent = time.time() - self._last_frame_time
self._last_frame_time = time.time()
time_to_sleep = self.control_time_step - time_spent
if time_to_sleep > 0:
time.sleep(time_to_sleep)
base_pos = self.spot.GetBasePosition()
# Keep the previous orientation of the camera set by the user.
[yaw, pitch,
dist] = self._pybullet_client.getDebugVisualizerCamera()[8:11]
self._pybullet_client.resetDebugVisualizerCamera(
dist, yaw, pitch, base_pos)
action = self._transform_action_to_motor_command(action)
self.spot.Step(action)
# NOTE: SMACH is passed to the reward method
reward = self._reward()
done = self._termination()
self._env_step_counter += 1
# DRAW FOOT PATH
if self.draw_foot_path:
self.DrawFootPath()
return np.array(self._get_observation()), reward, done, {}
def return_state(self):
return np.array(self._get_observation())
def return_yaw(self):
return self.yaw
def _reward(self):
# get observation
obs = self._get_observation()
orn = self.spot.GetBaseOrientation()
# Return StepVelocity with the sign of StepLength
DesiredVelicty = math.copysign(self.spot.StepVelocity / 4.0,
self.spot.StepLength)
fwd_speed = self.spot.prev_lin_twist[0] # vx
lat_speed = self.spot.prev_lin_twist[1] # vy
# DEBUG
lt, at = self.spot.GetBaseTwist()
# ONLY WORKS FOR MOVING PURELY FORWARD
pos = self.spot.GetBasePosition()
forward_reward = pos[0] - self.prev_pos[0]
# yaw_rate = obs[4]
rot_reward = 0.0
roll, pitch, yaw = self._pybullet_client.getEulerFromQuaternion(
[orn[0], orn[1], orn[2], orn[3]])
# if yaw < 0.0:
# yaw += np.pi
# else:
# yaw -= np.pi
# For auto correct
self.yaw = yaw
# penalty for nonzero PITCH and YAW(hidden) ONLY
# NOTE: Added Yaw mult
rp_reward = -(abs(obs[0]) + abs(obs[1]))
# print("YAW: {}".format(yaw))
# print("RP RWD: {:.2f}".format(rp_reward))
# print("ROLL: {} \t PITCH: {}".format(obs[0], obs[1]))
# penalty for nonzero acc(z) - UNRELIABLE ON IMU
shake_reward = 0
# penalty for nonzero rate (x,y,z)
rate_reward = -(abs(obs[2]) + abs(obs[3]))
# print("RATES: {}".format(obs[2:5]))
drift_reward = -abs(pos[1])
energy_reward = -np.abs(
np.dot(self.spot.GetMotorTorques(),
self.spot.GetMotorVelocities())) * self._time_step
reward = (self._distance_weight * forward_reward +
self._rotation_weight * rot_reward +
self._energy_weight * energy_reward +
self._drift_weight * drift_reward +
self._shake_weight * shake_reward +
self._rp_weight * rp_reward +
self._rate_weight * rate_reward)
self._objectives.append(
[forward_reward, energy_reward, drift_reward, shake_reward])
# print("REWARD: ", reward)
# NOTE: return yaw for automatic correction (not part of RL)
return reward | 9,666 | Python | 34.803704 | 79 | 0.581212 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spotmicro/GaitGenerator/Bezier.py | import numpy as np
from spotmicro.Kinematics.LieAlgebra import TransToRp
import copy
STANCE = 0
SWING = 1
# Bezier Curves from: https://dspace.mit.edu/handle/1721.1/98270
# Rotation Logic from: http://www.inase.org/library/2014/santorini/bypaper/ROBCIRC/ROBCIRC-54.pdf
class BezierGait():
def __init__(self, dSref=[0.0, 0.0, 0.5, 0.5], dt=0.01, Tswing=0.2):
# Phase Lag Per Leg: FL, FR, BL, BR
# Reference Leg is FL, always 0
self.dSref = dSref
self.Prev_fxyz = [0.0, 0.0, 0.0, 0.0]
# Number of control points is n + 1 = 11 + 1 = 12
self.NumControlPoints = 11
# Timestep
self.dt = dt
# Total Elapsed Time
self.time = 0.0
# Touchdown Time
self.TD_time = 0.0
# Time Since Last Touchdown
self.time_since_last_TD = 0.0
# Trajectory Mode
self.StanceSwing = SWING
# Swing Phase value [0, 1] of Reference Foot
self.SwRef = 0.0
self.Stref = 0.0
# Whether Reference Foot has Touched Down
self.TD = False
# Stance Time
self.Tswing = Tswing
# Reference Leg
self.ref_idx = 0
# Store all leg phases
self.Phases = self.dSref
def reset(self):
"""Resets the parameters of the Bezier Gait Generator
"""
self.Prev_fxyz = [0.0, 0.0, 0.0, 0.0]
# Total Elapsed Time
self.time = 0.0
# Touchdown Time
self.TD_time = 0.0
# Time Since Last Touchdown
self.time_since_last_TD = 0.0
# Trajectory Mode
self.StanceSwing = SWING
# Swing Phase value [0, 1] of Reference Foot
self.SwRef = 0.0
self.Stref = 0.0
# Whether Reference Foot has Touched Down
self.TD = False
def GetPhase(self, index, Tstance, Tswing):
"""Retrieves the phase of an individual leg.
NOTE modification
from original paper:
if ti < -Tswing:
ti += Tstride
This is to avoid a phase discontinuity if the user selects
a Step Length and Velocity combination that causes Tstance > Tswing.
:param index: the leg's index, used to identify the required
phase lag
:param Tstance: the current user-specified stance period
:param Tswing: the swing period (constant, class member)
:return: Leg Phase, and StanceSwing (bool) to indicate whether
leg is in stance or swing mode
"""
StanceSwing = STANCE
Sw_phase = 0.0
Tstride = Tstance + Tswing
ti = self.Get_ti(index, Tstride)
# NOTE: PAPER WAS MISSING THIS LOGIC!!
if ti < -Tswing:
ti += Tstride
# STANCE
if ti >= 0.0 and ti <= Tstance:
StanceSwing = STANCE
if Tstance == 0.0:
Stnphase = 0.0
else:
Stnphase = ti / float(Tstance)
if index == self.ref_idx:
# print("STANCE REF: {}".format(Stnphase))
self.StanceSwing = StanceSwing
return Stnphase, StanceSwing
# SWING
elif ti >= -Tswing and ti < 0.0:
StanceSwing = SWING
Sw_phase = (ti + Tswing) / Tswing
elif ti > Tstance and ti <= Tstride:
StanceSwing = SWING
Sw_phase = (ti - Tstance) / Tswing
# Touchdown at End of Swing
if Sw_phase >= 1.0:
Sw_phase = 1.0
if index == self.ref_idx:
# print("SWING REF: {}".format(Sw_phase))
self.StanceSwing = StanceSwing
self.SwRef = Sw_phase
# REF Touchdown at End of Swing
if self.SwRef >= 0.999:
self.TD = True
# else:
# self.TD = False
return Sw_phase, StanceSwing
def Get_ti(self, index, Tstride):
"""Retrieves the time index for the individual leg
:param index: the leg's index, used to identify the required
phase lag
:param Tstride: the total leg movement period (Tstance + Tswing)
:return: the leg's time index
"""
# NOTE: for some reason python's having numerical issues w this
# setting to 0 for ref leg by force
if index == self.ref_idx:
self.dSref[index] = 0.0
return self.time_since_last_TD - self.dSref[index] * Tstride
def Increment(self, dt, Tstride):
"""Increments the Bezier gait generator's internal clock (self.time)
:param dt: the time step
phase lag
:param Tstride: the total leg movement period (Tstance + Tswing)
:return: the leg's time index
"""
self.CheckTouchDown()
self.time_since_last_TD = self.time - self.TD_time
if self.time_since_last_TD > Tstride:
self.time_since_last_TD = Tstride
elif self.time_since_last_TD < 0.0:
self.time_since_last_TD = 0.0
# print("T STRIDE: {}".format(Tstride))
# Increment Time at the end in case TD just happened
# So that we get time_since_last_TD = 0.0
self.time += dt
# If Tstride = Tswing, Tstance = 0
# RESET ALL
if Tstride < self.Tswing + dt:
self.time = 0.0
self.time_since_last_TD = 0.0
self.TD_time = 0.0
self.SwRef = 0.0
def CheckTouchDown(self):
"""Checks whether a reference leg touchdown
has occured, and whether this warrants
resetting the touchdown time
"""
if self.SwRef >= 0.9 and self.TD:
self.TD_time = self.time
self.TD = False
self.SwRef = 0.0
def BernSteinPoly(self, t, k, point):
"""Calculate the point on the Berinstein Polynomial
based on phase (0->1), point number (0-11),
and the value of the control point itself
:param t: phase
:param k: point number
:param point: point value
:return: Value through Bezier Curve
"""
return point * self.Binomial(k) * np.power(t, k) * np.power(
1 - t, self.NumControlPoints - k)
def Binomial(self, k):
"""Solves the binomial theorem given a Bezier point number
relative to the total number of Bezier points.
:param k: Bezier point number
:returns: Binomial solution
"""
return np.math.factorial(self.NumControlPoints) / (
np.math.factorial(k) *
np.math.factorial(self.NumControlPoints - k))
def BezierSwing(self, phase, L, LateralFraction, clearance_height=0.04):
"""Calculates the step coordinates for the Bezier (swing) period
:param phase: current trajectory phase
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param clearance_height: foot clearance height during swing phase
:returns: X,Y,Z Foot Coordinates relative to unmodified body
"""
# Polar Leg Coords
X_POLAR = np.cos(LateralFraction)
Y_POLAR = np.sin(LateralFraction)
# Bezier Curve Points (12 pts)
# NOTE: L is HALF of STEP LENGTH
# Forward Component
STEP = np.array([
-L, # Ctrl Point 0, half of stride len
-L * 1.4, # Ctrl Point 1 diff btwn 1 and 0 = x Lift vel
-L * 1.5, # Ctrl Pts 2, 3, 4 are overlapped for
-L * 1.5, # Direction change after
-L * 1.5, # Follow Through
0.0, # Change acceleration during Protraction
0.0, # So we include three
0.0, # Overlapped Ctrl Pts: 5, 6, 7
L * 1.5, # Changing direction for swing-leg retraction
L * 1.5, # requires double overlapped Ctrl Pts: 8, 9
L * 1.4, # Swing Leg Retraction Velocity = Ctrl 11 - 10
L
])
# Account for lateral movements by multiplying with polar coord.
# LateralFraction switches leg movements from X over to Y+ or Y-
# As it tends away from zero
X = STEP * X_POLAR
# Account for lateral movements by multiplying with polar coord.
# LateralFraction switches leg movements from X over to Y+ or Y-
# As it tends away from zero
Y = STEP * Y_POLAR
# Vertical Component
Z = np.array([
0.0, # Double Overlapped Ctrl Pts for zero Lift
0.0, # Veloicty wrt hip (Pts 0 and 1)
clearance_height * 0.9, # Triple overlapped control for change in
clearance_height * 0.9, # Force direction during transition from
clearance_height * 0.9, # follow-through to protraction (2, 3, 4)
clearance_height * 0.9, # Double Overlapped Ctrl Pts for Traj
clearance_height * 0.9, # Dirctn Change during Protraction (5, 6)
clearance_height * 1.1, # Maximum Clearance at mid Traj, Pt 7
clearance_height * 1.1, # Smooth Transition from Protraction
clearance_height * 1.1, # To Retraction, Two Ctrl Pts (8, 9)
0.0, # Double Overlap Ctrl Pts for 0 Touchdown
0.0, # Veloicty wrt hip (Pts 10 and 11)
])
stepX = 0.
stepY = 0.
stepZ = 0.
# Bernstein Polynomial sum over control points
for i in range(len(X)):
stepX += self.BernSteinPoly(phase, i, X[i])
stepY += self.BernSteinPoly(phase, i, Y[i])
stepZ += self.BernSteinPoly(phase, i, Z[i])
return stepX, stepY, stepZ
def SineStance(self, phase, L, LateralFraction, penetration_depth=0.00):
"""Calculates the step coordinates for the Sinusoidal stance period
:param phase: current trajectory phase
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param penetration_depth: foot penetration depth during stance phase
:returns: X,Y,Z Foot Coordinates relative to unmodified body
"""
X_POLAR = np.cos(LateralFraction)
Y_POLAR = np.sin(LateralFraction)
# moves from +L to -L
step = L * (1.0 - 2.0 * phase)
stepX = step * X_POLAR
stepY = step * Y_POLAR
if L != 0.0:
stepZ = -penetration_depth * np.cos(
(np.pi * (stepX + stepY)) / (2.0 * L))
else:
stepZ = 0.0
return stepX, stepY, stepZ
def YawCircle(self, T_bf, index):
""" Calculates the required rotation of the trajectory plane
for yaw motion
:param T_bf: default body-to-foot Vector
:param index: the foot index in the container
:returns: phi_arc, the plane rotation angle required for yaw motion
"""
# Foot Magnitude depending on leg type
DefaultBodyToFoot_Magnitude = np.sqrt(T_bf[0]**2 + T_bf[1]**2)
# Rotation Angle depending on leg type
DefaultBodyToFoot_Direction = np.arctan2(T_bf[1], T_bf[0])
# Previous leg coordinates relative to default coordinates
g_xyz = self.Prev_fxyz[index] - np.array([T_bf[0], T_bf[1], T_bf[2]])
# Modulate Magnitude to keep tracing circle
g_mag = np.sqrt((g_xyz[0])**2 + (g_xyz[1])**2)
th_mod = np.arctan2(g_mag, DefaultBodyToFoot_Magnitude)
# Angle Traced by Foot for Rotation
# FR and BL
if index == 1 or index == 2:
phi_arc = np.pi / 2.0 + DefaultBodyToFoot_Direction + th_mod
# FL and BR
else:
phi_arc = np.pi / 2.0 - DefaultBodyToFoot_Direction + th_mod
# print("INDEX {}: \t Angle: {}".format(
# index, np.degrees(DefaultBodyToFoot_Direction)))
return phi_arc
def SwingStep(self, phase, L, LateralFraction, YawRate, clearance_height,
T_bf, key, index):
"""Calculates the step coordinates for the Bezier (swing) period
using a combination of forward and rotational step coordinates
initially decomposed from user input of
L, LateralFraction and YawRate
:param phase: current trajectory phase
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param YawRate: the desired body yaw rate
:param clearance_height: foot clearance height during swing phase
:param T_bf: default body-to-foot Vector
:param key: indicates which foot is being processed
:param index: the foot index in the container
:returns: Foot Coordinates relative to unmodified body
"""
# Yaw foot angle for tangent-to-circle motion
phi_arc = self.YawCircle(T_bf, index)
# Get Foot Coordinates for Forward Motion
X_delta_lin, Y_delta_lin, Z_delta_lin = self.BezierSwing(
phase, L, LateralFraction, clearance_height)
X_delta_rot, Y_delta_rot, Z_delta_rot = self.BezierSwing(
phase, YawRate, phi_arc, clearance_height)
coord = np.array([
X_delta_lin + X_delta_rot, Y_delta_lin + Y_delta_rot,
Z_delta_lin + Z_delta_rot
])
self.Prev_fxyz[index] = coord
return coord
def StanceStep(self, phase, L, LateralFraction, YawRate, penetration_depth,
T_bf, key, index):
"""Calculates the step coordinates for the Sine (stance) period
using a combination of forward and rotational step coordinates
initially decomposed from user input of
L, LateralFraction and YawRate
:param phase: current trajectory phase
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param YawRate: the desired body yaw rate
:param penetration_depth: foot penetration depth during stance phase
:param T_bf: default body-to-foot Vector
:param key: indicates which foot is being processed
:param index: the foot index in the container
:returns: Foot Coordinates relative to unmodified body
"""
# Yaw foot angle for tangent-to-circle motion
phi_arc = self.YawCircle(T_bf, index)
# Get Foot Coordinates for Forward Motion
X_delta_lin, Y_delta_lin, Z_delta_lin = self.SineStance(
phase, L, LateralFraction, penetration_depth)
X_delta_rot, Y_delta_rot, Z_delta_rot = self.SineStance(
phase, YawRate, phi_arc, penetration_depth)
coord = np.array([
X_delta_lin + X_delta_rot, Y_delta_lin + Y_delta_rot,
Z_delta_lin + Z_delta_rot
])
self.Prev_fxyz[index] = coord
return coord
def GetFootStep(self, L, LateralFraction, YawRate, clearance_height,
penetration_depth, Tstance, T_bf, index, key):
"""Calculates the step coordinates in either the Bezier or
Sine portion of the trajectory depending on the retrieved phase
:param phase: current trajectory phase
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param YawRate: the desired body yaw rate
:param clearance_height: foot clearance height during swing phase
:param penetration_depth: foot penetration depth during stance phase
:param Tstance: the current user-specified stance period
:param T_bf: default body-to-foot Vector
:param index: the foot index in the container
:param key: indicates which foot is being processed
:returns: Foot Coordinates relative to unmodified body
"""
phase, StanceSwing = self.GetPhase(index, Tstance, self.Tswing)
if StanceSwing == SWING:
stored_phase = phase + 1.0
else:
stored_phase = phase
# Just for keeping track
self.Phases[index] = stored_phase
# print("LEG: {} \t PHASE: {}".format(index, stored_phase))
if StanceSwing == STANCE:
return self.StanceStep(phase, L, LateralFraction, YawRate,
penetration_depth, T_bf, key, index)
elif StanceSwing == SWING:
return self.SwingStep(phase, L, LateralFraction, YawRate,
clearance_height, T_bf, key, index)
def GenerateTrajectory(self,
L,
LateralFraction,
YawRate,
vel,
T_bf_,
T_bf_curr,
clearance_height=0.06,
penetration_depth=0.01,
contacts=[0, 0, 0, 0],
dt=None):
"""Calculates the step coordinates for each foot
:param L: step length
:param LateralFraction: determines how lateral the movement is
:param YawRate: the desired body yaw rate
:param vel: the desired step velocity
:param clearance_height: foot clearance height during swing phase
:param penetration_depth: foot penetration depth during stance phase
:param contacts: array containing 1 for contact and 0 otherwise
:param dt: the time step
:returns: Foot Coordinates relative to unmodified body
"""
# First, get Tstance from desired speed and stride length
# NOTE: L is HALF of stride length
if vel != 0.0:
Tstance = 2.0 * abs(L) / abs(vel)
else:
Tstance = 0.0
L = 0.0
self.TD = False
self.time = 0.0
self.time_since_last_TD = 0.0
# Then, get time since last Touchdown and increment time counter
if dt is None:
dt = self.dt
YawRate *= dt
# Catch infeasible timesteps
if Tstance < dt:
Tstance = 0.0
L = 0.0
self.TD = False
self.time = 0.0
self.time_since_last_TD = 0.0
YawRate = 0.0
# NOTE: MUCH MORE STABLE WITH THIS
elif Tstance > 1.3 * self.Tswing:
Tstance = 1.3 * self.Tswing
# Check contacts
if contacts[0] == 1 and Tstance > dt:
self.TD = True
self.Increment(dt, Tstance + self.Tswing)
T_bf = copy.deepcopy(T_bf_)
for i, (key, Tbf_in) in enumerate(T_bf_.items()):
# TODO: MAKE THIS MORE ELEGANT
if key == "FL":
self.ref_idx = i
self.dSref[i] = 0.0
if key == "FR":
self.dSref[i] = 0.5
if key == "BL":
self.dSref[i] = 0.5
if key == "BR":
self.dSref[i] = 0.0
_, p_bf = TransToRp(Tbf_in)
if Tstance > 0.0:
step_coord = self.GetFootStep(L, LateralFraction, YawRate,
clearance_height,
penetration_depth, Tstance, p_bf,
i, key)
else:
step_coord = np.array([0.0, 0.0, 0.0])
T_bf[key][0, 3] = Tbf_in[0, 3] + step_coord[0]
T_bf[key][1, 3] = Tbf_in[1, 3] + step_coord[1]
T_bf[key][2, 3] = Tbf_in[2, 3] + step_coord[2]
return T_bf
| 19,596 | Python | 36.759152 | 97 | 0.5594 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/docs/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from recommonmark.parser import CommonMarkParser
sys.path.insert(0, os.path.abspath('..'))
source_parsers = {
'.md': CommonMarkParser,
}
# -- Project information -----------------------------------------------------
project = u'spot_mini_mini'
copyright = u'2020, Maurice Rahme'
author = u'Maurice Rahme'
# The short X.Y version
version = u''
# The full version, including alpha/beta/rc tags
release = u'1.0.0'
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'spot_mini_minidoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'spot_mini_mini.tex', u'spot\\_mini\\_mini Documentation',
u'Maurice Rahme', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'spot_mini_mini', u'spot_mini_mini Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'spot_mini_mini', u'spot_mini_mini Documentation',
author, 'spot_mini_mini', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
| 5,505 | Python | 28.287234 | 79 | 0.642688 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/MIT_mini-cheetah/mini-cheetah-CHAMP/yobo_model/yobotics_gazebo/scripts/imu_sensor.py | #! /usr/bin/env python
'''
Copyright (c) 2019-2020, Juan Miguel Jimeno
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, Quaternion
from yobotics_msgs.msg import Pose
import tf
class SimPose:
def __init__(self):
rospy.Subscriber("odom/ground_truth", Odometry, self.odometry_callback)
self.sim_pose_publisher = rospy.Publisher("/yobotics/gazebo/pose", Pose, queue_size=50)
def odometry_callback(self, data):
sim_pose_msg = Pose()
sim_pose_msg.roll = data.pose.pose.orientation.x
sim_pose_msg.pitch = data.pose.pose.orientation.y
sim_pose_msg.yaw = data.pose.pose.orientation.z
self.sim_pose_publisher.publish(sim_pose_msg)
if __name__ == "__main__":
rospy.init_node("yobotics_gazebo_sim_pose", anonymous = True)
odom = SimPose()
rospy.spin() | 2,342 | Python | 44.941176 | 95 | 0.752775 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/MIT_mini-cheetah/mini-cheetah-CHAMP/yobo_model/yobotics_gazebo/scripts/odometry_tf.py | #! /usr/bin/env python
'''
Copyright (c) 2019-2020, Juan Miguel Jimeno
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, Quaternion
import tf
class Odom:
def __init__(self):
rospy.Subscriber("odom/raw", Odometry, self.odometry_callback)
self.odom_broadcaster = tf.TransformBroadcaster()
def odometry_callback(self, data):
self.current_linear_speed_x = data.twist.twist.linear.x
self.current_angular_speed_z = data.twist.twist.angular.z
current_time = rospy.Time.now()
odom_quat = (
data.pose.pose.orientation.x,
data.pose.pose.orientation.y,
data.pose.pose.orientation.z,
data.pose.pose.orientation.w
)
self.odom_broadcaster.sendTransform(
(data.pose.pose.position.x, data.pose.pose.position.y, 0),
odom_quat,
current_time,
"base_footprint",
"odom"
)
if __name__ == "__main__":
rospy.init_node("yobotics_gazebo_odometry_transform", anonymous = True)
odom = Odom()
rospy.spin() | 2,612 | Python | 40.47619 | 80 | 0.714778 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/MIT_mini-cheetah/mini-cheetah-CHAMP/yobo_model/yobotics_gazebo/scripts/odometry.py | #! /usr/bin/env python
'''
Copyright (c) 2019-2020, Juan Miguel Jimeno
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import rospy
from yobotics_msgs.msg import Contacts
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, Quaternion, Pose, Twist, Vector3
import tf
from tf import TransformListener
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from nav_msgs.msg import Odometry
import math
class yoboticsOdometry:
def __init__(self):
rospy.Subscriber("/yobotics/gazebo/contacts", Contacts, self.contacts_callback)
self.odom_publisher = rospy.Publisher("odom/raw", Odometry, queue_size=50)
self.odom_broadcaster = tf.TransformBroadcaster()
self.tf = TransformListener()
self.foot_links = [
"lf_foot_link",
"rf_foot_link",
"lh_foot_link",
"rh_foot_link"
]
self.nominal_foot_positions = [[0,0],[0,0],[0,0],[0,0]]
self.prev_foot_positions = [[0,0],[0,0],[0,0],[0,0]]
self.prev_theta = [0,0,0,0]
self.prev_stance_angles = [0,0,0,0]
self.prev_time = 0
self.pos_x = 0
self.pos_y = 0
self.theta = 0
self.publish_odom_tf(0,0,0,0)
rospy.sleep(1)
for i in range(4):
self.nominal_foot_positions[i] = self.get_foot_position(i)
self.prev_foot_positions[i] = self.nominal_foot_positions[i]
self.prev_theta[i] = math.atan2(self.prev_foot_positions[i][1], self.prev_foot_positions[i][0])
def publish_odom(self, x, y, z, theta, vx, vy, vth):
current_time = rospy.Time.now()
odom = Odometry()
odom.header.stamp = current_time
odom.header.frame_id = "odom"
odom_quat = tf.transformations.quaternion_from_euler(0, 0, theta)
odom.pose.pose = Pose(Point(x, y, z), Quaternion(*odom_quat))
odom.child_frame_id = "base_footprint"
odom.twist.twist = Twist(Vector3(vx, vy, 0), Vector3(0, 0, vth))
# publish the message
self.odom_publisher.publish(odom)
def publish_odom_tf(self, x, y, z, theta):
current_time = rospy.Time.now()
odom_quat = quaternion_from_euler (0, 0, theta)
self.odom_broadcaster.sendTransform(
(x, y, z),
odom_quat,
current_time,
"base_footprint",
"odom"
)
def get_foot_position(self, leg_id):
if self.tf.frameExists("base_link" and self.foot_links[leg_id]) :
t = self.tf.getLatestCommonTime("base_link", self.foot_links[leg_id])
position, quaternion = self.tf.lookupTransform("base_link", self.foot_links[leg_id], t)
return position
else:
return 0, 0, 0
def contacts_callback(self, data):
self.leg_contact_states = data.contacts
def is_almost_equal(self, a, b, max_rel_diff):
diff = abs(a - b)
a = abs(a)
b = abs(b)
largest = 0
if b > a:
largest = b
else:
larget = a
if diff <= (largest * max_rel_diff):
return True
return False
def run(self):
while not rospy.is_shutdown():
leg_contact_states = self.leg_contact_states
current_foot_position = [[0,0],[0,0],[0,0],[0,0]]
stance_angles = [0, 0, 0, 0]
current_theta = [0, 0, 0, 0]
delta_theta = 0
in_xy = False
total_contact = sum(leg_contact_states)
x_sum = 0
y_sum = 0
theta_sum = 0
for i in range(4):
current_foot_position[i] = self.get_foot_position(i)
for i in range(4):
current_theta[i] = math.atan2(current_foot_position[i][1], current_foot_position[i][0])
from_nominal_x = self.nominal_foot_positions[i][0] - current_foot_position[i][0]
from_nominal_y = self.nominal_foot_positions[i][1] - current_foot_position[i][1]
stance_angles[i] = math.atan2(from_nominal_y, from_nominal_x)
# print stance_angles
#check if it's moving in the x or y axis
if self.is_almost_equal(stance_angles[i], abs(1.5708), 0.001) or self.is_almost_equal(stance_angles[i], abs(3.1416), 0.001):
in_xy = True
if current_foot_position[i] != None and leg_contact_states[i] == True and total_contact == 2:
delta_x = (self.prev_foot_positions[i][0] - current_foot_position[i][0]) / 2
delta_y = (self.prev_foot_positions[i][1] - current_foot_position[i][1]) / 2
x = delta_x * math.cos(self.theta) - delta_y * math.sin(self.theta)
y = delta_x * math.sin(self.theta) + delta_y * math.cos(self.theta)
x_sum += delta_x
y_sum += delta_y
self.pos_x += x
self.pos_y += y
if not in_xy:
delta_theta = self.prev_theta[i] - current_theta[i]
theta_sum += delta_theta
self.theta += delta_theta / 2
now = rospy.Time.now().to_sec()
dt = now - self.prev_time
vx = x_sum / dt
vy = y_sum / dt
vth = theta_sum / dt
self.publish_odom(self.pos_x, self.pos_y, 0, self.theta, vx, vy, vth)
# self.publish_odom_tf(self.pos_x, self.pos_y, 0, self.theta)
self.prev_foot_positions = current_foot_position
self.prev_theta = current_theta
self.prev_stance_angles = stance_angles
self.prev_time = now
rospy.sleep(0.01)
if __name__ == "__main__":
rospy.init_node("yobotics_gazebo_odometry", anonymous = True)
odom = yoboticsOdometry()
odom.run()
| 7,397 | Python | 37.331606 | 140 | 0.592402 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/MIT_mini-cheetah/mini-cheetah-CHAMP/yobo_model/yobotics_teleop/yobotics_teleop.py | #!/usr/bin/env python
#credits to: https://github.com/ros-teleop/teleop_twist_keyboard/blob/master/teleop_twist_keyboard.py
from __future__ import print_function
import roslib; roslib.load_manifest('yobotics_teleop')
import rospy
from sensor_msgs.msg import Joy
from geometry_msgs.msg import Twist
from yobotics_msgs.msg import Pose
import sys, select, termios, tty
import numpy as np
class Teleop:
def __init__(self):
self.velocity_publisher = rospy.Publisher('cmd_vel', Twist, queue_size = 1)
self.pose_publisher = rospy.Publisher('cmd_pose', Pose, queue_size = 1)
self.joy_subscriber = rospy.Subscriber('joy', Joy, self.joy_callback)
self.speed = rospy.get_param("~speed", 0.3)
self.turn = rospy.get_param("~turn", 1.0)
self.msg = """
Reading from the keyboard and Publishing to Twist!
---------------------------
Moving around:
u i o
j k l
m , .
For Holonomic mode (strafing), hold down the shift key:
---------------------------
U I O
J K L
M < >
t : up (+z)
b : down (-z)
anything else : stop
q/z : increase/decrease max speeds by 10%
w/x : increase/decrease only linear speed by 10%
e/c : increase/decrease only angular speed by 10%
CTRL-C to quit
"""
self.velocityBindings = {
'i':(1,0,0,0),
'o':(1,0,0,-1),
'j':(0,0,0,1),
'l':(0,0,0,-1),
'u':(1,0,0,1),
',':(-1,0,0,0),
'.':(-1,0,0,1),
'm':(-1,0,0,-1),
'O':(1,-1,0,0),
'I':(1,0,0,0),
'J':(0,1,0,0),
'L':(0,-1,0,0),
'U':(1,1,0,0),
'<':(-1,0,0,0),
'>':(-1,-1,0,0),
'M':(-1,1,0,0),
'v':(0,0,1,0),
'n':(0,0,-1,0),
}
self.poseBindings = {
'f':(-1,0,0,0),
'h':(1,0,0,0),
't':(0,1,0,0),
'b':(0,-1,0,0),
'r':(0,0,1,0),
'y':(0,0,-1,0),
}
self.speedBindings={
'q':(1.1,1.1),
'z':(.9,.9),
'w':(1.1,1),
'x':(.9,1),
'e':(1,1.1),
'c':(1,.9),
}
self.poll_keys()
def joy_callback(self, data):
twist = Twist()
twist.linear.x = data.axes[7] * self.speed
twist.linear.y = data.buttons[4] * data.axes[6] * self.speed
twist.linear.z = 0
twist.angular.x = 0
twist.angular.y = 0
twist.angular.z = (not data.buttons[4]) * data.axes[6] * self.turn
self.velocity_publisher.publish(twist)
body_pose = Pose()
body_pose.x = 0
body_pose.y = 0
body_pose.roll = (not data.buttons[5]) *-data.axes[3] * 0.349066
body_pose.pitch = data.axes[4] * 0.261799
body_pose.yaw = data.buttons[5] * data.axes[3] * 0.436332
if data.axes[5] < 0:
body_pose.z = self.map(data.axes[5], 0, -1.0, 1, 0.00001)
else:
body_pose.z = 1.0
self.pose_publisher.publish(body_pose)
def poll_keys(self):
self.settings = termios.tcgetattr(sys.stdin)
x = 0
y = 0
z = 0
th = 0
roll = 0
pitch = 0
yaw = 0
status = 0
cmd_attempts = 0
try:
print(self.msg)
print(self.vels( self.speed, self.turn))
while not rospy.is_shutdown():
key = self.getKey()
if key in self.velocityBindings.keys():
x = self.velocityBindings[key][0]
y = self.velocityBindings[key][1]
z = self.velocityBindings[key][2]
th = self.velocityBindings[key][3]
if cmd_attempts > 1:
twist = Twist()
twist.linear.x = x *self.speed
twist.linear.y = y * self.speed
twist.linear.z = z * self.speed
twist.angular.x = 0
twist.angular.y = 0
twist.angular.z = th * self.turn
self.velocity_publisher.publish(twist)
cmd_attempts += 1
elif key in self.poseBindings.keys():
#TODO: changes these values as rosparam
roll += 0.0174533 * self.poseBindings[key][0]
pitch += 0.0174533 * self.poseBindings[key][1]
yaw += 0.0174533 * self.poseBindings[key][2]
roll = np.clip(roll, -0.523599, 0.523599)
pitch = np.clip(pitch, -0.349066, 0.349066)
yaw = np.clip(yaw, -0.436332, 0.436332)
if cmd_attempts > 1:
body_pose = Pose()
body_pose.x = 0
body_pose.y = 0
body_pose.z = 0
body_pose.roll = roll
body_pose.pitch = pitch
body_pose.yaw = yaw
self.pose_publisher.publish(body_pose)
cmd_attempts += 1
elif key in self.speedBindings.keys():
self.speed = self.speed * self.speedBindings[key][0]
self.turn = self.turn * self.speedBindings[key][1]
print(self.vels(self.speed, self.turn))
if (status == 14):
print(self.msg)
status = (status + 1) % 15
else:
cmd_attempts = 0
if (key == '\x03'):
break
except Exception as e:
print(e)
finally:
twist = Twist()
twist.linear.x = 0
twist.linear.y = 0
twist.linear.z = 0
twist.angular.x = 0
twist.angular.y = 0
twist.angular.z = 0
self.velocity_publisher.publish(twist)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings)
def getKey(self):
tty.setraw(sys.stdin.fileno())
rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
if rlist:
key = sys.stdin.read(1)
else:
key = ''
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings)
return key
def vels(self, speed, turn):
return "currently:\tspeed %s\tturn %s " % (speed,turn)
def map(self, x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
if __name__ == "__main__":
rospy.init_node('yobotics_teleop')
teleop = Teleop() | 6,972 | Python | 31.282407 | 101 | 0.443632 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/KodlabPenn/kodlab_gazebo-master/other/objects_description/caster_stool/xacro.py | #! /usr/bin/env python
# Copyright (c) 2013, Willow Garage, Inc.
# Copyright (c) 2014, Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Open Source Robotics Foundation, Inc.
# nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Author: Stuart Glaser
# Maintainer: William Woodall <[email protected]>
from __future__ import print_function
import getopt
import glob
import os
import re
import string
import sys
import xml
from xml.dom.minidom import parse
try:
_basestr = basestring
except NameError:
_basestr = str
# Dictionary of subtitution args
substitution_args_context = {}
class XacroException(Exception):
pass
def isnumber(x):
return hasattr(x, '__int__')
# Better pretty printing of xml
# Taken from http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/
def fixed_writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent + "<" + self.tagName)
attrs = self._get_attributes()
a_names = list(attrs.keys())
a_names.sort()
for a_name in a_names:
writer.write(" %s=\"" % a_name)
xml.dom.minidom._write_data(writer, attrs[a_name].value)
writer.write("\"")
if self.childNodes:
if len(self.childNodes) == 1 \
and self.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE:
writer.write(">")
self.childNodes[0].writexml(writer, "", "", "")
writer.write("</%s>%s" % (self.tagName, newl))
return
writer.write(">%s" % (newl))
for node in self.childNodes:
# skip whitespace-only text nodes
if node.nodeType == xml.dom.minidom.Node.TEXT_NODE and \
not node.data.strip():
continue
node.writexml(writer, indent + addindent, addindent, newl)
writer.write("%s</%s>%s" % (indent, self.tagName, newl))
else:
writer.write("/>%s" % (newl))
# replace minidom's function with ours
xml.dom.minidom.Element.writexml = fixed_writexml
class Table:
def __init__(self, parent=None):
self.parent = parent
self.table = {}
def __getitem__(self, key):
if key in self.table:
return self.table[key]
elif self.parent:
return self.parent[key]
else:
raise KeyError(key)
def __setitem__(self, key, value):
self.table[key] = value
def __contains__(self, key):
return \
key in self.table or \
(self.parent and key in self.parent)
class QuickLexer(object):
def __init__(self, **res):
self.str = ""
self.top = None
self.res = []
for k, v in res.items():
self.__setattr__(k, len(self.res))
self.res.append(v)
def lex(self, str):
self.str = str
self.top = None
self.next()
def peek(self):
return self.top
def next(self):
result = self.top
self.top = None
for i in range(len(self.res)):
m = re.match(self.res[i], self.str)
if m:
self.top = (i, m.group(0))
self.str = self.str[m.end():]
break
return result
def first_child_element(elt):
c = elt.firstChild
while c:
if c.nodeType == xml.dom.Node.ELEMENT_NODE:
return c
c = c.nextSibling
return None
def next_sibling_element(elt):
c = elt.nextSibling
while c:
if c.nodeType == xml.dom.Node.ELEMENT_NODE:
return c
c = c.nextSibling
return None
# Pre-order traversal of the elements
def next_element(elt):
child = first_child_element(elt)
if child:
return child
while elt and elt.nodeType == xml.dom.Node.ELEMENT_NODE:
next = next_sibling_element(elt)
if next:
return next
elt = elt.parentNode
return None
# Pre-order traversal of all the nodes
def next_node(node):
if node.firstChild:
return node.firstChild
while node:
if node.nextSibling:
return node.nextSibling
node = node.parentNode
return None
def child_nodes(elt):
c = elt.firstChild
while c:
yield c
c = c.nextSibling
all_includes = []
# Deprecated message for <include> tags that don't have <xacro:include> prepended:
deprecated_include_msg = """DEPRECATED IN HYDRO:
The <include> tag should be prepended with 'xacro' if that is the intended use
of it, such as <xacro:include ...>. Use the following script to fix incorrect
xacro includes:
sed -i 's/<include/<xacro:include/g' `find . -iname *.xacro`"""
include_no_matches_msg = """Include tag filename spec \"{}\" matched no files."""
## @throws XacroException if a parsing error occurs with an included document
def process_includes(doc, base_dir):
namespaces = {}
previous = doc.documentElement
elt = next_element(previous)
while elt:
# Xacro should not use plain 'include' tags but only namespaced ones. Causes conflicts with
# other XML elements including Gazebo's <gazebo> extensions
is_include = False
if elt.tagName == 'xacro:include' or elt.tagName == 'include':
is_include = True
# Temporary fix for ROS Hydro and the xacro include scope problem
if elt.tagName == 'include':
# check if there is any element within the <include> tag. mostly we are concerned
# with Gazebo's <uri> element, but it could be anything. also, make sure the child
# nodes aren't just a single Text node, which is still considered a deprecated
# instance
if elt.childNodes and not (len(elt.childNodes) == 1 and
elt.childNodes[0].nodeType == elt.TEXT_NODE):
# this is not intended to be a xacro element, so we can ignore it
is_include = False
else:
# throw a deprecated warning
print(deprecated_include_msg, file=sys.stderr)
# Process current element depending on previous conditions
if is_include:
filename_spec = eval_text(elt.getAttribute('filename'), {})
if not os.path.isabs(filename_spec):
filename_spec = os.path.join(base_dir, filename_spec)
if re.search('[*[?]+', filename_spec):
# Globbing behaviour
filenames = sorted(glob.glob(filename_spec))
if len(filenames) == 0:
print(include_no_matches_msg.format(filename_spec), file=sys.stderr)
else:
# Default behaviour
filenames = [filename_spec]
for filename in filenames:
global all_includes
all_includes.append(filename)
try:
with open(filename) as f:
try:
included = parse(f)
except Exception as e:
raise XacroException(
"included file \"%s\" generated an error during XML parsing: %s"
% (filename, str(e)))
except IOError as e:
raise XacroException("included file \"%s\" could not be opened: %s" % (filename, str(e)))
# Replaces the include tag with the elements of the included file
for c in child_nodes(included.documentElement):
elt.parentNode.insertBefore(c.cloneNode(deep=True), elt)
# Grabs all the declared namespaces of the included document
for name, value in included.documentElement.attributes.items():
if name.startswith('xmlns:'):
namespaces[name] = value
elt.parentNode.removeChild(elt)
elt = None
else:
previous = elt
elt = next_element(previous)
# Makes sure the final document declares all the namespaces of the included documents.
for k, v in namespaces.items():
doc.documentElement.setAttribute(k, v)
# Returns a dictionary: { macro_name => macro_xml_block }
def grab_macros(doc):
macros = {}
previous = doc.documentElement
elt = next_element(previous)
while elt:
if elt.tagName == 'macro' or elt.tagName == 'xacro:macro':
name = elt.getAttribute('name')
macros[name] = elt
macros['xacro:' + name] = elt
elt.parentNode.removeChild(elt)
elt = None
else:
previous = elt
elt = next_element(previous)
return macros
# Returns a Table of the properties
def grab_properties(doc):
table = Table()
previous = doc.documentElement
elt = next_element(previous)
while elt:
if elt.tagName == 'property' or elt.tagName == 'xacro:property':
name = elt.getAttribute('name')
value = None
if elt.hasAttribute('value'):
value = elt.getAttribute('value')
else:
name = '**' + name
value = elt # debug
bad = string.whitespace + "${}"
has_bad = False
for b in bad:
if b in name:
has_bad = True
break
if has_bad:
sys.stderr.write('Property names may not have whitespace, ' +
'"{", "}", or "$" : "' + name + '"')
else:
table[name] = value
elt.parentNode.removeChild(elt)
elt = None
else:
previous = elt
elt = next_element(previous)
return table
def eat_ignore(lex):
while lex.peek() and lex.peek()[0] == lex.IGNORE:
lex.next()
def eval_lit(lex, symbols):
eat_ignore(lex)
if lex.peek()[0] == lex.NUMBER:
return float(lex.next()[1])
if lex.peek()[0] == lex.SYMBOL:
try:
key = lex.next()[1]
value = symbols[key]
except KeyError as ex:
raise XacroException("Property wasn't defined: %s" % str(ex))
if not (isnumber(value) or isinstance(value, _basestr)):
if value is None:
raise XacroException("Property %s recursively used" % key)
raise XacroException("WTF2")
try:
return int(value)
except:
try:
return float(value)
except:
# prevent infinite recursion
symbols[key] = None
result = eval_text(value, symbols)
# restore old entry
symbols[key] = value
return result
raise XacroException("Bad literal")
def eval_factor(lex, symbols):
eat_ignore(lex)
neg = 1
if lex.peek()[1] == '-':
lex.next()
neg = -1
if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL]:
return neg * eval_lit(lex, symbols)
if lex.peek()[0] == lex.LPAREN:
lex.next()
eat_ignore(lex)
result = eval_expr(lex, symbols)
eat_ignore(lex)
if lex.next()[0] != lex.RPAREN:
raise XacroException("Unmatched left paren")
eat_ignore(lex)
return neg * result
raise XacroException("Misplaced operator")
def eval_term(lex, symbols):
eat_ignore(lex)
result = 0
if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL, lex.LPAREN] \
or lex.peek()[1] == '-':
result = eval_factor(lex, symbols)
eat_ignore(lex)
while lex.peek() and lex.peek()[1] in ['*', '/']:
op = lex.next()[1]
n = eval_factor(lex, symbols)
if op == '*':
result = float(result) * float(n)
elif op == '/':
result = float(result) / float(n)
else:
raise XacroException("WTF")
eat_ignore(lex)
return result
def eval_expr(lex, symbols):
eat_ignore(lex)
op = None
if lex.peek()[0] == lex.OP:
op = lex.next()[1]
if not op in ['+', '-']:
raise XacroException("Invalid operation. Must be '+' or '-'")
result = eval_term(lex, symbols)
if op == '-':
result = -float(result)
eat_ignore(lex)
while lex.peek() and lex.peek()[1] in ['+', '-']:
op = lex.next()[1]
n = eval_term(lex, symbols)
if op == '+':
result = float(result) + float(n)
if op == '-':
result = float(result) - float(n)
eat_ignore(lex)
return result
def eval_text(text, symbols):
def handle_expr(s):
lex = QuickLexer(IGNORE=r"\s+",
NUMBER=r"(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?",
SYMBOL=r"[a-zA-Z_]\w*",
OP=r"[\+\-\*/^]",
LPAREN=r"\(",
RPAREN=r"\)")
lex.lex(s)
return eval_expr(lex, symbols)
def handle_extension(s):
return ("$(%s)" % s)
results = []
lex = QuickLexer(DOLLAR_DOLLAR_BRACE=r"\$\$+\{",
EXPR=r"\$\{[^\}]*\}",
EXTENSION=r"\$\([^\)]*\)",
TEXT=r"([^\$]|\$[^{(]|\$$)+")
lex.lex(text)
while lex.peek():
if lex.peek()[0] == lex.EXPR:
results.append(handle_expr(lex.next()[1][2:-1]))
elif lex.peek()[0] == lex.EXTENSION:
results.append(handle_extension(lex.next()[1][2:-1]))
elif lex.peek()[0] == lex.TEXT:
results.append(lex.next()[1])
elif lex.peek()[0] == lex.DOLLAR_DOLLAR_BRACE:
results.append(lex.next()[1][1:])
return ''.join(map(str, results))
# Expands macros, replaces properties, and evaluates expressions
def eval_all(root, macros, symbols):
# Evaluates the attributes for the root node
for at in root.attributes.items():
result = eval_text(at[1], symbols)
root.setAttribute(at[0], result)
previous = root
node = next_node(previous)
while node:
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
if node.tagName in macros:
body = macros[node.tagName].cloneNode(deep=True)
params = body.getAttribute('params').split()
# Parse default values for any parameters
defaultmap = {}
for param in params[:]:
splitParam = param.split(':=')
if len(splitParam) == 2:
defaultmap[splitParam[0]] = splitParam[1]
params.remove(param)
params.append(splitParam[0])
elif len(splitParam) != 1:
raise XacroException("Invalid parameter definition")
# Expands the macro
scoped = Table(symbols)
for name, value in node.attributes.items():
if not name in params:
raise XacroException("Invalid parameter \"%s\" while expanding macro \"%s\"" %
(str(name), str(node.tagName)))
params.remove(name)
scoped[name] = eval_text(value, symbols)
# Pulls out the block arguments, in order
cloned = node.cloneNode(deep=True)
eval_all(cloned, macros, symbols)
block = cloned.firstChild
for param in params[:]:
if param[0] == '*':
while block and block.nodeType != xml.dom.Node.ELEMENT_NODE:
block = block.nextSibling
if not block:
raise XacroException("Not enough blocks while evaluating macro %s" % str(node.tagName))
params.remove(param)
scoped[param] = block
block = block.nextSibling
# Try to load defaults for any remaining non-block parameters
for param in params[:]:
if param[0] != '*' and param in defaultmap:
scoped[param] = defaultmap[param]
params.remove(param)
if params:
raise XacroException("Parameters [%s] were not set for macro %s" %
(",".join(params), str(node.tagName)))
eval_all(body, macros, scoped)
# Replaces the macro node with the expansion
for e in list(child_nodes(body)): # Ew
node.parentNode.insertBefore(e, node)
node.parentNode.removeChild(node)
node = None
elif node.tagName == 'arg' or node.tagName == 'xacro:arg':
name = node.getAttribute('name')
if not name:
raise XacroException("Argument name missing")
default = node.getAttribute('default')
if default and name not in substitution_args_context['arg']:
substitution_args_context['arg'][name] = default
node.parentNode.removeChild(node)
node = None
elif node.tagName == 'insert_block' or node.tagName == 'xacro:insert_block':
name = node.getAttribute('name')
if ("**" + name) in symbols:
# Multi-block
block = symbols['**' + name]
for e in list(child_nodes(block)):
node.parentNode.insertBefore(e.cloneNode(deep=True), node)
node.parentNode.removeChild(node)
elif ("*" + name) in symbols:
# Single block
block = symbols['*' + name]
node.parentNode.insertBefore(block.cloneNode(deep=True), node)
node.parentNode.removeChild(node)
else:
raise XacroException("Block \"%s\" was never declared" % name)
node = None
elif node.tagName in ['if', 'xacro:if', 'unless', 'xacro:unless']:
value = eval_text(node.getAttribute('value'), symbols)
try:
if value == 'true': keep = True
elif value == 'false': keep = False
else: keep = float(value)
except ValueError:
raise XacroException("Xacro conditional evaluated to \"%s\". Acceptable evaluations are one of [\"1\",\"true\",\"0\",\"false\"]" % value)
if node.tagName in ['unless', 'xacro:unless']: keep = not keep
if keep:
for e in list(child_nodes(node)):
node.parentNode.insertBefore(e.cloneNode(deep=True), node)
node.parentNode.removeChild(node)
else:
# Evals the attributes
for at in node.attributes.items():
result = eval_text(at[1], symbols)
node.setAttribute(at[0], result)
previous = node
elif node.nodeType == xml.dom.Node.TEXT_NODE:
node.data = eval_text(node.data, symbols)
previous = node
else:
previous = node
node = next_node(previous)
return macros
# Expands everything except includes
def eval_self_contained(doc):
macros = grab_macros(doc)
symbols = grab_properties(doc)
eval_all(doc.documentElement, macros, symbols)
def print_usage(exit_code=0):
print("Usage: %s [-o <output>] <input>" % 'xacro.py')
print(" %s --deps Prints dependencies" % 'xacro.py')
print(" %s --includes Only evalutes includes" % 'xacro.py')
sys.exit(exit_code)
def set_substitution_args_context(context={}):
substitution_args_context['arg'] = context
def open_output(output_filename):
if output_filename is None:
return sys.stdout
else:
return open(output_filename, 'w')
def main():
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "ho:", ['deps', 'includes'])
except getopt.GetoptError as err:
print(str(err))
print_usage(2)
just_deps = False
just_includes = False
output_filename = None
for o, a in opts:
if o == '-h':
print_usage(0)
elif o == '-o':
output_filename = a
elif o == '--deps':
just_deps = True
elif o == '--includes':
just_includes = True
if len(args) < 1:
print("No input given")
print_usage(2)
# Process substitution args
# set_substitution_args_context(load_mappings(sys.argv))
set_substitution_args_context((sys.argv))
f = open(args[0])
doc = None
try:
doc = parse(f)
except xml.parsers.expat.ExpatError:
sys.stderr.write("Expat parsing error. Check that:\n")
sys.stderr.write(" - Your XML is correctly formed\n")
sys.stderr.write(" - You have the xacro xmlns declaration: " +
"xmlns:xacro=\"http://www.ros.org/wiki/xacro\"\n")
sys.stderr.write("\n")
raise
finally:
f.close()
process_includes(doc, os.path.dirname(args[0]))
if just_deps:
for inc in all_includes:
sys.stdout.write(inc + " ")
sys.stdout.write("\n")
elif just_includes:
doc.writexml(open_output(output_filename))
print()
else:
eval_self_contained(doc)
banner = [xml.dom.minidom.Comment(c) for c in
[" %s " % ('=' * 83),
" | This document was autogenerated by xacro from %-30s | " % args[0],
" | EDITING THIS FILE BY HAND IS NOT RECOMMENDED %-30s | " % "",
" %s " % ('=' * 83)]]
first = doc.firstChild
for comment in banner:
doc.insertBefore(comment, first)
open_output(output_filename).write(doc.toprettyxml(indent=' '))
print()
if __name__ == '__main__':
main()
| 23,887 | Python | 32.835694 | 157 | 0.542973 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros/spot_driver/setup.py | from setuptools import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=["spot_driver"], scripts=["scripts/spot_ros"], package_dir={"": "src"}
)
setup(**d)
| 219 | Python | 23.444442 | 83 | 0.721461 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros/spot_driver/src/spot_driver/spot_ros.py | import copy
import rospy
import math
import time
from std_srvs.srv import Trigger, TriggerResponse, SetBool, SetBoolResponse
from std_msgs.msg import Bool
from tf2_msgs.msg import TFMessage
from sensor_msgs.msg import Image, CameraInfo
from sensor_msgs.msg import PointCloud2
from sensor_msgs.msg import JointState
from geometry_msgs.msg import TwistWithCovarianceStamped, Twist, Pose, PoseStamped
from nav_msgs.msg import Odometry
from bosdyn.api.spot import robot_command_pb2 as spot_command_pb2
from bosdyn.api import geometry_pb2, trajectory_pb2
from bosdyn.api.geometry_pb2 import Quaternion, SE2VelocityLimit
from bosdyn.client import math_helpers
from google.protobuf.wrappers_pb2 import DoubleValue
import actionlib
import functools
import math
import bosdyn.geometry
import tf2_ros
import tf2_geometry_msgs
from spot_msgs.msg import Metrics
from spot_msgs.msg import LeaseArray, LeaseResource
from spot_msgs.msg import FootState, FootStateArray
from spot_msgs.msg import EStopState, EStopStateArray
from spot_msgs.msg import WiFiState
from spot_msgs.msg import PowerState
from spot_msgs.msg import BehaviorFault, BehaviorFaultState
from spot_msgs.msg import SystemFault, SystemFaultState
from spot_msgs.msg import BatteryState, BatteryStateArray
from spot_msgs.msg import DockAction, DockGoal, DockResult
from spot_msgs.msg import PoseBodyAction, PoseBodyGoal, PoseBodyResult
from spot_msgs.msg import Feedback
from spot_msgs.msg import MobilityParams, ObstacleParams, TerrainParams
from spot_msgs.msg import NavigateToAction, NavigateToResult, NavigateToFeedback
from spot_msgs.msg import TrajectoryAction, TrajectoryResult, TrajectoryFeedback
from spot_msgs.srv import ListGraph, ListGraphResponse
from spot_msgs.srv import SetLocomotion, SetLocomotionResponse
from spot_msgs.srv import SetTerrainParams, SetTerrainParamsResponse
from spot_msgs.srv import SetObstacleParams, SetObstacleParamsResponse
from spot_msgs.srv import ClearBehaviorFault, ClearBehaviorFaultResponse
from spot_msgs.srv import SetVelocity, SetVelocityResponse
from spot_msgs.srv import Dock, DockResponse, GetDockState, GetDockStateResponse
from spot_msgs.srv import PosedStand, PosedStandResponse
from spot_msgs.srv import SetSwingHeight, SetSwingHeightResponse
from spot_msgs.srv import (
ArmJointMovement,
ArmJointMovementResponse,
ArmJointMovementRequest,
)
from spot_msgs.srv import (
GripperAngleMove,
GripperAngleMoveResponse,
GripperAngleMoveRequest,
)
from spot_msgs.srv import (
ArmForceTrajectory,
ArmForceTrajectoryResponse,
ArmForceTrajectoryRequest,
)
from spot_msgs.srv import HandPose, HandPoseResponse, HandPoseRequest
from spot_msgs.srv import Grasp3d, Grasp3dRequest, Grasp3dResponse
from .ros_helpers import *
from spot_wrapper.wrapper import SpotWrapper
import actionlib
import logging
import threading
class RateLimitedCall:
"""
Wrap a function with this class to limit how frequently it can be called within a loop
"""
def __init__(self, fn, rate_limit):
"""
Args:
fn: Function to call
rate_limit: The function will not be called faster than this rate
"""
self.fn = fn
self.min_time_between_calls = 1.0 / rate_limit
self.last_call = 0
def __call__(self):
now_sec = time.time()
if (now_sec - self.last_call) > self.min_time_between_calls:
self.fn()
self.last_call = now_sec
class SpotROS:
"""Parent class for using the wrapper. Defines all callbacks and keeps the wrapper alive"""
def __init__(self):
self.spot_wrapper = None
self.last_tf_msg = TFMessage()
self.callbacks = {}
"""Dictionary listing what callback to use for what data task"""
self.callbacks["robot_state"] = self.RobotStateCB
self.callbacks["metrics"] = self.MetricsCB
self.callbacks["lease"] = self.LeaseCB
self.callbacks["front_image"] = self.FrontImageCB
self.callbacks["side_image"] = self.SideImageCB
self.callbacks["rear_image"] = self.RearImageCB
self.callbacks["hand_image"] = self.HandImageCB
self.callbacks["lidar_points"] = self.PointCloudCB
self.active_camera_tasks = []
self.camera_pub_to_async_task_mapping = {}
def RobotStateCB(self, results):
"""Callback for when the Spot Wrapper gets new robot state data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
state = self.spot_wrapper.robot_state
if state:
## joint states ##
joint_state = GetJointStatesFromState(state, self.spot_wrapper)
self.joint_state_pub.publish(joint_state)
## TF ##
tf_msg = GetTFFromState(state, self.spot_wrapper, self.mode_parent_odom_tf)
to_remove = []
if len(tf_msg.transforms) > 0:
for transform in tf_msg.transforms:
for last_tf in self.last_tf_msg.transforms:
if transform == last_tf:
to_remove.append(transform)
if to_remove:
# Do it this way to preserve the original tf message received. If we store the message we have
# destroyed then if there are two duplicates in a row we will not remove the second set.
deduplicated_tf = copy.deepcopy(tf_msg)
for repeat_tf in to_remove:
deduplicated_tf.transforms.remove(repeat_tf)
publish_tf = deduplicated_tf
else:
publish_tf = tf_msg
self.tf_pub.publish(publish_tf)
self.last_tf_msg = tf_msg
# Odom Twist #
twist_odom_msg = GetOdomTwistFromState(state, self.spot_wrapper)
self.odom_twist_pub.publish(twist_odom_msg)
# Odom #
use_vision = self.mode_parent_odom_tf == "vision"
odom_msg = GetOdomFromState(
state,
self.spot_wrapper,
use_vision=use_vision,
)
self.odom_pub.publish(odom_msg)
odom_corrected_msg = get_corrected_odom(odom_msg)
self.odom_corrected_pub.publish(odom_corrected_msg)
# Feet #
foot_array_msg = GetFeetFromState(state, self.spot_wrapper)
self.tf_pub.publish(generate_feet_tf(foot_array_msg))
self.feet_pub.publish(foot_array_msg)
# EStop #
estop_array_msg = GetEStopStateFromState(state, self.spot_wrapper)
self.estop_pub.publish(estop_array_msg)
# WIFI #
wifi_msg = GetWifiFromState(state, self.spot_wrapper)
self.wifi_pub.publish(wifi_msg)
# Battery States #
battery_states_array_msg = GetBatteryStatesFromState(
state, self.spot_wrapper
)
self.is_charging = (
battery_states_array_msg.battery_states[0].status
== BatteryState.STATUS_CHARGING
)
self.battery_pub.publish(battery_states_array_msg)
# Power State #
power_state_msg = GetPowerStatesFromState(state, self.spot_wrapper)
self.power_pub.publish(power_state_msg)
# System Faults #
system_fault_state_msg = GetSystemFaultsFromState(state, self.spot_wrapper)
self.system_faults_pub.publish(system_fault_state_msg)
# Behavior Faults #
behavior_fault_state_msg = getBehaviorFaultsFromState(
state, self.spot_wrapper
)
self.behavior_faults_pub.publish(behavior_fault_state_msg)
def MetricsCB(self, results):
"""Callback for when the Spot Wrapper gets new metrics data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
metrics = self.spot_wrapper.metrics
if metrics:
metrics_msg = Metrics()
local_time = self.spot_wrapper.robotToLocalTime(metrics.timestamp)
metrics_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
for metric in metrics.metrics:
if metric.label == "distance":
metrics_msg.distance = metric.float_value
if metric.label == "gait cycles":
metrics_msg.gait_cycles = metric.int_value
if metric.label == "time moving":
metrics_msg.time_moving = rospy.Time(
metric.duration.seconds, metric.duration.nanos
)
if metric.label == "electric power":
metrics_msg.electric_power = rospy.Time(
metric.duration.seconds, metric.duration.nanos
)
self.metrics_pub.publish(metrics_msg)
def LeaseCB(self, results):
"""Callback for when the Spot Wrapper gets new lease data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
lease_array_msg = LeaseArray()
lease_list = self.spot_wrapper.lease
if lease_list:
for resource in lease_list:
new_resource = LeaseResource()
new_resource.resource = resource.resource
new_resource.lease.resource = resource.lease.resource
new_resource.lease.epoch = resource.lease.epoch
for seq in resource.lease.sequence:
new_resource.lease.sequence.append(seq)
new_resource.lease_owner.client_name = resource.lease_owner.client_name
new_resource.lease_owner.user_name = resource.lease_owner.user_name
lease_array_msg.resources.append(new_resource)
self.lease_pub.publish(lease_array_msg)
def FrontImageCB(self, results):
"""Callback for when the Spot Wrapper gets new front image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.front_images
if data:
image_msg0, camera_info_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.frontleft_image_pub.publish(image_msg0)
self.frontleft_image_info_pub.publish(camera_info_msg0)
image_msg1, camera_info_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.frontright_image_pub.publish(image_msg1)
self.frontright_image_info_pub.publish(camera_info_msg1)
image_msg2, camera_info_msg2 = getImageMsg(data[2], self.spot_wrapper)
self.frontleft_depth_pub.publish(image_msg2)
self.frontleft_depth_info_pub.publish(camera_info_msg2)
image_msg3, camera_info_msg3 = getImageMsg(data[3], self.spot_wrapper)
self.frontright_depth_pub.publish(image_msg3)
self.frontright_depth_info_pub.publish(camera_info_msg3)
self.populate_camera_static_transforms(data[0])
self.populate_camera_static_transforms(data[1])
self.populate_camera_static_transforms(data[2])
self.populate_camera_static_transforms(data[3])
def SideImageCB(self, results):
"""Callback for when the Spot Wrapper gets new side image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.side_images
if data:
image_msg0, camera_info_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.left_image_pub.publish(image_msg0)
self.left_image_info_pub.publish(camera_info_msg0)
image_msg1, camera_info_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.right_image_pub.publish(image_msg1)
self.right_image_info_pub.publish(camera_info_msg1)
image_msg2, camera_info_msg2 = getImageMsg(data[2], self.spot_wrapper)
self.left_depth_pub.publish(image_msg2)
self.left_depth_info_pub.publish(camera_info_msg2)
image_msg3, camera_info_msg3 = getImageMsg(data[3], self.spot_wrapper)
self.right_depth_pub.publish(image_msg3)
self.right_depth_info_pub.publish(camera_info_msg3)
self.populate_camera_static_transforms(data[0])
self.populate_camera_static_transforms(data[1])
self.populate_camera_static_transforms(data[2])
self.populate_camera_static_transforms(data[3])
def RearImageCB(self, results):
"""Callback for when the Spot Wrapper gets new rear image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.rear_images
if data:
mage_msg0, camera_info_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.back_image_pub.publish(mage_msg0)
self.back_image_info_pub.publish(camera_info_msg0)
mage_msg1, camera_info_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.back_depth_pub.publish(mage_msg1)
self.back_depth_info_pub.publish(camera_info_msg1)
self.populate_camera_static_transforms(data[0])
self.populate_camera_static_transforms(data[1])
def HandImageCB(self, results):
"""Callback for when the Spot Wrapper gets new hand image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.hand_images
if data:
mage_msg0, camera_info_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.hand_image_mono_pub.publish(mage_msg0)
self.hand_image_mono_info_pub.publish(camera_info_msg0)
mage_msg1, camera_info_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.hand_depth_pub.publish(mage_msg1)
self.hand_depth_info_pub.publish(camera_info_msg1)
image_msg2, camera_info_msg2 = getImageMsg(data[2], self.spot_wrapper)
self.hand_image_color_pub.publish(image_msg2)
self.hand_image_color_info_pub.publish(camera_info_msg2)
image_msg3, camera_info_msg3 = getImageMsg(data[3], self.spot_wrapper)
self.hand_depth_in_hand_color_pub.publish(image_msg3)
self.hand_depth_in_color_info_pub.publish(camera_info_msg3)
self.populate_camera_static_transforms(data[0])
self.populate_camera_static_transforms(data[1])
self.populate_camera_static_transforms(data[2])
self.populate_camera_static_transforms(data[3])
def PointCloudCB(self, results):
"""Callback for when the Spot Wrapper gets new point cloud data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.point_clouds
if data:
point_cloud_msg = GetPointCloudMsg(data[0], self.spot_wrapper)
self.point_cloud_pub.publish(point_cloud_msg)
self.populate_lidar_static_transforms(data[0])
def handle_claim(self, req):
"""ROS service handler for the claim service"""
resp = self.spot_wrapper.claim()
return TriggerResponse(resp[0], resp[1])
def handle_release(self, req):
"""ROS service handler for the release service"""
resp = self.spot_wrapper.release()
return TriggerResponse(resp[0], resp[1])
def handle_locked_stop(self, req):
"""Stop the current motion of the robot and disallow any further motion until the allow motion service is
called"""
self.allow_motion = False
return self.handle_stop(req)
def handle_stop(self, req):
"""ROS service handler for the stop service. Interrupts the currently active motion"""
resp = self.spot_wrapper.stop()
message = "Spot stop service was called"
if self.navigate_as.is_active():
self.navigate_as.set_preempted(
NavigateToResult(success=False, message=message)
)
if self.trajectory_server.is_active():
self.trajectory_server.set_preempted(
TrajectoryResult(success=False, message=message)
)
if self.body_pose_as.is_active():
self.body_pose_as.set_preempted(
PoseBodyResult(success=False, message=message)
)
return TriggerResponse(resp[0], resp[1])
def handle_self_right(self, req):
"""ROS service handler for the self-right service"""
if not self.robot_allowed_to_move(autonomous_command=False):
return TriggerResponse(False, "Robot motion is not allowed")
resp = self.spot_wrapper.self_right()
return TriggerResponse(resp[0], resp[1])
def handle_sit(self, req):
"""ROS service handler for the sit service"""
if not self.robot_allowed_to_move(autonomous_command=False):
return TriggerResponse(False, "Robot motion is not allowed")
resp = self.spot_wrapper.sit()
return TriggerResponse(resp[0], resp[1])
def handle_stand(self, req):
"""ROS service handler for the stand service"""
if not self.robot_allowed_to_move(autonomous_command=False):
return TriggerResponse(False, "Robot motion is not allowed")
resp = self.spot_wrapper.stand()
return TriggerResponse(resp[0], resp[1])
def handle_posed_stand(self, req):
"""
Handle a service call for the posed stand
Args:
req: PosedStandRequest
Returns: PosedStandResponse
"""
success, message = self._posed_stand(
req.body_height, req.body_yaw, req.body_pitch, req.body_roll
)
return PosedStandResponse(success, message)
def handle_posed_stand_action(self, action):
"""
Handle a call to the posed stand actionserver
If no value is provided, this is equivalent to the basic stand commmand
Args:
action: PoseBodyGoal
"""
success, message = self._posed_stand(
action.body_height, action.yaw, action.pitch, action.roll
)
result = PoseBodyResult(success, message)
rospy.sleep(2) # Only return after the body has had a chance to move
if success:
self.body_pose_as.set_succeeded(result)
else:
self.body_pose_as.set_aborted(result)
def _posed_stand(self, body_height, yaw, pitch, roll):
"""
Make the robot do a posed stand with specified body height and orientation
By empirical observation, the limit on body height is [-0.16, 0.11], and RPY are probably limited to 30
degrees. Roll values are likely affected by the payload configuration as well. If the payload is
misconfigured a high roll value could cause it to hit the legs
Args:
body_height: Height of the body relative to the default height
yaw: Yaw to apply (in degrees)
pitch: Pitch to apply (in degrees)
roll: Roll to apply (in degrees)
Returns:
"""
if not self.robot_allowed_to_move(autonomous_command=False):
return False, "Robot motion is not allowed"
resp = self.spot_wrapper.stand(
body_height=body_height,
body_yaw=math.radians(yaw),
body_pitch=math.radians(pitch),
body_roll=math.radians(roll),
)
return resp[0], resp[1]
def handle_power_on(self, req):
"""ROS service handler for the power-on service"""
resp = self.spot_wrapper.power_on()
return TriggerResponse(resp[0], resp[1])
def handle_safe_power_off(self, req):
"""ROS service handler for the safe-power-off service"""
resp = self.spot_wrapper.safe_power_off()
return TriggerResponse(resp[0], resp[1])
def handle_estop_hard(self, req):
"""ROS service handler to hard-eStop the robot. The robot will immediately cut power to the motors"""
resp = self.spot_wrapper.assertEStop(True)
return TriggerResponse(resp[0], resp[1])
def handle_estop_soft(self, req):
"""ROS service handler to soft-eStop the robot. The robot will try to settle on the ground before cutting
power to the motors"""
resp = self.spot_wrapper.assertEStop(False)
return TriggerResponse(resp[0], resp[1])
def handle_estop_disengage(self, req):
"""ROS service handler to disengage the eStop on the robot."""
resp = self.spot_wrapper.disengageEStop()
return TriggerResponse(resp[0], resp[1])
def handle_clear_behavior_fault(self, req):
"""ROS service handler for clearing behavior faults"""
resp = self.spot_wrapper.clear_behavior_fault(req.id)
return ClearBehaviorFaultResponse(resp[0], resp[1])
def handle_stair_mode(self, req):
"""ROS service handler to set a stair mode to the robot."""
try:
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params.stair_hint = req.data
self.spot_wrapper.set_mobility_params(mobility_params)
return SetBoolResponse(True, "Success")
except Exception as e:
return SetBoolResponse(False, "Error:{}".format(e))
def handle_locomotion_mode(self, req):
"""ROS service handler to set locomotion mode"""
if req.locomotion_mode in [0, 9] or req.locomotion_mode > 10:
msg = "Attempted to set locomotion mode to {}, which is an invalid value.".format(
req.locomotion_mode
)
rospy.logerr(msg)
return SetLocomotionResponse(False, msg)
try:
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params.locomotion_hint = req.locomotion_mode
self.spot_wrapper.set_mobility_params(mobility_params)
return SetLocomotionResponse(True, "Success")
except Exception as e:
return SetLocomotionResponse(False, "Error:{}".format(e))
def handle_swing_height(self, req):
"""ROS service handler to set the step swing height"""
if req.swing_height == 0 or req.swing_height > 3:
msg = "Attempted to set step swing height to {}, which is an invalid value.".format(
req.swing_height
)
rospy.logerr(msg)
return SetSwingHeightResponse(False, msg)
try:
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params.swing_height = req.swing_height
self.spot_wrapper.set_mobility_params(mobility_params)
return SetSwingHeightResponse(True, "Success")
except Exception as e:
return SetSwingHeightResponse(False, "Error:{}".format(e))
def handle_vel_limit(self, req):
"""
Handle a velocity_limit service call.
Args:
req: SetVelocityRequest containing requested velocity limit
Returns: SetVelocityResponse
"""
success, message = self.set_velocity_limits(
req.velocity_limit.linear.x,
req.velocity_limit.linear.y,
req.velocity_limit.angular.z,
)
return SetVelocityResponse(success, message)
def set_velocity_limits(self, max_linear_x, max_linear_y, max_angular_z):
"""
Modify the mobility params to have a limit on the robot's velocity during trajectory commands.
Velocities sent to cmd_vel ignore these values
Passing 0 to any of the values will use spot's internal limits
Args:
max_linear_x: Maximum forwards/backwards velocity
max_linear_y: Maximum lateral velocity
max_angular_z: Maximum rotation velocity
Returns: (bool, str) boolean indicating whether the call was successful, along with a message
"""
if any(
map(lambda x: 0 < x < 0.15, [max_linear_x, max_linear_y, max_angular_z])
):
return (
False,
"Error: One of the values provided to velocity limits was below 0.15. Values in the range ("
"0,0.15) can cause unexpected behaviour of the trajectory command.",
)
try:
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params.vel_limit.CopyFrom(
SE2VelocityLimit(
max_vel=math_helpers.SE2Velocity(
max_linear_x, max_linear_y, max_angular_z
).to_proto(),
min_vel=math_helpers.SE2Velocity(
-max_linear_x, -max_linear_y, -max_angular_z
).to_proto(),
)
)
self.spot_wrapper.set_mobility_params(mobility_params)
return True, "Success"
except Exception as e:
return False, "Error:{}".format(e)
def _transform_pose_to_body_frame(self, pose):
"""
Transform a pose to the body frame
Args:
pose: PoseStamped to transform
Raises: tf2_ros.LookupException if the transform lookup fails
Returns: Transformed pose in body frame if given pose is not in the body frame, or the original pose if it is
in the body frame
"""
if pose.header.frame_id == "body":
return pose
body_to_fixed = self.tf_buffer.lookup_transform(
"body", pose.header.frame_id, rospy.Time()
)
pose_in_body = tf2_geometry_msgs.do_transform_pose(pose, body_to_fixed)
pose_in_body.header.frame_id = "body"
return pose_in_body
def robot_allowed_to_move(self, autonomous_command=True):
"""
Check if the robot is allowed to move. This means checking both that autonomy is enabled, which can only be
set when the driver is started, and also that motion is allowed, the state of which can change while the
driver is running
Args:
autonomous_command: If true, indicates that this function should also check if autonomy is enabled
Returns: True if the robot is allowed to move, false otherwise
"""
if not self.allow_motion:
rospy.logwarn(
"Spot is not currently allowed to move. Use the allow_motion service to allow the robot to "
"move."
)
autonomy_ok = True
if autonomous_command:
if not self.autonomy_enabled:
rospy.logwarn(
"Spot is not allowed to be autonomous because this instance of the driver was started "
"with it disabled. Set autonomy_enabled to true in the launch file to enable it."
)
autonomy_ok = False
if self.is_charging:
rospy.logwarn(
"Spot cannot be autonomous because it is connected to shore power."
)
autonomy_ok = False
return self.allow_motion and autonomy_ok
def handle_allow_motion(self, req):
"""
Handle a call to set whether motion is allowed or not
When motion is not allowed, any service call or topic which can move the robot will return without doing
anything
Returns: (bool, str) True if successful, along with a message
"""
self.allow_motion = req.data
rospy.loginfo(
"Robot motion is now {}".format(
"allowed" if self.allow_motion else "disallowed"
)
)
if not self.allow_motion:
# Always send a stop command if disallowing motion, in case the robot is moving when it is sent
self.spot_wrapper.stop()
return True, "Spot motion was {}".format("enabled" if req.data else "disabled")
def handle_obstacle_params(self, req):
"""
Handle a call to set the obstacle params part of mobility params. The previous values are always overwritten.
Args:
req:
Returns: (bool, str) True if successful, along with a message
"""
mobility_params = self.spot_wrapper.get_mobility_params()
obstacle_params = spot_command_pb2.ObstacleParams()
# Currently only the obstacle setting that we allow is the padding. The previous value is always overwritten
# Clamp to the range [0, 0.5] as on the controller
if req.obstacle_params.obstacle_avoidance_padding < 0:
rospy.logwarn(
"Received padding value of {}, clamping to 0".format(
req.obstacle_params.obstacle_avoidance_padding
)
)
req.obstacle_params.obstacle_avoidance_padding = 0
if req.obstacle_params.obstacle_avoidance_padding > 0.5:
rospy.logwarn(
"Received padding value of {}, clamping to 0.5".format(
req.obstacle_params.obstacle_avoidance_padding
)
)
req.obstacle_params.obstacle_avoidance_padding = 0.5
disable_notallowed = ""
if any(
[
req.obstacle_params.disable_vision_foot_obstacle_avoidance,
req.obstacle_params.disable_vision_foot_constraint_avoidance,
req.obstacle_params.disable_vision_body_obstacle_avoidance,
req.obstacle_params.disable_vision_foot_obstacle_body_assist,
req.obstacle_params.disable_vision_negative_obstacles,
]
):
disable_notallowed = " Disabling any of the obstacle avoidance components is not currently allowed."
rospy.logerr(
"At least one of the disable settings on obstacle params was true."
+ disable_notallowed
)
obstacle_params.obstacle_avoidance_padding = (
req.obstacle_params.obstacle_avoidance_padding
)
mobility_params.obstacle_params.CopyFrom(obstacle_params)
self.spot_wrapper.set_mobility_params(mobility_params)
return True, "Successfully set obstacle params" + disable_notallowed
def handle_terrain_params(self, req):
"""
Handle a call to set the terrain params part of mobility params. The previous values are always overwritten
Args:
req:
Returns: (bool, str) True if successful, along with a message
"""
mobility_params = self.spot_wrapper.get_mobility_params()
# We always overwrite the previous settings of these values. Reject if not within recommended limits (as on
# the controller)
if 0.2 <= req.terrain_params.ground_mu_hint <= 0.8:
# For some reason assignment to ground_mu_hint is not allowed once the terrain params are initialised
# Must initialise with the protobuf type DoubleValue for initialisation to work
terrain_params = spot_command_pb2.TerrainParams(
ground_mu_hint=DoubleValue(value=req.terrain_params.ground_mu_hint)
)
else:
return (
False,
"Failed to set terrain params, ground_mu_hint of {} is not in the range [0.4, 0.8]".format(
req.terrain_params.ground_mu_hint
),
)
if req.terrain_params.grated_surfaces_mode in [1, 2, 3]:
terrain_params.grated_surfaces_mode = (
req.terrain_params.grated_surfaces_mode
)
else:
return (
False,
"Failed to set terrain params, grated_surfaces_mode {} was not one of [1, 2, 3]".format(
req.terrain_params.grated_surfaces_mode
),
)
mobility_params.terrain_params.CopyFrom(terrain_params)
self.spot_wrapper.set_mobility_params(mobility_params)
return True, "Successfully set terrain params"
def trajectory_callback(self, msg):
"""
Handle a callback from the trajectory topic requesting to go to a location
The trajectory will time out after 5 seconds
Args:
msg: PoseStamped containing desired pose
Returns:
"""
if not self.robot_allowed_to_move():
rospy.logerr(
"Trajectory topic received a message but the robot is not allowed to move."
)
return
try:
self._send_trajectory_command(
self._transform_pose_to_body_frame(msg), rospy.Duration(5)
)
except tf2_ros.LookupException as e:
rospy.logerr(str(e))
def handle_trajectory(self, req):
"""ROS actionserver execution handler to handle receiving a request to move to a location"""
if not self.robot_allowed_to_move():
rospy.logerr(
"Trajectory service was called but robot is not allowed to move"
)
self.trajectory_server.set_aborted(
TrajectoryResult(False, "Robot is not allowed to move.")
)
return
target_pose = req.target_pose
if req.target_pose.header.frame_id != "body":
rospy.logwarn("Pose given was not in the body frame, will transform")
try:
target_pose = self._transform_pose_to_body_frame(target_pose)
except tf2_ros.LookupException as e:
self.trajectory_server.set_aborted(
TrajectoryResult(False, "Could not transform pose into body frame")
)
return
if req.duration.data.to_sec() <= 0:
self.trajectory_server.set_aborted(
TrajectoryResult(False, "duration must be larger than 0")
)
return
cmd_duration = rospy.Duration(req.duration.data.secs, req.duration.data.nsecs)
resp = self._send_trajectory_command(
target_pose, cmd_duration, req.precise_positioning
)
def timeout_cb(trajectory_server, _):
trajectory_server.publish_feedback(
TrajectoryFeedback("Failed to reach goal, timed out")
)
trajectory_server.set_aborted(
TrajectoryResult(False, "Failed to reach goal, timed out")
)
# Abort the actionserver if cmd_duration is exceeded - the driver stops but does not provide feedback to
# indicate this so we monitor it ourselves
cmd_timeout = rospy.Timer(
cmd_duration,
functools.partial(timeout_cb, self.trajectory_server),
oneshot=True,
)
# Sleep to allow some feedback to come through from the trajectory command
rospy.sleep(0.25)
if self.spot_wrapper._trajectory_status_unknown:
rospy.logerr(
"Sent trajectory request to spot but received unknown feedback. Resending command. This will "
"only be attempted once"
)
# If we receive an unknown result from the trajectory, something went wrong internally (not
# catastrophically). We need to resend the command, because getting status unknown happens right when
# the command is sent. It's unclear right now why this happens
resp = self._send_trajectory_command(
target_pose, cmd_duration, req.precise_positioning
)
cmd_timeout.shutdown()
cmd_timeout = rospy.Timer(
cmd_duration,
functools.partial(timeout_cb, self.trajectory_server),
oneshot=True,
)
# The trajectory command is non-blocking but we need to keep this function up in order to interrupt if a
# preempt is requested and to return success if/when the robot reaches the goal. Also check the is_active to
# monitor whether the timeout_cb has already aborted the command
rate = rospy.Rate(10)
while (
not rospy.is_shutdown()
and not self.trajectory_server.is_preempt_requested()
and not self.spot_wrapper.at_goal
and self.trajectory_server.is_active()
and not self.spot_wrapper._trajectory_status_unknown
):
if self.spot_wrapper.near_goal:
if self.spot_wrapper._last_trajectory_command_precise:
self.trajectory_server.publish_feedback(
TrajectoryFeedback("Near goal, performing final adjustments")
)
else:
self.trajectory_server.publish_feedback(
TrajectoryFeedback("Near goal")
)
else:
self.trajectory_server.publish_feedback(
TrajectoryFeedback("Moving to goal")
)
rate.sleep()
# If still active after exiting the loop, the command did not time out
if self.trajectory_server.is_active():
cmd_timeout.shutdown()
if self.trajectory_server.is_preempt_requested():
self.trajectory_server.publish_feedback(TrajectoryFeedback("Preempted"))
self.trajectory_server.set_preempted()
self.spot_wrapper.stop()
if self.spot_wrapper.at_goal:
self.trajectory_server.publish_feedback(
TrajectoryFeedback("Reached goal")
)
self.trajectory_server.set_succeeded(TrajectoryResult(resp[0], resp[1]))
else:
self.trajectory_server.publish_feedback(
TrajectoryFeedback("Failed to reach goal")
)
self.trajectory_server.set_aborted(
TrajectoryResult(False, "Failed to reach goal")
)
def handle_roll_over_right(self, req):
"""Robot sit down and roll on to it its side for easier battery access"""
del req
resp = self.spot_wrapper.battery_change_pose(1)
return TriggerResponse(resp[0], resp[1])
def handle_roll_over_left(self, req):
"""Robot sit down and roll on to it its side for easier battery access"""
del req
resp = self.spot_wrapper.battery_change_pose(2)
return TriggerResponse(resp[0], resp[1])
def handle_dock(self, req):
"""Dock the robot"""
resp = self.spot_wrapper.dock(req.dock_id)
return DockResponse(resp[0], resp[1])
def handle_undock(self, req):
"""Undock the robot"""
resp = self.spot_wrapper.undock()
return TriggerResponse(resp[0], resp[1])
def handle_dock_action(self, req: DockGoal):
if req.undock:
resp = self.spot_wrapper.undock()
else:
resp = self.spot_wrapper.dock(req.dock_id)
if resp[0]:
self.dock_as.set_succeeded(DockResult(resp[0], resp[1]))
else:
self.dock_as.set_aborted(DockResult(resp[0], resp[1]))
def handle_get_docking_state(self, req):
"""Get docking state of robot"""
resp = self.spot_wrapper.get_docking_state()
return GetDockStateResponse(GetDockStatesFromState(resp))
def _send_trajectory_command(self, pose, duration, precise=True):
"""
Send a trajectory command to the robot
Args:
pose: Pose the robot should go to. Must be in the body frame
duration: After this duration, the command will time out and the robot will stop
precise: If true, the robot will position itself precisely at the target pose, otherwise it will end up
near (within ~0.5m, rotation optional) the requested location
Returns: (bool, str) tuple indicating whether the command was successfully sent, and a message
"""
if not self.robot_allowed_to_move():
rospy.logerr("send trajectory was called but motion is not allowed.")
return
if pose.header.frame_id != "body":
rospy.logerr("Trajectory command poses must be in the body frame")
return
return self.spot_wrapper.trajectory_cmd(
goal_x=pose.pose.position.x,
goal_y=pose.pose.position.y,
goal_heading=math_helpers.Quat(
w=pose.pose.orientation.w,
x=pose.pose.orientation.x,
y=pose.pose.orientation.y,
z=pose.pose.orientation.z,
).to_yaw(),
cmd_duration=duration.to_sec(),
precise_position=precise,
)
def cmdVelCallback(self, data):
"""Callback for cmd_vel command"""
if not self.robot_allowed_to_move():
rospy.logerr("cmd_vel received a message but motion is not allowed.")
return
self.spot_wrapper.velocity_cmd(data.linear.x, data.linear.y, data.angular.z)
def in_motion_or_idle_pose_cb(self, data):
"""
Callback for pose to be used while in motion or idling
This sets the body control field in the mobility params. This means that the pose will be used while a motion
command is executed. Only the pitch is maintained while moving. The roll and yaw will be applied by the idle
stand command.
"""
if not self.robot_allowed_to_move(autonomous_command=False):
rospy.logerr("body pose received a message but motion is not allowed.")
return
self._set_in_motion_or_idle_body_pose(data)
def handle_in_motion_or_idle_body_pose(self, goal):
"""
Handle a goal received from the pose body actionserver
Args:
goal: PoseBodyGoal containing a pose to apply to the body
Returns:
"""
# We can change the body pose if autonomy is not allowed
if not self.robot_allowed_to_move(autonomous_command=False):
rospy.logerr("body pose actionserver was called but motion is not allowed.")
return
# If the body_pose is empty, we use the rpy + height components instead
if goal.body_pose == Pose():
# If the rpy+body height are all zero then we set the body to neutral pose
if not any(
[
goal.roll,
goal.pitch,
goal.yaw,
not math.isclose(goal.body_height, 0, abs_tol=1e-9),
]
):
pose = Pose()
pose.orientation.w = 1
self._set_in_motion_or_idle_body_pose(pose)
else:
pose = Pose()
# Multiplication order is important to get the correct quaternion
orientation_quat = (
math_helpers.Quat.from_yaw(math.radians(goal.yaw))
* math_helpers.Quat.from_pitch(math.radians(goal.pitch))
* math_helpers.Quat.from_roll(math.radians(goal.roll))
)
pose.orientation.x = orientation_quat.x
pose.orientation.y = orientation_quat.y
pose.orientation.z = orientation_quat.z
pose.orientation.w = orientation_quat.w
pose.position.z = goal.body_height
self._set_in_motion_or_idle_body_pose(pose)
else:
self._set_in_motion_or_idle_body_pose(goal.body_pose)
# Give it some time to move
rospy.sleep(2)
self.motion_or_idle_body_pose_as.set_succeeded(
PoseBodyResult(
success=True, message="Successfully applied in-motion pose to body"
)
)
def _set_in_motion_or_idle_body_pose(self, pose):
"""
Set the pose of the body which should be applied while in motion or idle
Args:
pose: Pose to be applied to the body. Only the body height is taken from the position component
Returns:
"""
q = Quaternion()
q.x = pose.orientation.x
q.y = pose.orientation.y
q.z = pose.orientation.z
q.w = pose.orientation.w
position = geometry_pb2.Vec3(z=pose.position.z)
pose = geometry_pb2.SE3Pose(position=position, rotation=q)
point = trajectory_pb2.SE3TrajectoryPoint(pose=pose)
traj = trajectory_pb2.SE3Trajectory(points=[point])
body_control = spot_command_pb2.BodyControlParams(base_offset_rt_footprint=traj)
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params.body_control.CopyFrom(body_control)
self.spot_wrapper.set_mobility_params(mobility_params)
def handle_list_graph(self, upload_path):
"""ROS service handler for listing graph_nav waypoint_ids"""
resp = self.spot_wrapper.list_graph(upload_path)
return ListGraphResponse(resp)
def handle_navigate_to_feedback(self):
"""Thread function to send navigate_to feedback"""
while not rospy.is_shutdown() and self.run_navigate_to:
localization_state = (
self.spot_wrapper._graph_nav_client.get_localization_state()
)
if localization_state.localization.waypoint_id:
self.navigate_as.publish_feedback(
NavigateToFeedback(localization_state.localization.waypoint_id)
)
rospy.Rate(10).sleep()
def handle_navigate_to(self, msg):
"""ROS service handler to run mission of the robot. The robot will replay a mission"""
if not self.robot_allowed_to_move():
rospy.logerr("navigate_to was requested but robot is not allowed to move.")
self.navigate_as.set_aborted(
NavigateToResult(False, "Autonomy is not enabled")
)
return
# create thread to periodically publish feedback
feedback_thraed = threading.Thread(
target=self.handle_navigate_to_feedback, args=()
)
self.run_navigate_to = True
feedback_thraed.start()
# run navigate_to
resp = self.spot_wrapper.navigate_to(
upload_path=msg.upload_path,
navigate_to=msg.navigate_to,
initial_localization_fiducial=msg.initial_localization_fiducial,
initial_localization_waypoint=msg.initial_localization_waypoint,
)
self.run_navigate_to = False
feedback_thraed.join()
# check status
if resp[0]:
self.navigate_as.set_succeeded(NavigateToResult(resp[0], resp[1]))
else:
self.navigate_as.set_aborted(NavigateToResult(resp[0], resp[1]))
def populate_camera_static_transforms(self, image_data):
"""Check data received from one of the image tasks and use the transform snapshot to extract the camera frame
transforms. This is the transforms from body->frontleft->frontleft_fisheye, for example. These transforms
never change, but they may be calibrated slightly differently for each robot so we need to generate the
transforms at runtime.
Args:
image_data: Image protobuf data from the wrapper
"""
# We exclude the odometry frames from static transforms since they are not static. We can ignore the body
# frame because it is a child of odom or vision depending on the mode_parent_odom_tf, and will be published
# by the non-static transform publishing that is done by the state callback
excluded_frames = [
self.tf_name_vision_odom,
self.tf_name_kinematic_odom,
"body",
]
for frame_name in image_data.shot.transforms_snapshot.child_to_parent_edge_map:
if frame_name in excluded_frames:
continue
parent_frame = (
image_data.shot.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
).parent_frame_name
)
existing_transforms = [
(transform.header.frame_id, transform.child_frame_id)
for transform in self.sensors_static_transforms
]
if (parent_frame, frame_name) in existing_transforms:
# We already extracted this transform
continue
transform = (
image_data.shot.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
)
)
local_time = self.spot_wrapper.robotToLocalTime(
image_data.shot.acquisition_time
)
tf_time = rospy.Time(local_time.seconds, local_time.nanos)
static_tf = populateTransformStamped(
tf_time,
transform.parent_frame_name,
frame_name,
transform.parent_tform_child,
)
self.sensors_static_transforms.append(static_tf)
self.sensors_static_transform_broadcaster.sendTransform(
self.sensors_static_transforms
)
def populate_lidar_static_transforms(self, point_cloud_data):
"""Check data received from one of the point cloud tasks and use the transform snapshot to extract the lidar frame
transforms. This is the transforms from body->sensor, for example. These transforms
never change, but they may be calibrated slightly differently for each robot so we need to generate the
transforms at runtime.
Args:
point_cloud_data: PointCloud protobuf data from the wrapper
"""
# We exclude the odometry frames from static transforms since they are not static. We can ignore the body
# frame because it is a child of odom or vision depending on the mode_parent_odom_tf, and will be published
# by the non-static transform publishing that is done by the state callback
excluded_frames = [
self.tf_name_vision_odom,
self.tf_name_kinematic_odom,
"body",
]
for (
frame_name
) in (
point_cloud_data.point_cloud.source.transforms_snapshot.child_to_parent_edge_map
):
if frame_name in excluded_frames:
continue
parent_frame = point_cloud_data.point_cloud.source.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
).parent_frame_name
existing_transforms = [
(transform.header.frame_id, transform.child_frame_id)
for transform in self.sensors_static_transforms
]
if (parent_frame, frame_name) in existing_transforms:
# We already extracted this transform
continue
transform = point_cloud_data.point_cloud.source.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
)
local_time = self.spot_wrapper.robotToLocalTime(
point_cloud_data.point_cloud.source.acquisition_time
)
tf_time = rospy.Time(local_time.seconds, local_time.nanos)
static_tf = populateTransformStamped(
tf_time,
transform.parent_frame_name,
frame_name,
transform.parent_tform_child,
)
self.sensors_static_transforms.append(static_tf)
self.sensors_static_transform_broadcaster.sendTransform(
self.sensors_static_transforms
)
# Arm functions ##################################################
def handle_arm_stow(self, srv_data):
"""ROS service handler to command the arm to stow, home position"""
resp = self.spot_wrapper.arm_stow()
return TriggerResponse(resp[0], resp[1])
def handle_arm_unstow(self, srv_data):
"""ROS service handler to command the arm to unstow, joints are all zeros"""
resp = self.spot_wrapper.arm_unstow()
return TriggerResponse(resp[0], resp[1])
def handle_arm_joint_move(self, srv_data: ArmJointMovementRequest):
"""ROS service handler to send joint movement to the arm to execute"""
resp = self.spot_wrapper.arm_joint_move(joint_targets=srv_data.joint_target)
return ArmJointMovementResponse(resp[0], resp[1])
def handle_force_trajectory(self, srv_data: ArmForceTrajectoryRequest):
"""ROS service handler to send a force trajectory up or down a vertical force"""
resp = self.spot_wrapper.force_trajectory(data=srv_data)
return ArmForceTrajectoryResponse(resp[0], resp[1])
def handle_gripper_open(self, srv_data):
"""ROS service handler to open the gripper"""
resp = self.spot_wrapper.gripper_open()
return TriggerResponse(resp[0], resp[1])
def handle_gripper_close(self, srv_data):
"""ROS service handler to close the gripper"""
resp = self.spot_wrapper.gripper_close()
return TriggerResponse(resp[0], resp[1])
def handle_gripper_angle_open(self, srv_data: GripperAngleMoveRequest):
"""ROS service handler to open the gripper at an angle"""
resp = self.spot_wrapper.gripper_angle_open(gripper_ang=srv_data.gripper_angle)
return GripperAngleMoveResponse(resp[0], resp[1])
def handle_arm_carry(self, srv_data):
"""ROS service handler to put arm in carry mode"""
resp = self.spot_wrapper.arm_carry()
return TriggerResponse(resp[0], resp[1])
def handle_hand_pose(self, srv_data: HandPoseRequest):
"""ROS service to give a position to the gripper"""
resp = self.spot_wrapper.hand_pose(data=srv_data)
return HandPoseResponse(resp[0], resp[1])
def handle_grasp_3d(self, srv_data: Grasp3dRequest):
"""ROS service to grasp an object by x,y,z coordinates in given frame"""
resp = self.spot_wrapper.grasp_3d(
frame=srv_data.frame_name,
object_rt_frame=srv_data.object_rt_frame,
)
return Grasp3dResponse(resp[0], resp[1])
##################################################################
def shutdown(self):
rospy.loginfo("Shutting down ROS driver for Spot")
self.spot_wrapper.sit()
rospy.Rate(0.25).sleep()
self.spot_wrapper.disconnect()
def publish_mobility_params(self):
mobility_params_msg = MobilityParams()
try:
mobility_params = self.spot_wrapper.get_mobility_params()
mobility_params_msg.body_control.position.x = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.position.x
)
mobility_params_msg.body_control.position.y = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.position.y
)
mobility_params_msg.body_control.position.z = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.position.z
)
mobility_params_msg.body_control.orientation.x = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.rotation.x
)
mobility_params_msg.body_control.orientation.y = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.rotation.y
)
mobility_params_msg.body_control.orientation.z = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.rotation.z
)
mobility_params_msg.body_control.orientation.w = (
mobility_params.body_control.base_offset_rt_footprint.points[
0
].pose.rotation.w
)
mobility_params_msg.locomotion_hint = mobility_params.locomotion_hint
mobility_params_msg.stair_hint = mobility_params.stair_hint
mobility_params_msg.swing_height = mobility_params.swing_height
mobility_params_msg.obstacle_params.obstacle_avoidance_padding = (
mobility_params.obstacle_params.obstacle_avoidance_padding
)
mobility_params_msg.obstacle_params.disable_vision_foot_obstacle_avoidance = (
mobility_params.obstacle_params.disable_vision_foot_obstacle_avoidance
)
mobility_params_msg.obstacle_params.disable_vision_foot_constraint_avoidance = (
mobility_params.obstacle_params.disable_vision_foot_constraint_avoidance
)
mobility_params_msg.obstacle_params.disable_vision_body_obstacle_avoidance = (
mobility_params.obstacle_params.disable_vision_body_obstacle_avoidance
)
mobility_params_msg.obstacle_params.disable_vision_foot_obstacle_body_assist = (
mobility_params.obstacle_params.disable_vision_foot_obstacle_body_assist
)
mobility_params_msg.obstacle_params.disable_vision_negative_obstacles = (
mobility_params.obstacle_params.disable_vision_negative_obstacles
)
if mobility_params.HasField("terrain_params"):
if mobility_params.terrain_params.HasField("ground_mu_hint"):
mobility_params_msg.terrain_params.ground_mu_hint = (
mobility_params.terrain_params.ground_mu_hint
)
# hasfield does not work on grated surfaces mode
if hasattr(mobility_params.terrain_params, "grated_surfaces_mode"):
mobility_params_msg.terrain_params.grated_surfaces_mode = (
mobility_params.terrain_params.grated_surfaces_mode
)
# The velocity limit values can be set independently so make sure each of them exists before setting
if mobility_params.HasField("vel_limit"):
if hasattr(mobility_params.vel_limit.max_vel.linear, "x"):
mobility_params_msg.velocity_limit.linear.x = (
mobility_params.vel_limit.max_vel.linear.x
)
if hasattr(mobility_params.vel_limit.max_vel.linear, "y"):
mobility_params_msg.velocity_limit.linear.y = (
mobility_params.vel_limit.max_vel.linear.y
)
if hasattr(mobility_params.vel_limit.max_vel, "angular"):
mobility_params_msg.velocity_limit.angular.z = (
mobility_params.vel_limit.max_vel.angular
)
except Exception as e:
rospy.logerr("Error:{}".format(e))
pass
self.mobility_params_pub.publish(mobility_params_msg)
def publish_feedback(self):
feedback_msg = Feedback()
feedback_msg.standing = self.spot_wrapper.is_standing
feedback_msg.sitting = self.spot_wrapper.is_sitting
feedback_msg.moving = self.spot_wrapper.is_moving
id_ = self.spot_wrapper.id
try:
feedback_msg.serial_number = id_.serial_number
feedback_msg.species = id_.species
feedback_msg.version = id_.version
feedback_msg.nickname = id_.nickname
feedback_msg.computer_serial_number = id_.computer_serial_number
except:
pass
self.feedback_pub.publish(feedback_msg)
def publish_allow_motion(self):
self.motion_allowed_pub.publish(self.allow_motion)
def check_for_subscriber(self):
for pub in list(self.camera_pub_to_async_task_mapping.keys()):
task_name = self.camera_pub_to_async_task_mapping[pub]
if (
task_name not in self.active_camera_tasks
and pub.get_num_connections() > 0
):
self.spot_wrapper.update_image_tasks(task_name)
self.active_camera_tasks.append(task_name)
print(
f"Detected subscriber for {task_name} task, adding task to publish"
)
def main(self):
"""Main function for the SpotROS class. Gets config from ROS and initializes the wrapper. Holds lease from
wrapper and updates all async tasks at the ROS rate"""
rospy.init_node("spot_ros", anonymous=True)
self.rates = rospy.get_param("~rates", {})
if "loop_frequency" in self.rates:
loop_rate = self.rates["loop_frequency"]
else:
loop_rate = 50
for param, rate in self.rates.items():
if rate > loop_rate:
rospy.logwarn(
"{} has a rate of {} specified, which is higher than the loop rate of {}. It will not "
"be published at the expected frequency".format(
param, rate, loop_rate
)
)
rate = rospy.Rate(loop_rate)
self.robot_name = rospy.get_param("~robot_name", "spot")
self.username = rospy.get_param("~username", "default_value")
self.password = rospy.get_param("~password", "default_value")
self.hostname = rospy.get_param("~hostname", "default_value")
self.motion_deadzone = rospy.get_param("~deadzone", 0.05)
self.start_estop = rospy.get_param("~start_estop", True)
self.estop_timeout = rospy.get_param("~estop_timeout", 9.0)
self.autonomy_enabled = rospy.get_param("~autonomy_enabled", True)
self.allow_motion = rospy.get_param("~allow_motion", True)
self.use_take_lease = rospy.get_param("~use_take_lease", False)
self.get_lease_on_action = rospy.get_param("~get_lease_on_action", False)
self.is_charging = False
self.tf_buffer = tf2_ros.Buffer()
self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)
self.sensors_static_transform_broadcaster = tf2_ros.StaticTransformBroadcaster()
# Static transform broadcaster is super simple and just a latched publisher. Every time we add a new static
# transform we must republish all static transforms from this source, otherwise the tree will be incomplete.
# We keep a list of all the static transforms we already have so they can be republished, and so we can check
# which ones we already have
self.sensors_static_transforms = []
# Spot has 2 types of odometries: 'odom' and 'vision'
# The former one is kinematic odometry and the second one is a combined odometry of vision and kinematics
# These params enables to change which odometry frame is a parent of body frame and to change tf names of each odometry frames.
self.mode_parent_odom_tf = rospy.get_param(
"~mode_parent_odom_tf", "odom"
) # 'vision' or 'odom'
self.tf_name_kinematic_odom = rospy.get_param("~tf_name_kinematic_odom", "odom")
self.tf_name_raw_kinematic = "odom"
self.tf_name_vision_odom = rospy.get_param("~tf_name_vision_odom", "vision")
self.tf_name_raw_vision = "vision"
if (
self.mode_parent_odom_tf != self.tf_name_raw_kinematic
and self.mode_parent_odom_tf != self.tf_name_raw_vision
):
rospy.logerr(
"rosparam '~mode_parent_odom_tf' should be 'odom' or 'vision'."
)
return
self.logger = logging.getLogger("rosout")
rospy.loginfo("Starting ROS driver for Spot")
self.spot_wrapper = SpotWrapper(
username=self.username,
password=self.password,
hostname=self.hostname,
robot_name=self.robot_name,
logger=self.logger,
start_estop=self.start_estop,
estop_timeout=self.estop_timeout,
rates=self.rates,
callbacks=self.callbacks,
use_take_lease=self.use_take_lease,
get_lease_on_action=self.get_lease_on_action,
)
if not self.spot_wrapper.is_valid:
return
# Images #
self.back_image_pub = rospy.Publisher("camera/back/image", Image, queue_size=10)
self.frontleft_image_pub = rospy.Publisher(
"camera/frontleft/image", Image, queue_size=10
)
self.frontright_image_pub = rospy.Publisher(
"camera/frontright/image", Image, queue_size=10
)
self.left_image_pub = rospy.Publisher("camera/left/image", Image, queue_size=10)
self.right_image_pub = rospy.Publisher(
"camera/right/image", Image, queue_size=10
)
self.hand_image_mono_pub = rospy.Publisher(
"camera/hand_mono/image", Image, queue_size=10
)
self.hand_image_color_pub = rospy.Publisher(
"camera/hand_color/image", Image, queue_size=10
)
# Depth #
self.back_depth_pub = rospy.Publisher("depth/back/image", Image, queue_size=10)
self.frontleft_depth_pub = rospy.Publisher(
"depth/frontleft/image", Image, queue_size=10
)
self.frontright_depth_pub = rospy.Publisher(
"depth/frontright/image", Image, queue_size=10
)
self.left_depth_pub = rospy.Publisher("depth/left/image", Image, queue_size=10)
self.right_depth_pub = rospy.Publisher(
"depth/right/image", Image, queue_size=10
)
self.hand_depth_pub = rospy.Publisher("depth/hand/image", Image, queue_size=10)
self.hand_depth_in_hand_color_pub = rospy.Publisher(
"depth/hand/depth_in_color", Image, queue_size=10
)
self.frontleft_depth_in_visual_pub = rospy.Publisher(
"depth/frontleft/depth_in_visual", Image, queue_size=10
)
self.frontright_depth_in_visual_pub = rospy.Publisher(
"depth/frontright/depth_in_visual", Image, queue_size=10
)
# EAP Pointcloud #
self.point_cloud_pub = rospy.Publisher(
"lidar/points", PointCloud2, queue_size=10
)
# Image Camera Info #
self.back_image_info_pub = rospy.Publisher(
"camera/back/camera_info", CameraInfo, queue_size=10
)
self.frontleft_image_info_pub = rospy.Publisher(
"camera/frontleft/camera_info", CameraInfo, queue_size=10
)
self.frontright_image_info_pub = rospy.Publisher(
"camera/frontright/camera_info", CameraInfo, queue_size=10
)
self.left_image_info_pub = rospy.Publisher(
"camera/left/camera_info", CameraInfo, queue_size=10
)
self.right_image_info_pub = rospy.Publisher(
"camera/right/camera_info", CameraInfo, queue_size=10
)
self.hand_image_mono_info_pub = rospy.Publisher(
"camera/hand_mono/camera_info", CameraInfo, queue_size=10
)
self.hand_image_color_info_pub = rospy.Publisher(
"camera/hand_color/camera_info", CameraInfo, queue_size=10
)
# Depth Camera Info #
self.back_depth_info_pub = rospy.Publisher(
"depth/back/camera_info", CameraInfo, queue_size=10
)
self.frontleft_depth_info_pub = rospy.Publisher(
"depth/frontleft/camera_info", CameraInfo, queue_size=10
)
self.frontright_depth_info_pub = rospy.Publisher(
"depth/frontright/camera_info", CameraInfo, queue_size=10
)
self.left_depth_info_pub = rospy.Publisher(
"depth/left/camera_info", CameraInfo, queue_size=10
)
self.right_depth_info_pub = rospy.Publisher(
"depth/right/camera_info", CameraInfo, queue_size=10
)
self.hand_depth_info_pub = rospy.Publisher(
"depth/hand/camera_info", CameraInfo, queue_size=10
)
self.hand_depth_in_color_info_pub = rospy.Publisher(
"camera/hand/depth_in_color/camera_info", CameraInfo, queue_size=10
)
self.frontleft_depth_in_visual_info_pub = rospy.Publisher(
"depth/frontleft/depth_in_visual/camera_info", CameraInfo, queue_size=10
)
self.frontright_depth_in_visual_info_pub = rospy.Publisher(
"depth/frontright/depth_in_visual/camera_info", CameraInfo, queue_size=10
)
self.camera_pub_to_async_task_mapping = {
self.frontleft_image_pub: "front_image",
self.frontleft_depth_pub: "front_image",
self.frontleft_image_info_pub: "front_image",
self.frontright_image_pub: "front_image",
self.frontright_depth_pub: "front_image",
self.frontright_image_info_pub: "front_image",
self.back_image_pub: "rear_image",
self.back_depth_pub: "rear_image",
self.back_image_info_pub: "rear_image",
self.right_image_pub: "side_image",
self.right_depth_pub: "side_image",
self.right_image_info_pub: "side_image",
self.left_image_pub: "side_image",
self.left_depth_pub: "side_image",
self.left_image_info_pub: "side_image",
self.hand_image_color_pub: "hand_image",
self.hand_image_mono_pub: "hand_image",
self.hand_image_mono_info_pub: "hand_image",
self.hand_depth_pub: "hand_image",
self.hand_depth_in_hand_color_pub: "hand_image",
}
# Status Publishers #
self.joint_state_pub = rospy.Publisher(
"joint_states", JointState, queue_size=10
)
"""Defining a TF publisher manually because of conflicts between Python3 and tf"""
self.tf_pub = rospy.Publisher("tf", TFMessage, queue_size=10)
self.metrics_pub = rospy.Publisher("status/metrics", Metrics, queue_size=10)
self.lease_pub = rospy.Publisher("status/leases", LeaseArray, queue_size=10)
self.odom_twist_pub = rospy.Publisher(
"odometry/twist", TwistWithCovarianceStamped, queue_size=10
)
self.odom_pub = rospy.Publisher("odometry", Odometry, queue_size=10)
self.odom_corrected_pub = rospy.Publisher(
"odometry_corrected", Odometry, queue_size=10
)
self.feet_pub = rospy.Publisher("status/feet", FootStateArray, queue_size=10)
self.estop_pub = rospy.Publisher("status/estop", EStopStateArray, queue_size=10)
self.wifi_pub = rospy.Publisher("status/wifi", WiFiState, queue_size=10)
self.power_pub = rospy.Publisher(
"status/power_state", PowerState, queue_size=10
)
self.battery_pub = rospy.Publisher(
"status/battery_states", BatteryStateArray, queue_size=10
)
self.behavior_faults_pub = rospy.Publisher(
"status/behavior_faults", BehaviorFaultState, queue_size=10
)
self.system_faults_pub = rospy.Publisher(
"status/system_faults", SystemFaultState, queue_size=10
)
self.motion_allowed_pub = rospy.Publisher(
"status/motion_allowed", Bool, queue_size=10
)
self.feedback_pub = rospy.Publisher("status/feedback", Feedback, queue_size=10)
self.mobility_params_pub = rospy.Publisher(
"status/mobility_params", MobilityParams, queue_size=10
)
rospy.Subscriber("cmd_vel", Twist, self.cmdVelCallback, queue_size=1)
rospy.Subscriber(
"go_to_pose", PoseStamped, self.trajectory_callback, queue_size=1
)
rospy.Subscriber(
"in_motion_or_idle_body_pose",
Pose,
self.in_motion_or_idle_pose_cb,
queue_size=1,
)
rospy.Service("claim", Trigger, self.handle_claim)
rospy.Service("release", Trigger, self.handle_release)
rospy.Service("self_right", Trigger, self.handle_self_right)
rospy.Service("sit", Trigger, self.handle_sit)
rospy.Service("stand", Trigger, self.handle_stand)
rospy.Service("power_on", Trigger, self.handle_power_on)
rospy.Service("power_off", Trigger, self.handle_safe_power_off)
rospy.Service("estop/hard", Trigger, self.handle_estop_hard)
rospy.Service("estop/gentle", Trigger, self.handle_estop_soft)
rospy.Service("estop/release", Trigger, self.handle_estop_disengage)
rospy.Service("allow_motion", SetBool, self.handle_allow_motion)
rospy.Service("stair_mode", SetBool, self.handle_stair_mode)
rospy.Service("locomotion_mode", SetLocomotion, self.handle_locomotion_mode)
rospy.Service("swing_height", SetSwingHeight, self.handle_swing_height)
rospy.Service("velocity_limit", SetVelocity, self.handle_vel_limit)
rospy.Service(
"clear_behavior_fault", ClearBehaviorFault, self.handle_clear_behavior_fault
)
rospy.Service("terrain_params", SetTerrainParams, self.handle_terrain_params)
rospy.Service("obstacle_params", SetObstacleParams, self.handle_obstacle_params)
rospy.Service("posed_stand", PosedStand, self.handle_posed_stand)
rospy.Service("list_graph", ListGraph, self.handle_list_graph)
rospy.Service("roll_over_right", Trigger, self.handle_roll_over_right)
rospy.Service("roll_over_left", Trigger, self.handle_roll_over_left)
# Docking
rospy.Service("dock", Dock, self.handle_dock)
rospy.Service("undock", Trigger, self.handle_undock)
rospy.Service("docking_state", GetDockState, self.handle_get_docking_state)
# Arm Services #########################################
rospy.Service("arm_stow", Trigger, self.handle_arm_stow)
rospy.Service("arm_unstow", Trigger, self.handle_arm_unstow)
rospy.Service("gripper_open", Trigger, self.handle_gripper_open)
rospy.Service("gripper_close", Trigger, self.handle_gripper_close)
rospy.Service("arm_carry", Trigger, self.handle_arm_carry)
rospy.Service(
"gripper_angle_open", GripperAngleMove, self.handle_gripper_angle_open
)
rospy.Service("arm_joint_move", ArmJointMovement, self.handle_arm_joint_move)
rospy.Service(
"force_trajectory", ArmForceTrajectory, self.handle_force_trajectory
)
rospy.Service("gripper_pose", HandPose, self.handle_hand_pose)
rospy.Service("grasp_3d", Grasp3d, self.handle_grasp_3d)
#########################################################
self.navigate_as = actionlib.SimpleActionServer(
"navigate_to",
NavigateToAction,
execute_cb=self.handle_navigate_to,
auto_start=False,
)
self.navigate_as.start()
self.trajectory_server = actionlib.SimpleActionServer(
"trajectory",
TrajectoryAction,
execute_cb=self.handle_trajectory,
auto_start=False,
)
self.trajectory_server.start()
self.motion_or_idle_body_pose_as = actionlib.SimpleActionServer(
"motion_or_idle_body_pose",
PoseBodyAction,
execute_cb=self.handle_in_motion_or_idle_body_pose,
auto_start=False,
)
self.motion_or_idle_body_pose_as.start()
self.body_pose_as = actionlib.SimpleActionServer(
"body_pose",
PoseBodyAction,
execute_cb=self.handle_posed_stand_action,
auto_start=False,
)
self.body_pose_as.start()
self.dock_as = actionlib.SimpleActionServer(
"dock",
DockAction,
execute_cb=self.handle_dock_action,
auto_start=False,
)
self.dock_as.start()
# Stop service calls other services so initialise it after them to prevent crashes which can happen if
# the service is immediately called
rospy.Service("stop", Trigger, self.handle_stop)
rospy.Service("locked_stop", Trigger, self.handle_locked_stop)
rospy.on_shutdown(self.shutdown)
max_linear_x = rospy.get_param("~max_linear_velocity_x", 0)
max_linear_y = rospy.get_param("~max_linear_velocity_y", 0)
max_angular_z = rospy.get_param("~max_angular_velocity_z", 0)
self.set_velocity_limits(max_linear_x, max_linear_y, max_angular_z)
self.auto_claim = rospy.get_param("~auto_claim", False)
self.auto_power_on = rospy.get_param("~auto_power_on", False)
self.auto_stand = rospy.get_param("~auto_stand", False)
if self.auto_claim:
self.spot_wrapper.claim()
if self.auto_power_on:
self.spot_wrapper.power_on()
if self.auto_stand:
self.spot_wrapper.stand()
rate_limited_feedback = RateLimitedCall(
self.publish_feedback, self.rates["feedback"]
)
rate_limited_mobility_params = RateLimitedCall(
self.publish_mobility_params, self.rates["mobility_params"]
)
rate_check_for_subscriber = RateLimitedCall(
self.check_for_subscriber, self.rates["check_subscribers"]
)
rate_limited_motion_allowed = RateLimitedCall(self.publish_allow_motion, 10)
rospy.loginfo("Driver started")
while not rospy.is_shutdown():
self.spot_wrapper.updateTasks()
rate_limited_feedback()
rate_limited_mobility_params()
rate_limited_motion_allowed()
rate_check_for_subscriber()
rate.sleep()
| 78,021 | Python | 41.634973 | 135 | 0.608644 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros/spot_driver/src/spot_driver/ros_helpers.py | import copy
import rospy
import tf2_ros
import transforms3d
from std_msgs.msg import Empty
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import TransformStamped, Transform
from sensor_msgs.msg import Image, CameraInfo
from sensor_msgs.msg import JointState
from sensor_msgs.msg import PointCloud2, PointField
from geometry_msgs.msg import PoseWithCovariance
from geometry_msgs.msg import TwistWithCovariance
from geometry_msgs.msg import TwistWithCovarianceStamped
from nav_msgs.msg import Odometry
from spot_msgs.msg import Metrics
from spot_msgs.msg import LeaseArray, LeaseResource
from spot_msgs.msg import FootState, FootStateArray
from spot_msgs.msg import EStopState, EStopStateArray
from spot_msgs.msg import WiFiState
from spot_msgs.msg import PowerState
from spot_msgs.msg import BehaviorFault, BehaviorFaultState
from spot_msgs.msg import SystemFault, SystemFaultState
from spot_msgs.msg import BatteryState, BatteryStateArray
from spot_msgs.msg import DockState
from bosdyn.api import image_pb2, point_cloud_pb2
from bosdyn.client.math_helpers import SE3Pose
from bosdyn.client.frame_helpers import get_odom_tform_body, get_vision_tform_body
import numpy as np
friendly_joint_names = {}
"""Dictionary for mapping BD joint names to more friendly names"""
friendly_joint_names["fl.hx"] = "front_left_hip_x"
friendly_joint_names["fl.hy"] = "front_left_hip_y"
friendly_joint_names["fl.kn"] = "front_left_knee"
friendly_joint_names["fr.hx"] = "front_right_hip_x"
friendly_joint_names["fr.hy"] = "front_right_hip_y"
friendly_joint_names["fr.kn"] = "front_right_knee"
friendly_joint_names["hl.hx"] = "rear_left_hip_x"
friendly_joint_names["hl.hy"] = "rear_left_hip_y"
friendly_joint_names["hl.kn"] = "rear_left_knee"
friendly_joint_names["hr.hx"] = "rear_right_hip_x"
friendly_joint_names["hr.hy"] = "rear_right_hip_y"
friendly_joint_names["hr.kn"] = "rear_right_knee"
# arm joints
friendly_joint_names["arm0.sh0"] = "arm_joint1"
friendly_joint_names["arm0.sh1"] = "arm_joint2"
friendly_joint_names["arm0.el0"] = "arm_joint3"
friendly_joint_names["arm0.el1"] = "arm_joint4"
friendly_joint_names["arm0.wr0"] = "arm_joint5"
friendly_joint_names["arm0.wr1"] = "arm_joint6"
friendly_joint_names["arm0.f1x"] = "arm_gripper"
class DefaultCameraInfo(CameraInfo):
"""Blank class extending CameraInfo ROS topic that defaults most parameters"""
def __init__(self):
super().__init__()
self.distortion_model = "plumb_bob"
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.K[1] = 0
self.K[3] = 0
self.K[6] = 0
self.K[7] = 0
self.K[8] = 1
self.R[0] = 1
self.R[1] = 0
self.R[2] = 0
self.R[3] = 0
self.R[4] = 1
self.R[5] = 0
self.R[6] = 0
self.R[7] = 0
self.R[8] = 1
self.P[1] = 0
self.P[3] = 0
self.P[4] = 0
self.P[7] = 0
self.P[8] = 0
self.P[9] = 0
self.P[10] = 1
self.P[11] = 0
def populateTransformStamped(time, parent_frame, child_frame, transform):
"""Populates a TransformStamped message
Args:
time: The time of the transform
parent_frame: The parent frame of the transform
child_frame: The child_frame_id of the transform
transform: A transform to copy into a StampedTransform object. Should have position (x,y,z) and rotation (x,
y,z,w) members
Returns:
TransformStamped message. Empty if transform does not have position or translation attribute
"""
if hasattr(transform, "position"):
position = transform.position
elif hasattr(transform, "translation"):
position = transform.translation
else:
rospy.logerr(
"Trying to generate StampedTransform but input transform has neither position nor translation "
"attributes"
)
return TransformStamped()
new_tf = TransformStamped()
new_tf.header.stamp = time
new_tf.header.frame_id = parent_frame
new_tf.child_frame_id = child_frame
new_tf.transform.translation.x = position.x
new_tf.transform.translation.y = position.y
new_tf.transform.translation.z = position.z
new_tf.transform.rotation.x = transform.rotation.x
new_tf.transform.rotation.y = transform.rotation.y
new_tf.transform.rotation.z = transform.rotation.z
new_tf.transform.rotation.w = transform.rotation.w
return new_tf
def getImageMsg(data, spot_wrapper):
"""Takes the imag and camera data and populates the necessary ROS messages
Args:
data: Image proto
spot_wrapper: A SpotWrapper object
Returns:
(tuple):
* Image: message of the image captured
* CameraInfo: message to define the state and config of the camera that took the image
"""
image_msg = Image()
local_time = spot_wrapper.robotToLocalTime(data.shot.acquisition_time)
image_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
image_msg.header.frame_id = data.shot.frame_name_image_sensor
image_msg.height = data.shot.image.rows
image_msg.width = data.shot.image.cols
# Color/greyscale formats.
# JPEG format
if data.shot.image.format == image_pb2.Image.FORMAT_JPEG:
image_msg.encoding = "rgb8"
image_msg.is_bigendian = True
image_msg.step = 3 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Uncompressed. Requires pixel_format.
if data.shot.image.format == image_pb2.Image.FORMAT_RAW:
# One byte per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_GREYSCALE_U8:
image_msg.encoding = "mono8"
image_msg.is_bigendian = True
image_msg.step = data.shot.image.cols
image_msg.data = data.shot.image.data
# Three bytes per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_RGB_U8:
image_msg.encoding = "rgb8"
image_msg.is_bigendian = True
image_msg.step = 3 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Four bytes per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_RGBA_U8:
image_msg.encoding = "rgba8"
image_msg.is_bigendian = True
image_msg.step = 4 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Little-endian uint16 z-distance from camera (mm).
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_DEPTH_U16:
image_msg.encoding = "16UC1"
image_msg.is_bigendian = False
image_msg.step = 2 * data.shot.image.cols
image_msg.data = data.shot.image.data
camera_info_msg = DefaultCameraInfo()
local_time = spot_wrapper.robotToLocalTime(data.shot.acquisition_time)
camera_info_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
camera_info_msg.header.frame_id = data.shot.frame_name_image_sensor
camera_info_msg.height = data.shot.image.rows
camera_info_msg.width = data.shot.image.cols
camera_info_msg.K[0] = data.source.pinhole.intrinsics.focal_length.x
camera_info_msg.K[2] = data.source.pinhole.intrinsics.principal_point.x
camera_info_msg.K[4] = data.source.pinhole.intrinsics.focal_length.y
camera_info_msg.K[5] = data.source.pinhole.intrinsics.principal_point.y
camera_info_msg.P[0] = data.source.pinhole.intrinsics.focal_length.x
camera_info_msg.P[2] = data.source.pinhole.intrinsics.principal_point.x
camera_info_msg.P[5] = data.source.pinhole.intrinsics.focal_length.y
camera_info_msg.P[6] = data.source.pinhole.intrinsics.principal_point.y
return image_msg, camera_info_msg
def GetPointCloudMsg(data, spot_wrapper):
"""Takes the imag and camera data and populates the necessary ROS messages
Args:
data: PointCloud proto (PointCloudResponse)
spot_wrapper: A SpotWrapper object
Returns:
PointCloud: message of the point cloud (PointCloud2)
"""
point_cloud_msg = PointCloud2()
local_time = spot_wrapper.robotToLocalTime(data.point_cloud.source.acquisition_time)
point_cloud_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
point_cloud_msg.header.frame_id = data.point_cloud.source.frame_name_sensor
if data.point_cloud.encoding == point_cloud_pb2.PointCloud.ENCODING_XYZ_32F:
point_cloud_msg.height = 1
point_cloud_msg.width = data.point_cloud.num_points
point_cloud_msg.fields = []
for i, ax in enumerate(("x", "y", "z")):
field = PointField()
field.name = ax
field.offset = i * 4
field.datatype = PointField.FLOAT32
field.count = 1
point_cloud_msg.fields.append(field)
point_cloud_msg.is_bigendian = False
point_cloud_np = np.frombuffer(data.point_cloud.data, dtype=np.uint8)
point_cloud_msg.point_step = 12 # float32 XYZ
point_cloud_msg.row_step = point_cloud_msg.width * point_cloud_msg.point_step
point_cloud_msg.data = point_cloud_np.tobytes()
point_cloud_msg.is_dense = True
else:
rospy.logwarn("Not supported point cloud data type.")
return point_cloud_msg
def GetJointStatesFromState(state, spot_wrapper):
"""Maps joint state data from robot state proto to ROS JointState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
JointState message
"""
joint_state = JointState()
local_time = spot_wrapper.robotToLocalTime(
state.kinematic_state.acquisition_timestamp
)
joint_state.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
for joint in state.kinematic_state.joint_states:
# there is a joint with name arm0.hr0 in the robot state, however this
# joint has no data and should not be there, this is why we ignore it
if joint.name == "arm0.hr0":
continue
joint_state.name.append(friendly_joint_names.get(joint.name, "ERROR"))
joint_state.position.append(joint.position.value)
joint_state.velocity.append(joint.velocity.value)
joint_state.effort.append(joint.load.value)
return joint_state
def GetEStopStateFromState(state, spot_wrapper):
"""Maps eStop state data from robot state proto to ROS EStopArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
EStopArray message
"""
estop_array_msg = EStopStateArray()
for estop in state.estop_states:
estop_msg = EStopState()
local_time = spot_wrapper.robotToLocalTime(estop.timestamp)
estop_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
estop_msg.name = estop.name
estop_msg.type = estop.type
estop_msg.state = estop.state
estop_msg.state_description = estop.state_description
estop_array_msg.estop_states.append(estop_msg)
return estop_array_msg
def GetFeetFromState(state, spot_wrapper):
"""Maps foot position state data from robot state proto to ROS FootStateArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
FootStateArray message
"""
foot_array_msg = FootStateArray()
for foot in state.foot_state:
foot_msg = FootState()
foot_msg.foot_position_rt_body.x = foot.foot_position_rt_body.x
foot_msg.foot_position_rt_body.y = foot.foot_position_rt_body.y
foot_msg.foot_position_rt_body.z = foot.foot_position_rt_body.z
foot_msg.contact = foot.contact
if foot.HasField("terrain"):
terrain = foot.terrain
foot_msg.terrain.ground_mu_est = terrain.ground_mu_est
foot_msg.terrain.frame_name = terrain.frame_name
foot_msg.terrain.foot_slip_distance_rt_frame = (
terrain.foot_slip_distance_rt_frame
)
foot_msg.terrain.foot_slip_velocity_rt_frame = (
terrain.foot_slip_velocity_rt_frame
)
foot_msg.terrain.ground_contact_normal_rt_frame = (
terrain.ground_contact_normal_rt_frame
)
foot_msg.terrain.visual_surface_ground_penetration_mean = (
terrain.visual_surface_ground_penetration_mean
)
foot_msg.terrain.visual_surface_ground_penetration_std = (
terrain.visual_surface_ground_penetration_std
)
foot_array_msg.states.append(foot_msg)
return foot_array_msg
def GetOdomTwistFromState(state, spot_wrapper):
"""Maps odometry data from robot state proto to ROS TwistWithCovarianceStamped message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
TwistWithCovarianceStamped message
"""
twist_odom_msg = TwistWithCovarianceStamped()
local_time = spot_wrapper.robotToLocalTime(
state.kinematic_state.acquisition_timestamp
)
twist_odom_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
twist_odom_msg.twist.twist.linear.x = (
state.kinematic_state.velocity_of_body_in_odom.linear.x
)
twist_odom_msg.twist.twist.linear.y = (
state.kinematic_state.velocity_of_body_in_odom.linear.y
)
twist_odom_msg.twist.twist.linear.z = (
state.kinematic_state.velocity_of_body_in_odom.linear.z
)
twist_odom_msg.twist.twist.angular.x = (
state.kinematic_state.velocity_of_body_in_odom.angular.x
)
twist_odom_msg.twist.twist.angular.y = (
state.kinematic_state.velocity_of_body_in_odom.angular.y
)
twist_odom_msg.twist.twist.angular.z = (
state.kinematic_state.velocity_of_body_in_odom.angular.z
)
return twist_odom_msg
def get_corrected_odom(base_odometry: Odometry):
"""
Get odometry from state but correct the twist portion of the message to be in the child frame id rather than the
odom/vision frame. https://dev.bostondynamics.com/protos/bosdyn/api/proto_reference#kinematicstate indicates the
twist in the state is in the odom frame and not the body frame, as is expected by many ROS components.
Conversion of https://github.com/tpet/nav_utils/blob/master/src/nav_utils/odom_twist_to_child_frame.cpp
Args:
base_odometry: Uncorrected odometry message
Returns:
Odometry with twist in the body frame
"""
# Note: transforms3d has quaternions in wxyz, not xyzw like ros.
# Get the transform from body to odom/vision so we have the inverse transform, which we will use to correct the
# twist. We don't actually care about the translation at any point since we're just rotating the twist vectors
inverse_rotation = transforms3d.quaternions.quat2mat(
transforms3d.quaternions.qinverse(
[
base_odometry.pose.pose.orientation.w,
base_odometry.pose.pose.orientation.x,
base_odometry.pose.pose.orientation.y,
base_odometry.pose.pose.orientation.z,
]
)
)
# transform the linear twist by rotating the vector according to the rotation from body to odom
linear_twist = np.array(
[
[base_odometry.twist.twist.linear.x],
[base_odometry.twist.twist.linear.y],
[base_odometry.twist.twist.linear.z],
]
)
corrected_linear = inverse_rotation.dot(linear_twist)
# Do the same for the angular twist
angular_twist = np.array(
[
[base_odometry.twist.twist.angular.x],
[base_odometry.twist.twist.angular.y],
[base_odometry.twist.twist.angular.z],
]
)
corrected_angular = inverse_rotation.dot(angular_twist)
corrected_odometry = copy.deepcopy(base_odometry)
corrected_odometry.twist.twist.linear.x = corrected_linear[0][0]
corrected_odometry.twist.twist.linear.y = corrected_linear[1][0]
corrected_odometry.twist.twist.linear.z = corrected_linear[2][0]
corrected_odometry.twist.twist.angular.x = corrected_angular[0][0]
corrected_odometry.twist.twist.angular.y = corrected_angular[1][0]
corrected_odometry.twist.twist.angular.z = corrected_angular[2][0]
return corrected_odometry
def GetOdomFromState(state, spot_wrapper, use_vision=True):
"""Maps odometry data from robot state proto to ROS Odometry message
WARNING: The odometry twist from this message is in the odom frame and not in the body frame. This will likely
cause issues. You should use the odometry_corrected topic instead
Args:
state: Robot State proto
spot_wrapper: A SpotWrapper object
use_vision: If true, the odometry frame will be vision rather than odom
Returns:
Odometry message
"""
odom_msg = Odometry()
local_time = spot_wrapper.robotToLocalTime(
state.kinematic_state.acquisition_timestamp
)
odom_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
if use_vision == True:
odom_msg.header.frame_id = "vision"
tform_body = get_vision_tform_body(state.kinematic_state.transforms_snapshot)
else:
odom_msg.header.frame_id = "odom"
tform_body = get_odom_tform_body(state.kinematic_state.transforms_snapshot)
odom_msg.child_frame_id = "body"
pose_odom_msg = PoseWithCovariance()
pose_odom_msg.pose.position.x = tform_body.position.x
pose_odom_msg.pose.position.y = tform_body.position.y
pose_odom_msg.pose.position.z = tform_body.position.z
pose_odom_msg.pose.orientation.x = tform_body.rotation.x
pose_odom_msg.pose.orientation.y = tform_body.rotation.y
pose_odom_msg.pose.orientation.z = tform_body.rotation.z
pose_odom_msg.pose.orientation.w = tform_body.rotation.w
odom_msg.pose = pose_odom_msg
twist_odom_msg = GetOdomTwistFromState(state, spot_wrapper).twist
odom_msg.twist = twist_odom_msg
return odom_msg
def GetWifiFromState(state, spot_wrapper):
"""Maps wireless state data from robot state proto to ROS WiFiState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
WiFiState message
"""
wifi_msg = WiFiState()
for comm_state in state.comms_states:
if comm_state.HasField("wifi_state"):
wifi_msg.current_mode = comm_state.wifi_state.current_mode
wifi_msg.essid = comm_state.wifi_state.essid
return wifi_msg
def generate_feet_tf(foot_states_msg):
"""
Generate a tf message containing information about foot states
Args:
foot_states_msg: FootStateArray message containing the foot states from the robot state
Returns: tf message with foot states
"""
foot_ordering = ["front_left", "front_right", "rear_left", "rear_right"]
foot_tfs = TFMessage()
time_now = rospy.Time.now()
for idx, foot_state in enumerate(foot_states_msg.states):
foot_transform = Transform()
# Rotation of the foot is not given
foot_transform.rotation.w = 1
foot_transform.translation.x = foot_state.foot_position_rt_body.x
foot_transform.translation.y = foot_state.foot_position_rt_body.y
foot_transform.translation.z = foot_state.foot_position_rt_body.z
foot_tfs.transforms.append(
populateTransformStamped(
time_now, "body", foot_ordering[idx] + "_foot", foot_transform
)
)
return foot_tfs
def GetTFFromState(state, spot_wrapper, inverse_target_frame):
"""Maps robot link state data from robot state proto to ROS TFMessage message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
inverse_target_frame: A frame name to be inversed to a parent frame.
Returns:
TFMessage message
"""
tf_msg = TFMessage()
for (
frame_name
) in state.kinematic_state.transforms_snapshot.child_to_parent_edge_map:
if state.kinematic_state.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
).parent_frame_name:
try:
transform = state.kinematic_state.transforms_snapshot.child_to_parent_edge_map.get(
frame_name
)
local_time = spot_wrapper.robotToLocalTime(
state.kinematic_state.acquisition_timestamp
)
tf_time = rospy.Time(local_time.seconds, local_time.nanos)
if inverse_target_frame == frame_name:
geo_tform_inversed = SE3Pose.from_obj(
transform.parent_tform_child
).inverse()
new_tf = populateTransformStamped(
tf_time,
frame_name,
transform.parent_frame_name,
geo_tform_inversed,
)
else:
new_tf = populateTransformStamped(
tf_time,
transform.parent_frame_name,
frame_name,
transform.parent_tform_child,
)
tf_msg.transforms.append(new_tf)
except Exception as e:
spot_wrapper.logger.error("Error: {}".format(e))
return tf_msg
def GetBatteryStatesFromState(state, spot_wrapper):
"""Maps battery state data from robot state proto to ROS BatteryStateArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
BatteryStateArray message
"""
battery_states_array_msg = BatteryStateArray()
for battery in state.battery_states:
battery_msg = BatteryState()
local_time = spot_wrapper.robotToLocalTime(battery.timestamp)
battery_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
battery_msg.identifier = battery.identifier
battery_msg.charge_percentage = battery.charge_percentage.value
battery_msg.estimated_runtime = rospy.Time(
battery.estimated_runtime.seconds, battery.estimated_runtime.nanos
)
battery_msg.current = battery.current.value
battery_msg.voltage = battery.voltage.value
for temp in battery.temperatures:
battery_msg.temperatures.append(temp)
battery_msg.status = battery.status
battery_states_array_msg.battery_states.append(battery_msg)
return battery_states_array_msg
def GetPowerStatesFromState(state, spot_wrapper):
"""Maps power state data from robot state proto to ROS PowerState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
PowerState message
"""
power_state_msg = PowerState()
local_time = spot_wrapper.robotToLocalTime(state.power_state.timestamp)
power_state_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
power_state_msg.motor_power_state = state.power_state.motor_power_state
power_state_msg.shore_power_state = state.power_state.shore_power_state
power_state_msg.locomotion_charge_percentage = (
state.power_state.locomotion_charge_percentage.value
)
power_state_msg.locomotion_estimated_runtime = rospy.Time(
state.power_state.locomotion_estimated_runtime.seconds,
state.power_state.locomotion_estimated_runtime.nanos,
)
return power_state_msg
def GetDockStatesFromState(state):
"""Maps dock state data from robot state proto to ROS DockState message
Args:
state: Robot State proto
Returns:
DockState message
"""
dock_state_msg = DockState()
dock_state_msg.status = state.status
dock_state_msg.dock_type = state.dock_type
dock_state_msg.dock_id = state.dock_id
dock_state_msg.power_status = state.power_status
return dock_state_msg
def getBehaviorFaults(behavior_faults, spot_wrapper):
"""Helper function to strip out behavior faults into a list
Args:
behavior_faults: List of BehaviorFaults
spot_wrapper: A SpotWrapper object
Returns:
List of BehaviorFault messages
"""
faults = []
for fault in behavior_faults:
new_fault = BehaviorFault()
new_fault.behavior_fault_id = fault.behavior_fault_id
local_time = spot_wrapper.robotToLocalTime(fault.onset_timestamp)
new_fault.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_fault.cause = fault.cause
new_fault.status = fault.status
faults.append(new_fault)
return faults
def getSystemFaults(system_faults, spot_wrapper):
"""Helper function to strip out system faults into a list
Args:
systen_faults: List of SystemFaults
spot_wrapper: A SpotWrapper object
Returns:
List of SystemFault messages
"""
faults = []
for fault in system_faults:
new_fault = SystemFault()
new_fault.name = fault.name
local_time = spot_wrapper.robotToLocalTime(fault.onset_timestamp)
new_fault.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_fault.duration = rospy.Time(fault.duration.seconds, fault.duration.nanos)
new_fault.code = fault.code
new_fault.uid = fault.uid
new_fault.error_message = fault.error_message
for att in fault.attributes:
new_fault.attributes.append(att)
new_fault.severity = fault.severity
faults.append(new_fault)
return faults
def GetSystemFaultsFromState(state, spot_wrapper):
"""Maps system fault data from robot state proto to ROS SystemFaultState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
SystemFaultState message
"""
system_fault_state_msg = SystemFaultState()
system_fault_state_msg.faults = getSystemFaults(
state.system_fault_state.faults, spot_wrapper
)
system_fault_state_msg.historical_faults = getSystemFaults(
state.system_fault_state.historical_faults, spot_wrapper
)
return system_fault_state_msg
def getBehaviorFaultsFromState(state, spot_wrapper):
"""Maps behavior fault data from robot state proto to ROS BehaviorFaultState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
BehaviorFaultState message
"""
behavior_fault_state_msg = BehaviorFaultState()
behavior_fault_state_msg.faults = getBehaviorFaults(
state.behavior_fault_state.faults, spot_wrapper
)
return behavior_fault_state_msg
| 26,982 | Python | 35.963014 | 116 | 0.662812 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros/docs/conf.py | # -*- coding: utf-8 -*-
import os
import sys
import xml.etree.ElementTree as etree
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.viewcode",
]
source_suffix = ".rst"
master_doc = "index"
project = "Spot ROS User Documentation"
copyright = "2020, Clearpath Robotics, 2023 Oxford Robotics Institute"
# Get version number from package.xml.
tree = etree.parse("../spot_driver/package.xml")
version = tree.find("version").text
release = version
# .. html_theme = 'nature'
# .. html_theme_path = ["."]
html_theme = "sphinx_rtd_theme"
html_theme_path = ["."]
html_sidebars = {"**": ["sidebartoc.html", "sourcelink.html", "searchbox.html"]}
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"SpotROSUserDocumentation.tex",
"Spot ROS User Documentation",
"Dave Niewinski, Michal Staniaszek",
"manual",
),
]
| 1,895 | Python | 25.333333 | 80 | 0.636939 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros-CHAMP/spot_driver/scripts/__init__.py | import spot_ros
import spot_wrapper.py
import ros_helpers.py
| 61 | Python | 14.499996 | 22 | 0.819672 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros-CHAMP/spot_driver/scripts/spot_ros.py | #!/usr/bin/env python3
import rospy
from std_srvs.srv import Trigger, TriggerResponse
from std_msgs.msg import Bool
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import TransformStamped
from sensor_msgs.msg import Image, CameraInfo
from sensor_msgs.msg import JointState
from geometry_msgs.msg import TwistWithCovarianceStamped, Twist, Pose
from bosdyn.api.geometry_pb2 import Quaternion
import bosdyn.geometry
from spot_msgs.msg import Metrics
from spot_msgs.msg import LeaseArray, LeaseResource
from spot_msgs.msg import FootState, FootStateArray
from spot_msgs.msg import EStopState, EStopStateArray
from spot_msgs.msg import WiFiState
from spot_msgs.msg import PowerState
from spot_msgs.msg import BehaviorFault, BehaviorFaultState
from spot_msgs.msg import SystemFault, SystemFaultState
from spot_msgs.msg import BatteryState, BatteryStateArray
from spot_msgs.msg import Feedback
from ros_helpers import *
from spot_wrapper import SpotWrapper
import logging
class SpotROS():
"""Parent class for using the wrapper. Defines all callbacks and keeps the wrapper alive"""
def __init__(self):
self.spot_wrapper = None
self.callbacks = {}
"""Dictionary listing what callback to use for what data task"""
self.callbacks["robot_state"] = self.RobotStateCB
self.callbacks["metrics"] = self.MetricsCB
self.callbacks["lease"] = self.LeaseCB
self.callbacks["front_image"] = self.FrontImageCB
self.callbacks["side_image"] = self.SideImageCB
self.callbacks["rear_image"] = self.RearImageCB
def RobotStateCB(self, results):
"""Callback for when the Spot Wrapper gets new robot state data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
state = self.spot_wrapper.robot_state
if state:
## joint states ##
joint_state = GetJointStatesFromState(state, self.spot_wrapper)
self.joint_state_pub.publish(joint_state)
## TF ##
tf_msg = GetTFFromState(state, self.spot_wrapper)
if len(tf_msg.transforms) > 0:
self.tf_pub.publish(tf_msg)
# Odom Twist #
twist_odom_msg = GetOdomTwistFromState(state, self.spot_wrapper)
self.odom_twist_pub.publish(twist_odom_msg)
# Feet #
foot_array_msg = GetFeetFromState(state, self.spot_wrapper)
self.feet_pub.publish(foot_array_msg)
# EStop #
estop_array_msg = GetEStopStateFromState(state, self.spot_wrapper)
self.estop_pub.publish(estop_array_msg)
# WIFI #
wifi_msg = GetWifiFromState(state, self.spot_wrapper)
self.wifi_pub.publish(wifi_msg)
# Battery States #
battery_states_array_msg = GetBatteryStatesFromState(state, self.spot_wrapper)
self.battery_pub.publish(battery_states_array_msg)
# Power State #
power_state_msg = GetPowerStatesFromState(state, self.spot_wrapper)
self.power_pub.publish(power_state_msg)
# System Faults #
system_fault_state_msg = GetSystemFaultsFromState(state, self.spot_wrapper)
self.system_faults_pub.publish(system_fault_state_msg)
# Behavior Faults #
behavior_fault_state_msg = getBehaviorFaultsFromState(state, self.spot_wrapper)
self.behavior_faults_pub.publish(behavior_fault_state_msg)
def MetricsCB(self, results):
"""Callback for when the Spot Wrapper gets new metrics data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
metrics = self.spot_wrapper.metrics
if metrics:
metrics_msg = Metrics()
local_time = self.spot_wrapper.robotToLocalTime(metrics.timestamp)
metrics_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
for metric in metrics.metrics:
if metric.label == "distance":
metrics_msg.distance = metric.float_value
if metric.label == "gait cycles":
metrics_msg.gait_cycles = metric.int_value
if metric.label == "time moving":
metrics_msg.time_moving = rospy.Time(metric.duration.seconds, metric.duration.nanos)
if metric.label == "electric power":
metrics_msg.electric_power = rospy.Time(metric.duration.seconds, metric.duration.nanos)
self.metrics_pub.publish(metrics_msg)
def LeaseCB(self, results):
"""Callback for when the Spot Wrapper gets new lease data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
lease_array_msg = LeaseArray()
lease_list = self.spot_wrapper.lease
if lease_list:
for resource in lease_list:
new_resource = LeaseResource()
new_resource.resource = resource.resource
new_resource.lease.resource = resource.lease.resource
new_resource.lease.epoch = resource.lease.epoch
for seq in resource.lease.sequence:
new_resource.lease.sequence.append(seq)
new_resource.lease_owner.client_name = resource.lease_owner.client_name
new_resource.lease_owner.user_name = resource.lease_owner.user_name
lease_array_msg.resources.append(new_resource)
self.lease_pub.publish(lease_array_msg)
def FrontImageCB(self, results):
"""Callback for when the Spot Wrapper gets new front image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.front_images
if data:
image_msg0, camera_info_msg0, camera_tf_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.frontleft_image_pub.publish(image_msg0)
self.frontleft_image_info_pub.publish(camera_info_msg0)
self.tf_pub.publish(camera_tf_msg0)
image_msg1, camera_info_msg1, camera_tf_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.frontright_image_pub.publish(image_msg1)
self.frontright_image_info_pub.publish(camera_info_msg1)
self.tf_pub.publish(camera_tf_msg1)
image_msg2, camera_info_msg2, camera_tf_msg2 = getImageMsg(data[2], self.spot_wrapper)
self.frontleft_depth_pub.publish(image_msg2)
self.frontleft_depth_info_pub.publish(camera_info_msg2)
self.tf_pub.publish(camera_tf_msg2)
image_msg3, camera_info_msg3, camera_tf_msg3 = getImageMsg(data[3], self.spot_wrapper)
self.frontright_depth_pub.publish(image_msg3)
self.frontright_depth_info_pub.publish(camera_info_msg3)
self.tf_pub.publish(camera_tf_msg3)
def SideImageCB(self, results):
"""Callback for when the Spot Wrapper gets new side image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.side_images
if data:
image_msg0, camera_info_msg0, camera_tf_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.left_image_pub.publish(image_msg0)
self.left_image_info_pub.publish(camera_info_msg0)
self.tf_pub.publish(camera_tf_msg0)
image_msg1, camera_info_msg1, camera_tf_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.right_image_pub.publish(image_msg1)
self.right_image_info_pub.publish(camera_info_msg1)
self.tf_pub.publish(camera_tf_msg1)
image_msg2, camera_info_msg2, camera_tf_msg2 = getImageMsg(data[2], self.spot_wrapper)
self.left_depth_pub.publish(image_msg2)
self.left_depth_info_pub.publish(camera_info_msg2)
self.tf_pub.publish(camera_tf_msg2)
image_msg3, camera_info_msg3, camera_tf_msg3 = getImageMsg(data[3], self.spot_wrapper)
self.right_depth_pub.publish(image_msg3)
self.right_depth_info_pub.publish(camera_info_msg3)
self.tf_pub.publish(camera_tf_msg3)
def RearImageCB(self, results):
"""Callback for when the Spot Wrapper gets new rear image data.
Args:
results: FutureWrapper object of AsyncPeriodicQuery callback
"""
data = self.spot_wrapper.rear_images
if data:
mage_msg0, camera_info_msg0, camera_tf_msg0 = getImageMsg(data[0], self.spot_wrapper)
self.back_image_pub.publish(mage_msg0)
self.back_image_info_pub.publish(camera_info_msg0)
self.tf_pub.publish(camera_tf_msg0)
mage_msg1, camera_info_msg1, camera_tf_msg1 = getImageMsg(data[1], self.spot_wrapper)
self.back_depth_pub.publish(mage_msg1)
self.back_depth_info_pub.publish(camera_info_msg1)
self.tf_pub.publish(camera_tf_msg1)
def handle_claim(self, req):
"""ROS service handler for the claim service"""
resp = self.spot_wrapper.claim()
return TriggerResponse(resp[0], resp[1])
def handle_release(self, req):
"""ROS service handler for the release service"""
resp = self.spot_wrapper.release()
return TriggerResponse(resp[0], resp[1])
def handle_stop(self, req):
"""ROS service handler for the stop service"""
resp = self.spot_wrapper.stop()
return TriggerResponse(resp[0], resp[1])
def handle_self_right(self, req):
"""ROS service handler for the self-right service"""
resp = self.spot_wrapper.self_right()
return TriggerResponse(resp[0], resp[1])
def handle_sit(self, req):
"""ROS service handler for the sit service"""
resp = self.spot_wrapper.sit()
return TriggerResponse(resp[0], resp[1])
def handle_stand(self, req):
"""ROS service handler for the stand service"""
resp = self.spot_wrapper.stand()
return TriggerResponse(resp[0], resp[1])
def handle_power_on(self, req):
"""ROS service handler for the power-on service"""
resp = self.spot_wrapper.power_on()
return TriggerResponse(resp[0], resp[1])
def handle_safe_power_off(self, req):
"""ROS service handler for the safe-power-off service"""
resp = self.spot_wrapper.safe_power_off()
return TriggerResponse(resp[0], resp[1])
def handle_estop_hard(self, req):
"""ROS service handler to hard-eStop the robot. The robot will immediately cut power to the motors"""
resp = self.spot_wrapper.assertEStop(True)
return TriggerResponse(resp[0], resp[1])
def handle_estop_soft(self, req):
"""ROS service handler to soft-eStop the robot. The robot will try to settle on the ground before cutting power to the motors"""
resp = self.spot_wrapper.assertEStop(False)
return TriggerResponse(resp[0], resp[1])
def cmdVelCallback(self, data):
"""Callback for cmd_vel command"""
self.spot_wrapper.velocity_cmd(data.linear.x, data.linear.y, data.angular.z)
def bodyPoseCallback(self, data):
"""Callback for cmd_vel command"""
q = Quaternion()
q.x = data.orientation.x
q.y = data.orientation.y
q.z = data.orientation.z
q.w = data.orientation.w
euler_zxy = q.to_euler_zxy()
self.spot_wrapper.set_mobility_params(data.position.z, euler_zxy)
def shutdown(self):
rospy.loginfo("Shutting down ROS driver for Spot")
self.spot_wrapper.sit()
rospy.Rate(0.25).sleep()
self.spot_wrapper.disconnect()
def main(self):
"""Main function for the SpotROS class. Gets config from ROS and initializes the wrapper. Holds lease from wrapper and updates all async tasks at the ROS rate"""
rospy.init_node('spot_ros', anonymous=True)
rate = rospy.Rate(50)
self.rates = rospy.get_param('~rates', {})
self.username = rospy.get_param('~username', 'default_value')
self.password = rospy.get_param('~password', 'default_value')
self.app_token = rospy.get_param('~app_token', 'default_value')
self.hostname = rospy.get_param('~hostname', 'default_value')
self.motion_deadzone = rospy.get_param('~deadzone', 0.05)
self.logger = logging.getLogger('rosout')
rospy.loginfo("Starting ROS driver for Spot")
self.spot_wrapper = SpotWrapper(self.username, self.password, self.app_token, self.hostname, self.logger, self.rates, self.callbacks)
if self.spot_wrapper.is_valid:
# Images #
self.back_image_pub = rospy.Publisher('camera/back/image', Image, queue_size=10)
self.frontleft_image_pub = rospy.Publisher('camera/frontleft/image', Image, queue_size=10)
self.frontright_image_pub = rospy.Publisher('camera/frontright/image', Image, queue_size=10)
self.left_image_pub = rospy.Publisher('camera/left/image', Image, queue_size=10)
self.right_image_pub = rospy.Publisher('camera/right/image', Image, queue_size=10)
# Depth #
self.back_depth_pub = rospy.Publisher('depth/back/image', Image, queue_size=10)
self.frontleft_depth_pub = rospy.Publisher('depth/frontleft/image', Image, queue_size=10)
self.frontright_depth_pub = rospy.Publisher('depth/frontright/image', Image, queue_size=10)
self.left_depth_pub = rospy.Publisher('depth/left/image', Image, queue_size=10)
self.right_depth_pub = rospy.Publisher('depth/right/image', Image, queue_size=10)
# Image Camera Info #
self.back_image_info_pub = rospy.Publisher('camera/back/camera_info', CameraInfo, queue_size=10)
self.frontleft_image_info_pub = rospy.Publisher('camera/frontleft/camera_info', CameraInfo, queue_size=10)
self.frontright_image_info_pub = rospy.Publisher('camera/frontright/camera_info', CameraInfo, queue_size=10)
self.left_image_info_pub = rospy.Publisher('camera/left/camera_info', CameraInfo, queue_size=10)
self.right_image_info_pub = rospy.Publisher('camera/right/camera_info', CameraInfo, queue_size=10)
# Depth Camera Info #
self.back_depth_info_pub = rospy.Publisher('depth/back/camera_info', CameraInfo, queue_size=10)
self.frontleft_depth_info_pub = rospy.Publisher('depth/frontleft/camera_info', CameraInfo, queue_size=10)
self.frontright_depth_info_pub = rospy.Publisher('depth/frontright/camera_info', CameraInfo, queue_size=10)
self.left_depth_info_pub = rospy.Publisher('depth/left/camera_info', CameraInfo, queue_size=10)
self.right_depth_info_pub = rospy.Publisher('depth/right/camera_info', CameraInfo, queue_size=10)
# Status Publishers #
self.joint_state_pub = rospy.Publisher('joint_states', JointState, queue_size=10)
"""Defining a TF publisher manually because of conflicts between Python3 and tf"""
self.tf_pub = rospy.Publisher('tf', TFMessage, queue_size=10)
self.metrics_pub = rospy.Publisher('status/metrics', Metrics, queue_size=10)
self.lease_pub = rospy.Publisher('status/leases', LeaseArray, queue_size=10)
self.odom_twist_pub = rospy.Publisher('odometry/twist', TwistWithCovarianceStamped, queue_size=10)
self.feet_pub = rospy.Publisher('status/feet', FootStateArray, queue_size=10)
self.estop_pub = rospy.Publisher('status/estop', EStopStateArray, queue_size=10)
self.wifi_pub = rospy.Publisher('status/wifi', WiFiState, queue_size=10)
self.power_pub = rospy.Publisher('status/power_state', PowerState, queue_size=10)
self.battery_pub = rospy.Publisher('status/battery_states', BatteryStateArray, queue_size=10)
self.behavior_faults_pub = rospy.Publisher('status/behavior_faults', BehaviorFaultState, queue_size=10)
self.system_faults_pub = rospy.Publisher('status/system_faults', SystemFaultState, queue_size=10)
self.feedback_pub = rospy.Publisher('status/feedback', Feedback, queue_size=10)
rospy.Subscriber('cmd_vel', Twist, self.cmdVelCallback)
rospy.Subscriber('body_pose', Pose, self.bodyPoseCallback)
rospy.Service("claim", Trigger, self.handle_claim)
rospy.Service("release", Trigger, self.handle_release)
rospy.Service("stop", Trigger, self.handle_stop)
rospy.Service("self_right", Trigger, self.handle_self_right)
rospy.Service("sit", Trigger, self.handle_sit)
rospy.Service("stand", Trigger, self.handle_stand)
rospy.Service("power_on", Trigger, self.handle_power_on)
rospy.Service("power_off", Trigger, self.handle_safe_power_off)
rospy.Service("estop/hard", Trigger, self.handle_estop_hard)
rospy.Service("estop/gentle", Trigger, self.handle_estop_soft)
rospy.on_shutdown(self.shutdown)
self.spot_wrapper.resetEStop()
self.auto_claim = rospy.get_param('~auto_claim', False)
self.auto_power_on = rospy.get_param('~auto_power_on', False)
self.auto_stand = rospy.get_param('~auto_stand', False)
if self.auto_claim:
self.spot_wrapper.claim()
if self.auto_power_on:
self.spot_wrapper.power_on()
if self.auto_stand:
self.spot_wrapper.stand()
while not rospy.is_shutdown():
self.spot_wrapper.updateTasks()
feedback_msg = Feedback()
feedback_msg.standing = self.spot_wrapper.is_standing
feedback_msg.sitting = self.spot_wrapper.is_sitting
feedback_msg.moving = self.spot_wrapper.is_moving
id = self.spot_wrapper.id
try:
feedback_msg.serial_number = id.serial_number
feedback_msg.species = id.species
feedback_msg.version = id.version
feedback_msg.nickname = id.nickname
feedback_msg.computer_serial_number = id.computer_serial_number
except:
pass
self.feedback_pub.publish(feedback_msg)
rate.sleep()
if __name__ == "__main__":
SR = SpotROS()
SR.main()
| 18,644 | Python | 46.202532 | 171 | 0.637041 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros-CHAMP/spot_driver/scripts/ros_helpers.py | import rospy
from std_msgs.msg import Empty
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import TransformStamped
from sensor_msgs.msg import Image, CameraInfo
from sensor_msgs.msg import JointState
from geometry_msgs.msg import TwistWithCovarianceStamped
from spot_msgs.msg import Metrics
from spot_msgs.msg import LeaseArray, LeaseResource
from spot_msgs.msg import FootState, FootStateArray
from spot_msgs.msg import EStopState, EStopStateArray
from spot_msgs.msg import WiFiState
from spot_msgs.msg import PowerState
from spot_msgs.msg import BehaviorFault, BehaviorFaultState
from spot_msgs.msg import SystemFault, SystemFaultState
from spot_msgs.msg import BatteryState, BatteryStateArray
from bosdyn.api import image_pb2
friendly_joint_names = {}
"""Dictionary for mapping BD joint names to more friendly names"""
friendly_joint_names["fl.hx"] = "front_left_hip_x"
friendly_joint_names["fl.hy"] = "front_left_hip_y"
friendly_joint_names["fl.kn"] = "front_left_knee"
friendly_joint_names["fr.hx"] = "front_right_hip_x"
friendly_joint_names["fr.hy"] = "front_right_hip_y"
friendly_joint_names["fr.kn"] = "front_right_knee"
friendly_joint_names["hl.hx"] = "rear_left_hip_x"
friendly_joint_names["hl.hy"] = "rear_left_hip_y"
friendly_joint_names["hl.kn"] = "rear_left_knee"
friendly_joint_names["hr.hx"] = "rear_right_hip_x"
friendly_joint_names["hr.hy"] = "rear_right_hip_y"
friendly_joint_names["hr.kn"] = "rear_right_knee"
class DefaultCameraInfo(CameraInfo):
"""Blank class extending CameraInfo ROS topic that defaults most parameters"""
def __init__(self):
super().__init__()
self.distortion_model = "plumb_bob"
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.D.append(0)
self.K[1] = 0
self.K[3] = 0
self.K[6] = 0
self.K[7] = 0
self.K[8] = 1
self.R[0] = 1
self.R[1] = 0
self.R[2] = 0
self.R[3] = 0
self.R[4] = 1
self.R[5] = 0
self.R[6] = 0
self.R[7] = 0
self.R[8] = 1
self.P[1] = 0
self.P[3] = 0
self.P[4] = 0
self.P[7] = 0
self.P[8] = 0
self.P[9] = 0
self.P[10] = 1
self.P[11] = 0
def getImageMsg(data, spot_wrapper):
"""Takes the image, camera, and TF data and populates the necessary ROS messages
Args:
data: Image proto
spot_wrapper: A SpotWrapper object
Returns:
(tuple):
* Image: message of the image captured
* CameraInfo: message to define the state and config of the camera that took the image
* TFMessage: with the transforms necessary to locate the image frames
"""
tf_msg = TFMessage()
for frame_name in data.shot.transforms_snapshot.child_to_parent_edge_map:
if data.shot.transforms_snapshot.child_to_parent_edge_map.get(frame_name).parent_frame_name:
transform = data.shot.transforms_snapshot.child_to_parent_edge_map.get(frame_name)
new_tf = TransformStamped()
local_time = spot_wrapper.robotToLocalTime(data.shot.acquisition_time)
new_tf.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_tf.header.frame_id = transform.parent_frame_name
new_tf.child_frame_id = frame_name
new_tf.transform.translation.x = transform.parent_tform_child.position.x
new_tf.transform.translation.y = transform.parent_tform_child.position.y
new_tf.transform.translation.z = transform.parent_tform_child.position.z
new_tf.transform.rotation.x = transform.parent_tform_child.rotation.x
new_tf.transform.rotation.y = transform.parent_tform_child.rotation.y
new_tf.transform.rotation.z = transform.parent_tform_child.rotation.z
new_tf.transform.rotation.w = transform.parent_tform_child.rotation.w
tf_msg.transforms.append(new_tf)
image_msg = Image()
local_time = spot_wrapper.robotToLocalTime(data.shot.acquisition_time)
image_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
image_msg.header.frame_id = data.shot.frame_name_image_sensor
image_msg.height = data.shot.image.rows
image_msg.width = data.shot.image.cols
# Color/greyscale formats.
# JPEG format
if data.shot.image.format == image_pb2.Image.FORMAT_JPEG:
image_msg.encoding = "rgb8"
image_msg.is_bigendian = True
image_msg.step = 3 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Uncompressed. Requires pixel_format.
if data.shot.image.format == image_pb2.Image.FORMAT_RAW:
# One byte per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_GREYSCALE_U8:
image_msg.encoding = "mono8"
image_msg.is_bigendian = True
image_msg.step = data.shot.image.cols
image_msg.data = data.shot.image.data
# Three bytes per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_RGB_U8:
image_msg.encoding = "rgb8"
image_msg.is_bigendian = True
image_msg.step = 3 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Four bytes per pixel.
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_RGBA_U8:
image_msg.encoding = "rgba8"
image_msg.is_bigendian = True
image_msg.step = 4 * data.shot.image.cols
image_msg.data = data.shot.image.data
# Little-endian uint16 z-distance from camera (mm).
if data.shot.image.pixel_format == image_pb2.Image.PIXEL_FORMAT_DEPTH_U16:
image_msg.encoding = "mono16"
image_msg.is_bigendian = False
image_msg.step = 2 * data.shot.image.cols
image_msg.data = data.shot.image.data
camera_info_msg = DefaultCameraInfo()
local_time = spot_wrapper.robotToLocalTime(data.shot.acquisition_time)
camera_info_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
camera_info_msg.header.frame_id = data.shot.frame_name_image_sensor
camera_info_msg.height = data.shot.image.rows
camera_info_msg.width = data.shot.image.cols
camera_info_msg.K[0] = data.source.pinhole.intrinsics.focal_length.x
camera_info_msg.K[2] = data.source.pinhole.intrinsics.principal_point.x
camera_info_msg.K[4] = data.source.pinhole.intrinsics.focal_length.y
camera_info_msg.K[5] = data.source.pinhole.intrinsics.principal_point.y
camera_info_msg.P[0] = data.source.pinhole.intrinsics.focal_length.x
camera_info_msg.P[2] = data.source.pinhole.intrinsics.principal_point.x
camera_info_msg.P[5] = data.source.pinhole.intrinsics.focal_length.y
camera_info_msg.P[6] = data.source.pinhole.intrinsics.principal_point.y
return image_msg, camera_info_msg, tf_msg
def GetJointStatesFromState(state, spot_wrapper):
"""Maps joint state data from robot state proto to ROS JointState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
JointState message
"""
joint_state = JointState()
local_time = spot_wrapper.robotToLocalTime(state.kinematic_state.acquisition_timestamp)
joint_state.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
for joint in state.kinematic_state.joint_states:
joint_state.name.append(friendly_joint_names.get(joint.name, "ERROR"))
joint_state.position.append(joint.position.value)
joint_state.velocity.append(joint.velocity.value)
joint_state.effort.append(joint.load.value)
return joint_state
def GetEStopStateFromState(state, spot_wrapper):
"""Maps eStop state data from robot state proto to ROS EStopArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
EStopArray message
"""
estop_array_msg = EStopStateArray()
for estop in state.estop_states:
estop_msg = EStopState()
local_time = spot_wrapper.robotToLocalTime(estop.timestamp)
estop_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
estop_msg.name = estop.name
estop_msg.type = estop.type
estop_msg.state = estop.state
estop_array_msg.estop_states.append(estop_msg)
return estop_array_msg
def GetFeetFromState(state, spot_wrapper):
"""Maps foot position state data from robot state proto to ROS FootStateArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
FootStateArray message
"""
foot_array_msg = FootStateArray()
for foot in state.foot_state:
foot_msg = FootState()
foot_msg.foot_position_rt_body.x = foot.foot_position_rt_body.x
foot_msg.foot_position_rt_body.y = foot.foot_position_rt_body.y
foot_msg.foot_position_rt_body.z = foot.foot_position_rt_body.z
foot_msg.contact = foot.contact
foot_array_msg.states.append(foot_msg)
return foot_array_msg
def GetOdomTwistFromState(state, spot_wrapper):
"""Maps odometry data from robot state proto to ROS TwistWithCovarianceStamped message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
TwistWithCovarianceStamped message
"""
twist_odom_msg = TwistWithCovarianceStamped()
local_time = spot_wrapper.robotToLocalTime(state.kinematic_state.acquisition_timestamp)
twist_odom_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
twist_odom_msg.twist.twist.linear.x = state.kinematic_state.velocity_of_body_in_odom.linear.x
twist_odom_msg.twist.twist.linear.y = state.kinematic_state.velocity_of_body_in_odom.linear.y
twist_odom_msg.twist.twist.linear.z = state.kinematic_state.velocity_of_body_in_odom.linear.z
twist_odom_msg.twist.twist.angular.x = state.kinematic_state.velocity_of_body_in_odom.angular.x
twist_odom_msg.twist.twist.angular.y = state.kinematic_state.velocity_of_body_in_odom.angular.y
twist_odom_msg.twist.twist.angular.z = state.kinematic_state.velocity_of_body_in_odom.angular.z
return twist_odom_msg
def GetWifiFromState(state, spot_wrapper):
"""Maps wireless state data from robot state proto to ROS WiFiState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
WiFiState message
"""
wifi_msg = WiFiState()
for comm_state in state.comms_states:
if comm_state.HasField('wifi_state'):
wifi_msg.current_mode = comm_state.wifi_state.current_mode
wifi_msg.essid = comm_state.wifi_state.essid
return wifi_msg
def GetTFFromState(state, spot_wrapper):
"""Maps robot link state data from robot state proto to ROS TFMessage message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
TFMessage message
"""
tf_msg = TFMessage()
for frame_name in state.kinematic_state.transforms_snapshot.child_to_parent_edge_map:
if state.kinematic_state.transforms_snapshot.child_to_parent_edge_map.get(frame_name).parent_frame_name:
transform = state.kinematic_state.transforms_snapshot.child_to_parent_edge_map.get(frame_name)
new_tf = TransformStamped()
local_time = spot_wrapper.robotToLocalTime(state.kinematic_state.acquisition_timestamp)
new_tf.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_tf.header.frame_id = transform.parent_frame_name
new_tf.child_frame_id = frame_name
new_tf.transform.translation.x = transform.parent_tform_child.position.x
new_tf.transform.translation.y = transform.parent_tform_child.position.y
new_tf.transform.translation.z = transform.parent_tform_child.position.z
new_tf.transform.rotation.x = transform.parent_tform_child.rotation.x
new_tf.transform.rotation.y = transform.parent_tform_child.rotation.y
new_tf.transform.rotation.z = transform.parent_tform_child.rotation.z
new_tf.transform.rotation.w = transform.parent_tform_child.rotation.w
tf_msg.transforms.append(new_tf)
return tf_msg
def GetBatteryStatesFromState(state, spot_wrapper):
"""Maps battery state data from robot state proto to ROS BatteryStateArray message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
BatteryStateArray message
"""
battery_states_array_msg = BatteryStateArray()
for battery in state.battery_states:
battery_msg = BatteryState()
local_time = spot_wrapper.robotToLocalTime(battery.timestamp)
battery_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
battery_msg.identifier = battery.identifier
battery_msg.charge_percentage = battery.charge_percentage.value
battery_msg.estimated_runtime = rospy.Time(battery.estimated_runtime.seconds, battery.estimated_runtime.nanos)
battery_msg.current = battery.current.value
battery_msg.voltage = battery.voltage.value
for temp in battery.temperatures:
battery_msg.temperatures.append(temp)
battery_msg.status = battery.status
battery_states_array_msg.battery_states.append(battery_msg)
return battery_states_array_msg
def GetPowerStatesFromState(state, spot_wrapper):
"""Maps power state data from robot state proto to ROS PowerState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
PowerState message
"""
power_state_msg = PowerState()
local_time = spot_wrapper.robotToLocalTime(state.power_state.timestamp)
power_state_msg.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
power_state_msg.motor_power_state = state.power_state.motor_power_state
power_state_msg.shore_power_state = state.power_state.shore_power_state
power_state_msg.locomotion_charge_percentage = state.power_state.locomotion_charge_percentage.value
power_state_msg.locomotion_estimated_runtime = rospy.Time(state.power_state.locomotion_estimated_runtime.seconds, state.power_state.locomotion_estimated_runtime.nanos)
return power_state_msg
def getBehaviorFaults(behavior_faults, spot_wrapper):
"""Helper function to strip out behavior faults into a list
Args:
behavior_faults: List of BehaviorFaults
spot_wrapper: A SpotWrapper object
Returns:
List of BehaviorFault messages
"""
faults = []
for fault in behavior_faults:
new_fault = BehaviorFault()
new_fault.behavior_fault_id = fault.behavior_fault_id
local_time = spot_wrapper.robotToLocalTime(fault.onset_timestamp)
new_fault.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_fault.cause = fault.cause
new_fault.status = fault.status
faults.append(new_fault)
return faults
def getSystemFaults(system_faults, spot_wrapper):
"""Helper function to strip out system faults into a list
Args:
systen_faults: List of SystemFaults
spot_wrapper: A SpotWrapper object
Returns:
List of SystemFault messages
"""
faults = []
for fault in system_faults:
new_fault = SystemFault()
new_fault.name = fault.name
local_time = spot_wrapper.robotToLocalTime(fault.onset_timestamp)
new_fault.header.stamp = rospy.Time(local_time.seconds, local_time.nanos)
new_fault.duration = rospy.Time(fault.duration.seconds, fault.duration.nanos)
new_fault.code = fault.code
new_fault.uid = fault.uid
new_fault.error_message = fault.error_message
for att in fault.attributes:
new_fault.attributes.append(att)
new_fault.severity = fault.severity
faults.append(new_fault)
return faults
def GetSystemFaultsFromState(state, spot_wrapper):
"""Maps system fault data from robot state proto to ROS SystemFaultState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
SystemFaultState message
"""
system_fault_state_msg = SystemFaultState()
system_fault_state_msg.faults = getSystemFaults(state.system_fault_state.faults, spot_wrapper)
system_fault_state_msg.historical_faults = getSystemFaults(state.system_fault_state.historical_faults, spot_wrapper)
return system_fault_state_msg
def getBehaviorFaultsFromState(state, spot_wrapper):
"""Maps behavior fault data from robot state proto to ROS BehaviorFaultState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
BehaviorFaultState message
"""
behavior_fault_state_msg = BehaviorFaultState()
behavior_fault_state_msg.faults = getBehaviorFaults(state.behavior_fault_state.faults, spot_wrapper)
return behavior_fault_state_msg
| 17,178 | Python | 40.098086 | 171 | 0.685295 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros-CHAMP/spot_driver/scripts/spot_wrapper.py | import time
from bosdyn.client import create_standard_sdk, ResponseError, RpcError
from bosdyn.client.async_tasks import AsyncPeriodicQuery, AsyncTasks
from bosdyn.geometry import EulerZXY
from bosdyn.client.robot_state import RobotStateClient
from bosdyn.client.robot_command import RobotCommandClient, RobotCommandBuilder
from bosdyn.client.power import PowerClient
from bosdyn.client.lease import LeaseClient, LeaseKeepAlive
from bosdyn.client.image import ImageClient, build_image_request
from bosdyn.api import image_pb2
from bosdyn.client.estop import EstopClient, EstopEndpoint, EstopKeepAlive
from bosdyn.client import power
import bosdyn.api.robot_state_pb2 as robot_state_proto
from bosdyn.api import basic_command_pb2
from google.protobuf.timestamp_pb2 import Timestamp
front_image_sources = ['frontleft_fisheye_image', 'frontright_fisheye_image', 'frontleft_depth', 'frontright_depth']
"""List of image sources for front image periodic query"""
side_image_sources = ['left_fisheye_image', 'right_fisheye_image', 'left_depth', 'right_depth']
"""List of image sources for side image periodic query"""
rear_image_sources = ['back_fisheye_image', 'back_depth']
"""List of image sources for rear image periodic query"""
class AsyncRobotState(AsyncPeriodicQuery):
"""Class to get robot state at regular intervals. get_robot_state_async query sent to the robot at every tick. Callback registered to defined callback function.
Attributes:
client: The Client to a service on the robot
logger: Logger object
rate: Rate (Hz) to trigger the query
callback: Callback function to call when the results of the query are available
"""
def __init__(self, client, logger, rate, callback):
super(AsyncRobotState, self).__init__("robot-state", client, logger,
period_sec=1.0/max(rate, 1.0))
self._callback = None
if rate > 0.0:
self._callback = callback
def _start_query(self):
if self._callback:
callback_future = self._client.get_robot_state_async()
callback_future.add_done_callback(self._callback)
return callback_future
class AsyncMetrics(AsyncPeriodicQuery):
"""Class to get robot metrics at regular intervals. get_robot_metrics_async query sent to the robot at every tick. Callback registered to defined callback function.
Attributes:
client: The Client to a service on the robot
logger: Logger object
rate: Rate (Hz) to trigger the query
callback: Callback function to call when the results of the query are available
"""
def __init__(self, client, logger, rate, callback):
super(AsyncMetrics, self).__init__("robot-metrics", client, logger,
period_sec=1.0/max(rate, 1.0))
self._callback = None
if rate > 0.0:
self._callback = callback
def _start_query(self):
if self._callback:
callback_future = self._client.get_robot_metrics_async()
callback_future.add_done_callback(self._callback)
return callback_future
class AsyncLease(AsyncPeriodicQuery):
"""Class to get lease state at regular intervals. list_leases_async query sent to the robot at every tick. Callback registered to defined callback function.
Attributes:
client: The Client to a service on the robot
logger: Logger object
rate: Rate (Hz) to trigger the query
callback: Callback function to call when the results of the query are available
"""
def __init__(self, client, logger, rate, callback):
super(AsyncLease, self).__init__("lease", client, logger,
period_sec=1.0/max(rate, 1.0))
self._callback = None
if rate > 0.0:
self._callback = callback
def _start_query(self):
if self._callback:
callback_future = self._client.list_leases_async()
callback_future.add_done_callback(self._callback)
return callback_future
class AsyncImageService(AsyncPeriodicQuery):
"""Class to get images at regular intervals. get_image_from_sources_async query sent to the robot at every tick. Callback registered to defined callback function.
Attributes:
client: The Client to a service on the robot
logger: Logger object
rate: Rate (Hz) to trigger the query
callback: Callback function to call when the results of the query are available
"""
def __init__(self, client, logger, rate, callback, image_requests):
super(AsyncImageService, self).__init__("robot_image_service", client, logger,
period_sec=1.0/max(rate, 1.0))
self._callback = None
if rate > 0.0:
self._callback = callback
self._image_requests = image_requests
def _start_query(self):
if self._callback:
callback_future = self._client.get_image_async(self._image_requests)
callback_future.add_done_callback(self._callback)
return callback_future
class AsyncIdle(AsyncPeriodicQuery):
"""Class to check if the robot is moving, and if not, command a stand with the set mobility parameters
Attributes:
client: The Client to a service on the robot
logger: Logger object
rate: Rate (Hz) to trigger the query
spot_wrapper: A handle to the wrapper library
"""
def __init__(self, client, logger, rate, spot_wrapper):
super(AsyncIdle, self).__init__("idle", client, logger,
period_sec=1.0/rate)
self._spot_wrapper = spot_wrapper
def _start_query(self):
if self._spot_wrapper._last_stand_command != None:
self._spot_wrapper._is_sitting = False
response = self._client.robot_command_feedback(self._spot_wrapper._last_stand_command)
if (response.feedback.mobility_feedback.stand_feedback.status ==
basic_command_pb2.StandCommand.Feedback.STATUS_IS_STANDING):
self._spot_wrapper._is_standing = True
self._spot_wrapper._last_stand_command = None
else:
self._spot_wrapper._is_standing = False
if self._spot_wrapper._last_sit_command != None:
self._spot_wrapper._is_standing = False
response = self._client.robot_command_feedback(self._spot_wrapper._last_sit_command)
if (response.feedback.mobility_feedback.sit_feedback.status ==
basic_command_pb2.SitCommand.Feedback.STATUS_IS_SITTING):
self._spot_wrapper._is_sitting = True
self._spot_wrapper._last_sit_command = None
else:
self._spot_wrapper._is_sitting = False
is_moving = False
if self._spot_wrapper._last_motion_command_time != None:
if time.time() < self._spot_wrapper._last_motion_command_time:
is_moving = True
else:
self._spot_wrapper._last_motion_command_time = None
if self._spot_wrapper._last_motion_command != None:
response = self._client.robot_command_feedback(self._spot_wrapper._last_motion_command)
if (response.feedback.mobility_feedback.se2_trajectory_feedback.status ==
basic_command_pb2.SE2TrajectoryCommand.Feedback.STATUS_GOING_TO_GOAL):
is_moving = True
else:
self._spot_wrapper._last_motion_command = None
self._spot_wrapper._is_moving = is_moving
if self._spot_wrapper.is_standing and not self._spot_wrapper.is_moving:
self._spot_wrapper.stand(False)
class SpotWrapper():
"""Generic wrapper class to encompass release 1.1.4 API features as well as maintaining leases automatically"""
def __init__(self, username, password, token, hostname, logger, rates = {}, callbacks = {}):
self._username = username
self._password = password
self._token = token
self._hostname = hostname
self._logger = logger
self._rates = rates
self._callbacks = callbacks
self._keep_alive = True
self._valid = True
self._mobility_params = RobotCommandBuilder.mobility_params()
self._is_standing = False
self._is_sitting = True
self._is_moving = False
self._last_stand_command = None
self._last_sit_command = None
self._last_motion_command = None
self._last_motion_command_time = None
self._front_image_requests = []
for source in front_image_sources:
self._front_image_requests.append(build_image_request(source, image_format=image_pb2.Image.Format.FORMAT_RAW))
self._side_image_requests = []
for source in side_image_sources:
self._side_image_requests.append(build_image_request(source, image_format=image_pb2.Image.Format.FORMAT_RAW))
self._rear_image_requests = []
for source in rear_image_sources:
self._rear_image_requests.append(build_image_request(source, image_format=image_pb2.Image.Format.FORMAT_RAW))
try:
self._sdk = create_standard_sdk('ros_spot')
except Exception as e:
self._logger.error("Error creating SDK object: %s", e)
self._valid = False
return
try:
self._sdk.load_app_token(self._token)
except Exception as e:
self._logger.error("Error loading developer token: %s", e)
self._valid = False
return
self._robot = self._sdk.create_robot(self._hostname)
try:
self._robot.authenticate(self._username, self._password)
self._robot.start_time_sync()
except RpcError as err:
self._logger.error("Failed to communicate with robot: %s", err)
self._valid = False
return
if self._robot:
# Clients
try:
self._robot_state_client = self._robot.ensure_client(RobotStateClient.default_service_name)
self._robot_command_client = self._robot.ensure_client(RobotCommandClient.default_service_name)
self._power_client = self._robot.ensure_client(PowerClient.default_service_name)
self._lease_client = self._robot.ensure_client(LeaseClient.default_service_name)
self._image_client = self._robot.ensure_client(ImageClient.default_service_name)
self._estop_client = self._robot.ensure_client(EstopClient.default_service_name)
except Exception as e:
self._logger.error("Unable to create client service: %s", e)
self._valid = False
return
# Async Tasks
self._async_task_list = []
self._robot_state_task = AsyncRobotState(self._robot_state_client, self._logger, max(0.0, self._rates.get("robot_state", 0.0)), self._callbacks.get("robot_state", lambda:None))
self._robot_metrics_task = AsyncMetrics(self._robot_state_client, self._logger, max(0.0, self._rates.get("metrics", 0.0)), self._callbacks.get("metrics", lambda:None))
self._lease_task = AsyncLease(self._lease_client, self._logger, max(0.0, self._rates.get("lease", 0.0)), self._callbacks.get("lease", lambda:None))
self._front_image_task = AsyncImageService(self._image_client, self._logger, max(0.0, self._rates.get("front_image", 0.0)), self._callbacks.get("front_image", lambda:None), self._front_image_requests)
self._side_image_task = AsyncImageService(self._image_client, self._logger, max(0.0, self._rates.get("side_image", 0.0)), self._callbacks.get("side_image", lambda:None), self._side_image_requests)
self._rear_image_task = AsyncImageService(self._image_client, self._logger, max(0.0, self._rates.get("rear_image", 0.0)), self._callbacks.get("rear_image", lambda:None), self._rear_image_requests)
self._idle_task = AsyncIdle(self._robot_command_client, self._logger, 10.0, self)
self._estop_endpoint = EstopEndpoint(self._estop_client, 'ros', 9.0)
self._async_tasks = AsyncTasks(
[self._robot_state_task, self._robot_metrics_task, self._lease_task, self._front_image_task, self._side_image_task, self._rear_image_task, self._idle_task])
self._robot_id = None
self._lease = None
@property
def is_valid(self):
"""Return boolean indicating if the wrapper initialized successfully"""
return self._valid
@property
def id(self):
"""Return robot's ID"""
return self._robot_id
@property
def robot_state(self):
"""Return latest proto from the _robot_state_task"""
return self._robot_state_task.proto
@property
def metrics(self):
"""Return latest proto from the _robot_metrics_task"""
return self._robot_metrics_task.proto
@property
def lease(self):
"""Return latest proto from the _lease_task"""
return self._lease_task.proto
@property
def front_images(self):
"""Return latest proto from the _front_image_task"""
return self._front_image_task.proto
@property
def side_images(self):
"""Return latest proto from the _side_image_task"""
return self._side_image_task.proto
@property
def rear_images(self):
"""Return latest proto from the _rear_image_task"""
return self._rear_image_task.proto
@property
def is_standing(self):
"""Return boolean of standing state"""
return self._is_standing
@property
def is_sitting(self):
"""Return boolean of standing state"""
return self._is_sitting
@property
def is_moving(self):
"""Return boolean of walking state"""
return self._is_moving
@property
def time_skew(self):
"""Return the time skew between local and spot time"""
return self._robot.time_sync.endpoint.clock_skew
def robotToLocalTime(self, timestamp):
"""Takes a timestamp and an estimated skew and return seconds and nano seconds
Args:
timestamp: google.protobuf.Timestamp
Returns:
google.protobuf.Timestamp
"""
rtime = Timestamp()
rtime.seconds = timestamp.seconds - self.time_skew.seconds
rtime.nanos = timestamp.nanos - self.time_skew.nanos
if rtime.nanos < 0:
rtime.nanos = rtime.nanos + 1000000000
rtime.seconds = rtime.seconds - 1
return rtime
def claim(self):
"""Get a lease for the robot, a handle on the estop endpoint, and the ID of the robot."""
try:
self._robot_id = self._robot.get_id()
self.getLease()
self.resetEStop()
return True, "Success"
except (ResponseError, RpcError) as err:
self._logger.error("Failed to initialize robot communication: %s", err)
return False, str(err)
def updateTasks(self):
"""Loop through all periodic tasks and update their data if needed."""
self._async_tasks.update()
def resetEStop(self):
"""Get keepalive for eStop"""
self._estop_endpoint.force_simple_setup() # Set this endpoint as the robot's sole estop.
self._estop_keepalive = EstopKeepAlive(self._estop_endpoint)
def assertEStop(self, severe=True):
"""Forces the robot into eStop state.
Args:
severe: Default True - If true, will cut motor power immediately. If false, will try to settle the robot on the ground first
"""
try:
if severe:
self._estop_endpoint.stop()
else:
self._estop_endpoint.settle_then_cut()
return True, "Success"
except:
return False, "Error"
def releaseEStop(self):
"""Stop eStop keepalive"""
if self._estop_keepalive:
self._estop_keepalive.stop()
self._estop_keepalive = None
def getLease(self):
"""Get a lease for the robot and keep the lease alive automatically."""
self._lease = self._lease_client.acquire()
self._lease_keepalive = LeaseKeepAlive(self._lease_client)
def releaseLease(self):
"""Return the lease on the body."""
if self._lease:
self._lease_client.return_lease(self._lease)
self._lease = None
def release(self):
"""Return the lease on the body and the eStop handle."""
try:
self.releaseLease()
self.releaseEStop()
return True, "Success"
except Exception as e:
return False, str(e)
def disconnect(self):
"""Release control of robot as gracefully as posssible."""
if self._robot.time_sync:
self._robot.time_sync.stop()
self.releaseLease()
self.releaseEStop()
def _robot_command(self, command_proto, end_time_secs=None):
"""Generic blocking function for sending commands to robots.
Args:
command_proto: robot_command_pb2 object to send to the robot. Usually made with RobotCommandBuilder
end_time_secs: (optional) Time-to-live for the command in seconds
"""
try:
id = self._robot_command_client.robot_command(lease=None, command=command_proto, end_time_secs=end_time_secs)
return True, "Success", id
except Exception as e:
return False, str(e), None
def stop(self):
"""Stop the robot's motion."""
response = self._robot_command(RobotCommandBuilder.stop_command())
return response[0], response[1]
def self_right(self):
"""Have the robot self-right itself."""
response = self._robot_command(RobotCommandBuilder.selfright_command())
return response[0], response[1]
def sit(self):
"""Stop the robot's motion and sit down if able."""
response = self._robot_command(RobotCommandBuilder.sit_command())
self._last_sit_command = response[2]
return response[0], response[1]
def stand(self, monitor_command=True):
"""If the e-stop is enabled, and the motor power is enabled, stand the robot up."""
response = self._robot_command(RobotCommandBuilder.stand_command(params=self._mobility_params))
if monitor_command:
self._last_stand_command = response[2]
return response[0], response[1]
def safe_power_off(self):
"""Stop the robot's motion and sit if possible. Once sitting, disable motor power."""
response = self._robot_command(RobotCommandBuilder.safe_power_off_command())
return response[0], response[1]
def power_on(self):
"""Enble the motor power if e-stop is enabled."""
try:
power.power_on(self._power_client)
return True, "Success"
except:
return False, "Error"
def set_mobility_params(self, body_height=0, footprint_R_body=EulerZXY(), locomotion_hint=1, stair_hint=False, external_force_params=None):
"""Define body, locomotion, and stair parameters.
Args:
body_height: Body height in meters
footprint_R_body: (EulerZXY) – The orientation of the body frame with respect to the footprint frame (gravity aligned framed with yaw computed from the stance feet)
locomotion_hint: Locomotion hint
stair_hint: Boolean to define stair motion
"""
self._mobility_params = RobotCommandBuilder.mobility_params(body_height, footprint_R_body, locomotion_hint, stair_hint, external_force_params)
def velocity_cmd(self, v_x, v_y, v_rot, cmd_duration=0.1):
"""Send a velocity motion command to the robot.
Args:
v_x: Velocity in the X direction in meters
v_y: Velocity in the Y direction in meters
v_rot: Angular velocity around the Z axis in radians
cmd_duration: (optional) Time-to-live for the command in seconds. Default is 125ms (assuming 10Hz command rate).
"""
end_time=time.time() + cmd_duration
self._robot_command(RobotCommandBuilder.velocity_command(
v_x=v_x, v_y=v_y, v_rot=v_rot, params=self._mobility_params),
end_time_secs=end_time)
self._last_motion_command_time = end_time
| 20,773 | Python | 42.010352 | 212 | 0.623117 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/BostonDynamics/spot_ros-CHAMP/spot_driver/doc/conf.py | import os
import sys
sys.path.insert(0, os.path.abspath('../scripts'))
project = 'spot_driver'
copyright = '2020, Dave Niewinski'
author = 'Dave Niewinski'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.napoleon'
]
html_theme = 'clearpath-sphinx-theme'
html_theme_path = ["."]
html_static_path = ['./clearpath-sphinx-theme/static']
html_sidebars = {
'**': ['sidebartoc.html', 'sourcelink.html', 'searchbox.html']
}
html_show_sphinx = False
html_logo = 'clearpath-sphinx-theme/static/clearpathlogo.png'
html_favicon = 'clearpath-sphinx-theme/static/favicon.ico'
| 597 | Python | 19.620689 | 65 | 0.710218 |
renanmb/Omniverse_legged_robotics/DigitRobot.jl-main/src/digit_manual_control.py | import pybullet as p
import time
import pybullet_data
p.connect(p.GUI)
p.setAdditionalSearchPath('..')
humanoid = p.loadURDF("urdf/digit_model.urdf",useFixedBase=True)
gravId = p.addUserDebugParameter("gravity", -10, 10, 0)
jointIds = []
paramIds = []
p.setPhysicsEngineParameter(numSolverIterations=10)
p.changeDynamics(humanoid, -1, linearDamping=0, angularDamping=0)
for j in range(p.getNumJoints(humanoid)):
p.changeDynamics(humanoid, j, linearDamping=0, angularDamping=0)
info = p.getJointInfo(humanoid, j)
#print(info)
jointName = info[1]
jointType = info[2]
if (jointType == p.JOINT_PRISMATIC or jointType == p.JOINT_REVOLUTE):
jointIds.append(j)
paramIds.append(p.addUserDebugParameter(jointName.decode("utf-8"), -4, 4, 0))
p.setRealTimeSimulation(1)
while (1):
p.setGravity(0, 0, p.readUserDebugParameter(gravId))
for i in range(len(paramIds)):
c = paramIds[i]
targetPos = p.readUserDebugParameter(c)
p.setJointMotorControl2(humanoid, jointIds[i], p.POSITION_CONTROL, targetPos, force=5 * 240.)
time.sleep(0.01) | 1,065 | Python | 30.35294 | 97 | 0.733333 |
ft-lab/omniverse_sample_scripts/Light/CheckLightPrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Check if prim is Light.
def checkLight (prim : Usd.Prim):
typeName = prim.GetTypeName()
if typeName == "DistantLight" or typeName == "CylinderLight" or \
typeName == "DiskLight" or typeName == "DomeLight" or \
typeName == "RectLight" or typeName == "SphereLight":
return True
return False
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if checkLight(prim):
print(f"[ {prim.GetPath().pathString} ] : {prim.GetTypeName()}")
| 741 | Python | 25.499999 | 72 | 0.661269 |
ft-lab/omniverse_sample_scripts/Light/CreateSphereLight.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere light.
pathName = "/World/sphereLight"
light = UsdLux.SphereLight.Define(stage, pathName)
# Set Radius.
light.CreateRadiusAttr(2.0)
# Set intensity.
light.CreateIntensityAttr(10000.0)
# Set color.
light.CreateColorAttr(Gf.Vec3f(1.0, 0.9, 0.8))
# Set Exposure.
light.CreateExposureAttr(0.0)
# cone angle.
shapingAPI = UsdLux.ShapingAPI(light)
shapingAPI.CreateShapingConeAngleAttr(180.0)
shapingAPI.Apply(light.GetPrim()) # Register ShapingAPI as a schema in prim.
# Compute extent.
boundable = UsdGeom.Boundable(light.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
light.CreateExtentAttr(extent)
| 778 | Python | 22.60606 | 77 | 0.75964 |
ft-lab/omniverse_sample_scripts/Light/CreateLight.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create distant light.
pathName = "/World/distantLight"
light = UsdLux.DistantLight.Define(stage, pathName)
# Set intensity.
light.CreateIntensityAttr(100.0)
# Set color.
light.CreateColorAttr(Gf.Vec3f(1.0, 0.5, 0.2))
# Set Exposure.
light.CreateExposureAttr(0.0)
# Compute extent.
boundable = UsdGeom.Boundable(light.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
light.CreateExtentAttr(extent)
| 560 | Python | 21.439999 | 71 | 0.75 |
ft-lab/omniverse_sample_scripts/Nucleus/createFolder.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# The following should be rewritten for your environment.
url = "omniverse://localhost/test/new_folder"
result = omni.client.create_folder(url)
if result == omni.client.Result.OK:
print("success !")
else:
print("failed ...")
| 366 | Python | 23.466665 | 94 | 0.73224 |