file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/tasks/__init__.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
| 428 |
Python
| 46.666661 | 76 | 0.808411 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/controllers/__init__.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.quadruped.controllers.qp_controller import A1QPController
from omni.isaac.quadruped.controllers.a1_robot_control import A1RobotControl
| 580 |
Python
| 47.416663 | 76 | 0.824138 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/controllers/a1_robot_control.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
# bezier is used in leg trajectory generation
import bezier
# use osqp to solve QP
import osqp
import scipy.sparse as sp
from typing import Tuple
from omni.isaac.quadruped.utils.rot_utils import skew
from omni.isaac.quadruped.utils.a1_ctrl_states import A1CtrlStates
from omni.isaac.quadruped.utils.a1_ctrl_params import A1CtrlParams
from omni.isaac.quadruped.utils.a1_desired_states import A1DesiredStates
class A1RobotControl:
"""[summary]
The A1 robot controller
This class uses A1CtrlStates to save data. The control joint torque is generated
using a QP controller
"""
def __init__(self) -> None:
"""Initializes the class instance.
"""
pass
"""
Operations
"""
# swing traj update
def update_plan(
self, desired_states: A1DesiredStates, input_states: A1CtrlStates, input_params: A1CtrlParams, dt: float
) -> None:
"""[summary]
update swing leg trajectory and several counters
Args:
desired_states {A1DesiredStates} -- the desired states
input_states {A1CtrlStates} -- the control states
input_params {A1CtrlParams} -- the control parameters
dt {float} -- The simulation time-step.
"""
self._update_gait_plan(input_states)
self._update_foot_plan(desired_states, input_states, input_params, dt)
# increase _counter
input_states._counter += 1
input_states._exp_time += dt
input_states._gait_counter += input_states._gait_counter_speed
input_states._gait_counter %= input_states._counter_per_gait
# 논문의 3-D
def generate_ctrl(
self, desired_states: A1DesiredStates, input_states: A1CtrlStates, input_params: A1CtrlParams
) -> None:
""" [summary]
main function, generate foot ground reaction force using QP and calculate joint torques
Args:
desired_states {A1DesiredStates} -- the desired states
input_states {A1CtrlStates} -- the control states
input_params {A1CtrlParams} -- the control parameters
"""
# first second, do nothing, wait sensor and stuff got stablized
if input_states._exp_time < 0.1:
return np.zeros(12)
# initial control
if input_states._init_transition == 0 and input_states._prev_transition == 0:
input_params._kp_linear[0:2] = np.array([500, 500])
# foot control
foot_pos_final = input_states._foot_pos_target_rel
foot_pos_cur = np.zeros([4, 3])
for i, leg in enumerate(["FL", "FR", "RL", "RR"]):
# robot frame으로 변환
foot_pos_cur[i, :] = input_states._rot_mat_z.T @ input_states._foot_pos_abs[i, :]
bezier_time = np.zeros(4)
for i in range(4):
# early contact, 상태 바꾸고 다시 리셋한다.
if input_states._gait_counter[i] < input_states._counter_per_swing:
bezier_time[i] = 0.0
input_states._foot_pos_start_rel[i, :] = foot_pos_cur[i, :]
input_states._early_contacts[i] = False
else:
bezier_time[i] = (
input_states._gait_counter[i] - input_states._counter_per_swing
) / input_states._counter_per_swing
# _rot_mat_z : R^{world}_{robot yaw}
#
# _foot_pos_start_rel : (R^{world}_{robot yaw}).T * _foot_pos_abs(rotated robot frame)
# => robot frame 기준 현재 다리 위치
# foot_pos_final : _foot_pos_target_rel (foot target pos in the relative frame (robot frame))
#
# foot_pos_target => robot frame 기준 target
# 논문의 3-C
# _kp_foot: swing foot position error coefficient
# _kp_linear: stance foot force position error coefficient
foot_pos_target = self._get_from_bezier_curve(input_states._foot_pos_start_rel, foot_pos_final, bezier_time)
foot_pos_error = foot_pos_target - foot_pos_cur
foot_forces_kin = (input_params._kp_foot * foot_pos_error).flatten()
# detect early contacts
# how to determine which foot is in contact: check gait counter
for i in range(4):
# slow contact
if not input_states._contacts[i] and input_states._gait_counter[i] <= input_states._counter_per_swing * 1.5:
input_states._early_contacts[i] = False
# early contact
if (
not input_states._contacts[i]
and input_states._early_contacts[i] is False
and input_states._foot_forces[i] > input_params._foot_force_low
and input_states._gait_counter[i] > input_states._counter_per_swing * 1.5
):
input_states._early_contacts[i] = True
for i in range(4):
input_states._contacts[i] = input_states._contacts[i] or input_states._early_contacts[i]
# root control
# grf : 지금 world frame 기준
# grf는 현재 COM에 가해지는 6dof 힘인 상황
grf = self._compute_grf(desired_states, input_states, input_params)
grf_rel = grf @ input_states._rot_mat
foot_forces_grf = -grf_rel.flatten()
# convert to torque
M = np.kron(np.eye(4, dtype=int), input_params._km_foot)
# torques_init = input_states._j_foot.T @ foot_forces_init
# J * 극좌표 = Cartesian
# 지금은 극좌표 = J.inv * Cartesian
# kin => swing / grf => contact
# 몸체를 중심점으로 생각하면, 끝점에 의한 모멘트 평형만 생각하면 된다.
# M @ foot_forces_kin => 토크
# np.linalg.inv(input_states._j_foot) 곱해주기 => 극 좌표 변환
# tau = J.inv @ M @ K_p(p_des - p)
torques_kin = np.linalg.inv(input_states._j_foot) @ M @ foot_forces_kin
# torques_kin = input_states._j_foot.T @ foot_forces_kin
# tau = J.T @ F
torques_grf = input_states._j_foot.T @ foot_forces_grf
# combine torques
torques_init = np.zeros(12)
for i in range(4):
torques_init[3 * i : 3 * i + 3] = torques_grf[3 * i : 3 * i + 3]
# combine torques
torques = np.zeros(12)
for i in range(4):
if input_states._contacts[i]:
torques[3 * i : 3 * i + 3] = torques_grf[3 * i : 3 * i + 3]
else:
torques[3 * i : 3 * i + 3] = torques_kin[3 * i : 3 * i + 3]
# _init_transition이면 => torques (grf + kin)
# 아니면 => torques_init (grf만 고려)
torques = (1 - input_states._init_transition) * torques_init + input_states._init_transition * torques
torques += input_params._torque_gravity
# for i in range(12):
# if torques[i] < -1000:
# torques[i] = -1000
# if torques[i] > 1000:
# torques[i] = 1000
return torques
"""
Internal helpers.
"""
# trot, gallop과 같은 보행 제어 + 카운터 설정
def _update_gait_plan(self, input_states: A1CtrlStates) -> None:
""" [summary]
update gait counters
Args:
input_states {A1CtrlStates} -- the control states
"""
# initialize _counter
if input_states._counter == 0 or input_states._gait_type != input_states._gait_type_last:
if input_states._gait_type == 2:
input_states._gait_counter = np.array([0.0, 120.0, 0.0, 120.0])
elif input_states._gait_type == 1:
input_states._gait_counter = np.array([0.0, 120.0, 120.0, 0.0])
else:
input_states._gait_counter = np.array([0.0, 0.0, 0.0, 0.0])
# update _counter speed
for i in range(4):
if input_states._gait_type == 2:
input_states._gait_counter_speed[i] = 1.4
elif input_states._gait_type == 1:
input_states._gait_counter_speed[i] = 1.4
else:
input_states._gait_counter_speed[i] = 0.0
input_states._contacts[i] = input_states._gait_counter[i] < input_states._counter_per_swing
input_states._gait_type_last = input_states._gait_type
# 논문의 3-E swing시 다리의 궤적을 2차원으로 사영시킨 위치를 계산한다.
def _update_foot_plan(
self, desired_states: A1DesiredStates, input_states: A1CtrlStates, input_params: A1CtrlParams, dt: float
) -> None:
""" [summary]
update foot swing target positions
Args:
input_states {A1DesiredStates} -- the desried states
input_states {A1CtrlStates} -- the control states
input_params {A1CtrlParams} -- the control parameters
dt {float} -- delta time since last update
"""
# heuristic plan
lin_pos = input_states._root_pos
# lin_pos_rel = input_states._rot_mat_z.T @ lin_pos
lin_pos_d = desired_states._root_pos_d
# lin_pos_rel_d = input_states._rot_mat_z.T @ lin_pos_d
lin_vel = input_states._root_lin_vel
# body frame
lin_vel_rel = input_states._rot_mat_z.T @ lin_vel
input_states._foot_pos_target_rel = input_params._default_foot_pos.copy()
for i in range(4):
weight_y = np.square(np.abs(input_params._default_foot_pos[i, 2]) / 9.8)
weight2 = input_states._counter_per_swing / input_states._gait_counter_speed[i] * dt / 2.0
delta_x = weight_y * (lin_vel_rel[0] - desired_states._root_lin_vel_d[0]) + weight2 * lin_vel_rel[0]
delta_y = weight_y * (lin_vel_rel[1] - desired_states._root_lin_vel_d[1]) + weight2 * lin_vel_rel[1]
if delta_x < -0.1:
delta_x = -0.1
if delta_x > 0.1:
delta_x = 0.1
if delta_y < -0.1:
delta_y = -0.1
if delta_y > 0.1:
delta_y = 0.1
input_states._foot_pos_target_rel[i, 0] += delta_x
input_states._foot_pos_target_rel[i, 1] += delta_y
# swing trajectory 계산 - 베지어 통해
def _get_from_bezier_curve(
self, foot_pos_start: np.ndarray, foot_pos_final: np.ndarray, bezier_time: float
) -> np.ndarray:
"""[summary]
generate swing foot position target from a bezier curve
Args:
foot_pos_start {np.ndarray} -- The curve start point
foot_pos_final {np.ndarray} -- The curve end point
bezier_time {float} -- The curve interpolation time, should be within [0,1].
"""
bezier_degree = 4
bezier_s = np.linspace(0, 1, bezier_degree + 1)
bezier_nodes = np.zeros([2, bezier_degree + 1])
bezier_nodes[0, :] = bezier_s
foot_pos_target = np.zeros([4, 3])
foot_pos_target_x = foot_pos_target[:, 0]
foot_pos_target_y = foot_pos_target[:, 1]
foot_pos_target_z = foot_pos_target[:, 2]
for i in range(4):
bezier_x = np.array(
[
foot_pos_start[i, 0],
foot_pos_start[i, 0],
foot_pos_final[i, 0],
foot_pos_final[i, 0],
foot_pos_final[i, 0],
]
)
bezier_nodes[1, :] = bezier_x
bezier_curve = bezier.Curve(bezier_nodes, bezier_degree)
foot_pos_target_x[i] = bezier_curve.evaluate(bezier_time[i])[1, 0]
for i in range(4):
bezier_y = np.array(
[
foot_pos_start[i, 1],
foot_pos_start[i, 1],
foot_pos_final[i, 1],
foot_pos_final[i, 1],
foot_pos_final[i, 1],
]
)
bezier_nodes[1, :] = bezier_y
bezier_curve = bezier.Curve(bezier_nodes, bezier_degree)
foot_pos_target_y[i] = bezier_curve.evaluate(bezier_time[i])[1, 0]
for i in range(4):
bezier_z = np.array(
[
foot_pos_start[i, 2],
foot_pos_start[i, 2],
foot_pos_final[i, 2],
foot_pos_final[i, 2],
foot_pos_final[i, 2],
]
)
foot_clearance1 = 0.0
foot_clearance2 = 0.5
bezier_z[1] += foot_clearance1
bezier_z[2] += foot_clearance2
bezier_nodes[1, :] = bezier_z
bezier_curve = bezier.Curve(bezier_nodes, bezier_degree)
foot_pos_target_z[i] = bezier_curve.evaluate(bezier_time[i])[1, 0]
return foot_pos_target
def _compute_grf(
self, desired_states: A1DesiredStates, input_states: A1CtrlStates, input_params: A1CtrlParams
) -> np.ndarray:
""" [summary]
main internal function, generate foot ground reaction force using QP
Args:
desired_states {A1DesiredStates} -- the desired states
input_states {A1CtrlStates} -- the control states
input_params {A1CtrlParams} -- the control parameters
Returns:
grf {np.ndarray}
"""
inertia_inv, root_acc, acc_weight, u_weight = self._get_qp_params(desired_states, input_states, input_params)
modified_contacts = np.array([True, True, True, True])
if input_states._init_transition < 1.0:
modified_contacts = np.array([True, True, True, True])
else:
modified_contacts = input_states._contacts
mu = 0.2
# use osqp
# np.diag(np.square(np.array([1, 1, 1, 20, 20, 10])))
# array([[ 1, 0, 0, 0, 0, 0],
# [ 0, 1, 0, 0, 0, 0],
# [ 0, 0, 1, 0, 0, 0],
# [ 0, 0, 0, 400, 0, 0],
# [ 0, 0, 0, 0, 400, 0],
# [ 0, 0, 0, 0, 0, 100]])
# u_weight = 1e-3
# QP prepare
Q = np.diag(np.square(acc_weight))
R = u_weight
F_min = 0
F_max = 250.0
# C.T @ Q @ C + R
# C : control - state matrix / x = Cu / x: root_acc & u : GRF
# R / Q : weight matrix
hessian = np.identity(12) * R + inertia_inv.T @ Q @ inertia_inv
# zero-reference MPC formulation
# TODO: 여기가 이해가 안간다.
# -C.T @ Q @ x
gradient = -inertia_inv.T @ Q @ root_acc
linearMatrix = np.zeros([20, 12])
lowerBound = np.zeros(20)
upperBound = np.zeros(20)
for i in range(4):
# extract F_zi
linearMatrix[i, 2 + i * 3] = 1.0
# friction pyramid
# 1. F_xi < uF_zi
linearMatrix[4 + i * 4, i * 3] = 1.0
linearMatrix[4 + i * 4, 2 + i * 3] = -mu
lowerBound[4 + i * 4] = -np.inf
# 2. -F_xi > uF_zi
linearMatrix[4 + i * 4 + 1, i * 3] = -1.0
linearMatrix[4 + i * 4 + 1, 2 + i * 3] = -mu
lowerBound[4 + i * 4 + 1] = -np.inf
# 3. F_yi < uF_zi
linearMatrix[4 + i * 4 + 2, 1 + i * 3] = 1.0
linearMatrix[4 + i * 4 + 2, 2 + i * 3] = -mu
lowerBound[4 + i * 4 + 2] = -np.inf
# 4. -F_yi > uF_zi
linearMatrix[4 + i * 4 + 3, 1 + i * 3] = -1.0
linearMatrix[4 + i * 4 + 3, 2 + i * 3] = -mu
lowerBound[4 + i * 4 + 3] = -np.inf
c_flag = 1.0 if modified_contacts[i] else 0.0
lowerBound[i] = c_flag * F_min
upperBound[i] = c_flag * F_max
# 0 <= FL_z <= 250
# 0 <= FR_z <= 250
# 0 <= RL_z <= 250
# 0 <= RR_z <= 250
# -0.2*FL_z <= FL_y <= 0.2*FL_z
# -0.2*FR_z <= FR_x <= 0.2*FR_z
# -0.2*FR_z <= FR_y <= 0.2*FR_z
# -0.2*RL_z <= RL_x <= 0.2*RL_z
# -0.2*RL_z <= RL_y <= 0.2*RL_z
# -0.2*RR_z <= RR_x <= 0.2*RR_z
# -0.2*RR_z <= RR_y <= 0.2*RR_z
# sp.csc_matrix example
#
# row = np.array([0, 2, 2, 0, 1, 2])
# col = np.array([0, 0, 1, 2, 2, 2])
# data = np.array([1, 2, 3, 4, 5, 6])
# csc_array((data, (row, col)), shape=(3, 3)).toarray()
# array([[1, 0, 4],
# [0, 0, 5],
# [2, 3, 6]])
# 어떤 컴팩트한 포맷으로 변환된다. 계산 효율위해서 인 것 같음
sparse_hessian = sp.csc_matrix(hessian)
# initialize the OSQP solver
solver = osqp.OSQP()
solver.setup(
P=sparse_hessian, q=gradient, A=sp.csc_matrix(linearMatrix), l=lowerBound, u=upperBound, verbose=False
)
results = solver.solve()
# print("compare casadi with osqp")
# print(grf_vec)
# print(results.x)
grf = results.x.reshape(4, 3)
# print(results.x)
# print(grf)
return grf
def _get_qp_params(
self, desired_states: A1DesiredStates, input_states: A1CtrlStates, input_params: A1CtrlParams
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
""" [summary]
main internal function, construct parameters of the QP problem
Args:
desired_states {A1DesiredStates} -- the desired states
input_states {A1CtrlStates} -- the control states
input_params {A1CtrlParams} -- the control parameters
Returns:
qp_params: {Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] -- inertia_inv, root_acc, acc_weight, u_weight}
"""
# continuous yaw error
# reference: http://ltu.diva-portal.org/smash/get/diva2:1010947/FULLTEXT01.pdf
euler_error = desired_states._euler_d - input_states._euler
# _euler_d : the desired body orientation in _euler angle
# _euler : robot _euler angle in world frame
# limit euler error to pi/2
if euler_error[2] > 3.1415926 * 1.5: # eulerd 3.14 euler -3.14
euler_error[2] = desired_states._euler_d[2] - 3.1415926 * 2 - input_states._euler[2]
# euler_error[2] = euler_error[2] - 3.1415926 * 2
elif euler_error[2] < -3.1415926 * 1.5:
euler_error[2] = desired_states._euler_d[2] + 3.1415926 * 2 - input_states._euler[2]
# 논문의 3-C
root_acc = np.zeros(6)
# _root_pos_d : the desired body position in world frame
# _root_pos : robot position in world frame
root_acc[0:3] = input_params._kp_linear * (desired_states._root_pos_d - input_states._root_pos)
# 결국 다 world로 바꾼다.
# _root_lin_vel_d이 robot frame 기준이어서 _root_lin_vel를 다시 robot frame으로 바꾼 뒤 다시 변환하는 것임
# _rot_mat_z : R^{world}_{robot yaw}
# _root_lin_vel_d : the desired body velocity in robot frame
# _root_lin_vel : robot linear velocity in world frame
root_acc[0:3] += input_states._rot_mat_z @ (
input_params._kd_linear
* (desired_states._root_lin_vel_d - input_states._rot_mat_z.T @ input_states._root_lin_vel)
)
# euler_error도 world 기준임
# _root_ang_vel_d : the desired body angular velocity
# _root_ang_vel : robot angular velocity in world frame TODO: 여기 조금 이상하네 주석이 잘못된건가?
root_acc[3:6] = input_params._kp_angular * euler_error
root_acc[3:6] += input_params._kd_angular * (
desired_states._root_ang_vel_d - input_states._rot_mat_z.T @ input_states._root_ang_vel
)
# Add gravity
mass = input_params._robot_mass
root_acc[2] += mass * 9.8
for i in range(6):
if root_acc[i] < -500:
root_acc[i] = -500
if root_acc[i] > 500:
root_acc[i] = 500
# Create inverse inertia matrix - 논문의 3B
#
# TODO: inertia_inv이 자체가 무슨 의미를 갖고 있지? => F=MA에서 M^{-1}에 해당해서 inertia_inv라고 하지 않았나 생각해봄
inertia_inv = np.zeros([6, 12])
inertia_inv[0:3] = np.tile(np.eye(3), 4) # TODO: use the real inertia from URDF
# _foot_pos_abs: the foot current pos in the absolute frame (rotated robot frame) - world frame 다리 위치임
# inertia_inv 하단부는 결국 robot frame 기준으로 _foot_pos_abs 변환한 것이다. => 이게 inertia inverse??
# 벡터와 벡터의 cross product는 skew-sym-matrix와 벡터의 곱으로 나타낼 수 있다. 동일함
for i in range(4):
skew_mat = skew(input_states._foot_pos_abs[i, :])
inertia_inv[3:6, i * 3 : i * 3 + 3] = input_states._rot_mat_z.T @ skew_mat
# QP weight
acc_weight = np.array([1, 1, 1, 20, 20, 10])
u_weight = 1e-3
return inertia_inv, root_acc, acc_weight, u_weight
| 20,885 |
Python
| 37.322936 | 125 | 0.537276 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/controllers/qp_controller.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Union, List
import numpy as np
import carb
# omni-isaac-a1
from omni.isaac.quadruped.utils.a1_classes import A1Measurement, A1Command
# QP controller related
from omni.isaac.quadruped.utils.a1_ctrl_states import A1CtrlStates
from omni.isaac.quadruped.utils.a1_ctrl_params import A1CtrlParams
from omni.isaac.quadruped.utils.a1_desired_states import A1DesiredStates
from omni.isaac.quadruped.controllers.a1_robot_control import A1RobotControl
from omni.isaac.quadruped.utils.a1_sys_model import A1SysModel
from omni.isaac.quadruped.utils.go1_sys_model import Go1SysModel
from omni.isaac.quadruped.utils.rot_utils import get_xyz_euler_from_quaternion, get_rotation_matrix_from_euler
class A1QPController:
"""[summary]
A1 QP controller as a layer.
An implementation of the QP controller[1]
References:
[1] Bledt, Gerardo, et al. "MIT Cheetah 3: Design and control of a robust, dynamic quadruped robot."
2018 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS). IEEE, 2018.
"""
def __init__(self, name: str, _simulate_dt: float, waypoint_pose=None) -> None:
"""Initialize the QP Controller.
Args:
name {str} -- The name of the layer.
_simulated_dt {float} -- rough estimation of the time interval of the control loop
"""
# rough estimation of the time interval of the control loop
self.simulate_dt = _simulate_dt
# (nearly) constant control related parameters
self._ctrl_params = A1CtrlParams()
# control state varibles
self._ctrl_states = A1CtrlStates()
# control goal state varibles
self._desired_states = A1DesiredStates()
# robot controller
self._root_control = A1RobotControl()
# kinematic calculator
if name == "A1":
self._sys_model = A1SysModel()
else:
self._sys_model = Go1SysModel()
# variables that toggle standing/moving mode
self._init_transition = 0
self._prev_transition = 0
# an auto planner for collecting data
self.waypoint_tgt_idx = 1
if waypoint_pose is not None:
self.waypoint_pose = waypoint_pose
else:
self.waypoint_pose = []
"""
Operations
"""
def setup(self) -> None:
"""[summary]
Reset the ctrl states.
"""
self.ctrl_state_reset()
def reset(self) -> np.ndarray:
"""[summary]
Reset the ctrl states.
"""
self.ctrl_state_reset()
def set_target_command(self, base_command: Union[List[float], np.ndarray]) -> None:
"""[summary]
Set target base velocity command from joystick
Args:
base_command{Union[List[float], np.ndarray} -- velocity commands for the robot
"""
self._current_base_command = base_command
def advance(self, dt: float, measurement: A1Measurement, path_follow=False, auto_start=True) -> np.array:
"""[summary]
Perform torque command generation.
Args:
dt {float} -- Timestep update in the world.
measurement {A1Measurement} -- Current measurement from robot.
path_follow {bool} -- True if a waypoint is pathed in, false if not
auto_start {bool} -- True to start trotting after 1 second automatically, False for start trotting after "Enter" is pressed
Returns:
np.ndarray -- The desired joint torques for the robot.
"""
# update controller states from A1Measurement
self.update(dt, measurement)
if auto_start:
if (self._ctrl_states._exp_time > 1) and self._ctrl_states._init_transition == 0:
self._ctrl_states._init_transition = 1
# 아주 간단한 P 제어 경로 추적
if path_follow:
if self._ctrl_states._exp_time > 6:
if self.waypoint_tgt_idx == len(self.waypoint_pose) and self._ctrl_states._init_transition == 1:
self._ctrl_states._init_transition = 0
self._ctrl_states._prev_transition = 1
carb.log_info("stop motion")
self.waypoint_tgt_idx += 1
elif self.waypoint_tgt_idx < len(self.waypoint_pose) and self._ctrl_states._init_transition == 1:
cur_pos = np.array(
[self._ctrl_states._root_pos[0], self._ctrl_states._root_pos[1], self._ctrl_states._euler[2]]
)
# position에서 x, y, yaw 만 빼낸다.
diff_pose = self.waypoint_pose[self.waypoint_tgt_idx] - cur_pos
diff_pos = np.array([diff_pose[0], diff_pose[1], 0])
# yaw angle 보정
# fix yaw angle for diff_pos
if diff_pose[2] > 1.5 * 3.14: # tgt 3.14, cur -3.14
diff_pose[2] = diff_pose[2] - 6.28
if diff_pose[2] < -1.5 * 3.14: # tgt -3.14, cur 3.14
diff_pose[2] = 6.28 + diff_pose[2]
# diff_pos를 body frame으로 변환한 뒤 아주 간단하게 * 10을 해서 경로로 전환한다.
# vel command body frame
diff_pos_r = self._ctrl_states._rot_mat_z.T @ diff_pos
self._current_base_command[0] = 10 * diff_pos_r[0]
self._current_base_command[1] = 10 * diff_pos_r[1]
# yaw command
self._current_base_command[2] = 10 * diff_pose[2]
# target pose에 도달하면 다음 target으로 넘어간다.
if np.linalg.norm(diff_pose) < 0.1 and self.waypoint_tgt_idx < len(self.waypoint_pose):
self.waypoint_tgt_idx += 1
# print(self.waypoint_tgt_idx, " - ", self.waypoint_pose[self.waypoint_tgt_idx])
else:
# 모든 target pose에 도달했을 때
# self.waypoint_tgt_idx > len(self.waypoint_pose), in this case the planner is disabled
carb.log_info("target reached, back to manual control mode")
path_follow = False
pass
# desired states update
# velocity updates
# update controller states from target command
self._desired_states._root_lin_vel_d[0] = self._current_base_command[0]
self._desired_states._root_lin_vel_d[1] = self._current_base_command[1]
self._desired_states._root_ang_vel_d[2] = self._current_base_command[2]
# euler angle update
# _euler_d : desired body orientation in _euler angle
self._desired_states._euler_d[2] += self._desired_states._root_ang_vel_d[2] * dt
# position locking
if self._ctrl_states._init_transition == 1:
if np.linalg.norm(self._desired_states._root_lin_vel_d[0]) > 0.05:
self._ctrl_params._kp_linear[0] = 0
self._desired_states._root_pos_d[0] = self._ctrl_states._root_pos[0]
if np.linalg.norm(self._desired_states._root_lin_vel_d[0]) < 0.05:
self._ctrl_params._kp_linear[0] = 5000
if np.linalg.norm(self._desired_states._root_lin_vel_d[1]) > 0.05:
self._ctrl_params._kp_linear[1] = 0
self._desired_states._root_pos_d[1] = self._ctrl_states._root_pos[1]
if np.linalg.norm(self._desired_states._root_lin_vel_d[1]) < 0.05:
self._ctrl_params._kp_linear[1] = 5000
if np.linalg.norm(self._desired_states._root_ang_vel_d[2]) == 0:
self._desired_states._euler_d[2] = self._ctrl_states._euler[2]
# record position once when moving back into init transition = 0 state
if self._ctrl_states._prev_transition == 1 and self._ctrl_states._init_transition < 1:
self._ctrl_params._kp_linear[0:2] = np.array([500, 500])
self._desired_states._euler_d[2] = self._ctrl_states._euler[2]
self._desired_states._root_pos_d[0:2] = self._ctrl_states._root_pos[0:2]
self._desired_states._root_lin_vel_d[0] = 0
self._desired_states._root_lin_vel_d[1] = 0
# make sure this logic only run once
self._ctrl_states._prev_transition = self._ctrl_states._init_transition
self._root_control.update_plan(self._desired_states, self._ctrl_states, self._ctrl_params, dt)
# update_plan updates swing foot target
# swing foot control and stance foot control
torques = self._root_control.generate_ctrl(self._desired_states, self._ctrl_states, self._ctrl_params)
return torques
def switch_mode(self):
"""[summary]
toggle between stationary/moving mode"""
self._ctrl_states._prev_transition = self._ctrl_states._init_transition
self._ctrl_states._init_transition = self._current_base_command[3]
"""
Internal helpers.
"""
def ctrl_state_reset(self) -> None:
"""[summary]
reset _ctrl_states and _ctrl_params to non-default values
"""
# following changes to A1CtrlParams alters the robot gait execution performance
self._ctrl_params = A1CtrlParams()
self._ctrl_params._kp_linear = np.array([500, 500.0, 1600.0])
self._ctrl_params._kd_linear = np.array([2000.0, 2000.0, 4000.0])
self._ctrl_params._kp_angular = np.array([600.0, 600.0, 0.0])
self._ctrl_params._kd_angular = np.array([0.0, 0.0, 500.0])
kp_foot_x = 11250.0
kp_foot_y = 11250.0
kp_foot_z = 11500.0
self._ctrl_params._kp_foot = np.array(
[
[kp_foot_x, kp_foot_y, kp_foot_z],
[kp_foot_x, kp_foot_y, kp_foot_z],
[kp_foot_x, kp_foot_y, kp_foot_z],
[kp_foot_x, kp_foot_y, kp_foot_z],
]
)
self._ctrl_params._kd_foot = np.array([0.0, 0.0, 0.0])
self._ctrl_params._km_foot = np.diag([0.7, 0.7, 0.7])
self._ctrl_params._robot_mass = 12.5
self._ctrl_params._foot_force_low = 5.0
self._ctrl_states = A1CtrlStates()
self._ctrl_states._counter = 0.0
self._ctrl_states._gait_counter = np.array([0.0, 0.0, 0.0, 0.0])
self._ctrl_states._exp_time = 0.0
def update(self, dt: float, measurement: A1Measurement):
"""[summary]
Fill measurement into _ctrl_states
Args:
dt {float} -- Timestep update in the world.
measurement {A1Measurement} -- Current measurement from robot.
"""
self._ctrl_states._root_quat[0] = measurement.state.base_frame.quat[3] # w
self._ctrl_states._root_quat[1] = measurement.state.base_frame.quat[0] # x
self._ctrl_states._root_quat[2] = measurement.state.base_frame.quat[1] # y
self._ctrl_states._root_quat[3] = measurement.state.base_frame.quat[2] # z
self._ctrl_states._root_pos = measurement.state.base_frame.pos
self._ctrl_states._root_lin_vel = measurement.state.base_frame.lin_vel
if self._ctrl_states._root_quat[0] < 0:
self._ctrl_states._root_quat = -self._ctrl_states._root_quat
self._ctrl_states._euler = get_xyz_euler_from_quaternion(self._ctrl_states._root_quat)
self._ctrl_states._rot_mat = get_rotation_matrix_from_euler(self._ctrl_states._euler)
# according to rl_controler in isaac.anymal, base_frame.ang_vel is in world frame
self._ctrl_states._root_ang_vel = self._ctrl_states._rot_mat.T @ measurement.state.base_frame.ang_vel
self._ctrl_states._rot_mat_z = get_rotation_matrix_from_euler(np.array([0.0, 0.0, self._ctrl_states._euler[2]]))
# still keep the option of using forward diff velocities
for i in range(12):
if abs(dt > 1e-10):
self._ctrl_states._joint_vel[i] = (
measurement.state.joint_pos[i] - self._ctrl_states._joint_pos[i]
) / dt
else:
self._ctrl_states._joint_vel[i] = 0.0
self._ctrl_states._joint_pos[i] = measurement.state.joint_pos[i]
# self._ctrl_states._joint_vel[i] = measurement.state.joint_vel[i]
for i, leg in enumerate(["FL", "FR", "RL", "RR"]):
# notice the id order of A1SysModel follows that on A1 hardware
# [1, 0, 3, 2] -> [FL, FR, RL, RR]
swap_i = self._ctrl_params._swap_foot_indices[i]
self._ctrl_states._foot_pos_rel[i, :] = self._sys_model.forward_kinematics(
swap_i, self._ctrl_states._joint_pos[i * 3 : (i + 1) * 3]
)
self._ctrl_states._j_foot[i * 3 : (i + 1) * 3, i * 3 : (i + 1) * 3] = self._sys_model.jacobian(
swap_i, self._ctrl_states._joint_pos[i * 3 : (i + 1) * 3]
)
self._ctrl_states._foot_pos_abs[i, :] = self._ctrl_states._rot_mat @ self._ctrl_states._foot_pos_rel[i, :]
self._ctrl_states._foot_forces[i] = measurement.foot_forces[i]
self._ctrl_states._exp_time += dt
| 13,538 |
Python
| 42.957792 | 135 | 0.583764 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/tests/test_a1.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
import omni.kit.commands
import carb.tokens
import asyncio
import numpy as np
from omni.isaac.core import World
from omni.isaac.quadruped.robots.unitree import Unitree
from omni.isaac.core.utils.physics import simulate_async
from omni.isaac.quadruped.utils.rot_utils import get_xyz_euler_from_quaternion
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import create_new_stage_async
class TestA1(omni.kit.test.AsyncTestCase):
async def setUp(self):
World.clear_instance()
await create_new_stage_async()
# This needs to be set so that kit updates match physics updates
self._physics_rate = 400
carb.settings.get_settings().set_bool("/app/runLoops/main/rateLimitEnabled", True)
carb.settings.get_settings().set_int("/app/runLoops/main/rateLimitFrequency", int(self._physics_rate))
carb.settings.get_settings().set_int("/persistent/simulation/minFrameRate", int(self._physics_rate))
self._physics_dt = 1 / self._physics_rate
self._world = World(stage_units_in_meters=1.0, physics_dt=self._physics_dt, rendering_dt=32 * self._physics_dt)
await self._world.initialize_simulation_context_async()
self._world.scene.add_default_ground_plane(
z_position=0,
name="default_ground_plane",
prim_path="/World/defaultGroundPlane",
static_friction=0.2,
dynamic_friction=0.2,
restitution=0.01,
)
self._base_command = [1.0, 0, 0, 0]
self._stage = omni.usd.get_context().get_stage()
self._timeline = omni.timeline.get_timeline_interface()
self._path_follow = False
self._auto_start = True
await omni.kit.app.get_app().next_update_async()
pass
async def tearDown(self):
await omni.kit.app.get_app().next_update_async()
self._timeline.stop()
while omni.usd.get_context().get_stage_loading_status()[2] > 0:
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await omni.kit.app.get_app().next_update_async()
pass
async def test_a1_add(self):
self._path_follow = False
self._auto_start = True
await self.spawn_a1()
await omni.kit.app.get_app().next_update_async()
self._a1 = self._a1 = self._world.scene.get_object("A1")
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self._a1.num_dof, 12)
self.assertTrue(get_prim_at_path("/World/A1").IsValid(), True)
print("robot articulation passed")
await omni.kit.app.get_app().next_update_async()
# if dc interface is valid, that means the prim is likely imported correctly
async def test_robot_move_command(self):
self._path_follow = False
self._auto_start = True
await self.spawn_a1()
await omni.kit.app.get_app().next_update_async()
self._a1 = self._a1 = self._world.scene.get_object("A1")
self.start_pos = np.array(self._a1.get_world_pose()[0])
await simulate_async(seconds=2.0)
self.current_pos = np.array(self._a1.get_world_pose()[0])
print(str(self.current_pos))
delta = np.linalg.norm(self.current_pos[0] - self.start_pos[0])
self.assertTrue(delta > 0.5)
pass
async def test_robot_move_forward_waypoint(self):
self._path_follow = True
self._auto_start = True
await self.spawn_a1(waypoints=[np.array([0.0, 0.0, 0.0]), np.array([0.5, 0.0, 0.0])])
await omni.kit.app.get_app().next_update_async()
self._a1 = self._world.scene.get_object("A1")
await omni.kit.app.get_app().next_update_async()
self.start_pos = np.array(self._a1.get_world_pose()[0])
await simulate_async(seconds=1.5)
self.current_pos = np.array(self._a1.get_world_pose()[0])
delta = self.current_pos - self.start_pos
print(str(delta))
# x should be around 1, y, z should be around 0
self.assertAlmostEquals(0.5, delta[0], 0)
self.assertTrue(abs(delta[1]) < 0.1)
self.assertTrue(abs(delta[2]) < 0.1)
async def test_robot_turn_waypoint(self):
self._path_follow = False
self._auto_start = True
# turn 90 degrees
await self.spawn_a1() # waypoints=[np.array([0.0, 0.0, -1.57])])
await omni.kit.app.get_app().next_update_async()
self._a1 = self._world.scene.get_object("A1")
await omni.kit.app.get_app().next_update_async()
self._base_command = [0.0, 0.0, 1.0, 0.0]
self.start_quat = np.array(self._a1.get_world_pose()[1][[1, 2, 3, 0]])
await simulate_async(seconds=1.5)
self.current_quat = np.array(self._a1.get_world_pose()[1][[1, 2, 3, 0]])
self.start_pos = get_xyz_euler_from_quaternion(self.start_quat)
self.current_pos = get_xyz_euler_from_quaternion(self.current_quat)
delta = np.array(abs(self.current_pos) - abs(self.start_pos))
print(str(delta))
self.assertTrue(abs(delta[2]) < 0.1)
self.assertTrue(abs(delta[1]) < 0.1)
self.assertTrue(abs(delta[0]) > 3.14 / 4)
# Add this test when the controller has better side movement performance
# async def test_robot_shift(self):
# await self.spawn_a1()
# # move side ways at 1.8 m/s (due to tuning, it is likely slower than that)
# self._base_command = [0.0, 1.8, 0, 0]
# await omni.kit.app.get_app().next_update_async()
# self._a1 = self._world.scene.get_object("A1")
# await omni.kit.app.get_app().next_update_async()
# self.start_pos = np.array(self.dc.get_rigid_body_pose(self._a1._root_handle).p)
# await simulate_async(seconds=10.0)
# self.current_pos = np.array(self.dc.get_rigid_body_pose(self._a1._root_handle).p)
# delta = self.current_pos - self.start_pos
# print("delta: " + str(delta))
# print("start: " + str(self.start_pos))
# print("current: " + str(self.current_pos))
# # y should be around 0.5, x, z should be around 0
# self.assertTrue(abs(delta[1]) > 0.5)
# self.assertTrue(abs(delta[0]) < 0.1)
# self.assertTrue(abs(delta[2]) < 0.1)
async def spawn_a1(self, waypoints=None, model="A1"):
self._prim_path = "/World/" + model
self._a1 = self._world.scene.get_object("A1")
if self._a1 is None:
self._a1 = self._world.scene.add(
Unitree(
prim_path=self._prim_path,
name=model,
position=np.array([0, 0, 0.40]),
physics_dt=self._physics_dt,
model=model,
way_points=waypoints,
)
)
self._a1._qp_controller.ctrl_state_reset()
self._world.add_physics_callback("a1_advance", callback_fn=self.on_physics_step)
await self._world.reset_async()
return
def on_physics_step(self, step_size):
if self._a1 and self._a1._handle:
self._a1.advance(
dt=step_size, goal=self._base_command, path_follow=self._path_follow, auto_start=self._auto_start
)
| 7,981 |
Python
| 37.191387 | 119 | 0.617466 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/tests/__init__.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_a1 import *
from .test_go1 import *
| 481 |
Python
| 39.166663 | 76 | 0.796258 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/tests/test_go1.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
import omni.kit.commands
import carb.tokens
import asyncio
import numpy as np
from omni.isaac.core import World
from omni.isaac.quadruped.robots.unitree import Unitree
from omni.isaac.core.utils.stage import create_new_stage_async
from omni.isaac.core.utils.prims import get_prim_at_path
class TestGo1(omni.kit.test.AsyncTestCase):
async def setUp(self):
World.clear_instance()
await create_new_stage_async()
# This needs to be set so that kit updates match physics updates
self._physics_rate = 400
carb.settings.get_settings().set_bool("/app/runLoops/main/rateLimitEnabled", True)
carb.settings.get_settings().set_int("/app/runLoops/main/rateLimitFrequency", int(self._physics_rate))
carb.settings.get_settings().set_int("/persistent/simulation/minFrameRate", int(self._physics_rate))
self._physics_dt = 1 / self._physics_rate
self._world = World(stage_units_in_meters=1.0, physics_dt=self._physics_dt, rendering_dt=32 * self._physics_dt)
await self._world.initialize_simulation_context_async()
self._world.scene.add_default_ground_plane(
z_position=0,
name="default_ground_plane",
prim_path="/World/defaultGroundPlane",
static_friction=0.2,
dynamic_friction=0.2,
restitution=0.01,
)
self._base_command = [0.0, 0, 0, 0]
self._stage = omni.usd.get_context().get_stage()
self._timeline = omni.timeline.get_timeline_interface()
self._path_follow = False
self._auto_start = True
await omni.kit.app.get_app().next_update_async()
pass
async def tearDown(self):
await omni.kit.app.get_app().next_update_async()
self._timeline.stop()
while omni.usd.get_context().get_stage_loading_status()[2] > 0:
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await omni.kit.app.get_app().next_update_async()
pass
async def test_go1_add(self):
self._path_follow = False
self._auto_start = True
await self.spawn_go1(model="Go1")
await omni.kit.app.get_app().next_update_async()
self._go1 = self._world.scene.get_object("Go1")
self.assertEqual(self._go1.num_dof, 12) # actually verify this number
self.assertTrue(get_prim_at_path("/World/Go1").IsValid(), True)
print("articulation check passed")
await omni.kit.app.get_app().next_update_async()
# if dc interface is valid, that means the prim is likely imported correctly
async def spawn_go1(self, waypoints=None, model="Go1"):
self._prim_path = "/World/" + model
self._go1 = self._world.scene.get_object("Go1")
if self._go1 is None:
self._go1 = self._world.scene.add(
Unitree(
prim_path=self._prim_path,
name=model,
position=np.array([1, 1, 0.45]),
physics_dt=self._physics_dt,
model=model,
way_points=waypoints,
)
)
self._go1._qp_controller.ctrl_state_reset()
self._world.add_physics_callback("go1_advance", callback_fn=self.on_physics_step)
await self._world.reset_async()
return
def on_physics_step(self, step_size):
if self._go1 and self._go1._handle:
# print(self._base_command)
self._go1.advance(
dt=step_size, goal=self._base_command, path_follow=self._path_follow, auto_start=self._auto_start
)
| 4,335 |
Python
| 38.063063 | 119 | 0.636448 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/a1_desired_states.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from dataclasses import dataclass, field
@dataclass
class A1DesiredStates:
""" A collection of desired goal states used by the QP agent """
_root_pos_d: np.array = field(default_factory=lambda: np.array([0.0, 0.0, 0.35]))
""" control goal paramter: the desired body position in world frame"""
_root_lin_vel_d: np.array = field(default_factory=lambda: np.array([0.0, 0.0, 0.0]))
""" control goal paramter: the desired body velocity in robot frame """
_euler_d: np.array = field(default_factory=lambda: np.array([0.0, 0.0, 0.0]))
""" control goal paramter: the desired body orientation in _euler angle """
_root_ang_vel_d: np.array = field(default_factory=lambda: np.array([0.0, 0.0, 0.0]))
""" control goal paramter: the desired body angular velocity """
| 1,244 |
Python
| 41.931033 | 88 | 0.721865 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/a1_classes.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from dataclasses import field, dataclass
import numpy as np
from omni.isaac.quadruped.utils.types import NamedTuple, FrameState
@dataclass
class A1State(NamedTuple):
"""The kinematic state of the articulated robot."""
base_frame: FrameState = field(default_factory=lambda: FrameState("root"))
"""State of base frame"""
joint_pos: np.ndarray = field(default_factory=lambda: np.zeros(12))
"""Joint positions with shape: (12,)"""
joint_vel: np.ndarray = field(default_factory=lambda: np.zeros(12))
"""Joint positions with shape: (12,)"""
@dataclass
class A1Measurement(NamedTuple):
"""The state of the robot along with the mounted sensor data."""
state: A1State = field(default=A1State)
"""The state of the robot."""
foot_forces: np.ndarray = field(default_factory=lambda: np.zeros(4))
"""Feet contact force of the robot in the order: FL, FR, RL, RR."""
base_lin_acc: np.ndarray = field(default_factory=lambda: np.zeros(3))
"""Accelerometer reading from IMU attached to robot's base."""
base_ang_vel: np.ndarray = field(default_factory=lambda: np.zeros(3))
"""Gyroscope reading from IMU attached to robot's base."""
@dataclass
class A1Command(NamedTuple):
"""The command on the robot actuators."""
desired_joint_torque: np.ndarray = field(default_factory=lambda: np.zeros(12))
"""Desired joint positions of the robot: (12,)"""
| 1,843 |
Python
| 34.461538 | 82 | 0.720564 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/actuator_network.py
|
# python
from typing import Union, Tuple
import numpy as np
from numpy import genfromtxt
import torch
class LstmSeaNetwork:
"""Implements an SEA network with LSTM hidden layers."""
def __init__(self):
# define the network
self._network = None
self._hidden_state = torch.zeros((2, 12, 8), requires_grad=False)
self._cell_state = torch.zeros((2, 12, 8), requires_grad=False)
# default joint position
self._default_joint_pos = None
"""
Properties
"""
def get_hidden_state(self) -> np.ndarray:
if self._hidden_state is None:
return np.zeros((12, 8))
else:
return self._hidden_state[1].detach().numpy()
"""
Operations
"""
def setup(self, path_or_buffer, default_joint_pos: Union[list, np.ndarray]):
# load the network from JIT file
self._network = torch.jit.load(path_or_buffer)
# set the default joint position
self._default_joint_pos = np.asarray(default_joint_pos)
def reset(self):
# reset the hidden state of LSTM
with torch.no_grad():
self._hidden_state[:, :, :] = 0.0
self._cell_state[:, :, :] = 0.0
@torch.no_grad()
def compute_torques(self, joint_pos, joint_vel, actions) -> Tuple[np.ndarray, np.ndarray]:
# create sea network input obs
actions = actions.copy()
actuator_net_input = torch.zeros((12, 1, 2))
actuator_net_input[:, 0, 0] = torch.from_numpy(actions + self._default_joint_pos - joint_pos)
actuator_net_input[:, 0, 1] = torch.from_numpy(np.clip(joint_vel, -20.0, 20))
# call the network
torques, (self._hidden_state, self._cell_state) = self._network(
actuator_net_input, (self._hidden_state, self._cell_state)
)
# return the torque to apply with clipping along with hidden state
return torques.detach().clip(-80.0, 80.0).numpy(), self._hidden_state[1].numpy()
class SeaNetwork(torch.nn.Module):
"""Implements a SEA network with MLP hidden layers."""
def __init__(self):
super().__init__()
# define layer architecture
self._sea_network = torch.nn.Sequential(
torch.nn.Linear(6, 32),
torch.nn.Softsign(),
torch.nn.Linear(32, 32),
torch.nn.Softsign(),
torch.nn.Linear(32, 1),
)
# define the delays
self._num_delays = 2
self._delays = [8, 3]
# define joint histories
self._history_size = self._delays[0]
self._joint_pos_history = np.zeros((12, self._history_size + 1))
self._joint_vel_history = np.zeros((12, self._history_size + 1))
# define scaling for the actuator network
self._sea_vel_scale = 0.4
self._sea_pos_scale = 3.0
self._sea_output_scale = 20.0
self._action_scale = 0.5
# default joint position
self._default_joint_pos = None
"""
Operations
"""
def setup(self, weights_path: str, default_joint_pos: Union[list, np.ndarray]):
# load the weights into network
self._load_weights(weights_path)
# set the default joint position
self._default_joint_pos = np.asarray(default_joint_pos)
def reset(self):
self._joint_pos_history.fill(0.0)
self._joint_vel_history.fill(0.0)
def compute_torques(self, joint_pos, joint_vel, actions) -> np.ndarray:
self._update_joint_history(joint_pos, joint_vel, actions)
return self._compute_sea_torque()
"""
Internal helpers.
"""
def _load_weights(self, weights_path: str):
# load the data
data = genfromtxt(weights_path, delimiter=",")
# manually defines the number of neurons in MLP
expected_num_params = 6 * 32 + 32 + 32 * 32 + 32 + 32 * 1 + 1
assert data.size == expected_num_params
# assign neuron weights to each linear layer
idx = 0
for layer in self._sea_network:
if not isinstance(layer, torch.nn.Softsign):
# layer weights
weight = np.reshape(
data[idx : idx + layer.in_features * layer.out_features],
newshape=(layer.in_features, layer.out_features),
).T
layer.weight = torch.nn.Parameter(torch.from_numpy(weight.astype(np.float32)))
idx += layer.out_features * layer.in_features
# layer biases
bias = data[idx : idx + layer.out_features]
layer.bias = torch.nn.Parameter(torch.from_numpy(bias.astype(np.float32)))
idx += layer.out_features
# set the module in eval mode
self.eval()
def _update_joint_history(self, joint_pos, joint_vel, actions):
# convert to numpy (sanity)
joint_pos = np.asarray(joint_pos)
joint_vel = np.asarray(joint_vel)
# compute error in position
joint_pos_error = self._action_scale * actions + self._default_joint_pos - joint_pos
# store into history
self._joint_pos_history[:, : self._history_size] = self._joint_pos_history[:, 1:]
self._joint_vel_history[:, : self._history_size] = self._joint_vel_history[:, 1:]
self._joint_pos_history[:, self._history_size] = joint_pos_error
self._joint_vel_history[:, self._history_size] = joint_vel
def _compute_sea_torque(self):
inp = torch.zeros((12, 6))
for dof in range(12):
inp[dof, 0] = self._sea_vel_scale * self._joint_vel_history[dof, self._history_size - self._delays[0]]
inp[dof, 1] = self._sea_vel_scale * self._joint_vel_history[dof, self._history_size - self._delays[1]]
inp[dof, 2] = self._sea_vel_scale * self._joint_vel_history[dof, self._history_size]
inp[dof, 3] = self._sea_pos_scale * self._joint_pos_history[dof, self._history_size - self._delays[0]]
inp[dof, 4] = self._sea_pos_scale * self._joint_pos_history[dof, self._history_size - self._delays[1]]
inp[dof, 5] = self._sea_pos_scale * self._joint_pos_history[dof, self._history_size]
return self._sea_output_scale * self._sea_network(inp)
# EOF
| 6,248 |
Python
| 38.301887 | 114 | 0.587388 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/rot_utils.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# python
import numba as nb
import numpy as np
@nb.jit(nopython=True)
def get_rotation_matrix_from_quaternion(quat: np.ndarray) -> np.ndarray:
"""Convert a quaternion to a rotation matrix.
Args:
quat (np.ndarray): A 4x1 vector in order (w, x, y, z)
Returns:
np.ndarray: The resulting 3x3 rotation matrix.
"""
w, x, y, z = quat
rot = np.array(
[
[2 * (w ** 2 + x ** 2) - 1, 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 2 * (w ** 2 + y ** 2) - 1, 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 2 * (w ** 2 + z ** 2) - 1],
]
)
return rot
@nb.jit(nopython=True)
def get_xyz_euler_from_quaternion(quat: np.ndarray) -> np.ndarray:
"""Convert a quaternion to XYZ euler angles.
Args:
quat (np.ndarray): A 4x1 vector in order (w, x, y, z).
Returns:
np.ndarray: A 3x1 vector containing (roll, pitch, yaw).
"""
w, x, y, z = quat
y_sqr = y * y
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y_sqr)
eulerx = np.arctan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
eulery = np.arcsin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y_sqr + z * z)
eulerz = np.arctan2(t3, t4)
result = np.zeros(3)
result[0] = eulerx
result[1] = eulery
result[2] = eulerz
return result
@nb.jit(nopython=True)
def get_quaternion_from_euler(euler: np.ndarray, order: str = "XYZ") -> np.ndarray:
"""Convert an euler angle to a quaternion based on specified euler angle order.
Supported Euler angle orders: {'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY'}.
Args:
euler (np.ndarray): A 3x1 vector with angles in radians.
order (str, optional): The specified order of input euler angles. Defaults to "XYZ".
Raises:
ValueError: If input order is not valid.
Reference:
[1] https://github.com/mrdoob/three.js/blob/master/src/math/Quaternion.js
"""
# extract input angles
r, p, y = euler
# compute constants
y = y / 2.0
p = p / 2.0
r = r / 2.0
c3 = np.cos(y)
s3 = np.sin(y)
c2 = np.cos(p)
s2 = np.sin(p)
c1 = np.cos(r)
s1 = np.sin(r)
# convert to quaternion based on order
if order == "XYZ":
result = np.array(
[
c1 * c2 * c3 - s1 * s2 * s3,
c1 * s2 * s3 + c2 * c3 * s1,
c1 * c3 * s2 - s1 * c2 * s3,
c1 * c2 * s3 + s1 * c3 * s2,
]
)
if result[0] < 0:
result = -result
return result
elif order == "YXZ":
result = np.array(
[
c1 * c2 * c3 + s1 * s2 * s3,
s1 * c2 * c3 + c1 * s2 * s3,
c1 * s2 * c3 - s1 * c2 * s3,
c1 * c2 * s3 - s1 * s2 * c3,
]
)
return result
elif order == "ZXY":
result = np.array(
[
c1 * c2 * c3 - s1 * s2 * s3,
s1 * c2 * c3 - c1 * s2 * s3,
c1 * s2 * c3 + s1 * c2 * s3,
c1 * c2 * s3 + s1 * s2 * c3,
]
)
return result
elif order == "ZYX":
result = np.array(
[
c1 * c2 * c3 + s1 * s2 * s3,
s1 * c2 * c3 - c1 * s2 * s3,
c1 * s2 * c3 + s1 * c2 * s3,
c1 * c2 * s3 - s1 * s2 * c3,
]
)
return result
elif order == "YZX":
result = np.array(
[
c1 * c2 * c3 - s1 * s2 * s3,
s1 * c2 * c3 + c1 * s2 * s3,
c1 * s2 * c3 + s1 * c2 * s3,
c1 * c2 * s3 - s1 * s2 * c3,
]
)
return result
elif order == "XZY":
result = np.array(
[
c1 * c2 * c3 + s1 * s2 * s3,
s1 * c2 * c3 - c1 * s2 * s3,
c1 * s2 * c3 - s1 * c2 * s3,
c1 * c2 * s3 + s1 * s2 * c3,
]
)
return result
else:
raise ValueError("Input euler angle order is meaningless.")
@nb.jit(nopython=True)
def get_rotation_matrix_from_euler(euler: np.ndarray, order: str = "XYZ") -> np.ndarray:
quat = get_quaternion_from_euler(euler, order)
return get_rotation_matrix_from_quaternion(quat)
@nb.jit(nopython=True)
def quat_multiplication(q: np.ndarray, p: np.ndarray) -> np.ndarray:
"""Compute the product of two quaternions.
Args:
q (np.ndarray): First quaternion in order (w, x, y, z).
p (np.ndarray): Second quaternion in order (w, x, y, z).
Returns:
np.ndarray: A 4x1 vector representing a quaternion in order (w, x, y, z).
"""
quat = np.array(
[
p[0] * q[0] - p[1] * q[1] - p[2] * q[2] - p[3] * q[3],
p[0] * q[1] + p[1] * q[0] - p[2] * q[3] + p[3] * q[2],
p[0] * q[2] + p[1] * q[3] + p[2] * q[0] - p[3] * q[1],
p[0] * q[3] - p[1] * q[2] + p[2] * q[1] + p[3] * q[0],
]
)
return quat
@nb.jit(nopython=True)
def skew(vector: np.ndarray) -> np.ndarray:
"""Convert vector to skew symmetric matrix.
This function returns a skew-symmetric matrix to perform cross-product
as a matrix multiplication operation, i.e.:
np.cross(a, b) = np.dot(skew(a), b)
Args:
vector (np.ndarray): A 3x1 vector.
Returns:
np.ndarray: The resluting skew-symmetric matrix.
"""
mat = np.array([[0, -vector[2], vector[1]], [vector[2], 0, -vector[0]], [-vector[1], vector[0], 0]])
return mat
| 6,140 |
Python
| 27.966981 | 104 | 0.484528 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/__init__.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.quadruped.utils.a1_classes import A1State, A1Command, A1Measurement
from omni.isaac.quadruped.utils.types import NamedTuple, FrameState
from omni.isaac.quadruped.utils.a1_ctrl_states import A1CtrlStates
from omni.isaac.quadruped.utils.a1_ctrl_params import A1CtrlParams
from omni.isaac.quadruped.utils.a1_desired_states import A1DesiredStates
from omni.isaac.quadruped.utils.a1_sys_model import A1SysModel
from omni.isaac.quadruped.utils.go1_sys_model import Go1SysModel
from omni.isaac.quadruped.utils.actuator_network import LstmSeaNetwork
from omni.isaac.quadruped.utils import rot_utils
| 1,036 |
Python
| 53.578945 | 83 | 0.833012 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/go1_sys_model.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""[summary]
The kinematics parameters value come from
https://github.com/unitreerobotics/unitree_ros/blob/master/robots/a1_description/xacro/const.xacro
It calculates the forward kinematics and jacobians of the Unitree A1 robot legs
"""
import numpy as np
from dataclasses import dataclass
@dataclass(frozen=True)
class Go1SysModel:
"""Constants and functions related to the forward kinematics of the robot"""
"""
Properties
"""
THIGH_OFFSET = 0.08
"""constant: the length of the thigh motor"""
LEG_OFFSET_X = 0.1881
"""constant: x distance from the robot COM to the leg base"""
LEG_OFFSET_Y = 0.04675
"""constant: y distance from the robot COM to the leg base"""
THIGH_LENGTH = 0.213
"""constant: length of the leg"""
C_FR = 0
"""constant: FR leg id in A1's hardware convention"""
C_FL = 1
"""constant: FL leg id in A1's hardware convention"""
C_RR = 2
"""constant: RR leg id in A1's hardware convention"""
C_RL = 3
"""constant: RL leg id in A1's hardware convention"""
def __init__(self):
"""Initializes the class instance.
"""
pass
"""
Operations
"""
def forward_kinematics(self, idx: int, q: np.array) -> np.array:
"""get the forward_kinematics of the leg
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
"""
# these two variables indicates the quadrant of the leg
fx = self.LEG_OFFSET_X
fy = self.LEG_OFFSET_Y
d = self.THIGH_OFFSET
if idx == self.C_FR:
fy *= -1
d *= -1
elif idx == self.C_FL:
pass
elif idx == self.C_RR:
fx *= -1
fy *= -1
d *= -1
else:
fx *= -1
length = self.THIGH_LENGTH
q1 = q[0]
q2 = q[1]
q3 = q[2]
p = np.zeros(3)
p[0] = fx - length * np.sin(q2 + q3) - length * np.sin(q2)
p[1] = (
fy
+ d * np.cos(q1)
+ length * np.cos(q2) * np.sin(q1)
+ length * np.cos(q2) * np.cos(q3) * np.sin(q1)
- length * np.sin(q1) * np.sin(q2) * np.sin(q3)
)
p[2] = (
d * np.sin(q1)
- length * np.cos(q1) * np.cos(q2)
- length * np.cos(q1) * np.cos(q2) * np.cos(q3)
+ length * np.cos(q1) * np.sin(q2) * np.sin(q3)
)
return p
def jacobian(self, idx: int, q: np.array) -> np.ndarray:
"""get the jacobian of the leg
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
"""
# these two variables indicates the quadrant of the leg
fx = self.LEG_OFFSET_X
fy = self.LEG_OFFSET_Y
d = self.THIGH_OFFSET
if idx == self.C_FR:
fy *= -1
d *= -1
elif idx == self.C_FL:
pass
elif idx == self.C_RR:
fx *= -1
fy *= -1
d *= -1
else:
fx *= -1
length = self.THIGH_LENGTH
q1 = q[0]
q2 = q[1]
q3 = q[2]
J = np.zeros([3, 3])
# J[1,1] = 0
J[0, 1] = -length * (np.cos(q2 + q3) + np.cos(q2))
J[0, 2] = -length * np.cos(q2 + q3)
J[1, 0] = (
length * np.cos(q1) * np.cos(q2)
- d * np.sin(q1)
+ length * np.cos(q1) * np.cos(q2) * np.cos(q3)
- length * np.cos(q1) * np.sin(q2) * np.sin(q3)
)
J[1, 1] = -length * np.sin(q1) * (np.sin(q2 + q3) + np.sin(q2))
J[1, 2] = -length * np.sin(q2 + q3) * np.sin(q1)
J[2, 0] = (
d * np.cos(q1)
+ length * np.cos(q2) * np.sin(q1)
+ length * np.cos(q2) * np.cos(q3) * np.sin(q1)
- length * np.sin(q1) * np.sin(q2) * np.sin(q3)
)
J[2, 1] = length * np.cos(q1) * (np.sin(q2 + q3) + np.sin(q2))
J[2, 2] = length * np.sin(q2 + q3) * np.cos(q1)
return J
def foot_vel(self, idx: int, q: np.array, dq: np.array) -> np.array:
"""get the foot velocity
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
dq {np.array}: the joint angular velocities of a leg
"""
my_jacobian = self.jacobian(idx, q)
vel = my_jacobian @ dq
return vel
| 5,027 |
Python
| 29.472727 | 98 | 0.519594 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/types.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# enable deferred annotations
from __future__ import annotations
# python
import dataclasses
from dataclasses import dataclass, field
from typing import List, Union, Dict, Any
import numpy as np
@dataclass
class NamedTuple(object):
"""[Summary]
The backend data structure for data-passing between various modules.
In order to support use cases where the data would have mixed types (such as bool/integer/array), we provide a
light data-class to capture this formalism while allowing the data to be shared between different modules easily.
The objective is to support complex agent designs and support multi-agent environments.
The usage of this class is quite similar to that of a dictionary, since underneath, we rely on the key names to
"pass" data from one container into another. However, we do not use the dictionary since a data-class helps in
providing type hints which is in practice quite useful.
Reference:
https://stackoverflow.com/questions/51671699/data-classes-vs-typing-namedtuple-primary-use-cases
"""
def update(self, data: Union[NamedTuple, List[NamedTuple], Dict[str, Any]]):
"""Update values from another named tuple.
Note:
Unlike `dict.update(dict)`, this method does not add element(s) to the instance if the key is not present.
Arguments:
data {Union[NamedTuple, List[NamedTuple], Dict[str, Any]} -- The input data to update values from.
Raises:
TypeError -- When input data is not of type :class:`NamedTuple` or :class:`List[NamedTuple]`.
"""
# convert to dictionary
if isinstance(data, dict):
data_dict = data
elif isinstance(data, list):
data_dict = {}
for d in data:
data_dict.update(d.__dict__)
elif isinstance(data, NamedTuple):
data_dict = data.__dict__
else:
name = self.__class__.__name__
raise TypeError(
f"Invalid input data type: {type(data)}. Valid: [`{name}`, `List[{name}]`, `Dict[str, Any]`]."
)
# iterate over dictionary and add values to matched keys
for key, value in data_dict.items():
try:
self.__setattr__(key, value)
except AttributeError:
pass
def as_dict(self) -> dict:
"""Converts the dataclass to dictionary recursively.
Returns:
dict: Instance information as a dictionary
"""
return dataclasses.asdict(self)
@dataclass
class FrameState(NamedTuple):
"""The state of a kinematic frame.
Attributes:
name: The name of the frame.
pos: The Cartesian position of the frame.
quat: The quaternion orientation (x, y, z, w) of the frame.
lin_vel: The linear velocity of the frame.
ang_vel: The angular velocity of the frame.
"""
name: str
"""Frame name."""
pos: np.ndarray = field(default_factory=lambda: np.zeros(3))
"""Catersian position of frame."""
quat: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0, 0.0, 1.0]))
"""Quaternion orientation of frame: (x, y, z, w)"""
lin_vel: np.ndarray = field(default_factory=lambda: np.zeros(3))
"""Linear velocity of frame."""
ang_vel: np.ndarray = field(default_factory=lambda: np.zeros(3))
"""Angular velocity of frame."""
@property
def pose(self) -> np.ndarray:
"""Returns: A numpy array with position and orientation."""
return np.concatenate([self.pos, self.quat])
# EOF
| 4,051 |
Python
| 33.931034 | 118 | 0.651691 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/a1_sys_model.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""[summary]
The kinematics parameters value come from
https://github.com/unitreerobotics/unitree_ros/blob/master/robots/a1_description/xacro/const.xacro
It calculates the forward kinematics and jacobians of the Unitree A1 robot legs
"""
import numpy as np
from dataclasses import dataclass
@dataclass(frozen=True)
class A1SysModel:
"""Constants and functions related to the forward kinematics of the robot"""
"""
Properties
"""
THIGH_OFFSET = 0.0838
"""constant: the length of the thigh motor"""
LEG_OFFSET_X = 0.1805
"""constant: x distance from the robot COM to the leg base"""
LEG_OFFSET_Y = 0.047
"""constant: y distance from the robot COM to the leg base"""
THIGH_LENGTH = 0.22
"""constant: length of the leg"""
C_FR = 0
"""constant: FR leg id in A1's hardware convention"""
C_FL = 1
"""constant: FL leg id in A1's hardware convention"""
C_RR = 2
"""constant: RR leg id in A1's hardware convention"""
C_RL = 3
"""constant: RL leg id in A1's hardware convention"""
def __init__(self):
"""Initializes the class instance.
"""
pass
"""
Operations
"""
def forward_kinematics(self, idx: int, q: np.array) -> np.array:
"""get the forward_kinematics of the leg
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
"""
# these two variables indicates the quadrant of the leg
fx = self.LEG_OFFSET_X
fy = self.LEG_OFFSET_Y
d = self.THIGH_OFFSET
if idx == self.C_FR:
fy *= -1
d *= -1
elif idx == self.C_FL:
pass
elif idx == self.C_RR:
fx *= -1
fy *= -1
d *= -1
else:
fx *= -1
length = self.THIGH_LENGTH
q1 = q[0]
q2 = q[1]
q3 = q[2]
p = np.zeros(3)
p[0] = fx - length * np.sin(q2 + q3) - length * np.sin(q2)
p[1] = (
fy
+ d * np.cos(q1)
+ length * np.cos(q2) * np.sin(q1)
+ length * np.cos(q2) * np.cos(q3) * np.sin(q1)
- length * np.sin(q1) * np.sin(q2) * np.sin(q3)
)
p[2] = (
d * np.sin(q1)
- length * np.cos(q1) * np.cos(q2)
- length * np.cos(q1) * np.cos(q2) * np.cos(q3)
+ length * np.cos(q1) * np.sin(q2) * np.sin(q3)
)
return p
def jacobian(self, idx: int, q: np.array) -> np.ndarray:
"""get the jacobian of the leg
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
"""
# these two variables indicates the quadrant of the leg
fx = self.LEG_OFFSET_X
fy = self.LEG_OFFSET_Y
d = self.THIGH_OFFSET
if idx == self.C_FR:
fy *= -1
d *= -1
elif idx == self.C_FL:
pass
elif idx == self.C_RR:
fx *= -1
fy *= -1
d *= -1
else:
fx *= -1
length = self.THIGH_LENGTH
q1 = q[0]
q2 = q[1]
q3 = q[2]
J = np.zeros([3, 3])
# J[1,1] = 0
J[0, 1] = -length * (np.cos(q2 + q3) + np.cos(q2))
J[0, 2] = -length * np.cos(q2 + q3)
J[1, 0] = (
length * np.cos(q1) * np.cos(q2)
- d * np.sin(q1)
+ length * np.cos(q1) * np.cos(q2) * np.cos(q3)
- length * np.cos(q1) * np.sin(q2) * np.sin(q3)
)
J[1, 1] = -length * np.sin(q1) * (np.sin(q2 + q3) + np.sin(q2))
J[1, 2] = -length * np.sin(q2 + q3) * np.sin(q1)
J[2, 0] = (
d * np.cos(q1)
+ length * np.cos(q2) * np.sin(q1)
+ length * np.cos(q2) * np.cos(q3) * np.sin(q1)
- length * np.sin(q1) * np.sin(q2) * np.sin(q3)
)
J[2, 1] = length * np.cos(q1) * (np.sin(q2 + q3) + np.sin(q2))
J[2, 2] = length * np.sin(q2 + q3) * np.cos(q1)
return J
def foot_vel(self, idx: int, q: np.array, dq: np.array) -> np.array:
"""get the foot velocity
Arguments:
idx {int}: the index of the leg, must use the A1 hardware convention
q {np.array}: the joint angles of a leg
dq {np.array}: the joint angular velocities of a leg
"""
my_jacobian = self.jacobian(idx, q)
vel = my_jacobian @ dq
return vel
| 5,025 |
Python
| 29.460606 | 98 | 0.519403 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/a1_ctrl_params.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from dataclasses import dataclass, field
@dataclass
class A1CtrlParams:
""" A collection of parameters used by the QP agent """
_robot_mass: float = field(default=16.0)
"""The mass of the robot"""
_swap_foot_indices: np.array = field(default=np.array([1, 0, 3, 2], dtype=int))
"""A index list help to convert between A1 hardware leg index order and A1 Isaac Sim leg index order"""
_foot_force_low: float = field(default=5.0)
""" controller parameter: the low threshold of foot contact force"""
_default_foot_pos: np.ndarray = field(
default=np.array([[+0.17, +0.15, -0.3], [+0.17, -0.15, -0.3], [-0.17, +0.15, -0.3], [-0.17, -0.15, -0.3]])
)
""" controller parameter: the default foot pos in robot frame when the robot is standing still"""
_kp_lin_x: float = field(default=0.0)
""" control parameter: the raibert foothold strategy, x position target coefficient"""
_kd_lin_x: float = field(default=0.15)
""" control parameter: the raibert foothold strategy, x velocity target coefficient"""
_kf_lin_x: float = field(default=0.2)
""" control parameter: the raibert foothold strategy, x desired velocity target coefficient"""
_kp_lin_y: float = field(default=0.0)
""" control parameter: the raibert foothold strategy, y position target coefficient"""
_kd_lin_y: float = field(default=0.1)
""" control parameter: the raibert foothold strategy, y velocity target coefficient"""
_kf_lin_y: float = field(default=0.2)
""" control parameter: the raibert foothold strategy, y desired velocity target coefficient"""
_kp_foot: np.ndarray = field(
default=np.array(
[[500.0, 500.0, 2000.0], [500.0, 500.0, 2000.0], [500.0, 500.0, 2000.0], [500.0, 500.0, 2000.0]]
)
)
""" control parameter: the swing foot position error coefficient"""
_kd_foot: np.ndarray = field(default=np.array([0.0, 0.0, 0.0]))
""" control parameter: the swing foot velocity error coefficient"""
_km_foot: np.ndarray = field(default=np.diag([0.1, 0.1, 0.02]))
""" control parameter: the swing foot force amplitude coefficient"""
_kp_linear: np.ndarray = field(default=np.array([20.0, 20.0, 2000.0]))
""" control parameter: the stance foot force position error coefficient"""
_kd_linear: np.ndarray = field(default=np.array([50.0, 50.0, 0.0]))
""" control parameter: the stance foot force velocity error coefficient"""
_kp_angular: np.ndarray = field(default=np.array([600.0, 600.0, 10.0]))
""" control parameter: the stance foot force orientation error coefficient"""
_kd_angular: np.ndarray = field(default=np.array([3.0, 3.0, 10.0]))
""" control parameter: the stance foot force orientation angular velocity error coefficient"""
_torque_gravity: np.ndarray = field(default=np.array([0.80, 0, 0, -0.80, 0, 0, 0.80, 0, 0, -0.80, 0, 0]))
""" control parameter: gravity compentation heuristic"""
| 3,415 |
Python
| 43.363636 | 114 | 0.675842 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/utils/a1_ctrl_states.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import numpy as np
from dataclasses import dataclass, field
@dataclass
class A1CtrlStates:
""" A collection of variables used by the QP agent """
_counter_per_gait: float = field(default=240.0)
"""The number of ticks of one gait cycle"""
_counter_per_swing: float = field(default=120.0)
"""The number of ticks of one swing phase (half of the gait cycle)"""
_counter: float = field(default=0.0)
"""A _counter used to determine how many ticks since the simulation starts"""
_exp_time: float = field(default=0.0)
"""Simulation time since the simulation starts"""
_gait_counter: np.array = field(default_factory=lambda: np.zeros(4))
"""Each leg has its own _counter with initial phase"""
_gait_counter_speed: np.array = field(default_factory=lambda: np.zeros(4))
"""The speed of gait _counter update"""
_root_pos: np.array = field(default_factory=lambda: np.zeros(3))
"""feedback state: robot position in world frame"""
_root_quat: np.array = field(default_factory=lambda: np.zeros(4))
"""feedback state: robot quaternion in world frame"""
_root_lin_vel: np.array = field(default_factory=lambda: np.zeros(3))
"""feedback state: robot linear velocity in world frame"""
_root_ang_vel: np.array = field(default_factory=lambda: np.zeros(3))
"""feedback state: robot angular velocity in world frame"""
# 오타 같은데, robot frame 같음
_joint_pos: np.array = field(default_factory=lambda: np.zeros(12))
"""feedback state: robot motor joint angles"""
_joint_vel: np.array = field(default_factory=lambda: np.zeros(12))
"""feedback state: robot motor joint angular velocities"""
_foot_forces: np.array = field(default_factory=lambda: np.zeros(4))
"""feedback state: robot foot contact forces"""
_foot_pos_target_world: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot target pos in the world frame"""
_foot_pos_target_abs: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot target pos in the absolute frame (rotated robot frame)"""
_foot_pos_target_rel: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot target pos in the relative frame (robot frame)"""
_foot_pos_start_rel: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot current pos in the relative frame (robot frame)"""
_euler: np.array = field(default_factory=lambda: np.zeros(3))
"""indirect feedback state: robot _euler angle in world frame"""
_rot_mat: np.ndarray = field(default_factory=lambda: np.zeros([3, 3]))
"""indirect feedback state: robot rotation matrix in world frame"""
_rot_mat_z: np.ndarray = field(default_factory=lambda: np.zeros([3, 3]))
"""indirect feedback state: robot rotation matrix with just the yaw angle in world frame"""
# R^{world}_{robot yaw}
_foot_pos_abs: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot current pos in the absolute frame (rotated robot frame)"""
_foot_pos_rel: np.ndarray = field(default_factory=lambda: np.zeros([4, 3]))
""" controller variables: the foot current pos in the relative frame (robot frame)"""
_j_foot: np.ndarray = field(default_factory=lambda: np.zeros([12, 12]))
""" controller variables: the foot jacobian in the relative frame (robot frame)"""
_gait_type: int = field(default=1)
""" control variable: type of gait, currently only 1 is defined, which is a troting gait"""
_gait_type_last: int = field(default=1)
""" control varialbe: saves the previous gait. Reserved for future use"""
_contacts: np.array = field(default_factory=lambda: np.array([False] * 4))
""" control varialbe: determine each foot has contact with ground or not"""
_early_contacts: np.array = field(default_factory=lambda: np.array([False] * 4))
""" control varialbe: determine each foot has early contact with ground or not (unexpect contact during foot swing)"""
_init_transition: int = field(default=0)
""" control variable: determine whether the robot should be in walking mode or standstill mode """
_prev_transition: int = field(default=0)
""" control variable: previous mode"""
| 4,796 |
Python
| 44.685714 | 122 | 0.69558 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/robots/unitree.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni
import omni.kit.commands
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path, define_prim
from omni.isaac.sensor import _sensor
from omni.isaac.core.utils.stage import get_current_stage, get_stage_units
from omni.isaac.core.articulations import Articulation
from omni.isaac.quadruped.utils.a1_classes import A1State, A1Measurement, A1Command
from omni.isaac.quadruped.controllers import A1QPController
from omni.isaac.sensor import ContactSensor, IMUSensor
from typing import Optional, List
from collections import deque
import numpy as np
import carb
class Unitree(Articulation):
"""For unitree based quadrupeds (A1 or Go1)"""
def __init__(
self,
prim_path: str,
name: str = "unitree_quadruped",
physics_dt: Optional[float] = 1 / 400.0,
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
model: Optional[str] = "A1",
way_points: Optional[np.ndarray] = None,
) -> None:
"""
[Summary]
initialize robot, set up sensors and controller
Args:
prim_path {str} -- prim path of the robot on the stage
name {str} -- name of the quadruped
physics_dt {float} -- physics downtime of the controller
usd_path {str} -- robot usd filepath in the directory
position {np.ndarray} -- position of the robot
orientation {np.ndarray} -- orientation of the robot
model {str} -- robot model (can be either A1 or Go1)
way_points {np.ndarray} -- waypoint and heading of the robot
"""
self._stage = get_current_stage()
self._prim_path = prim_path
prim = get_prim_at_path(self._prim_path)
if not prim.IsValid():
prim = define_prim(self._prim_path, "Xform")
if usd_path:
prim.GetReferences().AddReference(usd_path)
else:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets server")
if model == "A1":
asset_path = assets_root_path + "/Isaac/Robots/Unitree/a1.usd"
else:
asset_path = assets_root_path + "/Isaac/Robots/Unitree/go1.usd"
carb.log_warn("asset path is: " + asset_path)
prim.GetReferences().AddReference(asset_path)
# state, foot_forces, base_lin_acc, base_ang_vel
self._measurement = A1Measurement()
# desired_joint_torque
self._command = A1Command()
# base_frame, joint_pos, joint_vel
self._state = A1State()
# base_frame, joint_pos, joint_vel
self._default_a1_state = A1State()
if position is not None:
self._default_a1_state.base_frame.pos = np.asarray(position)
else:
self._default_a1_state.base_frame.pos = np.array([0.0, 0.0, 0.0])
self._default_a1_state.base_frame.quat = np.array([0.0, 0.0, 0.0, 1.0])
self._default_a1_state.base_frame.ang_vel = np.array([0.0, 0.0, 0.0])
self._default_a1_state.base_frame.lin_vel = np.array([0.0, 0.0, 0.0])
self._default_a1_state.joint_pos = np.array([0.0, 1.2, -1.8, 0, 1.2, -1.8, 0.0, 1.2, -1.8, 0, 1.2, -1.8])
self._default_a1_state.joint_vel = np.zeros(12)
self._goal = np.zeros(3)
self.meters_per_unit = get_stage_units()
super().__init__(prim_path=self._prim_path, name=name, position=position, orientation=orientation)
# contact sensor setup
# "FL", "FR", "RL", "RR"
self.feet_order = ["FL", "FR", "RL", "RR"]
self.feet_path = [
self._prim_path + "/FL_foot",
self._prim_path + "/FR_foot",
self._prim_path + "/RL_foot",
self._prim_path + "/RR_foot",
]
self.color = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)]
self._contact_sensors = [None] * 4
for i in range(4):
self._contact_sensors[i] = ContactSensor(
prim_path=self.feet_path[i] + "/sensor",
min_threshold=0,
max_threshold=1000000,
radius=0.03,
dt=physics_dt,
)
self.foot_force = np.zeros(4)
self.enable_foot_filter = True
self._FILTER_WINDOW_SIZE = 20
self._foot_filters = [deque(), deque(), deque(), deque()]
# imu sensor setup
self.imu_path = self._prim_path + "/imu_link"
self._imu_sensor = IMUSensor(
prim_path=self.imu_path + "/imu_sensor",
name="imu",
dt=physics_dt,
translation=np.array([0, 0, 0]),
orientation=np.array([1, 0, 0, 0]),
)
self.base_lin = np.zeros(3)
self.ang_vel = np.zeros(3)
# Controller
self.physics_dt = physics_dt
if way_points:
self._qp_controller = A1QPController(model, self.physics_dt, way_points)
else:
self._qp_controller = A1QPController(model, self.physics_dt)
self._qp_controller.setup()
self._dof_control_modes: List[int] = list()
return
def set_state(self, state: A1State) -> None:
"""[Summary]
Set the kinematic state of the robot.
Args:
state {A1State} -- The state of the robot to set.
Raises:
RuntimeError: When the DC Toolbox interface has not been configured.
"""
self.set_world_pose(position=state.base_frame.pos, orientation=state.base_frame.quat[[3, 0, 1, 2]])
self.set_linear_velocity(state.base_frame.lin_vel)
self.set_angular_velocity(state.base_frame.ang_vel)
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert controller order to DC order for setting state
self.set_joint_positions(
positions=np.asarray(np.array(state.joint_pos.reshape([4, 3]).T.flat), dtype=np.float32)
)
self.set_joint_velocities(
velocities=np.asarray(np.array(state.joint_vel.reshape([4, 3]).T.flat), dtype=np.float32)
)
self.set_joint_efforts(np.zeros_like(state.joint_pos))
return
def update_contact_sensor_data(self) -> None:
"""[summary]
Updates processed contact sensor data from the robot feets, store them in member variable foot_force
"""
# Order: FL, FR, BL, BR
for i in range(len(self.feet_path)):
frame = self._contact_sensors[i].get_current_frame()
if "force" in frame:
if self.enable_foot_filter:
self._foot_filters[i].append(frame["force"])
if len(self._foot_filters[i]) > self._FILTER_WINDOW_SIZE:
self._foot_filters[i].popleft()
self.foot_force[i] = np.mean(self._foot_filters[i])
else:
self.foot_force[i] = frame["force"]
def update_imu_sensor_data(self) -> None:
"""[summary]
Updates processed imu sensor data from the robot body, store them in member variable base_lin and ang_vel
"""
frame = self._imu_sensor.get_current_frame()
self.base_lin = frame["lin_acc"]
self.ang_vel = frame["ang_vel"]
return
def update(self) -> None:
"""[summary]
update robot sensor variables, state variables in A1Measurement
"""
self.update_contact_sensor_data()
self.update_imu_sensor_data()
# joint pos and vel from the DC interface
self.joint_state = super().get_joints_state()
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert DC order to controller order for joint info
self._state.joint_pos = np.array(self.joint_state.positions.reshape([3, 4]).T.flat)
self._state.joint_vel = np.array(self.joint_state.velocities.reshape([3, 4]).T.flat)
# base frame
base_pose = self.get_world_pose()
self._state.base_frame.pos = base_pose[0]
self._state.base_frame.quat = base_pose[1][[1, 2, 3, 0]]
self._state.base_frame.lin_vel = self.get_linear_velocity()
self._state.base_frame.ang_vel = self.get_angular_velocity()
# assign to _measurement obj
self._measurement.state = self._state
self._measurement.foot_forces = np.asarray(self.foot_force)
self._measurement.base_ang_vel = np.asarray(self.ang_vel)
self._measurement.base_lin_acc = np.asarray(self.base_lin)
return
def advance(self, dt, goal, path_follow=False, auto_start=True) -> np.ndarray:
"""[summary]
compute desired torque and set articulation effort to robot joints
Argument:
dt {float} -- Timestep update in the world.
goal {List[int]} -- x velocity, y velocity, angular velocity, state switch
path_follow {bool} -- true for following coordinates, false for keyboard control
auto_start {bool} -- true for start trotting after 1 sec, false for start trotting after switch mode function is called
Returns:
np.ndarray -- The desired joint torques for the robot.
"""
if goal is None:
goal = self._goal
else:
self._goal = goal
self.update()
self._qp_controller.set_target_command(goal)
self._command.desired_joint_torque = self._qp_controller.advance(dt, self._measurement, path_follow, auto_start)
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert controller order to DC order for command torque
torque_reorder = np.array(self._command.desired_joint_torque.reshape([4, 3]).T.flat)
self.set_joint_efforts(np.asarray(torque_reorder, dtype=np.float32))
return self._command
def initialize(self, physics_sim_view=None) -> None:
"""[summary]
initialize dc interface, set up drive mode and initial robot state
"""
super().initialize(physics_sim_view=physics_sim_view)
self.get_articulation_controller().set_effort_modes("force")
self.get_articulation_controller().switch_control_mode("effort")
self.set_state(self._default_a1_state)
for i in range(4):
self._contact_sensors[i].initialize()
return
def post_reset(self) -> None:
"""[summary]
post reset articulation and qp_controller
"""
super().post_reset()
for i in range(4):
self._contact_sensors[i].post_reset()
self._qp_controller.reset()
self.set_state(self._default_a1_state)
return
| 12,884 |
Python
| 39.518868 | 127 | 0.593294 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/robots/unitree_vision.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# python
from typing import Optional
import numpy as np
# omniverse
from pxr import UsdGeom, Gf
import omni.kit.commands
import omni.usd
import omni.graph.core as og
from omni.isaac.quadruped.robots import Unitree
from omni.isaac.core.utils.viewports import set_camera_view
from omni.kit.viewport.utility import get_active_viewport, get_viewport_from_window_name
from omni.isaac.core.utils.prims import set_targets
class UnitreeVision(Unitree):
"""[Summary]
For unitree based quadrupeds (A1 or Go1) with camera
"""
def __init__(
self,
prim_path: str,
name: str = "unitree_quadruped",
physics_dt: Optional[float] = 1 / 400.0,
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
model: Optional[str] = "A1",
is_ros2: Optional[bool] = False,
way_points: Optional[np.ndarray] = None,
) -> None:
"""
[Summary]
initialize robot, set up sensors and controller
Arguments:
prim_path {str} -- prim path of the robot on the stage
name {str} -- name of the quadruped
physics_dt {float} -- physics downtime of the controller
usd_path {str} -- robot usd filepath in the directory
position {np.ndarray} -- position of the robot
orientation {np.ndarray} -- orientation of the robot
model {str} -- robot model (can be either A1 or Go1)
way_points {np.ndarray} -- waypoints for the robot
"""
super().__init__(prim_path, name, physics_dt, usd_path, position, orientation, model, way_points)
self.image_width = 640
self.image_height = 480
self.cameras = [
# 0name, 1offset, 2orientation, 3hori aperture, 4vert aperture, 5projection, 6focal length, 7focus distance
("/camera_left", Gf.Vec3d(0.2693, 0.025, 0.067), (90, 0, -90), 21, 16, "perspective", 24, 400),
("/camera_right", Gf.Vec3d(0.2693, -0.025, 0.067), (90, 0, -90), 21, 16, "perspective", 24, 400),
]
self.camera_graphs = []
# after stage is defined
self._stage = omni.usd.get_context().get_stage()
# add cameras on the imu link
for i in range(len(self.cameras)):
# add camera prim
camera = self.cameras[i]
camera_path = self._prim_path + "/imu_link" + camera[0]
camera_prim = UsdGeom.Camera(self._stage.DefinePrim(camera_path, "Camera"))
xform_api = UsdGeom.XformCommonAPI(camera_prim)
xform_api.SetRotate(camera[2], UsdGeom.XformCommonAPI.RotationOrderXYZ)
xform_api.SetTranslate(camera[1])
camera_prim.GetHorizontalApertureAttr().Set(camera[3])
camera_prim.GetVerticalApertureAttr().Set(camera[4])
camera_prim.GetProjectionAttr().Set(camera[5])
camera_prim.GetFocalLengthAttr().Set(camera[6])
camera_prim.GetFocusDistanceAttr().Set(camera[7])
self.is_ros2 = is_ros2
ros_version = "ROS1"
ros_bridge_version = "ros_bridge."
self.ros_vp_offset = 1
if self.is_ros2:
ros_version = "ROS2"
ros_bridge_version = "ros2_bridge."
# Creating an on-demand push graph with cameraHelper nodes to generate ROS image publishers
keys = og.Controller.Keys
graph_path = "/ROS_" + camera[0].split("/")[-1]
(camera_graph, _, _, _) = og.Controller.edit(
{
"graph_path": graph_path,
"evaluator_name": "execution",
"pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION,
},
{
keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("createViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
("setViewportResolution", "omni.isaac.core_nodes.IsaacSetViewportResolution"),
("getRenderProduct", "omni.isaac.core_nodes.IsaacGetViewportRenderProduct"),
("setCamera", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"),
("cameraHelperRgb", "omni.isaac." + ros_bridge_version + ros_version + "CameraHelper"),
("cameraHelperInfo", "omni.isaac." + ros_bridge_version + ros_version + "CameraHelper"),
],
keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "createViewport.inputs:execIn"),
("createViewport.outputs:execOut", "setViewportResolution.inputs:execIn"),
("createViewport.outputs:viewport", "setViewportResolution.inputs:viewport"),
("createViewport.outputs:execOut", "getRenderProduct.inputs:execIn"),
("createViewport.outputs:viewport", "getRenderProduct.inputs:viewport"),
("getRenderProduct.outputs:execOut", "setCamera.inputs:execIn"),
("getRenderProduct.outputs:renderProductPath", "setCamera.inputs:renderProductPath"),
("setCamera.outputs:execOut", "cameraHelperRgb.inputs:execIn"),
("setCamera.outputs:execOut", "cameraHelperInfo.inputs:execIn"),
("getRenderProduct.outputs:renderProductPath", "cameraHelperRgb.inputs:renderProductPath"),
("getRenderProduct.outputs:renderProductPath", "cameraHelperInfo.inputs:renderProductPath"),
],
keys.SET_VALUES: [
("createViewport.inputs:name", "Viewport " + str(i + self.ros_vp_offset)),
("setViewportResolution.inputs:height", int(self.image_height)),
("setViewportResolution.inputs:width", int(self.image_width)),
("cameraHelperRgb.inputs:frameId", camera[0]),
("cameraHelperRgb.inputs:nodeNamespace", "/isaac_a1"),
("cameraHelperRgb.inputs:topicName", "camera_forward" + camera[0] + "/rgb"),
("cameraHelperRgb.inputs:type", "rgb"),
("cameraHelperInfo.inputs:frameId", camera[0]),
("cameraHelperInfo.inputs:nodeNamespace", "/isaac_a1"),
("cameraHelperInfo.inputs:topicName", camera[0] + "/camera_info"),
("cameraHelperInfo.inputs:type", "camera_info"),
],
},
)
set_targets(
prim=self._stage.GetPrimAtPath(graph_path + "/setCamera"),
attribute="inputs:cameraPrim",
target_prim_paths=[camera_path],
)
self.camera_graphs.append(camera_graph)
self.viewports = []
for viewport_name in ["Viewport", "Viewport 1", "Viewport 2"]:
viewport_api = get_viewport_from_window_name(viewport_name)
self.viewports.append(viewport_api)
self.set_camera_execution_step = True
def dockViewports(self) -> None:
"""
[Summary]
For instantiating and docking view ports
"""
# first, set main viewport
main_viewport = get_active_viewport()
set_camera_view(eye=[3.0, 3.0, 3.0], target=[0, 0, 0], camera_prim_path="/OmniverseKit_Persp")
main_viewport = omni.ui.Workspace.get_window("Viewport")
left_camera_viewport = omni.ui.Workspace.get_window("Viewport 1")
right_camera_viewport = omni.ui.Workspace.get_window("Viewport 2")
if main_viewport is not None and left_camera_viewport is not None and right_camera_viewport is not None:
left_camera_viewport.dock_in(main_viewport, omni.ui.DockPosition.RIGHT, 2 / 3.0)
right_camera_viewport.dock_in(left_camera_viewport, omni.ui.DockPosition.RIGHT, 0.5)
def setCameraExeutionStep(self, step: np.uint) -> None:
"""
[Summary]
Sets the execution step in the omni.isaac.core_nodes.IsaacSimulationGate node located in the camera sensor pipeline
"""
for viewport in self.viewports[self.ros_vp_offset :]:
if viewport is not None:
import omni.syntheticdata._syntheticdata as sd
rv = omni.syntheticdata.SyntheticData.convert_sensor_type_to_rendervar(sd.SensorType.Rgb.name)
rgb_camera_gate_path = omni.syntheticdata.SyntheticData._get_node_path(
rv + "IsaacSimulationGate", viewport.get_render_product_path()
)
camera_info_gate_path = omni.syntheticdata.SyntheticData._get_node_path(
"PostProcessDispatch" + "IsaacSimulationGate", viewport.get_render_product_path()
)
og.Controller.attribute(rgb_camera_gate_path + ".inputs:step").set(step)
og.Controller.attribute(camera_info_gate_path + ".inputs:step").set(step)
def update(self) -> None:
"""
[Summary]
Update robot variables from the environment
"""
super().update()
if self.set_camera_execution_step:
self.setCameraExeutionStep(1)
self.dockViewports()
self.set_camera_execution_step = False
def advance(self, dt, goal, path_follow=False) -> np.ndarray:
"""[summary]
calls the unitree advance to compute torque
Argument:
dt {float} -- Timestep update in the world.
goal {List[int]} -- x velocity, y velocity, angular velocity, state switch
path_follow {bool} -- True for following a set of coordinates, False for keyboard control
Returns:
np.ndarray -- The desired joint torques for the robot.
"""
super().advance(dt, goal, path_follow)
| 10,522 |
Python
| 44.752174 | 123 | 0.589052 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/robots/__init__.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.quadruped.robots.unitree import Unitree
from omni.isaac.quadruped.robots.unitree_vision import UnitreeVision
from omni.isaac.quadruped.robots.unitree_direct import UnitreeDirect
from omni.isaac.quadruped.robots.anymal import Anymal
| 677 |
Python
| 47.428568 | 76 | 0.827179 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/robots/unitree_direct.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path, define_prim
from omni.isaac.sensor import _sensor
from omni.isaac.core.utils.stage import get_current_stage, get_stage_units
from omni.isaac.core.articulations import Articulation
from omni.isaac.quadruped.utils.a1_classes import A1State, A1Measurement, A1Command
from omni.isaac.sensor import ContactSensor
from typing import Optional, List
from collections import deque
import numpy as np
import carb
class UnitreeDirect(Articulation):
""" For unitree based quadrupeds (A1 or Go1)
This class only read command from an external torque and send the torque command to the articulation directly,
perhaps a external ROS node generates the command
"""
def __init__(
self,
prim_path: str,
name: str = "unitree_quadruped_ROS",
physics_dt: Optional[float] = 1 / 400.0,
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
model: Optional[str] = "A1",
) -> None:
"""
[Summary]
initialize robot, set up sensors and controller
Args:
prim_path {str} -- prim path of the robot on the stage
name {str} -- name of the quadruped
physics_dt {float} -- physics downtime of the controller
usd_path {str} -- robot usd filepath in the directory
position {np.ndarray} -- position of the robot
orientation {np.ndarray} -- orientation of the robot
model {str} -- robot model (can be either A1 or Go1)
"""
self._stage = get_current_stage()
self._prim_path = prim_path
prim = get_prim_at_path(self._prim_path)
if not prim.IsValid():
prim = define_prim(self._prim_path, "Xform")
if usd_path:
prim.GetReferences().AddReference(usd_path)
else:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
if model == "A1":
asset_path = assets_root_path + "/Isaac/Robots/Unitree/a1.usd"
else:
asset_path = assets_root_path + "/Isaac/Robots/Unitree/go1.usd"
carb.log_warn("asset path is: " + asset_path)
prim.GetReferences().AddReference(asset_path)
self._measurement = A1Measurement()
self._state = A1State()
self._command = A1Command()
self._default_a1_state = A1State()
if position is not None:
self._default_a1_state.base_frame.pos = np.asarray(position)
else:
self._default_a1_state.base_frame.pos = np.array([0.0, 0.0, 0.0])
self._default_a1_state.base_frame.quat = np.array([0.0, 0.0, 0.0, 1.0])
self._default_a1_state.base_frame.ang_vel = np.array([0.0, 0.0, 0.0])
self._default_a1_state.base_frame.lin_vel = np.array([0.0, 0.0, 0.0])
self._default_a1_state.joint_pos = np.array([0.0, 1.2, -1.8, 0, 1.2, -1.8, 0.0, 1.2, -1.8, 0, 1.2, -1.8])
self._default_a1_state.joint_vel = np.zeros(12)
self.meters_per_unit = get_stage_units()
super().__init__(prim_path=self._prim_path, name=name, position=position, orientation=orientation)
# contact sensor setup
self.feet_order = ["FL", "FR", "RL", "RR"]
self.feet_path = [
self._prim_path + "/FL_foot",
self._prim_path + "/FR_foot",
self._prim_path + "/RL_foot",
self._prim_path + "/RR_foot",
]
self.color = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)]
self._contact_sensors = [None] * 4
for i in range(4):
self._contact_sensors[i] = ContactSensor(
prim_path=self.feet_path[i] + "/sensor",
min_threshold=0,
max_threshold=1000000,
radius=0.03,
dt=physics_dt,
)
self.foot_force = np.zeros(4)
self.enable_foot_filter = True
self._FILTER_WINDOW_SIZE = 20
self._foot_filters = [deque(), deque(), deque(), deque()]
# imu sensor setup
# imu sensor setup
self.imu_path = self._prim_path + "/imu_link"
self._imu_sensor = IMUSensor(
prim_path=self.imu_path + "/imu_sensor",
name="imu",
dt=physics_dt,
translation=np.array([0, 0, 0]),
orientation=np.array([1, 0, 0, 0]),
)
self.base_lin = np.zeros(3)
self.ang_vel = np.zeros(3)
# direct send command
self._dof_control_modes: List[int] = list()
return
def set_state(self, state: A1State) -> None:
"""[Summary]
Set the kinematic state of the robot.
Args:
state {A1State} -- The state of the robot to set.
Raises:
RuntimeError: When the DC Toolbox interface has not been configured.
"""
self.set_world_pose(position=state.base_frame.pos, orientation=state.base_frame.quat[[3, 0, 1, 2]])
self.set_linear_velocity(state.base_frame.lin_vel)
self.set_angular_velocity(state.base_frame.ang_vel)
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert controller order to DC order for setting state
self.set_joint_positions(
positions=np.asarray(np.array(state.joint_pos.reshape([4, 3]).T.flat), dtype=np.float32)
)
self.set_joint_velocities(
velocities=np.asarray(np.array(state.joint_vel.reshape([4, 3]).T.flat), dtype=np.float32)
)
self.set_joint_efforts(np.zeros_like(state.joint_pos))
return
def update_contact_sensor_data(self) -> None:
"""[summary]
Updates processed contact sensor data from the robot feets, store them in member variable foot_force
"""
# Order: FL, FR, BL, BR
for i in range(len(self.feet_path)):
frame = self._contact_sensors[i].get_current_frame()
if "force" in frame:
if self.enable_foot_filter:
self._foot_filters[i].append(frame["force"])
if len(self._foot_filters[i]) > self._FILTER_WINDOW_SIZE:
self._foot_filters[i].popleft()
self.foot_force[i] = np.mean(self._foot_filters[i])
else:
self.foot_force[i] = frame["force"]
def update_imu_sensor_data(self):
"""[summary]
Updates processed imu sensor data from the robot body, store them in member variable base_lin and ang_vel
"""
frame = self._imu_sensor.get_current_frame()
self.base_lin = frame["lin_acc"]
self.ang_vel = frame["ang_vel"]
return
def update(self):
"""[summary]
update robot sensor variables, state variables in A1Measurement
"""
self.update_contact_sensor_data()
self.update_imu_sensor_data()
# joint pos and vel from the DC interface
self.joint_state = super().get_joints_state()
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert DC order to controller order for joint info
self._state.joint_pos = np.array(self.joint_state.positions.reshape([3, 4]).T.flat)
self._state.joint_vel = np.array(self.joint_state.velocities.reshape([3, 4]).T.flat)
# base frame
# base frame
base_pose = self.get_world_pose()
self._state.base_frame.pos = base_pose[0]
self._state.base_frame.quat = base_pose[1][[1, 2, 3, 0]]
self._state.base_frame.lin_vel = self.get_linear_velocity()
self._state.base_frame.ang_vel = self.get_angular_velocity()
# assign to _measurement obj
self._measurement.state = self._state
self._measurement.foot_forces = np.asarray(self.foot_force)
self._measurement.base_ang_vel = np.asarray(self.ang_vel)
self._measurement.base_lin_acc = np.asarray(self.base_lin)
return
def advance(self):
"""[summary]
direct control the robot using desired_joint_torque
Argument:
dt {float} -- Timestep update in the world.
goal {List[int]} -- x velocity, y velocity, angular velocity, state switch
Returns:
np.ndarray -- The desired joint torques for the robot.
"""
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the QP controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# we convert controller order to DC order for command torque
torque_reorder = np.array(self._command.desired_joint_torque.reshape([4, 3]).T.flat)
self.set_joint_efforts(np.asarray(torque_reorder, dtype=np.float32))
return self._command
def initialize(self, physics_sim_view=None) -> None:
"""[summary]
initialize dc interface, set up drive mode and initial robot state
"""
super().initialize(physics_sim_view=physics_sim_view)
self.get_articulation_controller().set_effort_modes("force")
self.get_articulation_controller().switch_control_mode("effort")
self.set_state(self._default_a1_state)
return
def post_reset(self) -> None:
"""[summary]
post reset articulation and qp_controller
"""
super().post_reset()
self.set_state(self._default_a1_state)
return
def set_command_torque(self, _desired_joint_torque) -> None:
""" Allow external nodes directly set robot command torque
_desired_joint_torque should be a 12x1 vector of torques
"""
self._command.desired_joint_torque = _desired_joint_torque
return
| 11,922 |
Python
| 39.010067 | 119 | 0.592266 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/robots/anymal.py
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni
import omni.kit.commands
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path, define_prim
from omni.isaac.core.utils.rotations import quat_to_rot_matrix, quat_to_euler_angles, euler_to_rot_matrix
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.articulations import Articulation
from omni.isaac.quadruped.utils import LstmSeaNetwork
import io
from pxr import Gf
from typing import Optional, List
import numpy as np
import torch
import carb
class Anymal(Articulation):
"""The ANYmal quadruped"""
def __init__(
self,
prim_path: str,
name: str = "anymal",
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
) -> None:
"""
[Summary]
initialize robot, set up sensors and controller
Args:
prim_path {str} -- prim path of the robot on the stage
name {str} -- name of the quadruped
usd_path {str} -- robot usd filepath in the directory
position {np.ndarray} -- position of the robot
orientation {np.ndarray} -- orientation of the robot
"""
self._stage = get_current_stage()
self._prim_path = prim_path
prim = get_prim_at_path(self._prim_path)
assets_root_path = get_assets_root_path()
if not prim.IsValid():
prim = define_prim(self._prim_path, "Xform")
if usd_path:
prim.GetReferences().AddReference(usd_path)
else:
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
asset_path = assets_root_path + "/Isaac/Robots/ANYbotics/anymal_c.usd"
carb.log_warn("asset path is: " + asset_path)
prim.GetReferences().AddReference(asset_path)
super().__init__(prim_path=self._prim_path, name=name, position=position, orientation=orientation)
self._dof_control_modes: List[int] = list()
# Policy
file_content = omni.client.read_file(assets_root_path + "/Isaac/Samples/Quadruped/Anymal_Policies/policy_1.pt")[
2
]
file = io.BytesIO(memoryview(file_content).tobytes())
self._policy = torch.jit.load(file)
self._base_vel_lin_scale = 2.0
self._base_vel_ang_scale = 0.25
self._joint_pos_scale = 1.0
self._joint_vel_scale = 0.05
self._action_scale = 0.5
self._default_joint_pos = np.array([0.0, 0.4, -0.8, 0.0, -0.4, 0.8, -0.0, 0.4, -0.8, -0.0, -0.4, 0.8])
self._previous_action = np.zeros(12)
self._policy_counter = 0
# Actuator network
file_content = omni.client.read_file(
assets_root_path + "/Isaac/Samples/Quadruped/Anymal_Policies/sea_net_jit2.pt"
)[2]
file = io.BytesIO(memoryview(file_content).tobytes())
self._actuator_network = LstmSeaNetwork()
self._actuator_network.setup(file, self._default_joint_pos)
self._actuator_network.reset()
# Height scaner
y = np.arange(-0.5, 0.6, 0.1)
x = np.arange(-0.8, 0.9, 0.1)
grid_x, grid_y = np.meshgrid(x, y)
self._scan_points = np.zeros((grid_x.size, 3))
self._scan_points[:, 0] = grid_x.transpose().flatten()
self._scan_points[:, 1] = grid_y.transpose().flatten()
self.physx_query_interface = omni.physx.get_physx_scene_query_interface()
self._query_info = []
def _hit_report_callback(self, hit):
current_hit_body = hit.rigid_body
if "/World/GroundPlane" in current_hit_body:
self._query_info.append(hit.distance)
return True
def _compute_observation(self, command):
"""[summary]
compute the observation vector for the policy
Argument:
command {np.ndarray} -- the robot command (v_x, v_y, w_z)
Returns:
np.ndarray -- The observation vector.
"""
lin_vel_I = self.get_linear_velocity()
ang_vel_I = self.get_angular_velocity()
pos_IB, q_IB = self.get_world_pose()
R_IB = quat_to_rot_matrix(q_IB)
R_BI = R_IB.transpose()
lin_vel_b = np.matmul(R_BI, lin_vel_I)
ang_vel_b = np.matmul(R_BI, ang_vel_I)
gravity_b = np.matmul(R_BI, np.array([0.0, 0.0, -1.0]))
obs = np.zeros(235)
# Base lin vel
obs[:3] = self._base_vel_lin_scale * lin_vel_b
# Base ang vel
obs[3:6] = self._base_vel_ang_scale * ang_vel_b
# Gravity
obs[6:9] = gravity_b
# Command
obs[9] = self._base_vel_lin_scale * command[0]
obs[10] = self._base_vel_lin_scale * command[1]
obs[11] = self._base_vel_ang_scale * command[2]
# Joint states
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the learning controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# Convert DC order to controller order for joint info
current_joint_pos = self.get_joint_positions()
current_joint_vel = self.get_joint_velocities()
current_joint_pos = np.array(current_joint_pos.reshape([3, 4]).T.flat)
current_joint_vel = np.array(current_joint_vel.reshape([3, 4]).T.flat)
obs[12:24] = self._joint_pos_scale * (current_joint_pos - self._default_joint_pos)
obs[24:36] = self._joint_vel_scale * current_joint_vel
obs[36:48] = self._previous_action
# height_scanner
rpy = -quat_to_euler_angles(q_IB)
rpy[:2] = 0.0
yaw_rot = np.array(Gf.Matrix3f(euler_to_rot_matrix(rpy)))
world_scan_points = np.matmul(yaw_rot, self._scan_points.T).T + pos_IB
for i in range(world_scan_points.shape[0]):
self._query_info.clear()
self.physx_query_interface.raycast_all(
tuple(world_scan_points[i]), (0.0, 0.0, -1.0), 100, self._hit_report_callback
)
if self._query_info:
distance = min(self._query_info)
obs[48 + i] = np.clip(distance - 0.5, -1.0, 1.0)
else:
print("No hit")
return obs
def advance(self, dt, command):
"""[summary]
compute the desired torques and apply them to the articulation
Argument:
dt {float} -- Timestep update in the world.
command {np.ndarray} -- the robot command (v_x, v_y, w_z)
"""
if self._policy_counter % 4 == 0:
obs = self._compute_observation(command)
with torch.no_grad():
obs = torch.from_numpy(obs).view(1, -1).float()
self.action = self._policy(obs).detach().view(-1).numpy()
self._previous_action = self.action.copy()
self._dc_interface.wake_up_articulation(self._handle)
# joint_state from the DC interface now has the order of
# 'FL_hip_joint', 'FR_hip_joint', 'RL_hip_joint', 'RR_hip_joint',
# 'FL_thigh_joint', 'FR_thigh_joint', 'RL_thigh_joint', 'RR_thigh_joint',
# 'FL_calf_joint', 'FR_calf_joint', 'RL_calf_joint', 'RR_calf_joint'
# while the learning controller uses the order of
# FL_hip_joint FL_thigh_joint FL_calf_joint
# FR_hip_joint FR_thigh_joint FR_calf_joint
# RL_hip_joint RL_thigh_joint RL_calf_joint
# RR_hip_joint RR_thigh_joint RR_calf_joint
# Convert DC order to controller order for joint info
current_joint_pos = self.get_joint_positions()
current_joint_vel = self.get_joint_velocities()
current_joint_pos = np.array(current_joint_pos.reshape([3, 4]).T.flat)
current_joint_vel = np.array(current_joint_vel.reshape([3, 4]).T.flat)
joint_torques, _ = self._actuator_network.compute_torques(
current_joint_pos, current_joint_vel, self._action_scale * self.action
)
# finally convert controller order to DC order for command torque
torque_reorder = np.array(joint_torques.reshape([4, 3]).T.flat)
self._dc_interface.set_articulation_dof_efforts(self._handle, torque_reorder)
self._policy_counter += 1
def initialize(self, physics_sim_view=None) -> None:
"""[summary]
initialize the dc interface, set up drive mode
"""
super().initialize(physics_sim_view=physics_sim_view)
self.get_articulation_controller().set_effort_modes("force")
self.get_articulation_controller().switch_control_mode("effort")
def post_reset(self) -> None:
"""[summary]
post reset articulation
"""
super().post_reset()
| 9,695 |
Python
| 38.255061 | 120 | 0.597834 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/docs/CHANGELOG.md
|
# Changelog
## [1.3.0] - 2023-02-01
### Removed
- Removed Quadruped class
- Removed dynamic control extension dependency
- Used omni.isaac.sensor classes for Contact and IMU sensors
## [1.2.2] - 2022-12-10
### Fixed
- Updated camera pipeline with writers
## [1.2.1] - 2022-11-03
### Fixed
- Incorrect viewport name issue
- Viewports not docking correctly
## [1.2.0] - 2022-08-30
### Changed
- Remove direct legacy viewport calls
## [1.1.2] - 2022-05-19
### Changed
- Updated unitree vision class to use OG ROS nodes
- Updated ROS1/ROS2 quadruped standalone samples to use OG ROS nodes
## [1.1.1] - 2022-05-15
### Fixed
- DC joint order change related fixes.
## [1.1.0] - 2022-05-05
### Added
- added the ANYmal robot
## [1.0.2] - 2022-04-21
### Changed
- decoupled sensor testing from A1 and Go1 unit test
- fixed contact sensor bug in example and standalone
## [1.0.1] - 2022-04-20
### Changed
- Replaced find_nucleus_server() with get_assets_root_path()
## [1.0.0] - 2022-04-13
### Added
- quadruped class, unitree class (support both a1, go1), unitree vision class (unitree class with stereo cameras), and unitree direct class (unitree class that subscribe to external controllers)
- quadruped controllers
- documentations and unit tests
- quadruped standalone with ros 1 and ros 2 vio examples
| 1,318 |
Markdown
| 21.355932 | 194 | 0.704856 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/docs/README.md
|
# Usage
To enable this extension, go to the Extension Manager menu and enable omni.isaac.quadruped extension
| 109 |
Markdown
| 35.666655 | 100 | 0.816514 |
kimsooyoung/legged_robotics/omni.isaac.quadruped/docs/index.rst
|
Quadruped Robots [omni.isaac.quadruped]
#######################################
Quadruped
======================
.. automodule:: omni.isaac.quadruped.quadruped
:inherited-members:
:members:
:undoc-members:
:exclude-members:
Quadruped Controller
=======================
.. automodule:: omni.isaac.quadruped.controllers
:inherited-members:
:imported-members:
:members:
:undoc-members:
:exclude-members:
Quadruped Robots
======================
.. automodule:: omni.isaac.quadruped.robots
:inherited-members:
:imported-members:
:members:
:undoc-members:
:exclude-members:
Quadruped Utilities
========================
.. automodule:: omni.isaac.quadruped.utils
:inherited-members:
:imported-members:
:members:
:undoc-members:
:exclude-members:
| 829 |
reStructuredText
| 17.043478 | 48 | 0.576598 |
kimsooyoung/rb_issac_tutorial/data_test_ur.py
|
import h5py
import numpy as np
import pylab as plt
file_name = "./ur_bin_filling.hdf5"
# file_name = "./ur_bin_palleting.hdf5"
with h5py.File(file_name, 'r') as f:
print(f.keys())
print(f"keys: {f['isaac_dataset'].keys()}")
print(f"sim_time: {f['isaac_dataset']['sim_time'].shape}")
print(f"joint_positions: {f['isaac_dataset']['joint_positions'].shape}")
print(f"joint_velocities: {f['isaac_dataset']['joint_velocities'].shape}")
print(f"camera_images: {f['isaac_dataset']['camera_images'].keys()}")
sim_time = f['isaac_dataset']['sim_time'][:]
joint_positions = f['isaac_dataset']['joint_positions'][:]
joint_velocities = f['isaac_dataset']['joint_velocities'][:]
if file_name == "./ur_bin_filling.hdf5":
ee_camera = f['isaac_dataset']['camera_images']['ee_camera'][:]
side_camera = f['isaac_dataset']['camera_images']['side_camera'][:]
front_camera = f['isaac_dataset']['camera_images']['front_camera'][:]
plt.figure(1)
plt.imshow(ee_camera[7])
plt.figure(2)
plt.imshow(side_camera[7])
plt.figure(3)
plt.imshow(front_camera[7])
elif file_name == "./ur_bin_palleting.hdf5":
ee_camera = f['isaac_dataset']['camera_images']['ee_camera'][:]
left_camera = f['isaac_dataset']['camera_images']['left_camera'][:]
right_camera = f['isaac_dataset']['camera_images']['right_camera'][:]
front_camera = f['isaac_dataset']['camera_images']['front_camera'][:]
back_camera = f['isaac_dataset']['camera_images']['back_camera'][:]
plt.figure(1)
plt.imshow(ee_camera[1])
plt.figure(2)
plt.imshow(left_camera[1])
plt.figure(3)
plt.imshow(right_camera[1])
plt.figure(4)
plt.imshow(front_camera[1])
plt.figure(5)
plt.imshow(back_camera[1])
print(f"sim_time: {sim_time}")
print(f"joint_positions[0]: {joint_positions[0]}")
print(f"joint_velocities[0]: {joint_velocities[0]}")
plt.show()
| 2,038 |
Python
| 30.36923 | 78 | 0.592738 |
kimsooyoung/rb_issac_tutorial/data_test_franka.py
|
import h5py
import numpy as np
import pylab as plt
file_name = "./franka_nuts_basic.hdf5"
# file_name = "./franka_bolts_nuts_table.hdf5"
with h5py.File(file_name, 'r') as f:
print(f.keys())
print(f"keys: {f['isaac_dataset'].keys()}")
print(f"sim_time: {f['isaac_dataset']['sim_time'].shape}")
print(f"joint_positions: {f['isaac_dataset']['joint_positions'].shape}")
print(f"joint_velocities: {f['isaac_dataset']['joint_velocities'].shape}")
print(f"camera_images: {f['isaac_dataset']['camera_images'].keys()}")
print(f"camera_images: {f['isaac_dataset']['camera_images']['hand_camera'].shape}")
print(f"camera_images: {f['isaac_dataset']['camera_images']['top_camera'].shape}")
print(f"camera_images: {f['isaac_dataset']['camera_images']['front_camera'].shape}")
sim_time = f['isaac_dataset']['sim_time'][:]
joint_positions = f['isaac_dataset']['joint_positions'][:]
joint_velocities = f['isaac_dataset']['joint_velocities'][:]
hand_camera = f['isaac_dataset']['camera_images']['hand_camera'][:]
top_camera = f['isaac_dataset']['camera_images']['top_camera'][:]
front_camera = f['isaac_dataset']['camera_images']['front_camera'][:]
print(f"sim_time: {sim_time}")
print(f"joint_positions[0]: {joint_positions[0]}")
print(f"joint_velocities[0]: {joint_velocities[0]}")
plt.figure(1)
plt.imshow(hand_camera[7])
plt.figure(2)
plt.imshow(top_camera[7])
plt.figure(3)
plt.imshow(front_camera[7])
plt.show()
| 1,512 |
Python
| 34.186046 | 88 | 0.636905 |
kimsooyoung/rb_issac_tutorial/data_test.py
|
import h5py
import numpy as np
import pylab as plt
file_name = "/home/kimsooyoung/Documents/cam_test.hdf5"
with h5py.File(file_name, 'r') as f:
# data = f['my_dataset'][:]
print(f.keys())
print(f['isaac_save_data'].keys())
print(f['isaac_save_data']['image'].shape)
print(f['isaac_save_data']['sim_time'].shape)
print(type(f['isaac_save_data']['image'][0]))
print(f['isaac_save_data']['sim_time'][0])
plt.imshow(f['isaac_save_data']['image'][0])
plt.show()
| 497 |
Python
| 25.210525 | 55 | 0.617706 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"cobotta_pro_900.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "onrobot_rg6_base_link"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,388 |
Python
| 45.299998 | 125 | 0.698127 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .lula_kinematic_solver import LULAKinematicSolverExample
from .franka_test import FrankaIK
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="AddingNewManip",
name="LULAKinematicSolver",
title="LULAKinematicSolver",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LULAKinematicSolverExample(),
# sample=FrankaIK(),
)
return
| 2,173 |
Python
| 42.479999 | 135 | 0.743212 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/franka_test.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
# This extension has franka related tasks and controllers as well
from omni.isaac.franka import Franka
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.franka.controllers import PickPlaceController
from omni.isaac.franka.tasks import PickPlace
from omni.isaac.core.tasks import BaseTask
from omni.isaac.motion_generation import (ArticulationKinematicsSolver,
ArticulationMotionPolicy,
LulaKinematicsSolver, RmpFlow,
interface_config_loader)
import numpy as np
class FrankaIK(BaseSample):
def __init__(self) -> None:
super().__init__()
self._sim_step = 0
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
self._franka = self._world.scene.add(
Franka(
prim_path="/World/Fancy_Franka",
name="fancy_franka"
))
return
async def setup_post_load(self):
self._world = self.get_world()
self._franka = self._world.scene.get_object("fancy_franka")
self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions)
# define LulaKinematicsSolver & ArticulationKinematicsSolver
kinematics_config = interface_config_loader.load_supported_lula_kinematics_solver_config("Franka")
self._kine_solver = LulaKinematicsSolver(**kinematics_config)
self._art_kine_solver = ArticulationKinematicsSolver(self._franka, self._kine_solver, "right_gripper")
# acquire controller for action applying
self._articulation_controller = self._franka.get_articulation_controller()
self._action = None
self._world.add_physics_callback("sim_step", callback_fn=self.physics_step)
await self._world.play_async()
return
async def setup_post_reset(self):
await self._world.play_async()
return
def physics_step(self, step_size):
self._sim_step += 1
if (self._sim_step > 100) and (self._action is None):
target_pos = np.array([0.5, 0.0, 0.5])
robot_base_translation, robot_base_orientation = self._franka.get_world_pose()
self._kine_solver.set_robot_base_pose(robot_base_translation, robot_base_orientation)
self._action, ik_success = self._art_kine_solver.compute_inverse_kinematics(
target_pos
)
# Apply action
if ik_success:
print("IK Great")
else:
print("IK failed")
elif (self._sim_step > 100) and (self._action is not None):
self._franka.apply_action(self._action)
return
| 3,304 |
Python
| 37.430232 | 110 | 0.64316 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/lula_kinematic_solver.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.core.articulations import Articulation
from omni.isaac.manipulators import SingleManipulator
import numpy as np
import carb
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver, interface_config_loader
class LULAKinematicSolverExample(BaseSample):
def __init__(self) -> None:
super().__init__()
# robot usd path
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd"
# simulation step counter
self._sim_step = 0
# robot joint default positions
self._joints_default_positions = np.zeros(12)
self._joints_default_positions[7] = 0.628
self._joints_default_positions[8] = 0.628
# Desired end effector pose
self._target_pos = np.array([1.0, 0.0, 1.0])
self._target_rot = np.array([1.0, 0.0, 0.0, 0.0]) # wxyz quaternion
# various solvers and controllers
self._kine_solver = None
self._articulation = None
self._art_kine_solver = None
self._articulation_controller = None
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# add robot to the scene
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta")
self._articulation = Articulation("/World/cobotta")
#define the gripper
self._gripper = ParallelGripper(
#We chose the following values while inspecting the articulation
end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link",
joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
joint_opened_positions=np.array([0, 0]),
joint_closed_positions=np.array([0.628, -0.628]),
action_deltas=np.array([-0.628, 0.628]),
)
#define the manipulator
self._my_denso = self._world.scene.add(
SingleManipulator(
prim_path="/World/cobotta",
name="cobotta_robot",
end_effector_prim_name="onrobot_rg6_base_link",
gripper=self._gripper)
)
self._my_denso.set_joints_default_state(
positions=self._joints_default_positions
)
return
async def setup_post_load(self):
self._world = self.get_world()
self._my_denso = self._world.scene.get_object("cobotta_robot")
# laptop path
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/"
self._kine_solver = LulaKinematicsSolver(
# robot_description_path=self._desc_path+"rmpflow/robot_descriptor_common.yaml",
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"cobotta_pro_900.urdf",
)
self._art_kine_solver = ArticulationKinematicsSolver(self._my_denso, self._kine_solver, "onrobot_rg6_base_link")
self._articulation_controller = self._my_denso.get_articulation_controller()
self._action = None
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
await self._world.play_async()
return
async def setup_post_reset(self):
self._articulation_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
self._sim_step += 1
if (self._sim_step > 100) and (self._action is None):
target_pos = np.array([0.5, 0.0, 0.5])
robot_base_translation, robot_base_orientation = self._my_denso.get_world_pose()
self._kine_solver.set_robot_base_pose(robot_base_translation, robot_base_orientation)
self._action, ik_success = self._art_kine_solver.compute_inverse_kinematics(
target_pos
)
# Apply action
if ik_success:
print("IK Great")
else:
print("IK failed")
elif (self._sim_step > 100) and (self._action is not None):
self._articulation_controller.apply_action(self._action)
return
| 5,364 |
Python
| 39.037313 | 120 | 0.644295 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/rmpflow/robot_descriptor.yaml
|
api_version: 1.0
cspace:
- joint_1
- joint_2
- joint_3
- joint_4
- joint_5
- joint_6
root_link: world
default_q: [
0.00, 0.00, 0.00, 0.00, 0.00, 0.00
]
cspace_to_urdf_rules: []
composite_task_spaces: []
| 230 |
YAML
| 15.499999 | 38 | 0.56087 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/rmpflow/denso_rmpflow_common.yaml
|
joint_limit_buffers: [.01, .01, .01, .01, .01, .01]
rmp_params:
cspace_target_rmp:
metric_scalar: 50.
position_gain: 100.
damping_gain: 50.
robust_position_term_thresh: .5
inertia: 1.
cspace_trajectory_rmp:
p_gain: 100.
d_gain: 10.
ff_gain: .25
weight: 50.
cspace_affine_rmp:
final_handover_time_std_dev: .25
weight: 2000.
joint_limit_rmp:
metric_scalar: 1000.
metric_length_scale: .01
metric_exploder_eps: 1e-3
metric_velocity_gate_length_scale: .01
accel_damper_gain: 200.
accel_potential_gain: 1.
accel_potential_exploder_length_scale: .1
accel_potential_exploder_eps: 1e-2
joint_velocity_cap_rmp:
max_velocity: 1.
velocity_damping_region: .3
damping_gain: 1000.0
metric_weight: 100.
target_rmp:
accel_p_gain: 30.
accel_d_gain: 85.
accel_norm_eps: .075
metric_alpha_length_scale: .05
min_metric_alpha: .01
max_metric_scalar: 10000
min_metric_scalar: 2500
proximity_metric_boost_scalar: 20.
proximity_metric_boost_length_scale: .02
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
axis_target_rmp:
accel_p_gain: 210.
accel_d_gain: 60.
metric_scalar: 10
proximity_metric_boost_scalar: 3000.
proximity_metric_boost_length_scale: .08
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
collision_rmp:
damping_gain: 50.
damping_std_dev: .04
damping_robustness_eps: 1e-2
damping_velocity_gate_length_scale: .01
repulsion_gain: 800.
repulsion_std_dev: .01
metric_modulation_radius: .5
metric_scalar: 10000.
metric_exploder_std_dev: .02
metric_exploder_eps: .001
damping_rmp:
accel_d_gain: 30.
metric_scalar: 50.
inertia: 100.
canonical_resolve:
max_acceleration_norm: 50.
projection_tolerance: .01
verbose: false
body_cylinders:
- name: base
pt1: [0,0,.333]
pt2: [0,0,0.]
radius: .05
body_collision_controllers:
- name: onrobot_rg6_base_link
radius: .05
| 2,282 |
YAML
| 28.64935 | 51 | 0.583699 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/rmpflow/robot_descriptor_common.yaml
|
# Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# The robot descriptor defines the generalized coordinates and how to map those
# to the underlying URDF dofs.
api_version: 1.0
# Defines the generalized coordinates. Each generalized coordinate is assumed
# to have an entry in the URDF.
# RMPflow will only use these joints to control the robot position.
cspace:
- joint_1
- joint_2
- joint_3
- joint_4
- joint_5
- joint_6
# Global frame of the URDF
root_link: world
# The default cspace position of this robot
default_q: [
0.0,0.3,1.2,0.0,0.0,0.0
]
# RMPflow uses collision spheres to define the robot geometry in order to avoid
# collisions with external obstacles. If no spheres are specified, RMPflow will
# not be able to avoid obstacles.
collision_spheres:
- J1:
- "center": [0.0, 0.0, 0.1]
"radius": 0.08
- "center": [0.0, 0.0, 0.15]
"radius": 0.08
- "center": [0.0, 0.0, 0.2]
"radius": 0.08
- J2:
- "center": [0.0, 0.08, 0.0]
"radius": 0.08
- "center": [0.0, 0.16, 0.0]
"radius": 0.08
- "center": [0.0, 0.175, 0.05]
"radius": 0.065
- "center": [0.0, 0.175, 0.1]
"radius": 0.065
- "center": [0.0, 0.175, 0.15]
"radius": 0.065
- "center": [0.0, 0.175, 0.2]
"radius": 0.065
- "center": [0.0, 0.175, 0.25]
"radius": 0.065
- "center": [0.0, 0.175, 0.3]
"radius": 0.065
- "center": [0.0, 0.175, 0.35]
"radius": 0.065
- "center": [0.0, 0.175, 0.4]
"radius": 0.065
- "center": [0.0, 0.175, 0.45]
"radius": 0.065
- "center": [0.0, 0.175, 0.5]
"radius": 0.065
- "center": [0.0, 0.1, 0.5]
"radius": 0.07
- J3:
- "center": [0.0, 0.025, 0]
"radius": 0.065
- "center": [0.0, -0.025, 0]
"radius": 0.065
- "center": [0.0, -0.025, 0.05]
"radius": 0.065
- "center": [0.0, -0.025, 0.1]
"radius": 0.065
- "center": [0.0, -0.025, 0.15]
"radius": 0.06
- "center": [0.0, -0.025, 0.2]
"radius": 0.06
- "center": [0.0, -0.025, 0.25]
"radius": 0.06
- "center": [0.0, -0.025, 0.3]
"radius": 0.06
- "center": [0.0, -0.025, 0.35]
"radius": 0.055
- "center": [0.0, -0.025, 0.4]
"radius": 0.055
- J5:
- "center": [0.0, 0.05, 0]
"radius": 0.055
- "center": [0.0, 0.1, 0]
"radius": 0.055
- J6:
- "center": [0.0, 0.0, -0.05]
"radius": 0.05
- "center": [0.0, 0.0, -0.1]
"radius": 0.05
- "center": [0.0, 0.0, -0.15]
"radius": 0.05
- "center": [0.0, 0.0, 0.04]
"radius": 0.035
- "center": [0.0, 0.0, 0.08]
"radius": 0.035
- "center": [0.0, 0.0, 0.12]
"radius": 0.035
- right_inner_knuckle:
- "center": [0.0, 0.0, 0.0]
"radius": 0.02
- "center": [0.0, -0.03, 0.025]
"radius": 0.02
- "center": [0.0, -0.05, 0.05]
"radius": 0.02
- right_inner_finger:
- "center": [0.0, 0.02, 0.0]
"radius": 0.015
- "center": [0.0, 0.02, 0.015]
"radius": 0.015
- "center": [0.0, 0.02, 0.03]
"radius": 0.015
- "center": [0.0, 0.025, 0.04]
"radius": 0.01
- left_inner_knuckle:
- "center": [0.0, 0.0, 0.0]
"radius": 0.02
- "center": [0.0, -0.03, 0.025]
"radius": 0.02
- "center": [0.0, -0.05, 0.05]
"radius": 0.02
- left_inner_finger:
- "center": [0.0, 0.02, 0.0]
"radius": 0.015
- "center": [0.0, 0.02, 0.015]
"radius": 0.015
- "center": [0.0, 0.02, 0.03]
"radius": 0.015
- "center": [0.0, 0.025, 0.04]
"radius": 0.01
| 3,988 |
YAML
| 26.701389 | 80 | 0.522818 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/tasks/pick_place.py
|
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.stage import add_reference_to_stage
import omni.isaac.core.tasks as tasks
from typing import Optional
import numpy as np
import carb
class PickPlace(tasks.PickPlace):
def __init__(
self,
name: str = "denso_pick_place",
cube_initial_position: Optional[np.ndarray] = None,
cube_initial_orientation: Optional[np.ndarray] = None,
target_position: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
tasks.PickPlace.__init__(
self,
name=name,
cube_initial_position=cube_initial_position,
cube_initial_orientation=cube_initial_orientation,
target_position=target_position,
cube_size=np.array([0.0515, 0.0515, 0.0515]),
offset=offset,
)
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd"
return
def set_robot(self) -> SingleManipulator:
#TODO: change the asset path here
# laptop
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta")
gripper = ParallelGripper(
end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link",
joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
joint_opened_positions=np.array([0, 0]),
joint_closed_positions=np.array([0.628, -0.628]),
action_deltas=np.array([-0.2, 0.2])
)
manipulator = SingleManipulator(
prim_path="/World/cobotta",
name="cobotta_robot",
end_effector_prim_name="onrobot_rg6_base_link",
gripper=gripper
)
joints_default_positions = np.zeros(12)
joints_default_positions[7] = 0.628
joints_default_positions[8] = 0.628
manipulator.set_joints_default_state(positions=joints_default_positions)
return manipulator
| 2,427 |
Python
| 36.937499 | 117 | 0.639061 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/controllers/pick_place.py
|
import omni.isaac.manipulators.controllers as manipulators_controllers
from omni.isaac.manipulators.grippers import ParallelGripper
from .rmpflow import RMPFlowController
from omni.isaac.core.articulations import Articulation
class PickPlaceController(manipulators_controllers.PickPlaceController):
def __init__(
self,
name: str,
gripper: ParallelGripper,
robot_articulation: Articulation,
events_dt=None
) -> None:
if events_dt is None:
#These values needs to be tuned in general, you checkout each event in execution and slow it down or speed
#it up depends on how smooth the movments are
events_dt = [0.005, 0.002, 1, 0.05, 0.0008, 0.005, 0.0008, 0.1, 0.0008, 0.008]
manipulators_controllers.PickPlaceController.__init__(
self,
name=name,
cspace_controller=RMPFlowController(
name=name + "_cspace_controller", robot_articulation=robot_articulation
),
gripper=gripper,
events_dt=events_dt,
#This value can be changed
# start_picking_height=0.6
)
return
| 1,184 |
Python
| 38.499999 | 118 | 0.640203 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipLULA/controllers/rmpflow.py
|
import omni.isaac.motion_generation as mg
from omni.isaac.core.articulations import Articulation
class RMPFlowController(mg.MotionPolicyController):
def __init__(self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0) -> None:
# TODO: chamge the follow paths
# laptop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/"
self.rmpflow = mg.lula.motion_policies.RmpFlow(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
rmpflow_config_path=self._desc_path+"rmpflow/denso_rmpflow_common.yaml",
urdf_path=self._urdf_path+"cobotta_pro_900.urdf",
end_effector_frame_name="onrobot_rg6_base_link",
maximum_substep_size=0.00334
)
self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmpflow, physics_dt)
mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp)
self._default_position, self._default_orientation = (
self._articulation_motion_policy._robot_articulation.get_world_pose()
)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
return
def reset(self):
mg.MotionPolicyController.reset(self)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
| 1,686 |
Python
| 45.86111 | 125 | 0.68446 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .limo_diff_drive import LimoDiffDrive
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="WheeledRobots",
name="LimoDiffDrive",
title="LimoDiffDrive",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=LimoDiffDrive(),
)
return
| 2,061 |
Python
| 41.958332 | 135 | 0.741388 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/limo_diff_drive.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.wheeled_robots.controllers import WheelBasePoseController
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController
import numpy as np
import carb
class LimoDiffDrive(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
# self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_base.usd"
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_diff_thin.usd"
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
# Reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html?highlight=wheeledrobot#omni.isaac.wheeled_robots.robots.WheeledRobot
self._wheeled_robot = world.scene.add(
WheeledRobot(
prim_path="/World/Limo/base_link",
name="my_limo",
# Caution. Those are DOF "Joints", Not "Links"
wheel_dof_names=[
"front_left_wheel",
"front_right_wheel",
"rear_left_wheel",
"rear_right_wheel",
],
create_robot=False,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
return
async def setup_post_load(self):
self._world = self.get_world()
# Reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html?highlight=differentialcontroller
self._diff_controller = DifferentialController(
name="simple_control",
wheel_radius=0.045,
# Caution. This will not be the same with a real wheelbase for 4WD cases.
# Reference : https://forums.developer.nvidia.com/t/how-to-drive-clearpath-jackal-via-ros2-messages-in-isaac-sim/275907/4
wheel_base=0.43
)
self._diff_controller.reset()
self._wheeled_robot.initialize()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._save_count += 1
wheel_action = None
# linear X, angular Z commands
if self._save_count >= 0 and self._save_count < 150:
wheel_action = self._diff_controller.forward(command=[0.3, 0.0])
elif self._save_count >= 150 and self._save_count < 300:
wheel_action = self._diff_controller.forward(command=[-0.3, 0.0])
elif self._save_count >= 300 and self._save_count < 450:
wheel_action = self._diff_controller.forward(command=[0.0, 0.3])
elif self._save_count >= 450 and self._save_count < 600:
wheel_action = self._diff_controller.forward(command=[0.0, -0.3])
else:
self._save_count = 0
wheel_action.joint_velocities = np.hstack((wheel_action.joint_velocities, wheel_action.joint_velocities))
self._wheeled_robot.apply_wheel_actions(wheel_action)
return
async def setup_pre_reset(self):
if self._world.physics_callback_exists("sim_step"):
self._world.remove_physics_callback("sim_step")
self._save_count = 0
self._world.pause()
return
async def setup_post_reset(self):
self._diff_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return
| 5,079 |
Python
| 39.64 | 196 | 0.6456 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiff/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"mirobot_urdf_2.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "Link6"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,395 |
Python
| 45.533332 | 127 | 0.700358 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .pick_place_example import PickandPlaceExample
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="AddingNewManip2",
name="PickandPlaceROS2",
title="PickandPlaceROS2",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=PickandPlaceExample(),
)
return
| 2,084 |
Python
| 42.437499 | 135 | 0.744242 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/pick_place_example.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper
from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.dynamic_control import _dynamic_control as dc
from omni.isaac.core.prims import RigidPrim, GeometryPrim
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
import omni.graph.core as og
import numpy as np
import omni
import carb
from .controllers.pick_place import PickPlaceController
def createRigidBody(stage, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(stage, boxActorPath)
bodyPrim = stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
return bodyGeom
class PickandPlaceExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._gripper = None
self._my_mirobot = None
self._articulation_controller = None
# simulation step counter
self._sim_step = 0
self._target_position = np.array([0.2, -0.08, 0.06])
return
def og_setup(self):
domain_id = 30
try:
# Clock OG
og.Controller.edit(
{"graph_path": "/ROS2Clock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("onPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("context", "omni.isaac.ros2_bridge.ROS2Context"),
("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("publishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", domain_id),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "publishClock.inputs:execIn"),
("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"),
("context.outputs:context", "publishClock.inputs:context"),
],
},
)
# Joint Pub Sub
og.Controller.edit(
{"graph_path": "/ROS2JointPubSub", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("ArticulationController", "omni.isaac.core_nodes.IsaacArticulationController"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "ArticulationController.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("SubscribeJointState.outputs:jointNames", "ArticulationController.inputs:jointNames"),
("SubscribeJointState.outputs:positionCommand", "ArticulationController.inputs:positionCommand"),
("SubscribeJointState.outputs:velocityCommand", "ArticulationController.inputs:velocityCommand"),
("SubscribeJointState.outputs:effortCommand", "ArticulationController.inputs:effortCommand"),
],
og.Controller.Keys.SET_VALUES: [
("ArticulationController.inputs:usePath", True),
("ArticulationController.inputs:robotPath", "/World/mirobot"),
("PublishJointState.inputs:targetPrim", "/World/mirobot"),
("SubscribeJointState.inputs:topicName", "/issac/joint_command"),
("PublishJointState.inputs:topicName", "/issac/joint_states"),
],
},
)
except Exception as e:
print(e)
def setup_robot(self):
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/mirobot_urdf_2_ee.usd"
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/mirobot")
# define the gripper
self._gripper = SurfaceGripper(
end_effector_prim_path="/World/mirobot/ee_link",
translate=0.02947,
direction="x",
# kp=1.0e4,
# kd=1.0e3,
# disable_gravity=False,
)
self._gripper.set_force_limit(value=1.0e2)
self._gripper.set_torque_limit(value=1.0e3)
# define the manipulator
self._my_mirobot = self._world.scene.add(
SingleManipulator(
prim_path="/World/mirobot",
name="mirobot",
end_effector_prim_name="ee_link",
gripper=self._gripper
)
)
self._joints_default_positions = np.zeros(6)
self._my_mirobot.set_joints_default_state(positions=self._joints_default_positions)
def setup_bin(self):
self._nucleus_server = get_assets_root_path()
table_path = self._nucleus_server + "/Isaac/Props/KLT_Bin/small_KLT.usd"
add_reference_to_stage(usd_path=table_path, prim_path=f"/World/bin")
self._bin_initial_position = np.array([0.2, 0.08, 0.06]) / get_stage_units()
self._packing_bin = self._world.scene.add(
GeometryPrim(
prim_path="/World/bin",
name=f"packing_bin",
position=self._bin_initial_position,
orientation=euler_angles_to_quat(np.array([np.pi, 0, 0])),
scale=np.array([0.25, 0.25, 0.25]),
collision=True
)
)
self._packing_bin_geom = self._world.scene.get_object(f"packing_bin")
massAPI = UsdPhysics.MassAPI.Apply(self._packing_bin_geom.prim.GetPrim())
massAPI.CreateMassAttr().Set(0.001)
def setup_box(self):
# Box to be picked
self.box_start_pose = dc.Transform([0.2, 0.08, 0.06], [1, 0, 0, 0])
self._stage = omni.usd.get_context().get_stage()
self._boxGeom = createRigidBody(
self._stage,
UsdGeom.Cube,
"/World/Box",
0.0010,
[0.015, 0.015, 0.015],
self.box_start_pose.p,
self.box_start_pose.r,
[0.2, 0.2, 1]
)
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
self.setup_robot()
# self.setup_bin()
self.setup_box()
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._my_controller = PickPlaceController(
name="controller",
gripper=self._gripper,
robot_articulation=self._my_mirobot,
events_dt=[
0.008,
0.005,
0.1,
0.1,
0.0025,
0.5,
0.0025,
0.1,
0.008,
0.08
],
)
self._articulation_controller = self._my_mirobot.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
return
async def setup_post_reset(self):
self._my_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
# # bin case
# bin_pose, _ = self._packing_bin_geom.get_world_pose()
# pick_position = bin_pose
# place_position = self._target_position
# box case
box_matrix = omni.usd.get_world_transform_matrix(self._boxGeom)
box_trans = box_matrix.ExtractTranslation()
pick_position = np.array(box_trans)
place_position = self._target_position
joints_state = self._my_mirobot.get_joints_state()
actions = self._my_controller.forward(
picking_position=pick_position,
placing_position=place_position,
current_joint_positions=joints_state.positions,
# This offset needs tuning as well
end_effector_offset=np.array([0, 0, 0.02947+0.02]),
end_effector_orientation=euler_angles_to_quat(np.array([0, 0, 0])),
)
if self._my_controller.is_done():
print("done picking and placing")
self._articulation_controller.apply_action(actions)
return
| 10,546 |
Python
| 39.102661 | 140 | 0.583634 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/rmpflow/robot_descriptor.yaml
|
api_version: 1.0
cspace:
- joint1
- joint2
- joint3
- joint4
- joint5
- joint6
root_link: world
default_q: [
0.00, 0.00, 0.00, 0.00, 0.00, 0.00
]
cspace_to_urdf_rules: []
composite_task_spaces: []
| 224 |
YAML
| 15.071427 | 38 | 0.575893 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/rmpflow/mirrobot_rmpflow_common.yaml
|
joint_limit_buffers: [.01, .01, .01, .01, .01, .01]
rmp_params:
cspace_target_rmp:
metric_scalar: 50.
position_gain: 100.
damping_gain: 50.
robust_position_term_thresh: .5
inertia: 1.
cspace_trajectory_rmp:
p_gain: 100.
d_gain: 10.
ff_gain: .25
weight: 50.
cspace_affine_rmp:
final_handover_time_std_dev: .25
weight: 2000.
joint_limit_rmp:
metric_scalar: 1000.
metric_length_scale: .01
metric_exploder_eps: 1e-3
metric_velocity_gate_length_scale: .01
accel_damper_gain: 200.
accel_potential_gain: 1.
accel_potential_exploder_length_scale: .1
accel_potential_exploder_eps: 1e-2
joint_velocity_cap_rmp:
max_velocity: 1.
velocity_damping_region: .3
damping_gain: 1000.0
metric_weight: 100.
target_rmp:
accel_p_gain: 30.
accel_d_gain: 85.
accel_norm_eps: .075
metric_alpha_length_scale: .05
min_metric_alpha: .01
max_metric_scalar: 10000
min_metric_scalar: 2500
proximity_metric_boost_scalar: 20.
proximity_metric_boost_length_scale: .02
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
axis_target_rmp:
accel_p_gain: 210.
accel_d_gain: 60.
metric_scalar: 10
proximity_metric_boost_scalar: 3000.
proximity_metric_boost_length_scale: .08
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
collision_rmp:
damping_gain: 50.
damping_std_dev: .04
damping_robustness_eps: 1e-2
damping_velocity_gate_length_scale: .01
repulsion_gain: 800.
repulsion_std_dev: .01
metric_modulation_radius: .5
metric_scalar: 10000.
metric_exploder_std_dev: .02
metric_exploder_eps: .001
damping_rmp:
accel_d_gain: 30.
metric_scalar: 50.
inertia: 100.
canonical_resolve:
max_acceleration_norm: 50.
projection_tolerance: .01
verbose: false
body_cylinders:
- name: base
pt1: [0,0,.333]
pt2: [0,0,0.]
radius: .05
body_collision_controllers:
- name: Link6
radius: .05
| 2,266 |
YAML
| 28.441558 | 51 | 0.582083 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/rmpflow/denso_rmpflow_common.yaml
|
joint_limit_buffers: [.01, .01, .01, .01, .01, .01]
rmp_params:
cspace_target_rmp:
metric_scalar: 50.
position_gain: 100.
damping_gain: 50.
robust_position_term_thresh: .5
inertia: 1.
cspace_trajectory_rmp:
p_gain: 100.
d_gain: 10.
ff_gain: .25
weight: 50.
cspace_affine_rmp:
final_handover_time_std_dev: .25
weight: 2000.
joint_limit_rmp:
metric_scalar: 1000.
metric_length_scale: .01
metric_exploder_eps: 1e-3
metric_velocity_gate_length_scale: .01
accel_damper_gain: 200.
accel_potential_gain: 1.
accel_potential_exploder_length_scale: .1
accel_potential_exploder_eps: 1e-2
joint_velocity_cap_rmp:
max_velocity: 1.
velocity_damping_region: .3
damping_gain: 1000.0
metric_weight: 100.
target_rmp:
accel_p_gain: 30.
accel_d_gain: 85.
accel_norm_eps: .075
metric_alpha_length_scale: .05
min_metric_alpha: .01
max_metric_scalar: 10000
min_metric_scalar: 2500
proximity_metric_boost_scalar: 20.
proximity_metric_boost_length_scale: .02
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
axis_target_rmp:
accel_p_gain: 210.
accel_d_gain: 60.
metric_scalar: 10
proximity_metric_boost_scalar: 3000.
proximity_metric_boost_length_scale: .08
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
collision_rmp:
damping_gain: 50.
damping_std_dev: .04
damping_robustness_eps: 1e-2
damping_velocity_gate_length_scale: .01
repulsion_gain: 800.
repulsion_std_dev: .01
metric_modulation_radius: .5
metric_scalar: 10000.
metric_exploder_std_dev: .02
metric_exploder_eps: .001
damping_rmp:
accel_d_gain: 30.
metric_scalar: 50.
inertia: 100.
canonical_resolve:
max_acceleration_norm: 50.
projection_tolerance: .01
verbose: false
body_cylinders:
- name: base
pt1: [0,0,.333]
pt2: [0,0,0.]
radius: .05
body_collision_controllers:
- name: onrobot_rg6_base_link
radius: .05
| 2,282 |
YAML
| 28.64935 | 51 | 0.583699 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/controllers/pick_place.py
|
from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper
import omni.isaac.manipulators.controllers as manipulators_controllers
from .rmpflow import RMPFlowController
from omni.isaac.core.articulations import Articulation
# - Phase 0: Move end_effector above the cube center at the 'end_effector_initial_height'.
# - Phase 1: Lower end_effector down to encircle the target cube
# - Phase 2: Wait for Robot's inertia to settle.
# - Phase 3: close grip.
# - Phase 4: Move end_effector up again, keeping the grip tight (lifting the block).
# - Phase 5: Smoothly move the end_effector toward the goal xy, keeping the height constant.
# - Phase 6: Move end_effector vertically toward goal height at the 'end_effector_initial_height'.
# - Phase 7: loosen the grip.
# - Phase 8: Move end_effector vertically up again at the 'end_effector_initial_height'
# - Phase 9: Move end_effector towards the old xy position.
class PickPlaceController(manipulators_controllers.PickPlaceController):
def __init__(
self,
name: str,
gripper: SurfaceGripper,
robot_articulation: Articulation,
events_dt=None
) -> None:
if events_dt is None:
#These values needs to be tuned in general, you checkout each event in execution and slow it down or speed
#it up depends on how smooth the movments are
events_dt = [0.005, 0.002, 1, 0.05, 0.0008, 0.005, 0.0008, 0.1, 0.0008, 0.008]
manipulators_controllers.PickPlaceController.__init__(
self,
name=name,
cspace_controller=RMPFlowController(
name=name + "_cspace_controller", robot_articulation=robot_articulation
),
gripper=gripper,
events_dt=events_dt,
end_effector_initial_height=0.05,
#This value can be changed
# start_picking_height=0.6
)
return
| 1,930 |
Python
| 44.976189 | 118 | 0.674611 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlaceROS2/controllers/rmpflow.py
|
import omni.isaac.motion_generation as mg
from omni.isaac.core.articulations import Articulation
class RMPFlowController(mg.MotionPolicyController):
def __init__(self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0) -> None:
# TODO: chamge the follow paths
# # laptop
# self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/"
# desktop
self._desc_path = "/home/kimsooyoung/Downloads/source/RoadBalanceEdu/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/"
self._urdf_path = "/home/kimsooyoung/Downloads/source/mirobot_ros2/mirobot_description/urdf/"
self.rmpflow = mg.lula.motion_policies.RmpFlow(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
rmpflow_config_path=self._desc_path+"rmpflow/mirrobot_rmpflow_common.yaml",
urdf_path=self._urdf_path+"mirobot_urdf_2.urdf",
end_effector_frame_name="Link6",
maximum_substep_size=0.00334
)
self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmpflow, physics_dt)
mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp)
self._default_position, self._default_orientation = (
self._articulation_motion_policy._robot_articulation.get_world_pose()
)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
return
def reset(self):
mg.MotionPolicyController.reset(self)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
| 1,955 |
Python
| 47.899999 | 131 | 0.691049 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .hello_robot import HelloRobot
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="",
name="HelloRobot",
title="HelloRobot",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=HelloRobot(),
)
return
| 2,032 |
Python
| 41.354166 | 135 | 0.738189 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloRobot/hello_robot.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
import numpy as np
class HelloRobot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
assets_root_path = get_assets_root_path()
jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd"
self._jetbot = world.scene.add(
WheeledRobot(
prim_path="/World/Fancy_Robot",
name="fancy_robot",
wheel_dof_names=["left_wheel_joint", "right_wheel_joint"],
create_robot=True,
usd_path=jetbot_asset_path,
)
)
return
async def setup_post_load(self):
self._world = self.get_world()
self._jetbot = self._world.scene.get_object("fancy_robot")
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._jetbot.apply_wheel_actions(ArticulationAction(joint_positions=None,
joint_efforts=None,
joint_velocities=5 * np.random.rand(2,)))
return
| 1,954 |
Python
| 39.729166 | 101 | 0.634084 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .gripper_control import GripperControl
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="AddingNewManip",
name="GripperControl",
title="GripperControl",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=GripperControl(),
)
return
| 2,066 |
Python
| 42.062499 | 135 | 0.742498 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/gripper_control.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.manipulators import SingleManipulator
import numpy as np
import carb
class GripperControl(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd"
self._joints_default_positions = np.zeros(12)
self._joints_default_positions[7] = 0.628
self._joints_default_positions[8] = 0.628
# simulation step counter
self._sim_step = 0
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
# add robot to the scene
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta")
#define the gripper
self._gripper = ParallelGripper(
#We chose the following values while inspecting the articulation
end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link",
joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
joint_opened_positions=np.array([0, 0]),
joint_closed_positions=np.array([0.628, -0.628]),
action_deltas=np.array([-0.628, 0.628]),
)
#define the manipulator
self._my_denso = self._world.scene.add(
SingleManipulator(
prim_path="/World/cobotta",
name="cobotta_robot",
end_effector_prim_name="onrobot_rg6_base_link",
gripper=self._gripper)
)
self._my_denso.set_joints_default_state(
positions=self._joints_default_positions
)
return
async def setup_post_load(self):
self._world = self.get_world()
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._sim_step += 1
gripper_positions = self._my_denso.gripper.get_joint_positions()
if self._sim_step < 500:
#close the gripper slowly
self._my_denso.gripper.apply_action(
ArticulationAction(
joint_positions=[
gripper_positions[0] + 0.1,
gripper_positions[1] - 0.1
]
))
if self._sim_step > 500:
#open the gripper slowly
self._my_denso.gripper.apply_action(
ArticulationAction(
joint_positions=[
gripper_positions[0] - 0.1,
gripper_positions[1] + 0.1
]
))
if self._sim_step == 1000:
self._sim_step = 0
return
| 3,791 |
Python
| 35.461538 | 117 | 0.608283 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipGripperControl/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/garage_conveyor.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.franka.controllers import PickPlaceController
from omni.isaac.examples.base_sample import BaseSample
import numpy as np
from omni.isaac.core.physics_context.physics_context import PhysicsContext
from omni.isaac.core.prims.geometry_prim import GeometryPrim
# Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
from pxr import Sdf, UsdLux, Gf
from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core import SimulationContext
import omni.replicator.core as rep
import carb
import omni
from os.path import expanduser
import datetime
now = datetime.datetime.now()
PROPS = {
'spam' : "/Isaac/Props/YCB/Axis_Aligned/010_potted_meat_can.usd",
'jelly' : "/Isaac/Props/YCB/Axis_Aligned/009_gelatin_box.usd",
'tuna' : "/Isaac/Props/YCB/Axis_Aligned/007_tuna_fish_can.usd",
'cleanser' : "/Isaac/Props/YCB/Axis_Aligned/021_bleach_cleanser.usd",
'tomato_soup' : "/Isaac/Props/YCB/Axis_Aligned/005_tomato_soup_can.usd"
}
class GarageConveyor(BaseSample):
def __init__(self) -> None:
super().__init__()
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._nucleus_server = get_assets_root_path()
# Enable scripts
carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True)
# Disable capture on play and async rendering
carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False)
carb.settings.get_settings().set("/omni/replicator/asyncRendering", False)
carb.settings.get_settings().set("/app/asyncRendering", False)
# Replicator Writerdir
now_str = now.strftime("%Y-%m-%d_%H:%M:%S")
self._out_dir = str(expanduser("~") + "/Documents/grocery_data_" + now_str)
self._franka_position = np.array([-0.8064, 1.3602, 0.0])
# (w, x, y, z)
self._franka_rotation = np.array([0.0, 0.0, 0.0, 1.0])
self._table_scale = 0.01
self._table_height = 0.0
self._table_position = np.array([-0.7, 1.8, 0.007]) # Gf.Vec3f(0.5, 0.0, 0.0)
self._bin_path = self._nucleus_server + "/Isaac/Props/KLT_Bin/small_KLT_visual.usd"
self._bin_scale = np.array([2.0, 2.0, 1.0])
self._test_bin_position = np.array([-1.75, 1.2, 0.85])
self._test_bin_orientation = np.array([0.7071068, 0, 0, 0.7071068])
self._bin1_position = np.array([-0.5, 2.1, 0.90797])
self._bin2_position = np.array([-0.5, 1.6, 0.90797])
self._plane_scale = np.array([0.4, 0.24, 1.0])
self._plane_position = np.array([-1.75, 1.2, 0.9])
self._plane_rotation = np.array([0.0, 0.0, 0.0])
return
def add_background(self):
self._world = self.get_world()
bg_path = self._server_root + "/Projects/RBROS2/ConveyorGarage/Garage_wo_Conv_OG.usd"
add_reference_to_stage(usd_path=bg_path, prim_path=f"/World/Garage")
def add_training_bin(self):
add_reference_to_stage(usd_path=self._bin_path, prim_path="/World/training_bin")
self._world.scene.add(GeometryPrim(prim_path="/World/training_bin", name=f"training_bin_ref_geom", collision=True))
self._bin1_ref_geom = self._world.scene.get_object(f"training_bin_ref_geom")
self._bin1_ref_geom.set_local_scale(np.array([self._bin_scale]))
self._bin1_ref_geom.set_world_pose(
position=self._test_bin_position,
orientation=self._test_bin_orientation
)
self._bin1_ref_geom.set_default_state(
position=self._test_bin_position,
orientation=self._test_bin_orientation
)
def add_light(self):
stage = omni.usd.get_context().get_stage()
distantLight = UsdLux.CylinderLight.Define(stage, Sdf.Path("/World/cylinderLight"))
distantLight.CreateIntensityAttr(60000)
distantLight.AddTranslateOp().Set(Gf.Vec3f(-1.2, 0.9, 3.0))
distantLight.AddScaleOp().Set((0.1, 4.0, 0.1))
distantLight.AddRotateXYZOp().Set((0, 0, 90))
def random_props(self, file_name, class_name, max_number=3, one_in_n_chance=4):
file_name = self._nucleus_server + file_name
instances = rep.randomizer.instantiate(file_name, size=max_number, mode='scene_instance')
with instances:
rep.physics.collider()
rep.modify.semantics([('class', class_name)])
rep.randomizer.scatter_2d(self.plane, check_for_collisions=True)
rep.modify.pose(
rotation=rep.distribution.uniform((-180,-180, -180), (180, 180, 180)),
)
visibility_dist = [True] + [False]*(one_in_n_chance)
rep.modify.visibility(rep.distribution.choice(visibility_dist))
def add_replicator(self):
self.cam = rep.create.camera(
position=(-1.75, 1.2, 2.0),
# rotation=(-90, 0, 0),
look_at=(-1.75, 1.2, 0.8)
)
# self.rp = rep.create.render_product(self.cam, resolution=(1024, 1024))
self.rp = rep.create.render_product(self.cam, resolution=(1280, 720))
self.plane = rep.create.plane(
scale=self._plane_scale,
position=self._plane_position,
rotation=self._plane_rotation,
visible=False
)
rep.randomizer.register(self.random_props)
return
def setup_scene(self):
self._world = self.get_world()
self._stage = omni.usd.get_context().get_stage()
self.simulation_context = SimulationContext()
self.add_background()
self.add_light()
self.add_training_bin()
self.add_replicator()
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
return
async def setup_post_load(self):
self._world = self.get_world()
self._world.scene.enable_bounding_boxes_computations()
with rep.trigger.on_frame(num_frames=50, interval=2):
for n, f in PROPS.items():
self.random_props(f, n)
# Create a writer and apply the augmentations to its corresponding annotators
self._writer = rep.WriterRegistry.get("BasicWriter")
print(f"Writing data to: {self._out_dir}")
self._writer.initialize(
output_dir=self._out_dir,
rgb=True,
bounding_box_2d_tight=True,
)
# Attach render product to writer
self._writer.attach([self.rp])
return
async def setup_post_reset(self):
await self._world.play_async()
return
def world_cleanup(self):
self._world.pause()
return
| 7,479 |
Python
| 37.556701 | 123 | 0.63578 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "RoadBalanceEdu"
EXTENSION_DESCRIPTION = ""
| 495 |
Python
| 37.153843 | 76 | 0.80404 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .garage_conveyor import GarageConveyor
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="Replicator",
name="ReplicatorFactory",
title="ReplicatorFactory",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=GarageConveyor(),
)
return
| 2,068 |
Python
| 42.104166 | 135 | 0.742747 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/inference/model_info.py
|
import tritonclient.grpc as grpcclient
inference_server_url = "localhost:8003"
triton_client = grpcclient.InferenceServerClient(url=inference_server_url)
# find out info about model
model_name = "our_new_model"
config_info = triton_client.get_model_config(model_name)
print(config_info)
| 290 |
Python
| 25.454543 | 74 | 0.793103 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/inference/inference.py
|
from tritonclient.utils import triton_to_np_dtype
import tritonclient.grpc as grpcclient
import cv2
import numpy as np
from matplotlib import pyplot as plt
inference_server_url = "localhost:8003"
triton_client = grpcclient.InferenceServerClient(url=inference_server_url)
model_name = "our_new_model"
# load image data
target_width, target_height = 1280, 720
image_bgr = cv2.imread("rgb_0055.png")
# image_bgr = cv2.imread("rgb_0061.png")
# image_bgr = cv2.imread("rgb_0083.png")
image_bgr = cv2.resize(image_bgr, (target_width, target_height))
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
image = np.float32(image_rgb)
# preprocessing
image = image/255
image = np.moveaxis(image, -1, 0) # HWC to CHW
image = image[np.newaxis, :] # add batch dimension
image = np.float32(image)
plt.imshow(image_rgb)
# create input
input_name = "input"
inputs = [grpcclient.InferInput(input_name, image.shape, "FP32")]
inputs[0].set_data_from_numpy(image)
output_names = ["boxes", "labels", "scores"]
outputs = [grpcclient.InferRequestedOutput(n) for n in output_names]
results = triton_client.infer(model_name, inputs, outputs=outputs)
boxes, labels, scores = [results.as_numpy(o) for o in output_names]
# annotate
annotated_image = image_bgr.copy()
props_dict = {
0: 'klt_bin',
1: 'tomato_soup',
2: 'tuna',
3: 'spam',
4: 'jelly',
5: 'cleanser',
}
if boxes.size > 0: # ensure something is found
for box, lab, scr in zip(boxes, labels, scores):
if scr > 0.4:
box_top_left = int(box[0]), int(box[1])
box_bottom_right = int(box[2]), int(box[3])
text_origin = int(box[0]), int(box[3])
border_color = list(np.random.random(size=3) * 256)
text_color = (255, 255, 255)
font_scale = 0.9
thickness = 1
# bounding box2
img = cv2.rectangle(
annotated_image,
box_top_left,
box_bottom_right,
border_color,
thickness=5,
lineType=cv2.LINE_8
)
print(f"index: {lab}, label: {props_dict[lab]}, score: {scr:.2f}")
# For the text background
# Finds space required by the text so that we can put a background with that amount of width.
(w, h), _ = cv2.getTextSize(
props_dict[lab], cv2.FONT_HERSHEY_SIMPLEX,
0.6, 1
)
# Prints the text.
img = cv2.rectangle(
img, (box_top_left[0], box_top_left[1] - 20),
(box_top_left[0] + w, box_top_left[1]),
border_color, -1
)
img = cv2.putText(
img, props_dict[lab], box_top_left,
cv2.FONT_HERSHEY_SIMPLEX, 0.6,
text_color, 1
)
plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB))
plt.show()
| 2,945 |
Python
| 28.757575 | 105 | 0.582343 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/export/model_export.py
|
import os
import torch
import torchvision
import warnings
warnings.filterwarnings("ignore")
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# load the PyTorch model.
pytorch_dir = "/home/kimsooyoung/Documents/model.pth"
model = torch.load(pytorch_dir).cuda()
# Export Model
width = 1280
height = 720
dummy_input = torch.rand(1, 3, height, width).cuda()
torch.onnx.export(
model,
dummy_input,
"model.onnx",
opset_version=11,
input_names=["input"],
output_names=["boxes", "labels", "scores"]
)
| 556 |
Python
| 20.423076 | 83 | 0.69964 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/viz/data_visualize.py
|
import os
import json
import hashlib
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# # Desktop
# data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-21_18:52:00"
# Laptop
data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-23_16:43:00"
out_dir = "/home/kimsooyoung/Documents"
number = "0025"
# Write Visualization Functions
# data_to_colour
# takes in our data from a specific label ID and maps it to the proper color for the bounding box.
def data_to_colour(data):
if isinstance(data, str):
data = bytes(data, "utf-8")
else:
data = bytes(data)
m = hashlib.sha256()
m.update(data)
key = int(m.hexdigest()[:8], 16)
r = ((((key >> 0) & 0xFF) + 1) * 33) % 255
g = ((((key >> 8) & 0xFF) + 1) * 33) % 255
b = ((((key >> 16) & 0xFF) + 1) * 33) % 255
inv_norm_i = 128 * (3.0 / (r + g + b))
return (int(r * inv_norm_i) / 255, int(g * inv_norm_i) / 255, int(b * inv_norm_i) / 255)
# colorize_bbox_2d
# takes in the path to the RGB image for the background,
# the bounding box data, the labels, and the path to store the visualization.
# It outputs a colorized bounding box.
def colorize_bbox_2d(rgb_path, data, id_to_labels, file_path):
rgb_img = Image.open(rgb_path)
colors = [data_to_colour(bbox["semanticId"]) for bbox in data]
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(rgb_img)
for bbox_2d, color, index in zip(data, colors, id_to_labels.keys()):
labels = id_to_labels[str(index)]
rect = patches.Rectangle(
xy=(bbox_2d["x_min"], bbox_2d["y_min"]),
width=bbox_2d["x_max"] - bbox_2d["x_min"],
height=bbox_2d["y_max"] - bbox_2d["y_min"],
edgecolor=color,
linewidth=2,
label=labels,
fill=False,
)
ax.add_patch(rect)
plt.legend(loc="upper left")
plt.savefig(file_path)
# Load Synthetic Data and Visualize
rgb_path = data_dir
rgb = "rgb_"+number+".png"
rgb_path = os.path.join(rgb_path, rgb)
import os
print(os.path.abspath("."))
# load the bounding box data.
npy_path = data_dir
bbox2d_tight_file_name = "bounding_box_2d_tight_"+number+".npy"
data = np.load(os.path.join(npy_path, bbox2d_tight_file_name))
# load the labels corresponding to the image.
json_path = data_dir
bbox2d_tight_labels_file_name = "bounding_box_2d_tight_labels_"+number+".json"
bbox2d_tight_id_to_labels = None
with open(os.path.join(json_path, bbox2d_tight_labels_file_name), "r") as json_data:
bbox2d_tight_id_to_labels = json.load(json_data)
# Finally, we can call our function and see the labeled image!
colorize_bbox_2d(rgb_path, data, bbox2d_tight_id_to_labels, os.path.join(out_dir, "bbox2d_tight.png"))
| 2,789 |
Python
| 31.823529 | 102 | 0.642524 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactory/train/fast_rcnn_train.py
|
from PIL import Image
import os
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision import transforms as T
import json
import shutil
epochs = 15
num_classes = 6
data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-23_16:43:00"
output_file = "/home/kimsooyoung/Documents/model.pth"
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
print(f"Using device: {device}")
class GroceryDataset(torch.utils.data.Dataset):
# This function is run once when instantiating the Dataset object
def __init__(self, root, transforms):
self.root = root
self.transforms = transforms
# In the first portion of this code we are taking our single dataset folder
# and splitting it into three folders based on the file types.
# This is just a preprocessing step.
list_ = os.listdir(root)
for file_ in list_:
name, ext = os.path.splitext(file_)
ext = ext[1:]
if ext == '':
continue
if os.path.exists(root+ '/' + ext):
shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_)
else:
os.makedirs(root+'/'+ext)
shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_)
self.imgs = list(sorted(os.listdir(os.path.join(root, "png"))))
self.label = list(sorted(os.listdir(os.path.join(root, "json"))))
self.box = list(sorted(os.listdir(os.path.join(root, "npy"))))
# We have our three attributes with the img, label, and box data
# Loads and returns a sample from the dataset at the given index idx
def __getitem__(self, idx):
img_path = os.path.join(self.root, "png", self.imgs[idx])
img = Image.open(img_path).convert("RGB")
label_path = os.path.join(self.root, "json", self.label[idx])
with open(os.path.join('root', label_path), "r") as json_data:
json_labels = json.load(json_data)
box_path = os.path.join(self.root, "npy", self.box[idx])
dat = np.load(str(box_path))
boxes = []
labels = []
for i in dat:
obj_val = i[0]
xmin = torch.as_tensor(np.min(i[1]), dtype=torch.float32)
xmax = torch.as_tensor(np.max(i[3]), dtype=torch.float32)
ymin = torch.as_tensor(np.min(i[2]), dtype=torch.float32)
ymax = torch.as_tensor(np.max(i[4]), dtype=torch.float32)
if (ymax > ymin) & (xmax > xmin):
boxes.append([xmin, ymin, xmax, ymax])
area = (xmax - xmin) * (ymax - ymin)
labels += [json_labels.get(str(obj_val)).get('class')]
label_dict = {}
# Labels for the dataset
static_labels = {
'klt_bin' : 0,
'tomato_soup' : 1,
'tuna' : 2,
'spam' : 3,
'jelly' : 4,
'cleanser' : 5
}
labels_out = []
# Transforming the input labels into a static label dictionary to use
for i in range(len(labels)):
label_dict[i] = labels[i]
for i in label_dict:
fruit = label_dict[i]
final_fruit_label = static_labels[fruit]
labels_out += [final_fruit_label]
target = {}
target["boxes"] = torch.as_tensor(boxes, dtype=torch.float32)
target["labels"] = torch.as_tensor(labels_out, dtype=torch.int64)
target["image_id"] = torch.tensor([idx])
target["area"] = area
if self.transforms is not None:
img= self.transforms(img)
return img, target
# Finally we have a function for the number of samples in our dataset
def __len__(self):
return len(self.imgs)
# Create Helper Functions
# converting to `Tensor` objects and also converting the `dtypes`.
def get_transform(train):
transforms = []
transforms.append(T.PILToTensor())
transforms.append(T.ConvertImageDtype(torch.float))
return T.Compose(transforms)
# Create a function to collate our samples.
def collate_fn(batch):
return tuple(zip(*batch))
# Create Model and Train
# We are starting with the pretrained (default weights) object detection
# fasterrcnn_resnet50 model from Torchvision.
def create_model(num_classes):
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights='DEFAULT')
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
return model
# create our dataset by using our custom GroceryDataset class
# This is then passed into our DataLoader.
dataset = GroceryDataset(data_dir, get_transform(train=True))
data_loader = torch.utils.data.DataLoader(
dataset,
# batch_size=16,
batch_size=8,
shuffle=True,
collate_fn=collate_fn
)
# create our model with the N classes
# And then transfer it to the GPU for training.
model = create_model(num_classes)
model.to(device)
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.001)
len_dataloader = len(data_loader)
# Now we can actually train our model.
# Keep track of our loss and print it out as we train.
model.train()
ep = 0
for epoch in range(epochs):
optimizer.zero_grad()
ep += 1
i = 0
for imgs, annotations in data_loader:
i += 1
imgs = list(img.to(device) for img in imgs)
annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations]
loss_dict = model(imgs, annotations)
losses = sum(loss for loss in loss_dict.values())
losses.backward()
optimizer.step()
print(f'Epoch: {ep} Iteration: {i}/{len_dataloader}, Loss: {losses}')
torch.save(model, output_file)
| 5,909 |
Python
| 33.360465 | 84 | 0.616856 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"mirobot_urdf_2.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "Link6"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,395 |
Python
| 45.533332 | 127 | 0.700358 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .follow_target_example import FollowTargetExample
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="WegoRobotics",
name="FollowTarget",
title="FollowTarget",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=FollowTargetExample(),
)
return
| 2,076 |
Python
| 42.270832 | 135 | 0.743256 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/follow_target_example.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.manipulators import SingleManipulator
import omni.isaac.core.tasks as tasks
from typing import Optional
import numpy as np
import carb
from .ik_solver import KinematicsSolver
from .controllers.rmpflow import RMPFlowController
# Inheriting from the base class Follow Target
class FollowTarget(tasks.FollowTarget):
def __init__(
self,
name: str = "mirobot_follow_target",
target_prim_path: Optional[str] = None,
target_name: Optional[str] = None,
target_position: Optional[np.ndarray] = None,
target_orientation: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
tasks.FollowTarget.__init__(
self,
name=name,
target_prim_path=target_prim_path,
target_name=target_name,
target_position=target_position,
target_orientation=target_orientation,
offset=offset,
)
carb.log_info("Check /persistent/isaac/asset_root/default setting")
default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default")
self._server_root = get_url_root(default_asset_root)
self._robot_path = self._server_root + "/Projects/simple_robo_arm.usd"
self._joints_default_positions = np.zeros(7)
return
def set_robot(self) -> SingleManipulator:
# add robot to the scene
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/simple_robot")
# #define the gripper
# gripper = ParallelGripper(
# #We chose the following values while inspecting the articulation
# end_effector_prim_path="/World/mirobot/onrobot_rg6_base_link",
# joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
# joint_opened_positions=np.array([0, 0]),
# joint_closed_positions=np.array([0.628, -0.628]),
# action_deltas=np.array([-0.628, 0.628]),
# )
# define the manipulator
manipulator = SingleManipulator(
prim_path="/World/simple_robot",
name="simple_robot",
end_effector_prim_name="link8_1",
gripper=None,
)
manipulator.set_joints_default_state(positions=self._joints_default_positions)
return manipulator
class FollowTargetExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._articulation_controller = None
self._my_controller = None
# simulation step counter
self._sim_step = 0
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# We add the task to the world here
my_task = FollowTarget(
name="simple_robot_follow_target",
target_position=np.array([0.15, 0, 0.15]),
target_orientation=np.array([1, 0, 0, 0]),
)
self._world.add_task(my_task)
return
async def setup_post_load(self):
self._world = self.get_world()
self._task_params = self._world.get_task("simple_robot_follow_target").get_params()
self._target_name = self._task_params["target_name"]["value"]
self._my_mirobot = self._world.scene.get_object(self._task_params["robot_name"]["value"])
# # IK controller
# self._my_controller = KinematicsSolver(self._my_mirobot)
# RMPFlow controller
self._my_controller = RMPFlowController(name="target_follower_controller", robot_articulation=self._my_mirobot)
self._articulation_controller = self._my_mirobot.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
return
async def setup_post_reset(self):
self._my_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
observations = self._world.get_observations()
pos = observations[self._target_name]["position"]
ori = observations[self._target_name]["orientation"]
# # IK controller
# actions, succ = self._my_controller.compute_inverse_kinematics(
# target_position=pos
# )
# if succ:
# self._articulation_controller.apply_action(actions)
# else:
# carb.log_warn("IK did not converge to a solution. No action is being taken.")
# RMPFlow controller
actions = self._my_controller.forward(
target_end_effector_position=pos,
target_end_effector_orientation=ori,
)
self._articulation_controller.apply_action(actions)
return
| 5,527 |
Python
| 35.130719 | 119 | 0.641578 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/rmpflow/robot_descriptor.yaml
|
api_version: 1.0
cspace:
- link1_to_base_link
- link2_to_link1
- link3_to_link2
- link4_to_link3
- link5_to_link4
- link6_to_link5
- link7_to_link6
root_link: world
default_q: [
0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00
]
cspace_to_urdf_rules: []
composite_task_spaces: []
| 303 |
YAML
| 19.266665 | 44 | 0.60396 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/rmpflow/simple_robot_rmpflow_common.yaml
|
joint_limit_buffers: [.01, .01, .01, .01, .01, .01, .01]
rmp_params:
cspace_target_rmp:
metric_scalar: 50.
position_gain: 100.
damping_gain: 50.
robust_position_term_thresh: .5
inertia: 1.
cspace_trajectory_rmp:
p_gain: 100.
d_gain: 10.
ff_gain: .25
weight: 50.
cspace_affine_rmp:
final_handover_time_std_dev: .25
weight: 2000.
joint_limit_rmp:
metric_scalar: 1000.
metric_length_scale: .01
metric_exploder_eps: 1e-3
metric_velocity_gate_length_scale: .01
accel_damper_gain: 200.
accel_potential_gain: 1.
accel_potential_exploder_length_scale: .1
accel_potential_exploder_eps: 1e-2
joint_velocity_cap_rmp:
max_velocity: 1.
velocity_damping_region: .3
damping_gain: 1000.0
metric_weight: 100.
target_rmp:
accel_p_gain: 30.
accel_d_gain: 85.
accel_norm_eps: .075
metric_alpha_length_scale: .05
min_metric_alpha: .01
max_metric_scalar: 10000
min_metric_scalar: 2500
proximity_metric_boost_scalar: 20.
proximity_metric_boost_length_scale: .02
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
axis_target_rmp:
accel_p_gain: 210.
accel_d_gain: 60.
metric_scalar: 10
proximity_metric_boost_scalar: 3000.
proximity_metric_boost_length_scale: .08
xi_estimator_gate_std_dev: 20000.
accept_user_weights: false
collision_rmp:
damping_gain: 50.
damping_std_dev: .04
damping_robustness_eps: 1e-2
damping_velocity_gate_length_scale: .01
repulsion_gain: 800.
repulsion_std_dev: .01
metric_modulation_radius: .5
metric_scalar: 10000.
metric_exploder_std_dev: .02
metric_exploder_eps: .001
damping_rmp:
accel_d_gain: 30.
metric_scalar: 50.
inertia: 100.
canonical_resolve:
max_acceleration_norm: 50.
projection_tolerance: .01
verbose: false
body_cylinders:
- name: base
pt1: [0,0,.333]
pt2: [0,0,0.]
radius: .05
body_collision_controllers:
- name: link8_1
radius: .05
| 2,273 |
YAML
| 28.532467 | 56 | 0.58161 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/controllers/rmpflow.py
|
import omni.isaac.motion_generation as mg
from omni.isaac.core.articulations import Articulation
class RMPFlowController(mg.MotionPolicyController):
def __init__(self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0) -> None:
# TODO: chamge the follow paths
# laptop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/SimpleRobotFollowTarget/"
self._urdf_path = "/home/kimsooyoung/ros2_ws/src/simple_robo_arm_description/urdf/"
self.rmpflow = mg.lula.motion_policies.RmpFlow(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
rmpflow_config_path=self._desc_path+"rmpflow/simple_robot_rmpflow_common.yaml",
urdf_path=self._urdf_path+"simple_robo_arm.urdf",
end_effector_frame_name="link8_1",
maximum_substep_size=0.00334
)
self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmpflow, physics_dt)
mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp)
self._default_position, self._default_orientation = (
self._articulation_motion_policy._robot_articulation.get_world_pose()
)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
return
def reset(self):
mg.MotionPolicyController.reset(self)
self._motion_policy.set_robot_base_pose(
robot_position=self._default_position, robot_orientation=self._default_orientation
)
| 1,697 |
Python
| 46.166665 | 131 | 0.685327 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/ur10_gripper.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.manipulators.grippers import SurfaceGripper
from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController
import numpy as np
import carb
class UR10Gripper(BaseSample):
def __init__(self) -> None:
super().__init__()
self._my_controller = None
self._articulation_controller = None
# simulation step counter
self._sim_step = 0
return
def setup_robot(self):
self._world = self.get_world()
assets_root_path = get_assets_root_path()
asset_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/UR10")
gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd"
# add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link")
# gripper = SurfaceGripper(
# end_effector_prim_path="/World/UR10/ee_link",
# translate=0.1611,
# # direction="x",
# direction="z",
# )
# self._ur10 = self._world.scene.add(
# SingleManipulator(
# prim_path="/World/UR10",
# name="my_ur10",
# end_effector_prim_name="ee_link",
# # gripper=gripper
# gripper=None
# )
# )
# self._ur10.set_joints_default_state(
# positions=np.array([-np.pi/2, -np.pi/2, -np.pi/2, -np.pi/2, np.pi/2, 0])
# )
self._cube = self._world.scene.add(
DynamicCuboid(
name="cube",
position=np.array([0.3, 0.3, 0.3]),
prim_path="/World/Cube",
scale=np.array([0.0515, 0.0515, 0.0515]),
size=1.0,
color=np.array([0, 0, 1]),
)
)
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
self.setup_robot()
return
async def setup_post_load(self):
self._world = self.get_world()
# self._my_controller = PickPlaceController(
# name="pick_place_controller",
# gripper=self._ur10.gripper,
# robot_articulation=self._ur10
# )
# self._articulation_controller = self._ur10.get_articulation_controller()
# self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
# self._sim_step += 1
# observations = self._world.get_observations()
# actions = self._my_controller.forward(
# picking_position=self._cube.get_local_pose()[0],
# placing_position=np.array([0.7, 0.7, 0.0515 / 2.0]),
# current_joint_positions=self._ur10.get_joint_positions(),
# # end_effector_offset=np.array([0, 0, 0.02]),
# end_effector_offset=np.array([0, 0, 0.03]),
# )
# if self._my_controller.is_done():
# print("done picking and placing")
# self._articulation_controller.apply_action(actions)
return
| 4,054 |
Python
| 33.07563 | 98 | 0.594475 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/global_variables.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
EXTENSION_TITLE = "MyExtension"
EXTENSION_DESCRIPTION = ""
| 492 |
Python
| 36.923074 | 76 | 0.802846 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/extension.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from omni.isaac.examples.base_sample import BaseSampleExtension
from .ur10_gripper import UR10Gripper
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_physics_step: Called on every physics step
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class Extension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="RoadBalanceEdu",
submenu_name="AddingNewManip",
name="ManipURGripper",
title="ManipURGripper",
doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html",
overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.",
file_path=os.path.abspath(__file__),
sample=UR10Gripper(),
)
return
| 2,057 |
Python
| 41.874999 | 135 | 0.741371 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/__init__.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import Extension
| 464 |
Python
| 45.499995 | 76 | 0.814655 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/ui_builder.py
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import List
import omni.ui as ui
from omni.isaac.ui.element_wrappers import (
Button,
CheckBox,
CollapsableFrame,
ColorPicker,
DropDown,
FloatField,
IntField,
StateButton,
StringField,
TextBlock,
XYPlot,
)
from omni.isaac.ui.ui_utils import get_style
class UIBuilder:
def __init__(self):
# Frames are sub-windows that can contain multiple UI elements
self.frames = []
# UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers
self.wrapped_ui_elements = []
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
pass
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
pass
def on_physics_step(self, step):
"""Callback for Physics Step.
Physics steps only occur when the timeline is playing
Args:
step (float): Size of physics step
"""
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called
"""
# None of the UI elements in this template actually have any internal state that needs to be cleaned up.
# But it is best practice to call cleanup() on all wrapped UI elements to simplify development.
for ui_elem in self.wrapped_ui_elements:
ui_elem.cleanup()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
# Create a UI frame that prints the latest UI event.
self._create_status_report_frame()
# Create a UI frame demonstrating simple UI elements for user input
self._create_simple_editable_fields_frame()
# Create a UI frame with different button types
self._create_buttons_frame()
# Create a UI frame with different selection widgets
self._create_selection_widgets_frame()
# Create a UI frame with different plotting tools
self._create_plotting_frame()
def _create_status_report_frame(self):
self._status_report_frame = CollapsableFrame("Status Report", collapsed=False)
with self._status_report_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
self._status_report_field = TextBlock(
"Last UI Event",
num_lines=3,
tooltip="Prints the latest change to this UI",
include_copy_button=True,
)
def _create_simple_editable_fields_frame(self):
self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False)
with self._simple_fields_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
int_field = IntField(
"Int Field",
default_value=1,
tooltip="Type an int or click and drag to set a new value.",
lower_limit=-100,
upper_limit=100,
on_value_changed_fn=self._on_int_field_value_changed_fn,
)
self.wrapped_ui_elements.append(int_field)
float_field = FloatField(
"Float Field",
default_value=1.0,
tooltip="Type a float or click and drag to set a new value.",
step=0.5,
format="%.2f",
lower_limit=-100.0,
upper_limit=100.0,
on_value_changed_fn=self._on_float_field_value_changed_fn,
)
self.wrapped_ui_elements.append(float_field)
def is_usd_or_python_path(file_path: str):
# Filter file paths shown in the file picker to only be USD or Python files
_, ext = os.path.splitext(file_path.lower())
return ext == ".usd" or ext == ".py"
string_field = StringField(
"String Field",
default_value="Type Here or Use File Picker on the Right",
tooltip="Type a string or use the file picker to set a value",
read_only=False,
multiline_okay=False,
on_value_changed_fn=self._on_string_field_value_changed_fn,
use_folder_picker=True,
item_filter_fn=is_usd_or_python_path,
)
self.wrapped_ui_elements.append(string_field)
def _create_buttons_frame(self):
buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False)
with buttons_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
button = Button(
"Button",
"CLICK ME",
tooltip="Click This Button to activate a callback function",
on_click_fn=self._on_button_clicked_fn,
)
self.wrapped_ui_elements.append(button)
state_button = StateButton(
"State Button",
"State A",
"State B",
tooltip="Click this button to transition between two states",
on_a_click_fn=self._on_state_btn_a_click_fn,
on_b_click_fn=self._on_state_btn_b_click_fn,
physics_callback_fn=None, # See Loaded Scenario Template for example usage
)
self.wrapped_ui_elements.append(state_button)
check_box = CheckBox(
"Check Box",
default_value=False,
tooltip=" Click this checkbox to activate a callback function",
on_click_fn=self._on_checkbox_click_fn,
)
self.wrapped_ui_elements.append(check_box)
def _create_selection_widgets_frame(self):
self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False)
with self._selection_widgets_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def dropdown_populate_fn():
return ["Option A", "Option B", "Option C"]
dropdown = DropDown(
"Drop Down",
tooltip=" Select an option from the DropDown",
populate_fn=dropdown_populate_fn,
on_selection_fn=self._on_dropdown_item_selection,
)
self.wrapped_ui_elements.append(dropdown)
dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn
color_picker = ColorPicker(
"Color Picker",
default_value=[0.69, 0.61, 0.39, 1.0],
tooltip="Select a Color",
on_color_picked_fn=self._on_color_picked,
)
self.wrapped_ui_elements.append(color_picker)
def _create_plotting_frame(self):
self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False)
with self._plotting_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
import numpy as np
x = np.arange(-1, 6.01, 0.01)
y = np.sin((x - 0.5) * np.pi)
plot = XYPlot(
"XY Plot",
tooltip="Press mouse over the plot for data label",
x_data=[x[:300], x[100:400], x[200:]],
y_data=[y[:300], y[100:400], y[200:]],
x_min=None, # Use default behavior to fit plotted data to entire frame
x_max=None,
y_min=-1.5,
y_max=1.5,
x_label="X [rad]",
y_label="Y",
plot_height=10,
legends=["Line 1", "Line 2", "Line 3"],
show_legend=True,
plot_colors=[
[255, 0, 0],
[0, 255, 0],
[0, 100, 200],
], # List of [r,g,b] values; not necessary to specify
)
######################################################################################
# Functions Below This Point Are Callback Functions Attached to UI Element Wrappers
######################################################################################
def _on_int_field_value_changed_fn(self, new_value: int):
status = f"Value was changed in int field to {new_value}"
self._status_report_field.set_text(status)
def _on_float_field_value_changed_fn(self, new_value: float):
status = f"Value was changed in float field to {new_value}"
self._status_report_field.set_text(status)
def _on_string_field_value_changed_fn(self, new_value: str):
status = f"Value was changed in string field to {new_value}"
self._status_report_field.set_text(status)
def _on_button_clicked_fn(self):
status = "The Button was Clicked!"
self._status_report_field.set_text(status)
def _on_state_btn_a_click_fn(self):
status = "State Button was Clicked in State A!"
self._status_report_field.set_text(status)
def _on_state_btn_b_click_fn(self):
status = "State Button was Clicked in State B!"
self._status_report_field.set_text(status)
def _on_checkbox_click_fn(self, value: bool):
status = f"CheckBox was set to {value}!"
self._status_report_field.set_text(status)
def _on_dropdown_item_selection(self, item: str):
status = f"{item} was selected from DropDown"
self._status_report_field.set_text(status)
def _on_color_picked(self, color: List[float]):
formatted_color = [float("%0.2f" % i) for i in color]
status = f"RGBA Color {formatted_color} was picked in the ColorPicker"
self._status_report_field.set_text(status)
| 11,487 |
Python
| 38.888889 | 112 | 0.542178 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipURGripper/README.md
|
# Loading Extension
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator
# Extension Usage
This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop
custom UI tools with minimal boilerplate code.
# Template Code Overview
The template is well documented and is meant to be self-explanatory to the user should they
start reading the provided python files. A short overview is also provided here:
global_variables.py:
A script that stores in global variables that the user specified when creating this extension such as the Title and Description.
extension.py:
A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This
class is meant to fulfill most ues-cases without modification.
In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py.
ui_builder.py:
This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been
set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is
the most thoroughly documented, and the user should read through it before making serious modification.
| 1,488 |
Markdown
| 58.559998 | 132 | 0.793011 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"mirobot_urdf_2.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "Link6"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,395 |
Python
| 45.533332 | 127 | 0.700358 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.