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
|
---|---|---|---|---|---|---|
RoboEagles4828/rift2024/src/rift_bringup/launch/debugLayer.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch.substitutions import LaunchConfiguration, PythonExpression
from launch.event_handlers import OnProcessExit
from launch.actions import DeclareLaunchArgument, ExecuteProcess, RegisterEventHandler
from launch.conditions import IfCondition
import os
def generate_launch_description():
bringup_pkg_path = os.path.join(get_package_share_directory('rift_bringup'))
use_sim_time = LaunchConfiguration('use_sim_time')
namespace = LaunchConfiguration('namespace')
enable_rviz = LaunchConfiguration('enable_rviz')
enable_foxglove = LaunchConfiguration('enable_foxglove')
enable_debugger_gui = LaunchConfiguration('enable_debugger_gui')
enable_joint_state_publisher = LaunchConfiguration('enable_joint_state_publisher')
rviz_file = LaunchConfiguration('rviz_file')
foxglove = Node(
package='foxglove_bridge',
executable='foxglove_bridge',
namespace=namespace,
parameters=[{
'port': 8765,
'use_sim_time': use_sim_time
}],
condition=IfCondition(enable_foxglove)
)
parse_script = os.path.join(bringup_pkg_path, 'scripts', 'parseRviz.py')
parseRvizFile = ExecuteProcess(cmd=["python3", parse_script, rviz_file, namespace])
rviz2 = Node(
package='rviz2',
name='rviz2',
namespace=namespace,
executable='rviz2',
parameters=[{ 'use_sim_time': use_sim_time }],
output='screen',
arguments=[["-d"], [rviz_file]],
condition=IfCondition(enable_rviz)
)
rviz2_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=parseRvizFile,
on_exit=[rviz2],
)
)
debugger_gui = Node(
package='rift_debugger',
namespace=namespace,
executable='debugger',
name='debugger',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': 'true',
'source_list': ['joint_states']
}],
condition=IfCondition(enable_debugger_gui),
)
# Starts Joint State Publisher GUI for rviz (conflicts with rift_debugger)
joint_state_publisher_gui = Node (
package='joint_state_publisher_gui',
namespace=namespace,
executable='joint_state_publisher_gui',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': True,
}],
condition=IfCondition(enable_joint_state_publisher),
)
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
DeclareLaunchArgument(
'namespace',
default_value='default',
description='The namespace of nodes and links'),
DeclareLaunchArgument(
'enable_rviz',
default_value='true',
description='enables rviz'),
DeclareLaunchArgument(
'rviz_file',
default_value='',
description='The config file for rviz'),
DeclareLaunchArgument(
'enable_foxglove',
default_value='true',
description='enables foxglove bridge'),
DeclareLaunchArgument(
'enable_debugger_gui',
default_value='false',
description='enables the debugger gui tool'),
DeclareLaunchArgument(
'enable_joint_state_publisher',
default_value='false',
description='enables the joint state publisher tool'),
foxglove,
parseRvizFile,
rviz2_delay,
debugger_gui,
joint_state_publisher_gui,
]) | 3,908 | Python | 33.901785 | 87 | 0.620778 |
RoboEagles4828/rift2024/src/rift_bringup/launch/real-rviz.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
bringup_path = get_package_share_directory("rift_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'real.rviz')
common = {
'use_sim_time': 'false',
'namespace': 'real',
'forward_command_controller': 'false',
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_debugger_gui': 'true',
'rviz_file': rviz_file
}
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
# Launch!
return LaunchDescription([
debug_layer,
]) | 1,037 | Python | 31.437499 | 75 | 0.644166 |
RoboEagles4828/rift2024/src/rift_bringup/launch/rtab-real.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
rtabmap_ros_path = get_package_share_directory("rtabmap_launch")
rtabmap_args = {
'rtabmap_args': '--delete_db_on_start',
'use_sim_time': use_sim_time,
# Frames
'frame_id': f'real/base_link',
# 'odom_frame_id': f'{NAMESPACE}/zed/odom',
'map_frame_id': f'real/map',
# Topics
'rgb_topic': f'/real/zed/rgb/image_rect_color',
'camera_info_topic': f'/real/zed/rgb/camera_info',
'depth_topic': f'/real/zed/depth/depth_registered',
'imu_topic': f'/real/zed/imu/data',
# 'odom_topic': f'/{NAMESPACE}/zed/odom',
'approx_sync': 'false',
# 'wait_imu_to_init': 'true',
# 'visual_odometry': 'false',
# 'publish_tf_odom': 'false',
# 'qos': '1',
# 'rviz': 'true',
}
rtab_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
rtabmap_ros_path,'launch','rtabmap.launch.py'
)]), launch_arguments=rtabmap_args.items())
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='true',
description='Use sim time if true'),
rtab_layer,
]) | 1,749 | Python | 34.714285 | 91 | 0.621498 |
RoboEagles4828/rift2024/src/rift_bringup/launch/real-vslam.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("rift_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml')
rviz_file = os.path.join(bringup_path, 'config', 'view.rviz')
common = { 'use_sim_time': 'true', 'namespace': NAMESPACE }
real_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','real.launch.py'
)]), launch_arguments=common.items())
rtab_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','rtab-real.launch.py'
)]))
delay_rtab = TimerAction(period=5.0, actions=[rtab_layer])
# Launch!
return LaunchDescription([
real_layer,
rtab_layer
])
| 1,214 | Python | 34.735293 | 91 | 0.677924 |
RoboEagles4828/rift2024/src/rift_bringup/launch/real.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
bringup_path = get_package_share_directory("rift_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-real.yaml')
common = { 'use_sim_time': 'false', 'namespace': 'real' }
control_launch_args = common | {
'use_ros2_control': 'true',
'hardware_plugin': 'swerve_hardware/RealDriveHardware',
}
teleoplaunch_args = common | {
'joystick_file': joystick_file,
'enable_joy': 'false'
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
teleop_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','teleopLayer.launch.py'
)]), launch_arguments=teleoplaunch_args.items())
gym_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','gym.launch.py'
)]), launch_arguments={'use_sim_time': 'false'}.items()
)
# Launch!
return LaunchDescription([
control_layer,
teleop_layer,
gym_launch
])
| 1,611 | Python | 34.822221 | 75 | 0.634389 |
RoboEagles4828/rift2024/src/rift_bringup/launch/rio-debug.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("rift_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'riodebug.rviz')
common = { 'use_sim_time': 'false', 'namespace': 'real' }
control_launch_args = common | {
'use_ros2_control': 'true',
'load_controllers': 'false',
'forward_command_controller': 'true', # Change to false in order to disable publishing
'hardware_plugin': 'swerve_hardware/RealDriveHardware', # Use IsaacDriveHardware for isaac or RealDriveHardware for real.
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_debugger_gui': 'true',
'rviz_file': rviz_file
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer])
# Launch!
return LaunchDescription([
control_layer,
delay_debug_layer
])
| 1,762 | Python | 38.177777 | 129 | 0.662883 |
RoboEagles4828/rift2024/src/rift_bringup/scripts/parseRviz.py | import sys
import yaml
import os
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def processRvizFileForNamespace(rviz_file, NAMESPACE):
rviz_data = None
raw_rviz_data = None
with open(rviz_file, 'r') as stream:
raw_rviz_data = stream.read()
rviz_data = yaml.safe_load(raw_rviz_data)
# Get the namespace value from the rviz file
current_namespace = None
if rviz_data:
for display in rviz_data['Visualization Manager']['Displays']:
for k, v in display.items():
if 'Topic' in k and 'Value' in v:
segs = v['Value'].split('/')
if len(segs) > 1:
current_namespace = segs[1]
break
if current_namespace:
print('Found namespace: ', current_namespace)
print(f"mapping {current_namespace} -> {NAMESPACE}")
new_rviz_data = yaml.safe_load(raw_rviz_data.replace(current_namespace, NAMESPACE))
with open(rviz_file, 'w') as stream:
yaml.dump(new_rviz_data, stream)
else:
with open('err', 'w') as stream:
stream.write("Couldn't find namespace in rviz file")
if __name__ == "__main__":
processRvizFileForNamespace(sys.argv[1], sys.argv[2]) | 1,314 | Python | 33.605262 | 93 | 0.590563 |
RoboEagles4828/rift2024/src/rift_bringup/config/controllers.yaml | /*:
controller_manager:
ros__parameters:
update_rate: 20 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
swerve_controller:
type: swerve_controller/SwerveController
forward_position_controller:
type: position_controllers/JointGroupPositionController
forward_velocity_controller:
type: velocity_controllers/JointGroupVelocityController
joint_trajectory_controller:
type: joint_trajectory_controller/JointTrajectoryController
swerve_controller:
ros__parameters:
#Used to scale velocity
chassis_length_meters: 0.6032
chassis_width_meters: 0.6032
wheel_radius_meters: 0.0508
max_wheel_angular_velocity: 100.0
#If no new twist commands are created in 1 second the robot will halt
cmd_vel_timeout_seconds: 1.0
use_stamped_vel: false
front_left_wheel_joint: front_left_wheel_joint
front_right_wheel_joint: front_right_wheel_joint
rear_left_wheel_joint: rear_left_wheel_joint
rear_right_wheel_joint: rear_right_wheel_joint
front_left_axle_joint: front_left_axle_joint
front_right_axle_joint: front_right_axle_joint
rear_left_axle_joint: rear_left_axle_joint
rear_right_axle_joint: rear_right_axle_joint
linear.x.has_velocity_limits: false
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 3.0
linear.x.min_acceleration: -3.0
linear.x.max_jerk: 5.0
linear.x.min_jerk: -5.0
linear.y.has_velocity_limits: false
linear.y.has_acceleration_limits: true
linear.y.has_jerk_limits: false
linear.y.max_velocity: 2.0
linear.y.min_velocity: -2.0
linear.y.max_acceleration: 3.0
linear.y.min_acceleration: -3.0
linear.y.max_jerk: 5.0
linear.y.min_jerk: -5.0
angular.z.has_velocity_limits: false
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 3.0
angular.z.min_velocity: -3.0
angular.z.max_acceleration: 3.0
angular.z.min_acceleration: -3.0
angular.z.max_jerk: 5.0
angular.z.min_jerk: -5.0
forward_position_controller:
ros__parameters:
joints:
- 'front_left_axle_joint'
- 'front_right_axle_joint'
- 'rear_left_axle_joint'
- 'rear_right_axle_joint'
- 'arm_roller_bar_joint'
- 'elevator_outer_1_joint'
- 'elevator_center_joint'
- 'elevator_outer_2_joint'
- 'top_slider_joint'
- 'top_gripper_left_arm_joint'
- 'top_gripper_right_arm_joint'
- 'bottom_intake_joint'
forward_velocity_controller:
ros__parameters:
joints:
- 'front_left_wheel_joint'
- 'front_right_wheel_joint'
- 'rear_left_wheel_joint'
- 'rear_right_wheel_joint'
joint_trajectory_controller:
ros__parameters:
joints:
- 'arm_roller_bar_joint'
- 'elevator_center_joint'
- 'elevator_outer_1_joint'
- 'elevator_outer_2_joint'
- 'top_gripper_right_arm_joint'
- 'top_gripper_left_arm_joint'
- 'top_slider_joint'
- 'bottom_intake_joint'
command_interfaces:
- position
state_interfaces:
- position
- velocity
state_publish_rate: 50.0
action_monitor_rate: 20.0
allow_partial_joints_goal: false
open_loop_control: true
constraints:
stopped_velocity_tolerance: 0.01
goal_time: 0.0
| 3,706 | YAML | 28.188976 | 76 | 0.627361 |
RoboEagles4828/rift2024/src/rift_bringup/config/xbox-sim.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear:
x: 1.0
y: 1.0
scale_linear_turbo:
x: 2.5
y: 2.5
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular:
yaw: -1.0
scale_angular_turbo:
yaw: -2.2
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: 0.5
| 522 | YAML | 17.678571 | 51 | 0.5 |
RoboEagles4828/rift2024/src/rift_bringup/config/xbox-real.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear: #1/10000 to offset shifted 0 in /joystick-data
x: 0.0001
y: 0.0001
scale_linear_turbo:
x: 0.0004
y: 0.0004
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular: #negative to fix turning direction
yaw: -0.0001
scale_angular_turbo:
yaw: -0.0002
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: -0.25 | 610 | YAML | 24.458332 | 66 | 0.565574 |
RoboEagles4828/rift2024/src/rift_bringup/config/teleop-control.yaml | controller_mapping:
A: 0
B: 1
X: 2
Y: 3
LB: 4
RB: 5
squares: 6
menu: 7
xbox: 8
LSin: 9
RSin: 10
leftTriggerAxis: 2
rightTriggerAxis: 5
joint_limits:
arm_roller_bar_joint:
min: 0.0
max: 0.07
elevator_center_joint:
min: 0.0
max: 0.56
elevator_outer_1_joint:
min: 0.0
max: 0.2
elevator_outer_2_joint:
min: 0.0
max: 0.56
top_gripper_right_arm_joint:
min: -0.9
max: 0.0
top_gripper_left_arm_joint:
min: -0.9
max: 0.0
top_slider_joint:
min: 0.0
max: 0.30
bottom_intake_joint:
min: 0.0
max: 1.52
joint_mapping:
arm_roller_bar_joint: 0
elevator_center_joint: 1
elevator_outer_1_joint: 2
elevator_outer_2_joint: 3
top_gripper_right_arm_joint: 4
top_gripper_left_arm_joint: 5
top_slider_joint: 6
bottom_intake_joint: 7
function_mapping:
elevator_loading_station:
button: "RSin"
toggle: true
skis_up:
button: "leftTriggerAxis"
toggle: true
elevator_mid_level:
button: "LB"
toggle: true
elevator_high_level:
button: "X"
toggle: true
top_gripper_control:
button: "A"
toggle: true
elevator_pivot_control:
button: "Y"
toggle: true
top_slider_control:
button: "B"
toggle: true | 1,278 | YAML | 17.271428 | 32 | 0.606416 |
RoboEagles4828/rift2024/src/rift_tests/setup.py | from setuptools import setup
package_name = 'rift_tests'
setup(
name=package_name,
version='0.0.1',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='roboeagles',
maintainer_email='[email protected]',
description='Test robot functions',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'joint-arm = rift_tests.publish_joint_arm_command:main',
'joint-drive = rift_tests.publish_joint_drive_command:main',
'publish-twist = rift_tests.publish_twist_command:main',
'run-tests = rift_tests.run_tests_command:main',
'arm-tests = rift_tests.arm_tests:main'
],
},
) | 926 | Python | 29.899999 | 72 | 0.602592 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/publish_joint_drive_command.py | import rclpy
from rclpy.node import Node
import math
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_drive_joint_commands')
self.publisher_ = self.create_publisher(JointState, '/real/real_joint_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
cmds = JointState()
cmds.name = [
'front_left_wheel_joint',
'front_right_wheel_joint',
'rear_left_wheel_joint',
'rear_right_wheel_joint',
'front_left_axle_joint',
'front_right_axle_joint',
'rear_left_axle_joint',
'rear_right_axle_joint'
]
rad = math.pi
cmds.velocity = [
0.0,
0.0,
0.0,
0.0,
0.0, #ignore
0.0, #ignore
0.0, #ignore
0.0, #ignore
]
cmds.position = [
0.0, #ignore
0.0, #ignore
0.0, #ignore
0.0, #ignore
rad,
0.0,
0.0,
0.0
]
# position_cmds.position = []
self.publisher_.publish(cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,746 | Python | 23.263889 | 92 | 0.507446 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/publish_twist_command.py | import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, Vector3
class PublishTwistCmd(Node):
def __init__(self):
super().__init__('publish_twist_commands')
self.publisher_ = self.create_publisher(Twist, 'swerve_controller/cmd_vel_unstamped', 10)
timer_period = 0.1 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
twist = Twist()
twist.linear.x = 2.0
twist.linear.y = 0.0
twist.angular.z = 0.0
self.publisher_.publish(twist)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishTwistCmd()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 868 | Python | 22.486486 | 97 | 0.599078 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/arm_tests.py | import rclpy
import time
from .joint_test import TesterNode
# ROS Topics
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_TOPIC_NAME = '/real/real_arm_commands'
PUBLISH_INTERVAL = .5 # seconds
# Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
TESTS = [
# Here's where you define your tests, in the same style as this one.
# {"positions": [0.0]*6, "time": 3.0},
# Toggle pistons one at a time (to true)
{"positions": [0.0]*4 + [0.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [0.5] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [1.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*6, "time": 10.0},
]
JOINT_NAMES = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
def main():
rclpy.init()
testerNode = TesterNode(
tests=TESTS,
joint_names=JOINT_NAMES,
joint_range=[8, 14],
pub_topic_name=PUBLISH_TOPIC_NAME,
sub_topic_name=SUBSCRIBE_TOPIC_NAME,
pub_interval=PUBLISH_INTERVAL,
pass_tolerance=PASS_TOLERANCE,
warn_tolerance=WARN_TOLERANCE)
rclpy.spin(testerNode)
if __name__ == '__main__':
main() | 1,267 | Python | 22.481481 | 72 | 0.589582 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/run_tests_command.py | import rclpy
from rclpy.node import Node
import math
import time
from rclpy.action import ActionClient
from action_tutorials_interfaces.action import Fibonacci
from sensor_msgs.msg import JointState
import logging
vel_cmds = JointState()
rad = math.pi
vel_cmds.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.name = [
'front_left_wheel_joint',
'front_left_axle_joint',
'front_right_wheel_joint',
'front_right_axle_joint',
'rear_left_wheel_joint',
'rear_left_axle_joint',
'rear_right_wheel_joint',
'rear_right_axle_joint']
test_return = JointState()
class RunTests(Node):
def __init__(self):
super().__init__('run_tests')
self.publisher_ = self.create_publisher(
JointState,
'real_joint_commands',
10
)
timer_period = 0.1
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
self.subscription = self.create_subscription(
JointState,
'real_joint_states',
self.listener_callback,
10
)
self.subscription
self.get_logger().info('Testing: ...')
def timer_callback(self):
self.publisher_.publish(vel_cmds)
time.sleep(0.1)
self.i+=1
def listener_callback(self, msg):
test_return = msg
def check(msg, test, test_fail):
count = 0
working = True
for x in msg.velocity:
if (abs(msg.velocity[count] / 1000 - vel_cmds.velocity[count]) > 0.001 or abs(msg.position[count] / 1000 - vel_cmds.position[count]) > 0.001):
working = False
count+=1
if not working:
print(test_fail)
else:
print(test)
def test1(node):
vel_cmds.velocity=[rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Wheel is Spinning!', 'ERROR: Front Left Wheel is NOT spinning, something is wrong!')
def test2(node):
vel_cmds.position=[0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Axle is Spinning!', 'ERROR: Front Left Axle is NOT spinning, something is wrong!')
def test3(node):
vel_cmds.velocity=[0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Wheel is Spinning!', 'ERROR: Front Right Wheel is NOT spinning, something is wrong!')
def test4(node):
vel_cmds.position=[0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Axle is Spinning!', 'ERROR: Front Right Axle is NOT spinning, something is wrong!')
def test5(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Wheel is Spinning!', 'ERROR: Rear Left Wheel is NOT spinning, something is wrong!')
def test6(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Axle is Spinning!', 'ERROR: Rear Left Axle is NOT spinning, something is wrong!')
def test7(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Wheel is Spinning!', 'ERROR: Rear Right Wheel is NOT spinning, something is wrong!')
def test8(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Axle is Spinning!', 'ERROR: Rear Right Axle is NOT spinning, something is wrong!')
def main(args=None):
rclpy.init(args=args)
node = RunTests()
rclpy.spin_once(node)
test1(node)
test2(node)
test3(node)
test4(node)
test5(node)
test6(node)
test7(node)
test8(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main() | 4,771 | Python | 32.138889 | 154 | 0.590442 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/joint_test.py | import time
from rclpy.node import Node
from sensor_msgs.msg import JointState
# COLORS
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
RESET = "\033[0m"
# Default ROS values
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_INTERVAL = .5 # seconds
# Default Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
SCALING_FACTOR_FIX = 10000
class TesterNode(Node):
def __init__(self, tests, joint_names, joint_range, pub_topic_name, sub_topic_name=SUBSCRIBE_TOPIC_NAME, pub_interval=PUBLISH_INTERVAL, pass_tolerance=PASS_TOLERANCE, warn_tolerance=WARN_TOLERANCE):
super().__init__('arm_tester')
# Constructor Arguments
self.TESTS = tests
self.JOINT_NAMES = joint_names
self.JOINT_RANGE = joint_range
self.SUBSCRIBE_TOPIC_NAME = sub_topic_name
self.PUBLISH_TOPIC_NAME = pub_topic_name
self.PUBLISH_INTERVAL = pub_interval
self.PASS_TOLERANCE = pass_tolerance
self.WARN_TOLERANCE = warn_tolerance
self.currentTest = 0
self.testStatus = []
self.lastPositions = [None]*6
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.recieving = True
self.startTime = time.time()
self.subscription = self.create_subscription(JointState, self.SUBSCRIBE_TOPIC_NAME, self.recieve, 10)
self.publisher = self.create_publisher(JointState, self.PUBLISH_TOPIC_NAME, 10)
self.publishTimer = self.create_timer(self.PUBLISH_INTERVAL, self.publish)
def publish(self):
msg = JointState()
msg.name = self.JOINT_NAMES
msg.position = self.TESTS[self.currentTest]["positions"]
self.publisher.publish(msg)
self.doTests()
def doTests(self):
if not(self.recieving):
# Start running the next test
self.currentTest += 1
if self.currentTest > len(self.TESTS)-1:
print("\nTests Finished")
for index, test in enumerate(self.testStatus):
print(f"{RED if test['fail'] > 0 else YELLOW if test['warn'] > 0 else GREEN}Test {index} {'FAILED' if test['fail'] > 0 else 'PASSED'} {'with WARNINGS' if test['warn'] > 0 else ''}{RESET}")
exit(0) # shutting down rclpy just kills the node and hangs the process, without actually stopping the program
else:
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.lastPositions = [None]*6
self.recieving = True
self.startTime = time.time()
else:
# Check if the current test should end...
timeleft = time.time() - self.startTime
print(f"\rRunning Test {self.currentTest} ({round(self.TESTS[self.currentTest]['time'] - timeleft, 2)}s remaining)", end='')
if time.time() - self.startTime > self.TESTS[self.currentTest]["time"]:
self.recieving = False
self.testStatus.append({"pass": 0, "warn": 0, "fail": 0})
print(f"\rTest {self.currentTest} Completed ")
self.printResults()
print()
def recieve(self, msg : JointState):
if self.recieving:
self.lastPositions = [i / SCALING_FACTOR_FIX for i in msg.position[self.JOINT_RANGE[0]:self.JOINT_RANGE[1]]]
def testFinished(self):
if not self.recieving:
return
self.recieving = False
self.destroy_timer(self.publishTimer)
self.i += 1
def printResults(self):
for index, position in enumerate(self.lastPositions):
if position is None:
print(f"{RED}FAILED: Did not recieve any positions from the robot!{RESET}")
self.testStatus[self.currentTest]["fail"] += 1
continue
difference = abs(self.expectedPositions[index] - position)
if difference == 0:
print(f"{GREEN}Joint {index} PASSED{RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.PASS_TOLERANCE:
print(f"{GREEN}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.WARN_TOLERANCE:
print(f"{YELLOW}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["warn"] += 1
else:
print(f"{RED}FAILED: Expected position {self.expectedPositions[index]}, got {position}{RESET}")
self.testStatus[self.currentTest]["fail"] += 1 | 4,791 | Python | 43.785046 | 208 | 0.604467 |
RoboEagles4828/rift2024/src/rift_tests/rift_tests/publish_joint_arm_command.py | import rclpy
from rclpy.node import Node
import math
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_arm_joint_commands')
self.publisher_ = self.create_publisher(JointState, '/real/real_arm_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
# velocity_cmds = JointState()
position_cmds = JointState()
position_cmds.name = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
# position_cmds.name = []
# rad = math.pi
# velocity_cmds.velocity = [ 0.0 ] * 8
position_cmds.position = [
0.0, # Either a 0 (down) or a 1 (up)
0.0, # Either a 0 (fully back) or a 1 (fully extended)
0.0, # Either a 0 (open) or a 1 (closed)
0.0, # Value between 0.0 (fully back) and 2.0 (fully extended) (will be converted on their end, so just take the motor value and multiply it by two)
0.0 # Value between 0.0 (fully down) and 1.0 (fully up)
]
# position_cmds.position = []
self.publisher_.publish(position_cmds)
# self.publisher_.publish(position_cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,931 | Python | 28.723076 | 165 | 0.568099 |
RoboEagles4828/rift2024/src/isaac_hardware_test/setup.py | from setuptools import setup
package_name = 'isaac_hardware_test'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='admin',
maintainer_email='[email protected]',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'isaac_drive = isaac_hardware_test.isaac_drive:main',
],
},
)
| 696 | Python | 24.814814 | 65 | 0.604885 |
RoboEagles4828/rift2024/src/isaac_hardware_test/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
| 884 | Python | 33.03846 | 74 | 0.725113 |
RoboEagles4828/rift2024/src/isaac_hardware_test/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
| 803 | Python | 32.499999 | 74 | 0.743462 |
RoboEagles4828/rift2024/src/isaac_hardware_test/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_copyright.main import main
import pytest
# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 962 | Python | 36.03846 | 93 | 0.751559 |
RoboEagles4828/rift2024/src/isaac_hardware_test/isaac_hardware_test/isaac_drive.py | import rclpy
from rclpy.context import Context
from rclpy.node import Node
from rclpy.parameter import Parameter
from sensor_msgs.msg import JointState, Imu
from rclpy.time import Time, Duration
from std_msgs.msg import Header, String
import math
class IsaacDriveHardware(Node):
def __init__(self):
super().__init__('isaac_drive_hardware')
self.realtime_isaac_publisher_drive = self.create_publisher(JointState, 'isaac_drive_commands', 10)
self.realtime_isaac_publisher_arm = self.create_publisher(JointState, 'isaac_arm_commands', 10)
self.real_imu_publisher = self.create_publisher(String, 'real_imu', 10)
# self.joint_state_publisher = self.create_publisher(JointState, 'joint_states', 10)
self.isaac_subscriber = self.create_subscription(JointState, 'isaac_joint_states', self.isaac_callback, 10)
self.real_subscriber = self.create_subscription(JointState, '/real/real_joint_states', self.real_callback, 10)
self.imu_subscriber = self.create_subscription(Imu, 'imu', self.imu_callback, 10)
self.OKGREEN = '\033[92m'
self.ENDC = '\033[0m'
self.joint_names: list[str] = []
self.joint_state: JointState = None
self.joint_names2: list[str] = []
self.joint_state2: JointState = None
self.arm_joint_names = []
self.drive_joint_names = []
self.command_effort = []
self.command_position = []
self.empty = []
self.realtime_isaac_command: JointState = JointState()
self.joint_state_command: JointState = JointState()
self.header = Header()
self.get_logger().info(self.OKGREEN + "Configured and Activated Isaac Drive Hardware" + self.ENDC)
def imu_callback(self, imu: Imu):
if imu == None:
self.get_logger().warn("Imu message recieved was null")
imu_string = String()
data = f"{imu.orientation.w}|{imu.orientation.x}|{imu.orientation.y}|{imu.orientation.z}|{imu.angular_velocity.x}|{imu.angular_velocity.y}|{imu.angular_velocity.z}|{imu.linear_acceleration.x}|{imu.linear_acceleration.y}|{imu.linear_acceleration.z}"
imu_string.data = data
self.real_imu_publisher.publish(imu_string)
def real_callback(self, joint_state: JointState):
self.joint_names = list(joint_state.name)
self.joint_state = joint_state
self.get_logger().info(self.OKGREEN + "Recieved Real Joint State" + self.ENDC)
self.write()
def isaac_callback(self, joint_state: JointState):
self.joint_names2 = list(joint_state.name)
self.joint_state2 = joint_state
if self.joint_state2 == None:
self.get_logger().warn("Velocity message recieved was null")
else:
self.read()
def convertToRosPosition(self, isaac_position: float):
if isaac_position > math.pi:
return isaac_position - 2.0 * math.pi
elif isaac_position < -math.pi:
return isaac_position + 2.0 * math.pi
return isaac_position
def read(self):
self.joint_state_command.effort = []
names = self.joint_state2.name
positions = self.joint_state2.position
velocities = self.joint_state2.velocity
efforts = self.joint_state2.effort
for i in range(len(self.joint_names)-1):
for j in range(len(names)-1):
if names[j] == self.joint_names[i]:
self.joint_state_command.position.append(self.convertToRosPosition(positions[j]))
self.joint_state_command.velocity.append(velocities[j])
self.joint_state_command.effort.append(efforts[j])
break
# self.joint_state_command.header.stamp = Time(seconds=self._clock.now().seconds_nanoseconds()[0], nanoseconds=self._clock.now().seconds_nanoseconds()[1])
# self.joint_state_publisher.publish(self.joint_state_command)
def write(self):
self.command_effort = []
self.command_position = []
self.arm_joint_names.clear()
self.drive_joint_names.clear()
for j, i in enumerate(self.joint_names):
if i.__contains__("wheel") or i.__contains__("axle"):
vel = self.joint_state.velocity[j]
self.command_effort.append(vel/10000.0)
self.drive_joint_names.append(i)
else:
self.arm_joint_names.append(i)
position = self.joint_state.position[j]/10000.0
# Elevator
if i == "arm_roller_bar_joint":
# split position among 2 joints
self.command_position.append(position)
self.arm_joint_names.append("elevator_outer_1_joint")
if position == 0.07:
self.command_position.append(0.2)
elif position == 0.0:
self.command_position.append(0.0)
elif i == "top_slider_joint":
self.command_position.append(position)
elif i == "top_gripper_left_arm_joint":
self.command_position.append(position)
self.arm_joint_names.append("top_gripper_right_arm_joint")
self.command_position.append(position)
elif i == "elevator_center_joint":
elevator_max = 0.56
elevator_min = 0.0
#scale position to be between 0 and 1
position = (position - elevator_min)/(elevator_max - elevator_min)
self.command_position.append(position/2.0)
self.arm_joint_names.append("elevator_outer_2_joint")
self.command_position.append(position/2.0)
self.header.stamp = self._clock.now().to_msg()
self.realtime_isaac_command.header = self.header
self.realtime_isaac_command.name = self.drive_joint_names
self.realtime_isaac_command.velocity = self.command_effort
self.realtime_isaac_command.position = self.empty
self.realtime_isaac_command.effort = self.empty
self.realtime_isaac_publisher_drive.publish(self.realtime_isaac_command)
self.header.stamp = self._clock.now().to_msg()
self.realtime_isaac_command.header = self.header
self.realtime_isaac_command.name = self.arm_joint_names
self.realtime_isaac_command.velocity = self.empty
self.realtime_isaac_command.position = self.command_position
self.realtime_isaac_command.effort = self.empty
self.realtime_isaac_publisher_arm.publish(self.realtime_isaac_command)
def main(args=None):
rclpy.init(args=args)
isaac_drive_hardware = IsaacDriveHardware()
rclpy.spin(isaac_drive_hardware)
isaac_drive_hardware.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| 7,251 | Python | 43.219512 | 256 | 0.588884 |
RoboEagles4828/rift2024/src/rift_debugger/setup.py | from setuptools import setup
package_name = 'rift_debugger'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='admin',
maintainer_email='[email protected]',
description='GUI Robot Control Debugger',
license='Apache License 2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'debugger = rift_debugger.debugger:main'
],
},
)
| 674 | Python | 23.999999 | 53 | 0.60089 |
RoboEagles4828/rift2024/src/rift_debugger/rift_debugger/flow_layout.py | # Implement a FlowLayout so sliders move around in a grid as the window is
# resized. Originally taken from:
# https://forum.qt.io/topic/109408/is-there-a-qt-layout-grid-that-can-dynamically-change-row-and-column-counts-to-best-fit-the-space/2
# with the license:
#
# This file taken from
# https://code.qt.io/cgit/qt/qtbase.git/tree/examples/widgets/layouts/flowlayout/flowlayout.cpp?h=5.13
# Modified/adapted by jon, 10/07/2019, to translate into Python/PyQt
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of the examples of the Qt Toolkit.
#
# $QT_BEGIN_LICENSE:BSD$
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# BSD License Usage
# Alternatively, you may use this file under the terms of the BSD license
# as follows:
#
# "Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of The Qt Company Ltd nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#
# $QT_END_LICENSE$
#
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import QPoint
from python_qt_binding.QtCore import QRect
from python_qt_binding.QtCore import QSize
from python_qt_binding.QtWidgets import QLayout
from python_qt_binding.QtWidgets import QSizePolicy
from python_qt_binding.QtWidgets import QStyle
class FlowLayout(QLayout):
def __init__(self, parent=None, margin=-1, hSpacing=-1, vSpacing=-1):
super().__init__(parent)
self.itemList = list()
self.m_hSpace = hSpacing
self.m_vSpace = vSpacing
self.setContentsMargins(margin, margin, margin, margin)
def __del__(self):
# copied for consistency, not sure this is needed or ever called
item = self.takeAt(0)
while item:
item = self.takeAt(0)
def addItem(self, item):
self.itemList.append(item)
def horizontalSpacing(self):
if self.m_hSpace >= 0:
return self.m_hSpace
else:
return self.smartSpacing(QStyle.PM_LayoutHorizontalSpacing)
def verticalSpacing(self):
if self.m_vSpace >= 0:
return self.m_vSpace
else:
return self.smartSpacing(QStyle.PM_LayoutVerticalSpacing)
def count(self):
return len(self.itemList)
def itemAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList[index]
return None
def takeAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList.pop(index)
return None
def expandingDirections(self):
return Qt.Orientations(Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
return self.doLayout(QRect(0, 0, width, 0), True)
def setGeometry(self, rect):
super().setGeometry(rect)
self.doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
def minimumSize(self):
size = QSize()
for item in self.itemList:
size = size.expandedTo(item.minimumSize())
margins = self.contentsMargins()
size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom())
return size
def smartSpacing(self, pm):
parent = self.parent()
if not parent:
return -1
elif parent.isWidgetType():
return parent.style().pixelMetric(pm, None, parent)
return parent.spacing()
def doLayout(self, rect, testOnly):
left, top, right, bottom = self.getContentsMargins()
effectiveRect = rect.adjusted(+left, +top, -right, -bottom)
x = effectiveRect.x()
y = effectiveRect.y()
lineHeight = 0
for item in self.itemList:
wid = item.widget()
spaceX = self.horizontalSpacing()
if spaceX == -1:
spaceX = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
spaceY = self.verticalSpacing()
if spaceY == -1:
spaceY = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > effectiveRect.right() and lineHeight > 0:
x = effectiveRect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0
if not testOnly:
item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y() + bottom | 6,445 | Python | 35.834286 | 134 | 0.672149 |
RoboEagles4828/rift2024/src/rift_debugger/rift_debugger/debugger.py |
import argparse
import random
import signal
import sys
import threading
import rclpy
from python_qt_binding.QtCore import pyqtSlot
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import Signal
from python_qt_binding.QtGui import QFont
from python_qt_binding.QtWidgets import QApplication
from python_qt_binding.QtWidgets import QFormLayout
from python_qt_binding.QtWidgets import QGridLayout
from python_qt_binding.QtWidgets import QHBoxLayout
from python_qt_binding.QtWidgets import QLabel
from python_qt_binding.QtWidgets import QLineEdit
from python_qt_binding.QtWidgets import QMainWindow
from python_qt_binding.QtWidgets import QPushButton
from python_qt_binding.QtWidgets import QSlider
from python_qt_binding.QtWidgets import QScrollArea
from python_qt_binding.QtWidgets import QVBoxLayout
from python_qt_binding.QtWidgets import QWidget
from rift_debugger.joint_state_publisher import JointStatePublisher
from rift_debugger.flow_layout import FlowLayout
RANGE = 10000
LINE_EDIT_WIDTH = 45
SLIDER_WIDTH = 200
INIT_NUM_SLIDERS = 7 # Initial number of sliders to show in window
# Defined by style - currently using the default style
DEFAULT_WINDOW_MARGIN = 11
DEFAULT_CHILD_MARGIN = 9
DEFAULT_BTN_HEIGHT = 25
DEFAULT_SLIDER_HEIGHT = 64 # Is the combination of default heights in Slider
# Calculate default minimums for window sizing
MIN_WIDTH = SLIDER_WIDTH + DEFAULT_CHILD_MARGIN * 4 + DEFAULT_WINDOW_MARGIN * 2
MIN_HEIGHT = DEFAULT_BTN_HEIGHT * 2 + DEFAULT_WINDOW_MARGIN * 2 + DEFAULT_CHILD_MARGIN * 2
PNEUMATICS_JOINTS = [
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'bottom_intake_joint'
]
class Button(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
self.row_layout = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout)
self.button = QPushButton('toggle', self)
self.button.setCheckable(True)
self.joint_layout.addWidget(self.button)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.remove_widget(self.button)
self.button.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class Slider(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
# top row
self.row_layout_top = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout_top.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout_top)
# subscribing row
self.row_layout_sub = QHBoxLayout()
self.display_sub = QLineEdit("0.00")
self.display_sub.setAlignment(Qt.AlignRight)
self.display_sub.setFont(font)
self.display_sub.setReadOnly(True)
self.display_sub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_sub.addWidget(self.display_sub)
self.slider_sub = QSlider(Qt.Horizontal)
self.slider_sub.setFont(font)
self.slider_sub.setRange(0, RANGE)
self.slider_sub.setValue(int(RANGE / 2))
self.slider_sub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_sub.addWidget(self.slider_sub)
self.joint_layout.addLayout(self.row_layout_sub)
# publishing row
self.row_layout_pub = QHBoxLayout()
self.display_pub = QLineEdit("0.00")
self.display_pub.setAlignment(Qt.AlignRight)
self.display_pub.setFont(font)
self.display_pub.setReadOnly(False)
self.display_pub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_pub.addWidget(self.display_pub)
self.slider_pub = QSlider(Qt.Horizontal)
self.slider_pub.setFont(font)
self.slider_pub.setRange(0, RANGE)
self.slider_pub.setValue(int(RANGE / 2))
self.slider_pub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_pub.addWidget(self.slider_pub)
self.joint_layout.addLayout(self.row_layout_pub)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.removeWidget(self.slider)
self.slider.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class JointStatePublisherGui(QMainWindow):
sliderUpdateTrigger = Signal()
initialize = Signal()
def __init__(self, title, jsp : JointStatePublisher):
super(JointStatePublisherGui, self).__init__()
self.joint_map = {}
self.setWindowTitle(title)
# Button for randomizing the sliders
self.rand_button = QPushButton('Randomize', self)
self.rand_button.clicked.connect(self.randomizeEvent)
# Button for centering the sliders
self.ctr_button = QPushButton('Center', self)
self.ctr_button.clicked.connect(self.centerEvent)
# Button for resetting the joint butttons
self.reset_button = QPushButton('Reset Pistons', self)
self.reset_button.clicked.connect(self.resetButtons)
# Scroll area widget contents - layout
self.scroll_layout = FlowLayout()
# Scroll area widget contents
self.scroll_widget = QWidget()
self.scroll_widget.setLayout(self.scroll_layout)
# Scroll area for sliders
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.scroll_widget)
# Main layout
self.main_layout = QVBoxLayout()
# Add buttons and scroll area to main layout
self.main_layout.addWidget(self.rand_button)
self.main_layout.addWidget(self.ctr_button)
self.main_layout.addWidget(self.reset_button)
self.main_layout.addWidget(self.scroll_area)
# central widget
self.central_widget = QWidget()
self.central_widget.setLayout(self.main_layout)
self.setCentralWidget(self.central_widget)
self.jsp = jsp
self.jsp.set_source_update_cb(self.sliderUpdateCb)
self.jsp.set_robot_description_update_cb(self.initializeCb)
self.running = True
self.sliders = {}
self.buttons = {}
# Setup signal for initializing the window
self.initialize.connect(self.initializeSliders)
# Set up a signal for updating the sliders based on external joint info
self.sliderUpdateTrigger.connect(self.updateSliders)
# Tell self to draw sliders in case the JointStatePublisher already has a robot_description
self.initialize.emit()
def initializeSliders(self):
self.joint_map = {}
for sl, _ in self.sliders.items():
self.scroll_layout.removeWidget(sl)
sl.remove()
### Generate sliders ###
for name in self.jsp.joint_list:
if name not in self.jsp.free_joints_sub:
continue
joint = self.jsp.free_joints_sub[name]
if joint['min'] == joint['max']:
continue
if (name in PNEUMATICS_JOINTS):
button = Button(name)
self.joint_map[name] = {'button': button.button, 'joint': joint}
self.scroll_layout.addWidget(button)
button.button.toggled.connect(lambda event,name=name: self.onInputValueChanged(name))
self.buttons[button] = button
else:
slider = Slider(name)
self.joint_map[name] = {'display_sub': slider.display_sub, 'slider_sub': slider.slider_sub, 'display_pub': slider.display_pub, 'slider_pub': slider.slider_pub, 'joint': joint}
self.scroll_layout.addWidget(slider)
slider.display_pub.textEdited.connect(lambda event,name=name: self.makeSliderEqualToText(name))
slider.slider_pub.valueChanged.connect(lambda event,name=name: self.makeTextEqualToSlider(name))
self.sliders[slider] = slider
# Set zero positions read from parameters
self.centerEvent(None)
# Set size of min size of window based on number of sliders.
if len(self.sliders) >= INIT_NUM_SLIDERS: # Limits min size to show INIT_NUM_SLIDERS
num_sliders = INIT_NUM_SLIDERS
else:
num_sliders = len(self.sliders)
scroll_layout_height = num_sliders * DEFAULT_SLIDER_HEIGHT
scroll_layout_height += (num_sliders + 1) * DEFAULT_CHILD_MARGIN
self.setMinimumSize(MIN_WIDTH, scroll_layout_height + MIN_HEIGHT)
self.sliderUpdateTrigger.emit()
def sliderUpdateCb(self):
self.sliderUpdateTrigger.emit()
def initializeCb(self):
self.initialize.emit()
# def onButtonClicked(self, name):
# # self.jsp.get_logger().info("button changed")
# joint_info = self.joint_map[name]
# buttonValue = 1 if joint_info['button'].isChecked() == True else 0
# joint_info['joint']['position'] = buttonValue
# joint_info['display'].setText(str(buttonValue))
# def onSliderTextEdited(self, slider, joint):
# self.jsp.get_logger().info(slider.display.text())
# slider.slider1.setSliderPosition(self.valueToSlider(float(slider.display.displayText()), joint))
def makeSliderEqualToText(self, name):
joint_info = self.joint_map[name]
textvalue = joint_info['display_pub'].text()
try:
joint_info['slider_pub'].setValue(self.valueToSlider(float(textvalue), joint_info['joint']))
self.onInputValueChanged(name)
except:
pass
def makeTextEqualToSlider(self, name):
joint_info = self.joint_map[name]
slidervalue = joint_info['slider_pub'].value()
joint_info['display_pub'].setText(str(round(self.sliderToValue(slidervalue, joint_info['joint']), 2)))
self.onInputValueChanged(name)
def onInputValueChanged(self, name):
# A slider value was changed, but we need to change the joint_info metadata.
joint_info = self.joint_map[name]
if ('slider_pub' in joint_info):
slidervalue = joint_info['slider_pub'].value()
joint = joint_info['joint']
if 'wheel' in name:
self.jsp.free_joints_pub[name]['velocity'] = self.sliderToValue(slidervalue, joint)
else:
self.jsp.free_joints_pub[name]['position'] = self.sliderToValue(slidervalue, joint)
elif ('button' in joint_info):
buttonValue = joint_info['joint']['max'] if joint_info['button'].isChecked() == True else joint_info['joint']['min']
self.jsp.free_joints_pub[name]['position'] = buttonValue
@pyqtSlot()
def updateSliders(self):
for name, joint_info in self.joint_map.items():
joint = joint_info['joint']
if ('slider_sub' in joint_info):
if 'wheel' in name:
slidervalue = self.valueToSlider(joint['velocity'], joint)
else:
slidervalue = self.valueToSlider(joint['position'], joint)
joint_info['slider_sub'].setValue(slidervalue)
joint_info['display_sub'].setText(str(round(self.sliderToValue(slidervalue, joint), 2)))
elif ('button' in joint_info):
buttonvalue = True if joint['position'] == joint['max'] else False
if (joint_info['button'].isChecked() == buttonvalue):
joint_info['button'].setStyleSheet('background-color: green')
else:
joint_info['button'].setStyleSheet('background-color: yellow')
def resetButtons(self, event):
self.jsp.get_logger().info("Toggling off")
for name, joint_info in self.joint_map.items():
if('button' in joint_info):
if(joint_info['button'].isChecked()):
joint_info['button'].setChecked(False)
def centerEvent(self, event):
self.jsp.get_logger().info("Centering")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(self.valueToSlider(joint['zero'], joint))
def randomizeEvent(self, event):
self.jsp.get_logger().info("Randomizing")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(
self.valueToSlider(random.uniform(joint['min'], joint['max']), joint))
def valueToSlider(self, value, joint):
# return int(value * 5000)
return int((value - joint['min']) * float(RANGE) / (joint['max'] - joint['min']))
def sliderToValue(self, slider, joint):
pctvalue = slider / float(RANGE)
return joint['min'] + (joint['max']-joint['min']) * pctvalue
def closeEvent(self, event):
self.running = False
def loop(self):
while self.running:
rclpy.spin_once(self.jsp, timeout_sec=0.1)
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
app = QApplication(sys.argv)
jsp_gui = JointStatePublisherGui('Debugger',
JointStatePublisher(parsed_args.urdf_file))
jsp_gui.show()
threading.Thread(target=jsp_gui.loop).start()
signal.signal(signal.SIGINT, signal.SIG_DFL)
sys.exit(app.exec_())
if __name__ == '__main__':
main() | 14,516 | Python | 35.2925 | 191 | 0.640052 |
RoboEagles4828/rift2024/src/rift_debugger/rift_debugger/joint_state_publisher.py | # Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Standard Python imports
import argparse
import math
import sys
import time
import xml.dom.minidom
# ROS 2 imports
import rclpy
import rclpy.node
from rcl_interfaces.msg import ParameterDescriptor, ParameterType
import sensor_msgs.msg
import std_msgs.msg
POSITION_JOINTS = {
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
'front_left_axle_joint',
'front_right_axle_joint',
'rear_left_axle_joint',
'rear_right_axle_joint',
}
VELOCITY_JOINTS = [
'front_left_wheel_joint',
'front_right_wheel_joint',
'rear_left_wheel_joint',
'rear_right_wheel_joint',
]
class JointStatePublisher(rclpy.node.Node):
def get_param(self, name):
return self.get_parameter(name).value
def _init_joint(self, minval, maxval, zeroval):
joint = {'min': minval, 'max': maxval, 'zero': zeroval}
if self.pub_def_positions:
joint['position'] = zeroval
if self.pub_def_vels:
joint['velocity'] = 0.0
if self.pub_def_efforts:
joint['effort'] = 0.0
return joint
def init_collada(self, robot):
robot = robot.getElementsByTagName('kinematics_model')[0].getElementsByTagName('technique_common')[0]
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
name = child.getAttribute('name')
if child.getElementsByTagName('revolute'):
joint = child.getElementsByTagName('revolute')[0]
else:
self.get_logger().warn('Unknown joint type %s', child)
continue
if joint:
limit = joint.getElementsByTagName('limits')[0]
minval = float(limit.getElementsByTagName('min')[0].childNodes[0].nodeValue)
maxval = float(limit.getElementsByTagName('max')[0].childNodes[0].nodeValue)
if minval == maxval: # this is a fixed joint
continue
self.joint_list.append(name)
minval *= math.pi/180.0
maxval *= math.pi/180.0
self.free_joints_sub[name] = self._init_joint(minval, maxval, 0.0)
self.free_joints_pub[name] = self.free_joints_sub[name]
def init_urdf(self, robot):
robot = robot.getElementsByTagName('robot')[0]
# Find all non-fixed joints
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
jtype = child.getAttribute('type')
if jtype in ['fixed', 'floating', 'planar']:
continue
name = child.getAttribute('name')
self.joint_list.append(name)
if jtype == 'continuous':
if name in VELOCITY_JOINTS:
minval = -39.4 # this is not a good number i pulled it out of thin air
maxval = 39.4 # please someone calculate the actual thing using the circumference of the wheels and that stuff
else:
minval = -math.pi
maxval = math.pi
else:
try:
limit = child.getElementsByTagName('limit')[0]
minval = float(limit.getAttribute('lower'))
maxval = float(limit.getAttribute('upper'))
except:
self.get_logger().warn('%s is not fixed, nor continuous, but limits are not specified!' % name)
continue
safety_tags = child.getElementsByTagName('safety_controller')
if self.use_small and len(safety_tags) == 1:
tag = safety_tags[0]
if tag.hasAttribute('soft_lower_limit'):
minval = max(minval, float(tag.getAttribute('soft_lower_limit')))
if tag.hasAttribute('soft_upper_limit'):
maxval = min(maxval, float(tag.getAttribute('soft_upper_limit')))
mimic_tags = child.getElementsByTagName('mimic')
if self.use_mimic and len(mimic_tags) == 1:
tag = mimic_tags[0]
entry = {'parent': tag.getAttribute('joint')}
if tag.hasAttribute('multiplier'):
entry['factor'] = float(tag.getAttribute('multiplier'))
if tag.hasAttribute('offset'):
entry['offset'] = float(tag.getAttribute('offset'))
self.dependent_joints[name] = entry
continue
if name in self.dependent_joints:
continue
if self.zeros and name in self.zeros:
zeroval = self.zeros[name]
elif minval > 0 or maxval < 0:
zeroval = (maxval + minval)/2
else:
zeroval = 0
joint = self._init_joint(minval, maxval, zeroval)
if jtype == 'continuous':
joint['continuous'] = True
self.free_joints_sub[name] = joint
self.free_joints_pub[name] = joint.copy()
def configure_robot(self, description):
self.get_logger().debug('Got description, configuring robot')
try:
robot = xml.dom.minidom.parseString(description)
except xml.parsers.expat.ExpatError:
# If the description fails to parse for some reason, print an error
# and get out of here without doing further work. If we were
# already running with a description, we'll continue running with
# that older one.
self.get_logger().warn('Invalid robot_description given, ignoring')
return
# Make sure to clear out the old joints so we don't get duplicate joints
# on a new robot description.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
if robot.getElementsByTagName('COLLADA'):
self.init_collada(robot)
else:
self.init_urdf(robot)
if self.robot_description_update_cb is not None:
self.robot_description_update_cb()
def parse_dependent_joints(self):
dj = {}
dependent_joints = self.get_parameters_by_prefix('dependent_joints')
# get_parameters_by_prefix returned a dictionary of keynames like
# 'head.parent', 'head.offset', etc. that map to rclpy Parameter values.
# The rest of the code assumes that the dependent_joints dictionary is
# a map of name -> dict['parent': parent, factor: factor, offset: offset],
# where both factor and offset are optional. Thus we parse the values we
# got into that structure.
for name, param in dependent_joints.items():
# First split on the dots; there should be one and exactly one dot
split = name.split('.')
if len(split) != 2:
raise Exception("Invalid dependent_joint name '%s'" % (name))
newkey = split[0]
newvalue = split[1]
if newvalue not in ['parent', 'factor', 'offset']:
raise Exception("Invalid dependent_joint name '%s' (allowed values are 'parent', 'factor', and 'offset')" % (newvalue))
if newkey in dj:
dj[newkey].update({newvalue: param.value})
else:
dj[newkey] = {newvalue: param.value}
# Now ensure that there is at least a 'parent' in all keys
for name,outdict in dj.items():
if outdict.get('parent', None) is None:
raise Exception('All dependent_joints must at least have a parent')
return dj
def declare_ros_parameter(self, name, default, descriptor):
# When the automatically_declare_parameters_from_overrides parameter to
# rclpy.create_node() is True, then any parameters passed in on the
# command-line are automatically declared. In that case, calling
# node.declare_parameter() will raise an exception. However, in the case
# where a parameter is *not* overridden, we still want to declare it
# (so it shows up in "ros2 param list", for instance). Thus we always do
# a declaration and just ignore ParameterAlreadyDeclaredException.
try:
self.declare_parameter(name, default, descriptor)
except rclpy.exceptions.ParameterAlreadyDeclaredException:
pass
def __init__(self, urdf_file):
super().__init__('joint_state_publisher', automatically_declare_parameters_from_overrides=True)
self.declare_ros_parameter('publish_default_efforts', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_positions', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_velocities', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('rate', 10, ParameterDescriptor(type=ParameterType.PARAMETER_INTEGER))
self.declare_ros_parameter('source_list', [], ParameterDescriptor(type=ParameterType.PARAMETER_STRING_ARRAY))
self.declare_ros_parameter('use_mimic_tags', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('use_smallest_joint_limits', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('delta', 0.0, ParameterDescriptor(type=ParameterType.PARAMETER_DOUBLE))
# In theory we would also declare 'dependent_joints' and 'zeros' here.
# Since rclpy doesn't support maps natively, though, we just end up
# letting 'automatically_declare_parameters_from_overrides' declare
# any parameters for us.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
self.dependent_joints = self.parse_dependent_joints()
self.use_mimic = self.get_param('use_mimic_tags')
self.use_small = self.get_param('use_smallest_joint_limits')
zeros = self.get_parameters_by_prefix('zeros')
# get_parameters_by_prefix() returns a map of name -> Parameter
# structures, but self.zeros is expected to be a list of name -> float;
# fix that here.
self.zeros = {k:v.value for (k, v) in zeros.items()}
self.pub_def_positions = self.get_param('publish_default_positions')
self.pub_def_vels = self.get_param('publish_default_velocities')
self.pub_def_efforts = self.get_param('publish_default_efforts')
self.robot_description_update_cb = None
if urdf_file is not None:
# If we were given a URDF file on the command-line, use that.
with open(urdf_file, 'r') as infp:
description = infp.read()
self.configure_robot(description)
else:
# Otherwise, subscribe to the '/robot_description' topic and wait
# for a callback there
self.get_logger().info('Waiting for robot_description to be published on the robot_description topic...')
self.create_subscription(std_msgs.msg.String, 'robot_description',
lambda msg: self.configure_robot(msg.data),
rclpy.qos.QoSProfile(depth=1, durability=rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL))
self.delta = self.get_param('delta')
source_list = self.get_param('source_list')
self.sources = []
# for source in source_list:
# self.sources.append(self.create_subscription(sensor_msgs.msg.JointState, source, self.source_cb, 10))
# The source_update_cb will be called at the end of self.source_cb.
# The main purpose is to allow external observers (such as the
# joint_state_publisher_gui) to be notified when things are updated.
self.source_update_cb = None
# Override topic name here
self.pub_pos = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_position_controller/commands', 10)
self.pub_vel = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_velocity_controller/commands', 10)
self.create_subscription(sensor_msgs.msg.JointState, 'joint_states', self.source_cb, 10)
self.timer = self.create_timer(1.0 / self.get_param('rate'), self.timer_callback)
def source_cb(self, msg):
# self.get_logger().info("ran source callback")
for i in range(len(msg.name)):
name = msg.name[i]
if name not in self.free_joints_sub:
continue
if msg.position:
position = msg.position[i]
else:
position = None
if msg.velocity:
velocity = msg.velocity[i]
else:
velocity = None
if msg.effort:
effort = msg.effort[i]
else:
effort = None
joint = self.free_joints_sub[name]
if position is not None:
joint['position'] = position
if velocity is not None:
joint['velocity'] = velocity
if effort is not None:
joint['effort'] = effort
if self.source_update_cb is not None:
self.source_update_cb()
def set_source_update_cb(self, user_cb):
self.source_update_cb = user_cb
def set_robot_description_update_cb(self, user_cb):
self.robot_description_update_cb = user_cb
def timer_callback(self):
# Publish Joint States
msg = sensor_msgs.msg.JointState()
msg.header.stamp = self.get_clock().now().to_msg()
if self.delta > 0:
self.update(self.delta)
# Initialize msg.position, msg.velocity, and msg.effort.
has_position = False
has_velocity = False
has_effort = False
for name, joint in self.free_joints_pub.items():
if not has_position and 'position' in joint:
has_position = True
if not has_velocity and 'velocity' in joint:
has_velocity = True
if not has_effort and 'effort' in joint:
has_effort = True
num_joints = (len(self.free_joints_pub.items()) +
len(self.dependent_joints.items()))
if has_position:
msg.position = []
if has_velocity:
msg.velocity = []
if has_effort:
msg.effort = num_joints * [0.0]
for i, name in enumerate(self.joint_list):
msg.name.append(str(name))
joint = None
# Add Free Joint
if name in self.free_joints_pub:
joint = self.free_joints_pub[name]
factor = 1
offset = 0
# Add Dependent Joint
elif name in self.dependent_joints:
param = self.dependent_joints[name]
parent = param['parent']
factor = param.get('factor', 1.0)
offset = param.get('offset', 0.0)
# Handle recursive mimic chain
recursive_mimic_chain_joints = [name]
while parent in self.dependent_joints:
if parent in recursive_mimic_chain_joints:
error_message = 'Found an infinite recursive mimic chain'
self.get_logger().error(f'{error_message}: {recursive_mimic_chain_joints + [parent]}')
sys.exit(1)
recursive_mimic_chain_joints.append(parent)
param = self.dependent_joints[parent]
parent = param['parent']
offset += factor * param.get('offset', 0)
factor *= param.get('factor', 1)
joint = self.free_joints_pub[parent]
# the issue here is that its setting [i] either to the joint, or its skipping i in the list when we need it to be the next value.
# For some reason, [list].append() ends up putting way too many empty values that come from nowhere into the list.
# The best thing to do here would be having two separate iterators which only increment if the variable has a position or a velocity.
if has_position and 'position' in joint and name in POSITION_JOINTS:
msg.position.append(float(joint['position']) * factor + offset)
if has_velocity and 'velocity' in joint and name in VELOCITY_JOINTS:
msg.velocity.append(float(joint['velocity']) * factor)
if has_effort and 'effort' in joint:
msg.effort[i] = float(joint['effort'])
# Only publish non-empty messages
if not (msg.name or msg.position or msg.velocity or msg.effort):
return
pos_msg = std_msgs.msg.Float64MultiArray()
vel_msg = std_msgs.msg.Float64MultiArray()
pos_msg.data = msg.position
vel_msg.data = msg.velocity
self.pub_pos.publish(pos_msg)
self.pub_vel.publish(vel_msg)
def update(self, delta):
for name, joint in self.free_joints_sub.items():
forward = joint.get('forward', True)
if forward:
joint['position'] += delta
if joint['position'] > joint['max']:
if joint.get('continuous', False):
joint['position'] = joint['min']
else:
joint['position'] = joint['max']
joint['forward'] = not forward
else:
joint['position'] -= delta
if joint['position'] < joint['min']:
joint['position'] = joint['min']
joint['forward'] = not forward
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
jsp = JointStatePublisher(parsed_args.urdf_file)
try:
rclpy.spin(jsp)
except KeyboardInterrupt:
pass
jsp.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 20,839 | Python | 42.873684 | 145 | 0.595038 |
RoboEagles4828/rift2024/isaac/README.md | # Isaac Sim Code and Assests | 28 | Markdown | 27.999972 | 28 | 0.785714 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
title = "rift"
description = "Extension for running rift in Isaac Sim"
authors = ["Gage Miller, Nitin C"]
repository = ""
keywords = ["isaac", "samples", "manipulation"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
writeTarget.kit = true
[dependencies]
"omni.kit.uiapp" = {}
"omni.physx" = {}
"omni.physx.vehicle" = {}
"omni.isaac.dynamic_control" = {}
"omni.isaac.motion_planning" = {}
"omni.isaac.synthetic_utils" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
"omni.isaac.franka" = {}
"omni.isaac.dofbot" = {}
"omni.isaac.universal_robots" = {}
"omni.isaac.motion_generation" = {}
"omni.isaac.demos" = {}
"omni.graph.action" = {}
"omni.graph.nodes" = {}
"omni.graph.core" = {}
"omni.isaac.quadruped" = {}
"omni.isaac.wheeled_robots" = {}
"omni.isaac.examples" = {}
[[python.module]]
name = "omni.isaac.rift.import_bot"
[[test]]
timeout = 960
| 1,012 | TOML | 21.021739 | 55 | 0.656126 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/base_sample/base_sample.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 omni.isaac.core import World
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async
import gc
from abc import abstractmethod
class BaseSample(object):
def __init__(self) -> None:
self._world = None
self._current_tasks = None
self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0}
# self._logging_info = ""
return
def get_world(self):
return self._world
def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None):
if physics_dt is not None:
self._world_settings["physics_dt"] = physics_dt
if stage_units_in_meters is not None:
self._world_settings["stage_units_in_meters"] = stage_units_in_meters
if rendering_dt is not None:
self._world_settings["rendering_dt"] = rendering_dt
return
async def load_world_async(self):
"""Function called when clicking load buttton
"""
if World.instance() is None:
await create_new_stage_async()
self._world = World(**self._world_settings)
await self._world.initialize_simulation_context_async()
self.setup_scene()
else:
self._world = World.instance()
self._current_tasks = self._world.get_current_tasks()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_load()
if len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
async def load_game_piece_async(self):
"""Function called when clicking load buttton
"""
self.add_game_piece()
return
async def reset_async(self):
"""Function called when clicking reset buttton
"""
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.remove_physics_callback("tasks_step")
await self._world.play_async()
await update_stage_async()
await self.setup_pre_reset()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_reset()
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
@abstractmethod
def setup_scene(self, scene: Scene) -> None:
"""used to setup anything in the world, adding tasks happen here for instance.
Args:
scene (Scene): [description]
"""
return
@abstractmethod
async def setup_post_load(self):
"""called after first reset of the world when pressing load,
intializing provate variables happen here.
"""
return
@abstractmethod
async def setup_pre_reset(self):
""" called in reset button before resetting the world
to remove a physics callback for instance or a controller reset
"""
return
@abstractmethod
async def setup_post_reset(self):
""" called in reset button after resetting the world which includes one step with rendering
"""
return
@abstractmethod
async def setup_post_clear(self):
"""called after clicking clear button
or after creating a new stage and clearing the instance of the world with its callbacks
"""
return
# def log_info(self, info):
# self._logging_info += str(info) + "\n"
# return
def _world_cleanup(self):
self._world.stop()
self._world.clear_all_callbacks()
self._current_tasks = None
self.world_cleanup()
return
def world_cleanup(self):
"""Function called when extension shutdowns and starts again, (hot reloading feature)
"""
return
async def clear_async(self):
"""Function called when clicking clear buttton
"""
await create_new_stage_async()
if self._world is not None:
self._world_cleanup()
self._world.clear_instance()
self._world = None
gc.collect()
await self.setup_post_clear()
return
| 4,816 | Python | 33.905797 | 115 | 0.622093 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/base_sample/base_sample_extension.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 abc import abstractmethod
import omni.ext
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
import weakref
from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder
import asyncio
from omni.isaac.rift.base_sample import BaseSample
from omni.isaac.core import World
class BaseSampleExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
self._menu_items = None
self._buttons = None
self._ext_id = ext_id
self._sample = None
self._extra_frames = []
return
def start_extension(
self,
menu_name: str,
submenu_name: str,
name: str,
title: str,
doc_link: str,
overview: str,
file_path: str,
sample=None,
number_of_extra_frames=1,
window_width=350,
):
if sample is None:
self._sample = BaseSample()
else:
self._sample = sample
menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())]
if menu_name == "" or menu_name is None:
self._menu_items = menu_items
elif submenu_name == "" or submenu_name is None:
self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)]
else:
self._menu_items = [
MenuItemDescription(
name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)]
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._buttons = dict()
self._build_ui(
name=name,
title=title,
doc_link=doc_link,
overview=overview,
file_path=file_path,
number_of_extra_frames=number_of_extra_frames,
window_width=window_width,
)
if self.get_world() is not None:
self._on_load_world()
return
@property
def sample(self):
return self._sample
def get_frame(self, index):
if index >= len(self._extra_frames):
raise Exception("there were {} extra frames created only".format(len(self._extra_frames)))
return self._extra_frames[index]
def get_world(self):
return World.instance()
def get_buttons(self):
return self._buttons
def _build_ui(self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width):
self._window = omni.ui.Window(
name, width=window_width, height=0, visible=True, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
setup_ui_headers(self._ext_id, file_path, title, doc_link, overview)
self._controls_frame = ui.CollapsableFrame(
title="World Controls",
width=ui.Fraction(1),
height=0,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with ui.VStack(style=get_style(), spacing=5, height=0):
for i in range(number_of_extra_frames):
self._extra_frames.append(
ui.CollapsableFrame(
title="",
width=ui.Fraction(0.33),
height=0,
visible=False,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
)
with self._controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
dict = {
"label": "Load World",
"type": "button",
"text": "Load",
"tooltip": "Load World and Task",
"on_clicked_fn": self._on_load_world,
}
self._buttons["Load World"] = btn_builder(**dict)
self._buttons["Load World"].enabled = True
dict = {
"label": "Reset",
"type": "button",
"text": "Reset",
"tooltip": "Reset robot and environment",
"on_clicked_fn": self._on_reset,
}
self._buttons["Reset"] = btn_builder(**dict)
self._buttons["Reset"].enabled = False
dict = {
"label": "Clear",
"type": "button",
"text": "Clear",
"tooltip": "Clear the full environment",
"on_clicked_fn": self._on_clear,
}
self._buttons["Clear"] = btn_builder(**dict)
self._buttons["Clear"].enabled = True
dict = {
"label": "Load Game Piece",
"type": "button",
"text": "Game Piece",
"tooltip": "Populate the substation with game pieces",
"on_clicked_fn": self._on_load_game_piece,
}
self._buttons["Load Game Piece"] = btn_builder(**dict)
self._buttons["Load Game Piece"].enabled = True
return
def _set_button_tooltip(self, button_name, tool_tip):
self._buttons[button_name].set_tooltip(tool_tip)
return
def _on_load_world(self):
async def _on_load_world_async():
await self._sample.load_world_async()
await omni.kit.app.get_app().next_update_async()
self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event)
self._enable_all_buttons(True)
self._buttons["Load World"].enabled = False
self.post_load_button_event()
self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event)
asyncio.ensure_future(_on_load_world_async())
return
def _on_load_game_piece(self):
async def _on_load_game_piece_async():
await self._sample.load_game_piece_async()
await omni.kit.app.get_app().next_update_async()
# self._sample._world.add_stage_callback("stage_event_2", self.on_stage_event)
# self.post_load_game_piece_button_event()
# self._sample._world.add_timeline_callback("stop_reset_event_2", self._reset_on_stop_event)
asyncio.ensure_future(_on_load_game_piece_async())
return
def _on_reset(self):
async def _on_reset_async():
await self._sample.reset_async()
await omni.kit.app.get_app().next_update_async()
self.post_reset_button_event()
asyncio.ensure_future(_on_reset_async())
return
def _on_clear(self):
async def _on_clear_async():
await self._sample.clear_async()
await omni.kit.app.get_app().next_update_async()
self.post_clear_button_event()
self._buttons["Load World"].enabled = True
asyncio.ensure_future(_on_clear_async())
return
@abstractmethod
def post_load_game_piece_button_event(self):
return
@abstractmethod
def post_reset_button_event(self):
return
@abstractmethod
def post_load_button_event(self):
return
@abstractmethod
def post_clear_button_event(self):
return
def _enable_all_buttons(self, flag):
for btn_name, btn in self._buttons.items():
if isinstance(btn, omni.ui._ui.Button):
btn.enabled = flag
return
def _menu_callback(self):
self._window.visible = not self._window.visible
return
def _on_window(self, status):
# if status:
return
def on_shutdown(self):
self._extra_frames = []
if self._sample._world is not None:
self._sample._world_cleanup()
if self._menu_items is not None:
self._sample_window_cleanup()
if self._buttons is not None:
self._buttons["Load World"].enabled = True
self._enable_all_buttons(False)
self.shutdown_cleanup()
return
def shutdown_cleanup(self):
return
def _sample_window_cleanup(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
self._menu_items = None
self._buttons = None
return
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
if World.instance() is not None:
self.sample._world_cleanup()
self.sample._world.clear_instance()
if hasattr(self, "_buttons"):
if self._buttons is not None:
self._enable_all_buttons(False)
self._buttons["Load World"].enabled = True
return
def _reset_on_stop_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._buttons["Load World"].enabled = False
self._buttons["Reset"].enabled = True
self.post_clear_button_event()
return
| 10,520 | Python | 36.981949 | 114 | 0.527567 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/base_sample/__init__.py | # Copyright (c) 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 omni.isaac.rift.base_sample.base_sample import BaseSample
from omni.isaac.rift.base_sample.base_sample_extension import BaseSampleExtension
| 574 | Python | 46.916663 | 81 | 0.818815 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/import_bot/__init__.py |
from omni.isaac.rift.import_bot.import_bot import ImportBot
from omni.isaac.rift.import_bot.import_bot_extension import ImportBotExtension
| 140 | Python | 34.249991 | 78 | 0.842857 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/import_bot/import_bot_extension.py | # Copyright (c) 2020-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.
import os
from omni.isaac.rift.base_sample import BaseSampleExtension
from omni.isaac.rift.import_bot.import_bot import ImportBot
import omni.ui as ui
from omni.isaac.ui.ui_utils import state_btn_builder
class ImportBotExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Rift FRC",
submenu_name="",
name="Import URDF",
title="Load the URDF for Rift FRC 2023 Robot",
doc_link="",
overview="This loads the Rift robot into Isaac Sim.",
file_path=os.path.abspath(__file__),
sample=ImportBot(),
number_of_extra_frames=1
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_toggle_camera_button_event(self, val):
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Toggle Cameras",
"type": "button",
"a_text": "START",
"b_text": "STOP",
"tooltip": "Start the cameras",
"on_clicked_fn": self._on_toggle_camera_button_event,
}
self.task_ui_elements["Toggle Camera"] = state_btn_builder(**dict)
self.task_ui_elements["Toggle Camera"].enabled = False
| 2,080 | Python | 36.836363 | 82 | 0.597596 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/omni/isaac/rift/import_bot/import_bot.py | from omni.isaac.core.utils.stage import add_reference_to_stage
import omni.graph.core as og
import omni.usd
from omni.isaac.rift.base_sample import BaseSample
from omni.isaac.urdf import _urdf
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils import prims
from omni.isaac.core.prims import GeometryPrim, RigidPrim
from omni.isaac.core_nodes.scripts.utils import set_target_prims
# from omni.kit.viewport_legacy import get_default_viewport_window
# from omni.isaac.sensor import IMUSensor
from pxr import UsdPhysics, UsdShade, Sdf, Gf
import omni.kit.commands
import os
import numpy as np
import math
import carb
from omni.isaac.core.materials import PhysicsMaterial
from random import randint, choice
NAMESPACE = f"{os.environ.get('ROS_NAMESPACE')}" if 'ROS_NAMESPACE' in os.environ else 'default'
def set_drive_params(drive, stiffness, damping, max_force):
drive.GetStiffnessAttr().Set(stiffness)
drive.GetDampingAttr().Set(damping)
if(max_force != 0.0):
drive.GetMaxForceAttr().Set(max_force)
return
def add_physics_material_to_prim(prim, materialPath):
bindingAPI = UsdShade.MaterialBindingAPI.Apply(prim)
materialPrim = UsdShade.Material(materialPath)
bindingAPI.Bind(materialPrim, UsdShade.Tokens.weakerThanDescendants, "physics")
class ImportBot(BaseSample):
def __init__(self) -> None:
super().__init__()
self.cone_list = []
self.cube_list = []
return
def set_friction(self, robot_prim_path):
stage = omni.usd.get_context().get_stage()
omni.kit.commands.execute('AddRigidBodyMaterialCommand',stage=stage, path='/World/Physics_Materials/Rubber',staticFriction=1.1,dynamicFriction=1.5,restitution=None)
omni.kit.commands.execute('AddRigidBodyMaterialCommand',stage=stage, path='/World/Physics_Materials/RubberProMax',staticFriction=1.5,dynamicFriction=2.0,restitution=None)
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/Rubber',prim_path=[f"{robot_prim_path}/front_left_wheel_link"],strength=['weakerThanDescendants'])
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/Rubber',prim_path=[f"{robot_prim_path}/front_right_wheel_link"],strength=['weakerThanDescendants'])
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/Rubber',prim_path=[f"{robot_prim_path}/rear_left_wheel_link"],strength=['weakerThanDescendants'])
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/Rubber',prim_path=[f"{robot_prim_path}/rear_right_wheel_link"],strength=['weakerThanDescendants'])
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/Rubber',prim_path=[f"/World/defaultGroundPlane"],strength=['weakerThanDescendants'])
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_2/Charge_Station/station_pivot_base"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_2/Charge_Station/station_incline_panel_01"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_2/Charge_Station/station_incline_panel"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_2/Charge_Station/station_pivot_connector/station_top_panel"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_1/Charge_Station/station_pivot_base"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_1/Charge_Station/station_incline_panel_01"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_1/Charge_Station/station_incline_panel"],strength=['weakerThanDescendants'],material_purpose='physics')
omni.kit.commands.execute('BindMaterialExt',material_path='/World/Physics_Materials/RubberProMax',prim_path=[f"/World/ChargeStation_1/Charge_Station/station_pivot_connector/station_top_panel"],strength=['weakerThanDescendants'],material_purpose='physics')
# omni.kit.commands.execute('BindMaterial',material_path='/World/Physics_Materials/Rubber',prim_path=[f"/World/FE_2023/FE_2023/FE_2023_01"],strength=['weakerThanDescendants'])
# omni.kit.commands.execute('BindMaterial',material_path='/World/Physics_Materials/Rubber',prim_path=[f"/World/FE_2023/FE_2023/FE_2023_01_01"],strength=['weakerThanDescendants'])
def setup_scene(self):
world = self.get_world()
# world.get_physics_context().enable_gpu_dynamics(True)
world.set_simulation_dt(1/300.0,1/60.0)
world.scene.add_default_ground_plane()
self.setup_field()
# self.setup_perspective_cam()
self.setup_world_action_graph()
return
def add_game_piece(self):
print("asdklj;f;asdjdfdl;asdjfkl;asdjfkl;asdjfkl;asfjkla;sdjkflka;k")
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
cone = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23700_JFH.usd")
cube = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23701_JFL.usd")
add_reference_to_stage(cone, "/World/Cone_1")
substation_empty = [True, True, True, True]
game_piece_list = self.cone_list+self.cube_list
for game_piece in game_piece_list:
pose, orienation = game_piece.get_world_pose()
print(pose)
if(pose[0]<8.17+0.25 and pose[0]>8.17-0.25):
if(pose[1]<-2.65+0.25 and pose[1]>-2.65-0.25):
substation_empty[0]=False
print("substation_empty[0]=False")
elif pose[1]<-3.65+0.25 and pose[1]>-3.65-0.25:
substation_empty[1]=False
print("substation_empty[1]=False")
elif (pose[0]<-8.17+0.25 and pose[0]>-8.17-0.25):
if(pose[1]<-2.65+0.25 and pose[1]>-2.65-0.25):
substation_empty[2]=False
print("substation_empty[2]=False")
elif pose[1]<-3.65+0.25 and pose[1]>-3.65-0.25:
substation_empty[3]=False
print("substation_empty[3]=False")
for i in range(4):
if substation_empty[i]:
next_cube = (len(self.cube_list)+1)
next_cone = (len(self.cone_list)+1)
if(i==0):
position = [8.17, -2.65, 1.15]
elif(i==1):
position = [-8.17, -2.65, 1.15]
elif(i==2):
position = [8.17, -3.65, 1.15]
else:
position = [-8.17, -3.65, 1.15]
if choice([True, False]):
print("yes")
name = "/World/Cube_"+str(next_cube)
view = "cube_"+str(next_cube)+"_view"
add_reference_to_stage(cube, "/World/Cube_"+str(next_cube))
self.cube_list.append(GeometryPrim(name, view, position=position))
else:
print("yesss")
name = "/World/Cone_"+str(next_cone)
view = "cone_"+str(next_cone)+"_view"
add_reference_to_stage(cone, name)
self.cone_list.append(GeometryPrim(name, view, position=position))
return
def setup_field(self):
world = self.get_world()
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
field = os.path.join(self.project_root_path, "assets/flattened_field/field2.usd")
cone = os.path.join(self.project_root_path, "assets/game_pieces/GE-23700_JFH.usd")
cube = os.path.join(self.project_root_path, "assets/game_pieces/GE-23701_JFL.usd")
chargestation = os.path.join(self.project_root_path, "assets/chargestation/chargestation.usd")
add_reference_to_stage(chargestation, "/World/ChargeStation_1")
add_reference_to_stage(chargestation, "/World/ChargeStation_2")
add_reference_to_stage(field, "/World/FE_2023")
add_reference_to_stage(cone, "/World/Cone_1")
add_reference_to_stage(cone, "/World/Cone_2")
add_reference_to_stage(cone, "/World/Cone_3")
add_reference_to_stage(cone, "/World/Cone_4")
add_reference_to_stage(cone, "/World/Cone_5")
add_reference_to_stage(cone, "/World/Cone_6")
# add_reference_to_stage(cone, "/World/Cone_7")
# add_reference_to_stage(cone, "/World/Cone_8")
field_1 = RigidPrim("/World/FE_2023","field_1_view",position=np.array([0.0,0.0,0.0]),scale=np.array([1, 1, 1]))
# cone_1 = RigidPrim("/World/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,-0.4]))
# cone_2 = GeometryPrim("/World/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0]))
# cone_3 = GeometryPrim("/World/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0]))
# cone_4 = GeometryPrim("/World/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0]))
chargestation_1 = GeometryPrim("/World/ChargeStation_1","cone_3_view",position=np.array([-4.53419,1.26454,0.025]),scale=np.array([0.0486220472,0.0486220472,0.0486220472]), orientation=np.array([ 1,1,0,0 ]))
chargestation_2 = GeometryPrim("/World/ChargeStation_2","cone_4_view",position=np.array([4.53419,1.26454,0.025]),scale=np.array([0.0486220472,0.0486220472,0.0486220472]), orientation=np.array([ 1,1,0,0 ]))
self.cone_list.append( RigidPrim("/World/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,0.0])))
self.cone_list.append( RigidPrim("/World/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0])))
self.cone_list.append( RigidPrim("/World/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0])))
self.cone_list.append( RigidPrim("/World/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0])))
self.cone_list.append( RigidPrim("/World/Cone_5","cone_5_view",position=np.array([-7.23149,-1.97376,0.86292])))
self.cone_list.append( RigidPrim("/World/Cone_6","cone_6_view",position=np.array([7.23149,-1.97376,0.86292])))
add_reference_to_stage(cube, "/World/Cube_1")
add_reference_to_stage(cube, "/World/Cube_2")
add_reference_to_stage(cube, "/World/Cube_3")
add_reference_to_stage(cube, "/World/Cube_4")
add_reference_to_stage(cube, "/World/Cube_5")
add_reference_to_stage(cube, "/World/Cube_6")
# add_reference_to_stage(cube, "/World/Cube_7")
# # add_reference_to_stage(cube, "/World/Cube_8")
# cube_1 = GeometryPrim("/World/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121]))
# cube_2 = GeometryPrim("/World/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121]))
# cube_3 = GeometryPrim("/World/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121]))
# cube_4 = GeometryPrim("/World/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121]))
self.cube_list.append( RigidPrim("/World/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121])))
self.cube_list.append( RigidPrim("/World/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121])))
self.cube_list.append( RigidPrim("/World/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121])))
self.cube_list.append( RigidPrim("/World/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121])))
self.cube_list.append( RigidPrim("/World/Cube_5","cube_5_view",position=np.array([-7.25682,-2.99115,1.00109])))
self.cube_list.append( RigidPrim("/World/Cube_6","cube_6_view",position=np.array([7.25682,-2.99115,1.00109])))
async def setup_post_load(self):
self._world = self.get_world()
# self._world.get_physics_context().enable_gpu_dynamics(True)
self.robot_name = "rift"
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
self.path_to_urdf = os.path.join(self.extension_path, "../../../../../../../..", "src/rift_description/urdf/rift.urdf")
carb.log_info(self.path_to_urdf)
self._robot_prim_path = self.import_robot(self.path_to_urdf)
if self._robot_prim_path is None:
print("Error: failed to import robot")
return
self._robot_prim = self._world.scene.add(
Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.5]))
)
self.configure_robot(self._robot_prim_path)
return
def import_robot(self, urdf_path):
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = False
import_config.import_inertia_tensor = True
import_config.default_drive_strength = 1047.19751
import_config.default_position_drive_damping = 52.35988
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.distance_scale = 1.0
import_config.density = 0.0
result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config)
if result:
return prim_path
return None
def configure_robot(self, robot_prim_path):
w_sides = ['left', 'right']
l_sides = ['front', 'back']
stage = self._world.stage
chassis_name = f"swerve_chassis_link"
front_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_left_axle_joint"), "angular")
front_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_right_axle_joint"), "angular")
rear_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_left_axle_joint"), "angular")
rear_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_right_axle_joint"), "angular")
front_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_left_axle_link/front_left_wheel_joint"), "angular")
front_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_right_axle_link/front_right_wheel_joint"), "angular")
rear_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_left_axle_link/rear_left_wheel_joint"), "angular")
rear_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_right_axle_link/rear_right_wheel_joint"), "angular")
arm_roller_bar_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_elevator_leg_link/arm_roller_bar_joint"), "linear")
elevator_center_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_1_link/elevator_center_joint"), "linear")
elevator_outer_2_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_center_link/elevator_outer_2_joint"), "linear")
elevator_outer_1_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_back_leg_link/elevator_outer_1_joint"), "angular")
top_gripper_left_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_left_arm_joint"), "angular")
top_gripper_right_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_right_arm_joint"), "angular")
top_slider_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_2_link/top_slider_joint"), "linear")
set_drive_params(front_left_axle, 1, 1000, 0)
set_drive_params(front_right_axle, 1, 1000, 0)
set_drive_params(rear_left_axle, 1, 1000, 0)
set_drive_params(rear_right_axle, 1, 1000, 0)
set_drive_params(front_left_wheel, 1, 100000000, 0)
set_drive_params(front_right_wheel, 1, 100000000, 0)
set_drive_params(rear_left_wheel, 1, 100000000, 0)
set_drive_params(rear_right_wheel, 1, 100000000, 0)
set_drive_params(arm_roller_bar_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_center_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_outer_1_joint, 10000000, 100000, 2000.0)
set_drive_params(elevator_outer_2_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_left_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_right_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_slider_joint, 10000000, 100000, 98.0)
# self.create_lidar(robot_prim_path)
self.create_imu(robot_prim_path)
self.create_depth_camera(robot_prim_path)
self.setup_camera_action_graph(robot_prim_path)
self.setup_imu_action_graph(robot_prim_path)
self.setup_robot_action_graph(robot_prim_path)
self.set_friction(robot_prim_path)
return
def create_lidar(self, robot_prim_path):
lidar_parent = f"{robot_prim_path}/lidar_link"
lidar_path = "/lidar"
self.lidar_prim_path = lidar_parent + lidar_path
result, prim = omni.kit.commands.execute(
"RangeSensorCreateLidar",
path=lidar_path,
parent=lidar_parent,
min_range=0.4,
max_range=25.0,
draw_points=False,
draw_lines=True,
horizontal_fov=360.0,
vertical_fov=30.0,
horizontal_resolution=0.4,
vertical_resolution=4.0,
rotation_rate=0.0,
high_lod=False,
yaw_offset=0.0,
enable_semantics=False
)
return
def create_imu(self, robot_prim_path):
imu_parent = f"{robot_prim_path}/zed2i_camera_center"
imu_path = "/imu"
self.imu_prim_path = imu_parent + imu_path
result, prim = omni.kit.commands.execute(
"IsaacSensorCreateImuSensor",
path=imu_path,
parent=imu_parent,
translation=Gf.Vec3d(0, 0, 0),
orientation=Gf.Quatd(1, 0, 0, 0),
visualize=False,
)
return
def create_depth_camera(self, robot_prim_path):
self.depth_left_camera_path = f"{robot_prim_path}/zed2i_right_camera_optical_frame/left_cam"
self.depth_right_camera_path = f"{robot_prim_path}/zed2i_right_camera_optical_frame/right_cam"
self.left_camera = prims.create_prim(
prim_path=self.depth_left_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
self.right_camera = prims.create_prim(
prim_path=self.depth_right_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
# # omni.kit.commands.execute('ChangeProperty',
# # prop_path=Sdf.Path('/rift/zed2i_right_camera_isaac_frame/left_cam.xformOp:orient'),
# # value=Gf.Quatd(0.0, Gf.Vec3d(1.0, 0.0, 0.0)),
# # prev=Gf.Quatd(1.0, Gf.Vec3d(0, 0, 0))
# # )
# # omni.kit.commands.execute('ChangeProperty',
# # prop_path=Sdf.Path('/rift/zed2i_right_camera_isaac_frame/right_cam.xformOp:orient'),
# # value=Gf.Quatd(0.0, Gf.Vec3d(1.0, 0.0, 0.0)),
# # prev=Gf.Quatd(1.0, Gf.Vec3d(0, 0, 0))
# )
return
def setup_world_action_graph(self):
og.Controller.edit(
{"graph_path": "/globalclock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"),
("Context.outputs:context", "PublishClock.inputs:context"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
],
}
)
return
def setup_camera_action_graph(self, robot_prim_path):
camera_graph = "{}/camera_sensor_graph".format(robot_prim_path)
enable_left_cam = True
enable_right_cam = False
rgbType = "RgbType"
infoType = "InfoType"
depthType = "DepthType"
depthPclType = "DepthPclType"
def createCamType(side, name, typeNode, topic):
return {
"create": [
(f"{side}CamHelper{name}", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
],
"connect": [
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamHelper{name}.inputs:renderProductPath"),
(f"{side}CamSet.outputs:execOut", f"{side}CamHelper{name}.inputs:execIn"),
(f"{typeNode}.inputs:value", f"{side}CamHelper{name}.inputs:type"),
],
"setvalues": [
(f"{side}CamHelper{name}.inputs:topicName", f"{side.lower()}/{topic}"),
(f"{side}CamHelper{name}.inputs:frameId", f"{NAMESPACE}/zed2i_{side.lower()}_camera_frame"),
(f"{side}CamHelper{name}.inputs:nodeNamespace", f"/{NAMESPACE}"),
]
}
def getCamNodes(side, enable):
camNodes = {
"create": [
(f"{side}CamBranch", "omni.graph.action.Branch"),
(f"{side}CamCreateViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(f"{side}CamViewportResolution", "omni.isaac.core_nodes.IsaacSetViewportResolution"),
(f"{side}CamViewProduct", "omni.isaac.core_nodes.IsaacGetViewportRenderProduct"),
(f"{side}CamSet", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"),
],
"connect": [
("OnPlaybackTick.outputs:tick", f"{side}CamBranch.inputs:execIn"),
(f"{side}CamBranch.outputs:execTrue", f"{side}CamCreateViewport.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:execOut", f"{side}CamViewportResolution.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewportResolution.inputs:viewport"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewProduct.inputs:viewport"),
(f"{side}CamViewportResolution.outputs:execOut", f"{side}CamViewProduct.inputs:execIn"),
(f"{side}CamViewProduct.outputs:execOut", f"{side}CamSet.inputs:execIn"),
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamSet.inputs:renderProductPath"),
],
"setvalues": [
(f"{side}CamBranch.inputs:condition", enable),
(f"{side}CamCreateViewport.inputs:name", f"{side}Cam"),
(f"{side}CamViewportResolution.inputs:width", 640),
(f"{side}CamViewportResolution.inputs:height", 360),
]
}
rgbNodes = createCamType(side, "RGB", rgbType, "rgb")
infoNodes = createCamType(side, "Info", infoType, "camera_info")
depthNodes = createCamType(side, "Depth", depthType, "depth")
depthPClNodes = createCamType(side, "DepthPcl", depthPclType, "depth_pcl")
camNodes["create"] += rgbNodes["create"] + infoNodes["create"] + depthNodes["create"] + depthPClNodes["create"]
camNodes["connect"] += rgbNodes["connect"] + infoNodes["connect"] + depthNodes["connect"] + depthPClNodes["connect"]
camNodes["setvalues"] += rgbNodes["setvalues"] + infoNodes["setvalues"] + depthNodes["setvalues"] + depthPClNodes["setvalues"]
return camNodes
leftCamNodes = getCamNodes("Left", enable_left_cam)
rightCamNodes = getCamNodes("Right", enable_right_cam)
og.Controller.edit(
{"graph_path": camera_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
(rgbType, "omni.graph.nodes.ConstantToken"),
(infoType, "omni.graph.nodes.ConstantToken"),
(depthType, "omni.graph.nodes.ConstantToken"),
(depthPclType, "omni.graph.nodes.ConstantToken"),
] + leftCamNodes["create"] + rightCamNodes["create"],
og.Controller.Keys.CONNECT: leftCamNodes["connect"] + rightCamNodes["connect"],
og.Controller.Keys.SET_VALUES: [
(f"{rgbType}.inputs:value", "rgb"),
(f"{infoType}.inputs:value", "camera_info"),
(f"{depthType}.inputs:value", "depth"),
(f"{depthPclType}.inputs:value", "depth_pcl"),
] + leftCamNodes["setvalues"] + rightCamNodes["setvalues"],
}
)
set_target_prims(primPath=f"{camera_graph}/RightCamSet", targetPrimPaths=[self.depth_right_camera_path], inputName="inputs:cameraPrim")
set_target_prims(primPath=f"{camera_graph}/LeftCamSet", targetPrimPaths=[self.depth_left_camera_path], inputName="inputs:cameraPrim")
return
def setup_imu_action_graph(self, robot_prim_path):
sensor_graph = "{}/imu_sensor_graph".format(robot_prim_path)
swerve_link = "{}/swerve_chassis_link".format(robot_prim_path)
lidar_link = "{}/lidar_link/lidar".format(robot_prim_path)
og.Controller.edit(
{"graph_path": sensor_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
# General Nodes
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("SimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
# Odometry Nodes
("ComputeOdometry", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("PublishOdometry", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("RawOdomTransform", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
# LiDAR Nodes
# ("ReadLidar", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
# ("PublishLidar", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
# IMU Nodes
("IsaacReadImu", "omni.isaac.sensor.IsaacReadIMU"),
("PublishImu", "omni.isaac.ros2_bridge.ROS2PublishImu"),
],
og.Controller.Keys.SET_VALUES: [
("PublishOdometry.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishImu.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:frameId", f"{NAMESPACE}/lidar_link"),
("RawOdomTransform.inputs:childFrameId", f"{NAMESPACE}/base_link"),
("RawOdomTransform.inputs:parentFrameId", f"{NAMESPACE}/zed/odom"),
("PublishOdometry.inputs:chassisFrameId", f"{NAMESPACE}/base_link"),
("PublishOdometry.inputs:odomFrameId", f"{NAMESPACE}/zed/odom"),
# ("PublishImu.inputs:frameId", f"{NAMESPACE}/zed2i_imu_link"),
("PublishImu.inputs:frameId", f"{NAMESPACE}/zed2i_camera_center"),
("PublishOdometry.inputs:topicName", "zed/odom")
],
og.Controller.Keys.CONNECT: [
# Odometry Connections
("OnPlaybackTick.outputs:tick", "ComputeOdometry.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "RawOdomTransform.inputs:execIn"),
("ComputeOdometry.outputs:execOut", "PublishOdometry.inputs:execIn"),
("ComputeOdometry.outputs:angularVelocity", "PublishOdometry.inputs:angularVelocity"),
("ComputeOdometry.outputs:linearVelocity", "PublishOdometry.inputs:linearVelocity"),
("ComputeOdometry.outputs:orientation", "PublishOdometry.inputs:orientation"),
("ComputeOdometry.outputs:orientation", "RawOdomTransform.inputs:rotation"),
("ComputeOdometry.outputs:position", "PublishOdometry.inputs:position"),
("ComputeOdometry.outputs:position", "RawOdomTransform.inputs:translation"),
("Context.outputs:context", "PublishOdometry.inputs:context"),
("Context.outputs:context", "RawOdomTransform.inputs:context"),
("SimTime.outputs:simulationTime", "PublishOdometry.inputs:timeStamp"),
("SimTime.outputs:simulationTime", "RawOdomTransform.inputs:timeStamp"),
# LiDAR Connections
# ("OnPlaybackTick.outputs:tick", "ReadLidar.inputs:execIn"),
# ("ReadLidar.outputs:execOut", "PublishLidar.inputs:execIn"),
# ("Context.outputs:context", "PublishLidar.inputs:context"),
# ("SimTime.outputs:simulationTime", "PublishLidar.inputs:timeStamp"),
# ("ReadLidar.outputs:azimuthRange", "PublishLidar.inputs:azimuthRange"),
# ("ReadLidar.outputs:depthRange", "PublishLidar.inputs:depthRange"),
# ("ReadLidar.outputs:horizontalFov", "PublishLidar.inputs:horizontalFov"),
# ("ReadLidar.outputs:horizontalResolution", "PublishLidar.inputs:horizontalResolution"),
# ("ReadLidar.outputs:intensitiesData", "PublishLidar.inputs:intensitiesData"),
# ("ReadLidar.outputs:linearDepthData", "PublishLidar.inputs:linearDepthData"),
# ("ReadLidar.outputs:numCols", "PublishLidar.inputs:numCols"),
# ("ReadLidar.outputs:numRows", "PublishLidar.inputs:numRows"),
# ("ReadLidar.outputs:rotationRate", "PublishLidar.inputs:rotationRate"),
# IMU Connections
("OnPlaybackTick.outputs:tick", "IsaacReadImu.inputs:execIn"),
("IsaacReadImu.outputs:execOut", "PublishImu.inputs:execIn"),
("Context.outputs:context", "PublishImu.inputs:context"),
("SimTime.outputs:simulationTime", "PublishImu.inputs:timeStamp"),
("IsaacReadImu.outputs:angVel", "PublishImu.inputs:angularVelocity"),
("IsaacReadImu.outputs:linAcc", "PublishImu.inputs:linearAcceleration"),
("IsaacReadImu.outputs:orientation", "PublishImu.inputs:orientation"),
],
}
)
# Setup target prims for the Odometry and the Lidar
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/IsaacReadImu", targetPrimPaths=[self.imu_prim_path], inputName="inputs:imuPrim")
return
def setup_robot_action_graph(self, robot_prim_path):
robot_controller_path = f"{robot_prim_path}/ros_interface_controller"
og.Controller.edit(
{"graph_path": robot_controller_path, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeDriveState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("SubscribeArmState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
("arm_articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeDriveState.inputs:topicName", "isaac_joint_commands"),
("SubscribeDriveState.inputs:topicName", "isaac_drive_commands"),
("SubscribeArmState.inputs:topicName", "isaac_arm_commands"),
("articulation_controller.inputs:usePath", False),
("arm_articulation_controller.inputs:usePath", False),
("SubscribeDriveState.inputs:nodeNamespace", f"/{NAMESPACE}"),
("SubscribeArmState.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishJointState.inputs:nodeNamespace", f"/{NAMESPACE}"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeDriveState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeArmState.inputs:execIn"),
("SubscribeDriveState.outputs:execOut", "articulation_controller.inputs:execIn"),
("SubscribeArmState.outputs:execOut", "arm_articulation_controller.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeDriveState.inputs:context"),
("Context.outputs:context", "SubscribeArmState.inputs:context"),
("SubscribeDriveState.outputs:jointNames", "articulation_controller.inputs:jointNames"),
("SubscribeDriveState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"),
("SubscribeArmState.outputs:jointNames", "arm_articulation_controller.inputs:jointNames"),
("SubscribeArmState.outputs:positionCommand", "arm_articulation_controller.inputs:positionCommand"),
],
}
)
set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/arm_articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path])
return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
async def setup_post_clear(self):
return
def world_cleanup(self):
carb.log_info(f"Removing {self.robot_name}")
if self._world is not None:
self._world.scene.remove_object(self.robot_name)
return | 37,823 | Python | 59.421725 | 263 | 0.613886 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/docs/CHANGELOG.md | **********
CHANGELOG
**********
[0.1.0] - 2022-6-26
[0.1.1] - 2022-10-15
========================
Added
-------
- Initial version of Swerve Bot Extension
- Enhanced physX
| 175 | Markdown | 10.733333 | 41 | 0.468571 |
RoboEagles4828/rift2024/isaac/exts/omni.isaac.rift/docs/README.md | # Usage
To enable this extension, go to the Extension Manager menu and enable omni.isaac.swerve_bot extension.
| 113 | Markdown | 21.799996 | 102 | 0.787611 |
RoboEagles4828/rift2024/scripts/quickpub.py | #!/usr/bin/python3
import time
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
from threading import Thread
JOINT_NAMES = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'bottom_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
class ROSNode(Node):
def __init__(self):
super().__init__('quickpublisher')
self.publish_positions = [0.0]*6
self.publisher = self.create_publisher(JointState, "/real/real_arm_commands", 10)
self.publishTimer = self.create_timer(0.5, self.publish)
def publish(self):
msg = JointState()
msg.name = JOINT_NAMES
msg.position = self.publish_positions
self.publisher.publish(msg)
def main():
rclpy.init()
node = ROSNode()
Thread(target=rclpy.spin, args=(node,)).start()
while True:
try:
joint_index = int(input("Joint index: "))
position = float(input("Position: "))
node.publish_positions[joint_index] = position
except:
print("Invalid input")
continue
if __name__ == '__main__':
main() | 1,227 | Python | 25.127659 | 89 | 0.605542 |
RoboEagles4828/rift2024/scripts/config/omniverse.toml |
[bookmarks]
IsaacAssets = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac"
Scenarios = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Samples/ROS2/Scenario"
rift = "/workspaces/rift2024"
localhost = "omniverse://localhost"
[cache]
data_dir = "/root/.cache/ov/Cache"
proxy_cache_enabled = false
proxy_cache_server = ""
[connection_library]
proxy_dict = "*#localhost:8891,f"
| 397 | TOML | 25.533332 | 92 | 0.743073 |
RoboEagles4828/rift2024/docker/developer/README.md | # Docker for Development
This directory has the configuration for building the image used in the rift devcontainer.
It uses the osrf ros humble image as a base and installs rift related software on top.
When loading the devcontainer the common utils feature is used to update the user GID/UID to match local and setup zsh and other terminal nice to haves.
**Common Utils**: `devcontainers/features/common-utils` \
**URL**: https://github.com/devcontainers/features/tree/main/src/common-utils
# Build
1. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \
This will be used to push the image to the registry
2. Run `./build` to build the image. \
The script will prompt you if you would like to do a quick test or push to the registry. | 897 | Markdown | 48.888886 | 210 | 0.782609 |
RoboEagles4828/rift2024/docker/jetson/README.md | # Jetson Docker Image | 21 | Markdown | 20.999979 | 21 | 0.809524 |
RoboEagles4828/rift2024/docker/developer-zed/zed2i.launch.py | import os
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
from ament_index_python.packages import get_package_share_directory
from launch_ros.actions import Node
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
NAMESPACE = 'real'
def generate_launch_description():
# Camera model (force value)
camera_model = 'zed2i'
config_common_path = os.path.join(
get_package_share_directory('zed_wrapper'),
'config',
'common.yaml'
)
config_camera_path = os.path.join(
get_package_share_directory('zed_wrapper'),
'config',
camera_model + '.yaml'
)
# ZED Wrapper node
zed_wrapper_node = Node(
package='zed_wrapper',
namespace=str(NAMESPACE),
executable='zed_wrapper',
name='zed',
output='screen',
#prefix=['xterm -e valgrind --tools=callgrind'],
#prefix=['xterm -e gdb -ex run --args'],
parameters=[
# YAML files
config_common_path, # Common parameters
config_camera_path, # Camera related parameters
# Overriding
{
'general.camera_name': f'{NAMESPACE}/{camera_model}',
'general.camera_model': camera_model,
'general.svo_file': 'live',
'publish_urdf': 'false',
'pos_tracking.base_frame': f'{NAMESPACE}/base_link',
'pos_tracking.map_frame': f'{NAMESPACE}/map',
'pos_tracking.odometry_frame': f'{NAMESPACE}/odom',
# 'general.zed_id': 0,
# 'general.serial_number': 0,
'pos_tracking.publish_tf': True,
'pos_tracking.publish_map_tf': True,
'pos_tracking.publish_imu_tf': True
}
]
)
# throttle_zed_node = Node(
# package='topic_tools',
# executable='throttle',
# name='throttle_zed',
# namespace=str(NAMESPACE),
# output='screen',
# parameters=[
# {
# 'topics': [
# f'{NAMESPACE}/zed/rgb/image_rect_color',
# f'{NAMESPACE}/zed/depth/depth_registered'
# ],
# 'throttle_rate': 2.0
# }
# ]
# )
delay_zed_wrapper = TimerAction(period=5.0, actions=[zed_wrapper_node])
# Define LaunchDescription variable
ld = LaunchDescription()
# Add nodes to LaunchDescription
ld.add_action(delay_zed_wrapper)
# ld.add_action(throttle_zed_node)
return ld
| 2,744 | Python | 30.193181 | 93 | 0.559038 |
RoboEagles4828/rift2024/docker/developer-isaac-ros/README.md | # Docker for isaac ros
This directory has the configuration for building the image used for isaac utilities that require l4t.
It uses the isaac ros common container as a base and installs rift related software on top.
# Build
1. Docker Login to the nvidia NGC registry. [Guide](https://docs.nvidia.com/ngc/ngc-catalog-user-guide/index.html)\
This will be used to download nvidia images.
2. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \
This will be used to push the image to the registry
3. Run `./build` to build the image. \
The script will prompt you if you would like to do a quick test or push to the registry. | 780 | Markdown | 59.076919 | 210 | 0.783333 |
RoboEagles4828/rift2024/docker/jetson-isaac-ros/README.md | # Jetson Docker Image with Isaac ROS | 36 | Markdown | 35.999964 | 36 | 0.805556 |
RoboEagles4828/rift2024/rio/old-robot.py | from hardware_interface.drivetrain import DriveTrain
import hardware_interface.drivetrain as dt
from hardware_interface.joystick import Joystick
from hardware_interface.armcontroller import ArmController
from commands2 import *
import wpilib
from wpilib import Field2d
from wpilib.shuffleboard import Shuffleboard
from wpilib.shuffleboard import SuppliedFloatValueWidget
from hardware_interface.commands.drive_commands import *
from auton_selector import AutonSelector
import time
from dds.dds import DDS_Publisher, DDS_Subscriber
import os
import inspect
import logging
import traceback
import threading
from lib.mathlib.conversions import Conversions
from pathplannerlib.auto import NamedCommands
ENABLE_STAGE_BROADCASTER = True
ENABLE_ENCODER = True
# Global Variables
arm_controller : ArmController = None
drive_train : DriveTrain = None
navx_sim_data : list = None
frc_stage = "DISABLED"
fms_attached = False
stop_threads = False
# Logging
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
# XML Path for DDS configuration
curr_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
xml_path = os.path.join(curr_path, "dds/xml/ROS_RTI.xml")
############################################
## Hardware
def initDriveTrain():
global drive_train
if drive_train == None:
drive_train = DriveTrain()
logging.info("Success: DriveTrain created")
return drive_train
def initArmController():
global arm_controller
if arm_controller == None:
arm_controller = ArmController()
logging.info("Success: ArmController created")
return arm_controller
def initDDS(ddsAction, participantName, actionName):
dds = None
with rti_init_lock:
dds = ddsAction(xml_path, participantName, actionName)
return dds
############################################
## Threads
def threadLoop(name, dds, action):
logging.info(f"Starting {name} thread")
global stop_threads
global frc_stage
try:
while stop_threads == False:
if (frc_stage == 'AUTON' and name != "joystick") or (name in ["stage-broadcaster", "service", "imu", "zed"]) or (frc_stage == 'TELEOP'):
action(dds)
time.sleep(20/1000)
except Exception as e:
logging.error(f"An issue occured with the {name} thread")
logging.error(e)
logging.error(traceback.format_exc())
logging.info(f"Closing {name} thread")
dds.close()
# Generic Start Thread Function
def startThread(name) -> threading.Thread | None:
thread = None
# if name == "encoder":
# thread = threading.Thread(target=encoderThread, daemon=True)
if name == "stage-broadcaster":
thread = threading.Thread(target=stageBroadcasterThread, daemon=True)
elif name == "service":
thread = threading.Thread(target=serviceThread, daemon=True)
elif name == "imu":
thread = threading.Thread(target=imuThread, daemon=True)
elif name == "zed":
thread = threading.Thread(target=zedThread, daemon=True)
thread.start()
return thread
# Locks
rti_init_lock = threading.Lock()
drive_train_lock = threading.Lock()
arm_controller_lock = threading.Lock()
############################################
################## ENCODER ##################
ENCODER_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::encoder_info"
ENCODER_WRITER_NAME = "encoder_info_publisher::encoder_info_writer"
# def encoderThread():
# encoder_publisher = initDDS(DDS_Publisher, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME)
# threadLoop('encoder', encoder_publisher, encoderAction)
def encoderAction(publisher):
# TODO: Make these some sort of null value to identify lost data
data = {
'name': [],
'position': [],
'velocity': [],
'effort': []
}
global drive_train
with drive_train_lock:
drive_data = drive_train.getModuleCommand()
data['name'] += drive_data['name']
data['position'] += drive_data['position']
data['velocity'] += drive_data['velocity']
global arm_controller
with arm_controller_lock:
arm_data = arm_controller.getEncoderData()
data['name'] += arm_data['name']
data['position'] += arm_data['position']
data['velocity'] += arm_data['velocity']
publisher.write(data)
############################################
################## SERVICE ##################
SERVICE_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::service"
SERVICE_WRITER_NAME = "service_pub::service_writer"
def serviceThread():
service_publisher = initDDS(DDS_Publisher, SERVICE_PARTICIPANT_NAME, SERVICE_WRITER_NAME)
threadLoop('service', service_publisher, serviceAction)
def serviceAction(publisher : DDS_Publisher):
temp_service = True
publisher.write({ "data": temp_service })
############################################
################## STAGE ##################
STAGE_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::stage_broadcaster"
STAGE_WRITER_NAME = "stage_publisher::stage_writer"
def stageBroadcasterThread():
stage_publisher = initDDS(DDS_Publisher, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME)
threadLoop('stage-broadcaster', stage_publisher, stageBroadcasterAction)
def stageBroadcasterAction(publisher : DDS_Publisher):
global frc_stage
global fms_attached
is_disabled = wpilib.DriverStation.isDisabled()
publisher.write({ "data": f"{frc_stage}|{fms_attached}|{is_disabled}" })
############################################
################## IMU #####################
IMU_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::imu"
IMU_READER_NAME = "imu_subscriber::imu_reader"
def imuThread():
imu_subscriber = initDDS(DDS_Subscriber, IMU_PARTICIPANT_NAME, IMU_READER_NAME)
threadLoop("imu", imu_subscriber, imuAction)
def imuAction(subscriber):
data: dict = subscriber.read()
if data is not None:
arr = data["data"].split("|")
w = float(arr[0])
x = float(arr[1])
y = float(arr[2])
z = float(arr[3])
angular_velocity_x = float(arr[4])
angular_velocity_y = float(arr[5])
angular_velocity_z = float(arr[6])
linear_acceleration_x = float(arr[7])
linear_acceleration_y = float(arr[8])
linear_acceleration_z = float(arr[9])
global navx_sim_data
navx_sim_data = [
w, x, y, z,
angular_velocity_x, angular_velocity_y, angular_velocity_z,
linear_acceleration_x, linear_acceleration_y, linear_acceleration_z
]
############################################
object_pos = [0.0, 0.0, 0.0]
ZED_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::zed_objects"
ZED_READER_NAME = "zed_objects_subscriber::zed_objects_reader"
def zedThread():
zed_subscriber = initDDS(DDS_Subscriber, ZED_PARTICIPANT_NAME, ZED_READER_NAME)
threadLoop("zed", zed_subscriber, zedAction)
def zedAction(subscriber):
global object_pos
data: dict = subscriber.read()
if data is not None:
arr = data["data"].split("|")
object_pos[0] = float(arr[0])
object_pos[1] = float(arr[1])
object_pos[2] = float(arr[2])
class Robot(wpilib.TimedRobot):
def robotInit(self):
self.use_threading = True
wpilib.CameraServer.launch()
logging.warning("Running in simulation!") if wpilib.RobotBase.isSimulation() else logging.info("Running in real!")
self.threads = []
if self.use_threading:
logging.info("Initializing Threads")
global stop_threads
stop_threads = False
# if ENABLE_ENCODER: self.threads.append({"name": "encoder", "thread": startThread("encoder") })
if ENABLE_STAGE_BROADCASTER: self.threads.append({"name": "stage-broadcaster", "thread": startThread("stage-broadcaster") })
self.threads.append({"name": "service", "thread": startThread("service") })
self.threads.append({"name": "imu", "thread": startThread("imu") })
self.threads.append({"name": "zed", "thread": startThread("zed") })
else:
# self.encoder_publisher = DDS_Publisher(xml_path, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME)
self.stage_publisher = DDS_Publisher(xml_path, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME)
self.service_publisher = DDS_Publisher(xml_path, SERVICE_PARTICIPANT_NAME, SERVICE_WRITER_NAME)
self.imu_subscriber = DDS_Subscriber(xml_path, IMU_PARTICIPANT_NAME, IMU_READER_NAME)
self.zed_subscriber = DDS_Subscriber(xml_path, ZED_PARTICIPANT_NAME, ZED_READER_NAME)
self.arm_controller = initArmController()
self.drive_train = initDriveTrain()
self.drive_train.is_sim = self.isSimulation()
self.joystick = Joystick("xbox")
self.auton_selector = AutonSelector(self.arm_controller, self.drive_train)
self.joystick_selector = wpilib.SendableChooser()
self.joystick_selector.setDefaultOption("XBOX", "xbox")
self.joystick_selector.addOption("PS4", "ps4")
self.auton_run = False
self.shuffleboard = Shuffleboard.getTab("Main")
self.shuffleboard.add(title="AUTON", defaultValue=self.auton_selector.autonChooser)
# self.shuffleboard.add(title="JOYSTICK", defaultValue=self.joystick_selector)
# self.shuffleboard.add("WHINE REMOVAL", self.drive_train.whine_remove_selector)
self.shuffleboard.addDoubleArray("MOTOR VELOCITY", lambda: (self.drive_train.motor_vels))
self.shuffleboard.addDoubleArray("MOTOR POSITIONS", lambda: (self.drive_train.motor_pos))
# self.shuffleboard.add("ANGLE SOURCE", self.drive_train.angle_source_selector)
# self.shuffleboard.add("PROFILE", self.drive_train.profile_selector)
self.shuffleboard.add("NAVX", self.drive_train.navx)
self.shuffleboard.add("PP Auton", self.auton_selector.ppchooser)
self.shuffleboard.addDouble("YAW", lambda: (self.drive_train.navx.getYaw()))
self.shuffleboard.addBoolean("FIELD ORIENTED", lambda: (self.drive_train.field_oriented_value))
# self.shuffleboard.addBoolean("SLOW", lambda: (self.drive_train.slow))
self.shuffleboard.addDoubleArray("MOTOR TEMPS", lambda: (self.drive_train.motor_temps))
self.shuffleboard.addDoubleArray("JOYSTICK OUTPUT", lambda: ([self.drive_train.linX, self.drive_train.linY, self.drive_train.angZ]))
self.shuffleboard.addDoubleArray("POSE: ", lambda: ([self.auton_selector.drive_subsystem.getPose().X(), self.auton_selector.drive_subsystem.getPose().Y(), self.auton_selector.drive_subsystem.getPose().rotation().degrees()]))
self.shuffleboard.add("PP Chooser", self.auton_selector.ppchooser)
self.shuffleboard.addDouble("Pose X", lambda: self.auton_selector.drive_subsystem.getPose().X())
self.shuffleboard.addDouble("Pose Y", lambda: self.auton_selector.drive_subsystem.getPose().Y())
self.shuffleboard.addDouble("Pose Rotation", lambda: self.auton_selector.drive_subsystem.getPose().rotation().degrees())
self.shuffleboard.addDouble("Sweeping Rotation", lambda: self.auton_selector.drive_subsystem.drivetrain.navx.getRotation2d().__mul__(-1).degrees())
self.shuffleboard.addDoubleArray("CHASSIS SPEEDS", lambda: [
self.auton_selector.drive_subsystem.getRobotRelativeChassisSpeeds().vx,
self.auton_selector.drive_subsystem.getRobotRelativeChassisSpeeds().vy,
self.auton_selector.drive_subsystem.getRobotRelativeChassisSpeeds().omega
])
# self.shuffleboard.addString("AUTO TURN STATE", lambda: (self.drive_train.auto_turn_value))
# self.second_order_chooser = wpilib.SendableChooser()
# self.second_order_chooser.setDefaultOption("1st Order", False)
# self.second_order_chooser.addOption("2nd Order", True)
# self.shuffleboard.add("2nd Order", self.second_order_chooser)
self.arm_controller.setToggleButtons()
self.auton_run = False
self.turn_90 = TurnToAngleCommand(self.auton_selector.drive_subsystem, 90.0)
self.turn_180 = TurnToAngleCommand(self.auton_selector.drive_subsystem, 180.0)
self.turn_270 = TurnToAngleCommand(self.auton_selector.drive_subsystem, 270.0)
self.turn_0 = TurnToAngleCommand(self.auton_selector.drive_subsystem, 0.0)
NamedCommands.registerCommand("Turn180", self.turn_180)
def robotPeriodic(self):
self.joystick.type = self.joystick_selector.getSelected()
self.auton_selector.drive_subsystem.updateOdometry()
if navx_sim_data is not None:
self.drive_train.navx_sim.update(*navx_sim_data)
# Auton
def autonomousInit(self):
self.drive_train.navx.reset()
self.drive_train.set_navx_offset(0)
self.auton_selector.run()
global object_pos
# self.cone_move = ConeMoveAuton(self.auton_selector.drive_subsystem, object_pos)
logging.info("Entering Auton")
global frc_stage
frc_stage = "AUTON"
def autonomousPeriodic(self):
CommandScheduler.getInstance().run()
global object_pos
global fms_attached
# dist = math.sqrt(object_pos[0]**2 + object_pos[1]**2)
# if dist > 0.5:
# self.cone_move.execute()
# self.cone_move.object_pos = object_pos
# else:
# print(f"GIVEN POS: {object_pos} ********************")
# self.drive_train.swerveDriveAuton(0, 0, 0)
# self.drive_train.stop()(
# self.drive_train.swerveDriveAuton(object_pos[0]/5.0, object_pos[1]/5.0, object_pos[2]/5.0)
logging.info(f"Robot Pose: {self.auton_selector.drive_subsystem.getPose()}")
fms_attached = wpilib.DriverStation.isFMSAttached()
if self.use_threading:
self.manageThreads()
else:
self.doActions()
def autonomousExit(self):
CommandScheduler.getInstance().cancelAll()
logging.info("Exiting Auton")
global frc_stage
frc_stage = "AUTON"
# Teleop
def teleopInit(self):
self.arm_controller.setToggleButtons()
CommandScheduler.getInstance().cancelAll()
logging.info("Entering Teleop")
global frc_stage
frc_stage = "TELEOP"
def teleopPeriodic(self):
self.drive_train.swerveDrive(self.joystick)
self.arm_controller.setArm(self.joystick)
global fms_attached
fms_attached = wpilib.DriverStation.isFMSAttached()
if self.use_threading:
self.manageThreads()
else:
self.doActions()
def manageThreads(self):
# Check all threads and make sure they are alive
for thread in self.threads:
if thread["thread"].is_alive() == False:
logging.warning(f"Thread {thread['name']} is not alive, restarting...")
thread["thread"] = startThread(thread["name"])
def doActions(self):
# encoderAction(self.encoder_publisher)
stageBroadcasterAction(self.stage_publisher)
serviceAction(self.service_publisher)
imuAction(self.imu_subscriber)
zedAction(self.zed_subscriber)
def stopThreads(self):
global stop_threads
stop_threads = True
for thread in self.threads:
thread.join()
logging.info('All Threads Stopped')
if __name__ == '__main__':
wpilib.run(Robot) | 15,702 | Python | 38.956743 | 232 | 0.642975 |
RoboEagles4828/rift2024/rio/README.md | # RIO Code | 10 | Markdown | 9.99999 | 10 | 0.7 |
RoboEagles4828/rift2024/rio/srcrobot/CTREConfigs.py | from phoenix6.configs import CANcoderConfiguration
from phoenix6.configs import TalonFXConfiguration
from phoenix6.signals.spn_enums import AbsoluteSensorRangeValue
from phoenix6.signals import InvertedValue
from constants import Constants
from copy import deepcopy
from wpimath.units import radiansToRotations
class CTREConfigs:
swerveAngleFXConfig = TalonFXConfiguration()
swerveDriveFXConfig = TalonFXConfiguration()
swerveCANcoderConfig = CANcoderConfiguration()
# swerveCANcoderConfigList = [CANcoderConfiguration(), CANcoderConfiguration(), CANcoderConfiguration(), CANcoderConfiguration()]
def __init__(self):
# Swerve CANCoder Configuration
# for config in self.swerveCANcoderConfigList:
self.swerveCANcoderConfig.magnet_sensor.sensor_direction = Constants.Swerve.cancoderInvert
#Swerve Angle Motor Configurations
# Motor Inverts and Neutral Mode
self.swerveAngleFXConfig.motor_output.inverted = Constants.Swerve.angleMotorInvert
self.swerveAngleFXConfig.motor_output.neutral_mode = Constants.Swerve.angleNeutralMode
# Gear Ratio and Wrapping Config
self.swerveAngleFXConfig.feedback.sensor_to_mechanism_ratio = Constants.Swerve.angleGearRatio
self.swerveAngleFXConfig.closed_loop_general.continuous_wrap = True
# Current Limiting
self.swerveAngleFXConfig.current_limits.supply_current_limit_enable = Constants.Swerve.angleEnableCurrentLimit
self.swerveAngleFXConfig.current_limits.supply_current_limit = Constants.Swerve.angleCurrentLimit
self.swerveAngleFXConfig.current_limits.supply_current_threshold = Constants.Swerve.angleCurrentThreshold
self.swerveAngleFXConfig.current_limits.supply_time_threshold = Constants.Swerve.angleCurrentThresholdTime
# PID Config
self.swerveAngleFXConfig.slot0.k_p = Constants.Swerve.angleKP
self.swerveAngleFXConfig.slot0.k_i = Constants.Swerve.angleKI
self.swerveAngleFXConfig.slot0.k_d = Constants.Swerve.angleKD
#* Swerve Drive Motor Configuration
# Motor Inverts and Neutral Mode
self.swerveDriveFXConfig.motor_output.inverted = Constants.Swerve.driveMotorInvert
self.swerveDriveFXConfig.motor_output.neutral_mode = Constants.Swerve.driveNeutralMode
# Gear Ratio Config
self.swerveDriveFXConfig.feedback.sensor_to_mechanism_ratio = Constants.Swerve.driveGearRatio
# Current Limiting
self.swerveDriveFXConfig.current_limits.supply_current_limit_enable = Constants.Swerve.driveEnableCurrentLimit
self.swerveDriveFXConfig.current_limits.supply_current_limit = Constants.Swerve.driveCurrentLimit
self.swerveDriveFXConfig.current_limits.supply_current_threshold = Constants.Swerve.driveCurrentThreshold
self.swerveDriveFXConfig.current_limits.supply_time_threshold = Constants.Swerve.driveCurrentThresholdTime
# PID Config
self.swerveDriveFXConfig.slot0.k_p = Constants.Swerve.driveKP
self.swerveDriveFXConfig.slot0.k_i = Constants.Swerve.driveKI
self.swerveDriveFXConfig.slot0.k_d = Constants.Swerve.driveKD
# Open and Closed Loop Ramping
self.swerveDriveFXConfig.open_loop_ramps.duty_cycle_open_loop_ramp_period = Constants.Swerve.openLoopRamp
self.swerveDriveFXConfig.open_loop_ramps.voltage_open_loop_ramp_period = Constants.Swerve.openLoopRamp
self.swerveDriveFXConfig.closed_loop_ramps.duty_cycle_closed_loop_ramp_period = Constants.Swerve.closedLoopRamp
self.swerveDriveFXConfig.closed_loop_ramps.voltage_closed_loop_ramp_period = Constants.Swerve.closedLoopRamp
self.swerveDriveFXConfigFR = deepcopy(self.swerveDriveFXConfig)
# self.swerveDriveFXConfigFR.motor_output.inverted = InvertedValue.CLOCKWISE_POSITIVE | 3,847 | Python | 51.712328 | 133 | 0.77359 |
RoboEagles4828/rift2024/rio/srcrobot/pyproject.toml | #
# Use this configuration file to control what RobotPy packages are installed
# on your RoboRIO
#
[tool.robotpy]
# Version of robotpy this project depends on
robotpy_version = "2024.3.2.1"
# Which extra RobotPy components should be installed
# -> equivalent to `pip install robotpy[extra1, ...]
robotpy_extras = [
# "all",
"apriltag",
# "commands2",
"cscore",
"navx",
# "pathplannerlib",
"phoenix5",
# "phoenix6",
# "playingwithfusion",
"rev",
# "romi",
# "sim",
# "xrp"
]
# Other pip packages to install
requires = [
"robotpy-commands-v2>=2024.2.2",
"robotpy-ctre",
"squaternion",
"robotpy-pathplannerlib>=2024.1.2",
"rticonnextdds-connector",
"photonlibpy==2024.2.8",
"robotpy-pathplannerlib==2024.2.7",
"pytreemap"
]
| 809 | TOML | 19.25 | 76 | 0.6267 |
RoboEagles4828/rift2024/rio/srcrobot/constants.py | from phoenix6.signals import InvertedValue
from phoenix6.signals import NeutralModeValue
from phoenix6.signals import SensorDirectionValue
from wpimath.geometry import Rotation2d
from wpimath.geometry import Translation2d
from wpimath.kinematics import SwerveDrive4Kinematics
from wpimath.trajectory import TrapezoidProfile, TrapezoidProfileRadians
import lib.mathlib.units as Units
from lib.util.COTSTalonFXSwerveConstants import COTSTalonFXSwerveConstants
from lib.util.SwerveModuleConstants import SwerveModuleConstants
import math
from enum import Enum
from pytreemap import TreeMap
from lib.util.InterpolatingTreeMap import InterpolatingTreeMap
from wpimath.units import rotationsToRadians
from pathplannerlib.auto import HolonomicPathFollowerConfig
from pathplannerlib.controller import PIDConstants
from pathplannerlib.config import ReplanningConfig
class Constants:
stickDeadband = 0.1
class Swerve:
navxID = 0
chosenModule = COTSTalonFXSwerveConstants.MK4i.Falcon500(COTSTalonFXSwerveConstants.MK4i.driveRatios.L2)
# Drivetrain Constants
trackWidth = Units.inchesToMeters(20.75)
wheelBase = Units.inchesToMeters(20.75)
rotationBase = Units.inchesToMeters(31.125 - 5.25)
robotWidth = 26.0
robotLength = 31.125
armLength = 18.5
frontOffset = rotationBase - wheelBase
wheelCircumference = chosenModule.wheelCircumference
frontLeftLocation = Translation2d(-((wheelBase / 2.0) - frontOffset), -trackWidth / 2.0)
frontRightLocation = Translation2d(-((wheelBase / 2.0) - frontOffset), trackWidth / 2.0)
backLeftLocation = Translation2d(wheelBase / 2.0, -trackWidth / 2.0)
backRightLocation = Translation2d(wheelBase / 2.0, trackWidth / 2.0)
# frontLeftLocation = Translation2d(-wheelBase / 2.0, -trackWidth / 2.0)
# frontRightLocation = Translation2d(-wheelBase / 2.0, trackWidth / 2.0)
# backLeftLocation = Translation2d(wheelBase / 2.0, -trackWidth / 2.0)
# backRightLocation = Translation2d(wheelBase / 2.0, trackWidth / 2.0)
robotCenterLocation = Translation2d(0.0, 0.0)
swerveKinematics = SwerveDrive4Kinematics(
frontLeftLocation,
frontRightLocation,
backLeftLocation,
backRightLocation
)
# Module Gear Ratios
driveGearRatio = chosenModule.driveGearRatio
angleGearRatio = chosenModule.angleGearRatio
# Motor Inverts
angleMotorInvert = chosenModule.angleMotorInvert
driveMotorInvert = chosenModule.driveMotorInvert
# Angle Encoder Invert
cancoderInvert = chosenModule.cancoderInvert
# Swerve Current Limiting
angleCurrentLimit = 25
angleCurrentThreshold = 40
angleCurrentThresholdTime = 0.1
angleEnableCurrentLimit = True
driveCurrentLimit = 35
driveCurrentThreshold = 60
driveCurrentThresholdTime = 0.1
driveEnableCurrentLimit = True
openLoopRamp = 0.0
closedLoopRamp = 0.0
# Angle Motor PID Values
angleKP = chosenModule.angleKP
angleKI = chosenModule.angleKI
angleKD = chosenModule.angleKD
# Drive Motor PID Values
driveKP = 2.5
driveKI = 0.0
driveKD = 0.0
driveKF = 0.0
driveKS = 0.2
driveKV = 0.28
driveKA = 0.0
# Swerve Profiling Values
# Meters per Second
maxSpeed = 5.0
maxAutoModuleSpeed = 4.5
# Radians per Second
maxAngularVelocity = 2.5 * math.pi
# Neutral Modes
angleNeutralMode = NeutralModeValue.COAST
driveNeutralMode = NeutralModeValue.BRAKE
holonomicPathConfig = HolonomicPathFollowerConfig(
PIDConstants(5.0, 0.0, 0.0),
PIDConstants(4.0, 0.0, 0.0),
maxAutoModuleSpeed,
#distance from center to the furthest module
Units.inchesToMeters(16),
ReplanningConfig(),
)
# Slowdown speed
## The speed is multiplied by this value when the trigger is fully held down
slowMoveModifier = 0.8
slowTurnModifier = 0.8
# Module Specific Constants
# Front Left Module - Module 0
class Mod0:
driveMotorID = 2
angleMotorID = 1
canCoderID = 3
angleOffset = Rotation2d(rotationsToRadians(0.145020))
constants = SwerveModuleConstants(driveMotorID, angleMotorID, canCoderID, angleOffset)
# Front Right Module - Module 1
class Mod1:
driveMotorID = 19
angleMotorID = 18
canCoderID = 20
angleOffset = Rotation2d(rotationsToRadians(1.267334))
constants = SwerveModuleConstants(driveMotorID, angleMotorID, canCoderID, angleOffset)
# Back Left Module - Module 2
class Mod2:
driveMotorID = 9
angleMotorID = 8
canCoderID = 7
angleOffset = Rotation2d(rotationsToRadians(0.648926))
constants = SwerveModuleConstants(driveMotorID, angleMotorID, canCoderID, angleOffset)
# Back Right Module - Module 3
class Mod3:
driveMotorID = 12
angleMotorID = 11
canCoderID = 10
angleOffset = Rotation2d(rotationsToRadians(1.575195))
constants = SwerveModuleConstants(driveMotorID, angleMotorID, canCoderID, angleOffset)
class AutoConstants:
kMaxSpeedMetersPerSecond = 3
kMaxModuleSpeed = 4.5
kMaxAccelerationMetersPerSecondSquared = 3
kMaxAngularSpeedRadiansPerSecond = math.pi
kMaxAngularSpeedRadiansPerSecondSquared = math.pi
kPXController = 4.0
kPYController = 4.0
kPThetaController = 1.5
kThetaControllerConstraints = TrapezoidProfileRadians.Constraints(
kMaxAngularSpeedRadiansPerSecond,
kMaxAngularSpeedRadiansPerSecondSquared
)
class ShooterConstants:
kSubwooferPivotAngle = 0.0
kPodiumPivotAngle = 45.0
kAmpPivotAngle = 90.0
kSubwooferShootSpeed = 25.0
kPodiumShootSpeed = 20.0
kAmpShootSpeed = 5.0
kMechanicalAngle = 30.0
class IntakeConstants:
kIntakeMotorID = 0
kIntakeSpeed = 5.0
class IndexerConstants:
kIndexerMotorID = 14
kIndexerMaxSpeedMS = 20.0
kIndexerIntakeSpeedMS = 0.5
kBeamBreakerID = 0
class ClimberConstants:
kLeftMotorID = 14
kRightMotorID = 13
kLeftCANID = 4
kRightCANID = 15
maxClimbHeight = 0
kClimberSpeed = 0.85 # percent output
class ArmConstants:
kKnownArmAngles = InterpolatingTreeMap()
# kKnownArmAngles.put(0.0, 5.0)
# kKnownArmAngles.put(1.0, 6.5)
# kKnownArmAngles.put(2.0, 10.0)
# kKnownArmAngles.put(3.0, 12.0)
# kKnownArmAngles.put(4.0, 17.0)
# kKnownArmAngles.put(5.0, 20.0)
# kKnownArmAngles.put(6.0, 23.0)
kKnownArmAngles.put(0.0, 5.0)
kKnownArmAngles.put(0.833, 11.8)
kKnownArmAngles.put(1.667, 18.0)
kKnownArmAngles.put(2.5, 22.0)
kKnownArmAngles.put(3.333, 26.0)
kKnownArmAngles.put(4.1667,28.7)
kKnownArmAngles.put(5.0, 30.0)
kKnownArmAngles.put(5.833, 32.35)
kKnownArmAngles.put(6.667, 33.3)
kKnownArmAngles.put(7.5, 34.15)
# An enumeration of known shot locations and data critical to executing the
# shot. TODO decide on shooter velocity units and tune angles.
class NextShot(Enum):
AMP = (0, -90.0, 90.0, 85.0, 8.0, 5, 6)
SPEAKER_AMP = (1, -60.0, -60.0, 6.5, 25.0, 4, 7)
SPEAKER_CENTER = (2, 0.0, 0.0, 6.5, 25.0, 4, 7)
SPEAKER_SOURCE = (3, 60.0, 60.0, 6.5, 25.0, 4, 7)
PODIUM = (4, -30.0, 30.0, 26.5, 35.0, 4, 7)
CENTER_AUTO = (5, -30.0, 30.0, 31.0, 35.0, 4, 7)
DYNAMIC = (6, 0.0, 0.0, 0.0, 35.0, 4, 7)
def __init__(self, value, blueSideBotHeading, redSideBotHeading, armAngle, shooterVelocity, red_tagID, blue_tagID):
self._value_ = value
self.m_blueSideBotHeading = blueSideBotHeading
self.m_redSideBotHeading = redSideBotHeading
self.m_armAngle = armAngle
self.m_shooterVelocity = shooterVelocity
self.m_redTagID = red_tagID
self.m_blueTagID = blue_tagID
def calculateArmAngle(self, distance: float) -> float:
# a = -0.0694444
# b = 0.755952
# c = 0.968254
# d = 5.0
# armRegressionEquation = lambda x: a * (x**3) + b * (x**2) + c * x + d
a = 0.130952
b = 2.35714
c = 4.58333
armRegressionEquation = lambda x: a * (x**2) + b * x + c
if distance <= 0.5:
armAngle = armRegressionEquation(0)
else:
armAngle = armRegressionEquation(distance) + 2.0
return armAngle
def calculateInterpolatedArmAngle(self, distance: float) -> float:
armAngle = Constants.ArmConstants.kKnownArmAngles.get(distance)
return armAngle
def calculateShooterVelocity(self, distance: float) -> float:
if distance <= 0.5:
shooterVelocity = 25.0
else:
shooterVelocity = 35.0
return shooterVelocity
| 9,461 | Python | 32.434629 | 121 | 0.63376 |
RoboEagles4828/rift2024/rio/srcrobot/SwerveModule.py | from phoenix6.controls import DutyCycleOut, PositionVoltage, VelocityVoltage, VoltageOut
from phoenix6.hardware import CANcoder, TalonFX
from wpimath.controller import SimpleMotorFeedforwardMeters
from wpimath.geometry import Rotation2d
from wpimath.kinematics import SwerveModuleState, SwerveModulePosition
from lib.mathlib.conversions import Conversions
from lib.util.SwerveModuleConstants import SwerveModuleConstants
from constants import Constants
from CTREConfigs import CTREConfigs
from phoenix6.configs import CANcoderConfiguration
from phoenix6.configs import TalonFXConfiguration
from sim.SwerveModuleSim import SwerveModuleSim
from wpilib import RobotBase
from wpimath.units import radiansToRotations, rotationsToRadians
class SwerveModule:
ctreConfigs = CTREConfigs()
moduleNumber: int
angleOffset: Rotation2d
mAngleMotor: TalonFX
mDriveMotor: TalonFX
angleEncoder: CANcoder
driveFeedForward = SimpleMotorFeedforwardMeters(Constants.Swerve.driveKS, Constants.Swerve.driveKV, Constants.Swerve.driveKA)
driveDutyCycle: DutyCycleOut = DutyCycleOut(0).with_enable_foc(True)
driveVelocity: VelocityVoltage = VelocityVoltage(0).with_enable_foc(True)
anglePosition: PositionVoltage = PositionVoltage(0).with_enable_foc(True)
def __init__(self, moduleNumber: int, moduleConstants: SwerveModuleConstants):
self.moduleNumber = moduleNumber
self.angleOffset = moduleConstants.angleOffset
self.angleEncoder = CANcoder(moduleConstants.cancoderID, "canivore")
self.angleEncoder.configurator.apply(self.ctreConfigs.swerveCANcoderConfig)
self.mAngleMotor = TalonFX(moduleConstants.angleMotorID, "canivore")
self.mAngleMotor.configurator.apply(self.ctreConfigs.swerveAngleFXConfig)
self.resetToAbsolute()
self.mDriveMotor = TalonFX(moduleConstants.driveMotorID, "canivore")
if moduleNumber == 1:
self.mDriveMotor.configurator.apply(self.ctreConfigs.swerveDriveFXConfigFR)
else:
self.mDriveMotor.configurator.apply(self.ctreConfigs.swerveDriveFXConfig)
self.mDriveMotor.configurator.set_position(0.0)
if RobotBase.isSimulation():
self.simModule = SwerveModuleSim()
def setDesiredState(self, desiredState: SwerveModuleState, isOpenLoop: bool):
desiredState = SwerveModuleState.optimize(desiredState, self.getState().angle)
self.mAngleMotor.set_control(self.anglePosition.with_position(radiansToRotations(desiredState.angle.radians())))
self.setSpeed(desiredState, isOpenLoop)
if RobotBase.isSimulation():
self.simModule.updateStateAndPosition(desiredState)
def setDesiredStateNoOptimize(self, desiredState: SwerveModuleState, isOpenLoop: bool):
# desiredState = SwerveModuleState.optimize(desiredState, self.getState().angle)
self.mAngleMotor.set_control(self.anglePosition.with_position(radiansToRotations(desiredState.angle.radians())))
self.setSpeed(desiredState, isOpenLoop)
def setSpeed(self, desiredState: SwerveModuleState, isOpenLoop: bool):
if isOpenLoop:
self.driveDutyCycle.output = desiredState.speed / Constants.Swerve.maxSpeed
self.mDriveMotor.set_control(self.driveDutyCycle)
else:
self.driveVelocity.velocity = Conversions.MPSToRPS(desiredState.speed, Constants.Swerve.wheelCircumference)
self.driveVelocity.feed_forward = self.driveFeedForward.calculate(desiredState.speed)
self.mDriveMotor.set_control(self.driveVelocity)
def driveMotorVoltage(self, volts):
self.mDriveMotor.set_control(VoltageOut(volts, enable_foc=False))
def getCANcoder(self):
return Rotation2d(rotationsToRadians(self.angleEncoder.get_absolute_position().value_as_double))
def resetToAbsolute(self):
absolutePosition = self.getCANcoder().radians() - self.angleOffset.radians()
self.mAngleMotor.set_position(radiansToRotations(absolutePosition))
def getState(self):
if RobotBase.isSimulation():
return self.simModule.getState()
return SwerveModuleState(
Conversions.RPSToMPS(self.mDriveMotor.get_velocity().value_as_double, Constants.Swerve.wheelCircumference),
Rotation2d(rotationsToRadians(self.mAngleMotor.get_position().value_as_double))
)
def getPosition(self):
if RobotBase.isSimulation():
return self.simModule.getPosition()
return SwerveModulePosition(
Conversions.rotationsToMeters(self.mDriveMotor.get_position().value_as_double, Constants.Swerve.wheelCircumference),
Rotation2d(rotationsToRadians(self.mAngleMotor.get_position().value_as_double))
)
| 4,774 | Python | 42.807339 | 129 | 0.753456 |
RoboEagles4828/rift2024/rio/srcrobot/gameState.py | from constants import Constants
from wpilib import DriverStation
class GameState:
"""
The single game state object holds information on the current state of our
game play. It includes that next desired shot and if we do or do not
currently hold a note.
"""
def __new__(cls):
if not hasattr(cls, "instance"):
cls.instance = super(GameState, cls).__new__(cls)
return cls.instance
m_hasNote = True
m_noteInIntake = True
""" Do we have a note onboard? Start auto holding a note. """
m_nextShot = Constants.NextShot.SPEAKER_CENTER
""" What is our next planned shot? Default for basic autos. """
# Sets the next shot to take. If null is passed, the shot is reset to its
# initial speaker center state. The next shot setting is never allowed to be
# None.
#
# nextShot must be an instance of Constants.NextShot
def setNextShot(self, nextShot):
"""
Sets the next shot to take. If null is passed, the shot is reset to its
initial speaker center state. The next shot setting is never allowed to be
None.
:param nextShot: must be an instance of Constants.NextShot
"""
if isinstance(nextShot, Constants.NextShot):
self.m_nextShot = nextShot
else:
self.m_nextShot = Constants.NextShot.SPEAKER_CENTER
def getNextShot(self) -> Constants.NextShot:
"""
Return the next desired shot. Never None.
"""
return self.m_nextShot
def getNextShotRobotAngle(self) -> float:
"""
Return the angle the robot needs to be turned to for the next shot. This
value is alliance adjusted. If the FMS is misbehaving, we assume blue.
"""
alliance = DriverStation.getAlliance()
nextShot = self.getNextShot()
if alliance == DriverStation.Alliance.kRed:
return nextShot.m_redSideBotHeading
return nextShot.m_blueSideBotHeading
def getNextShotTagID(self) -> int:
"""
Return the tag ID for the next shot. This value is alliance adjusted. If
the FMS is misbehaving, we assume blue.
"""
alliance = DriverStation.getAlliance()
nextShot = self.getNextShot()
if alliance == DriverStation.Alliance.kRed:
return nextShot.m_redTagID
return nextShot.m_blueTagID
def setHasNote(self, hasNote):
"""
Generally called by the indexer with True and the shooter with False.
:param hasNote: the new setting for has note.
"""
self.m_hasNote = hasNote
def hasNote(self) -> bool:
"""
Return true if the robot is currently holding a note. False, otherwise.
"""
return self.m_hasNote
def setNoteInIntake(self, m_noteInIntake):
self.m_noteInIntake = m_noteInIntake
def getNoteInIntake(self) -> bool:
return self.m_noteInIntake
| 2,974 | Python | 31.336956 | 82 | 0.632482 |
RoboEagles4828/rift2024/rio/srcrobot/robot.py | from wpilib import TimedRobot
from commands2 import Command
from commands2 import CommandScheduler
from CTREConfigs import CTREConfigs
from constants import Constants
from gameState import GameState
from robot_container import RobotContainer
from wpimath.geometry import Rotation2d
import wpilib
from wpilib.shuffleboard import Shuffleboard, ShuffleboardTab
from wpilib import SmartDashboard, DriverStation
class Robot(TimedRobot):
m_autonomousCommand: Command = None
m_robotContainer: RobotContainer
auton_tab: ShuffleboardTab
teleop_tab: ShuffleboardTab
def robotInit(self):
# Instantiate our RobotContainer. This will perform all our button bindings, and put our
# autonomous chooser on the dashboard.
# wpilib.CameraServer.launch()
self.m_robotContainer = RobotContainer()
self.m_robotContainer.m_robotState.m_gameState.setHasNote(False)
CommandScheduler.getInstance().setPeriod(0.02)
def robotPeriodic(self):
# Runs the Scheduler. This is responsible for polling buttons, adding newly-scheduled
# commands, running already-scheduled commands, removing finished or interrupted commands,
# and running subsystem periodic() methods. This must be called from the robot's periodic
# block in order for anything in the Command-based framework to work.
CommandScheduler.getInstance().run()
def autonomousInit(self):
# self.m_robotContainer.s_Shooter.setDefaultCommand(self.m_robotContainer.s_Shooter.idle())
m_autonomousCommand: Command = self.m_robotContainer.getAutonomousCommand()
# schedule the autonomous command (example)
if m_autonomousCommand != None:
m_autonomousCommand.schedule()
def teleopInit(self):
# This makes sure that the autonomous stops running when
# teleop starts running. If you want the autonomous to
# continue until interrupted by another command, remove
# this line or comment it out.
# flip heading
if DriverStation.getAlliance() == DriverStation.Alliance.kRed:
self.m_robotContainer.s_Swerve.setHeading(self.m_robotContainer.s_Swerve.getHeading().rotateBy(Rotation2d.fromDegrees(180.0)))
GameState().setNextShot(Constants.NextShot.SPEAKER_CENTER)
self.m_robotContainer.s_Shooter.setDefaultCommand(self.m_robotContainer.s_Shooter.stop())
if self.m_autonomousCommand is not None:
self.m_autonomousCommand.cancel()
def testInit(self):
CommandScheduler.getInstance().cancelAll() | 2,453 | Python | 38.580645 | 132 | 0.773746 |
RoboEagles4828/rift2024/rio/srcrobot/robot_container.py | from wpilib.interfaces import GenericHID
from wpilib import Joystick
from wpilib import XboxController
from commands2.button import CommandXboxController, Trigger
from commands2 import Command, ParallelDeadlineGroup, Subsystem
from commands2 import InstantCommand, ConditionalCommand, WaitCommand, PrintCommand, RunCommand, SequentialCommandGroup, ParallelCommandGroup, WaitUntilCommand, StartEndCommand, DeferredCommand
from commands2.button import JoystickButton
import commands2.cmd as cmd
from CTREConfigs import CTREConfigs
from commands2 import CommandScheduler
import math
from wpimath.geometry import *
import wpimath.units as Units
import lib.mathlib.units as CustomUnits
from lib.mathlib.conversions import Conversions
from constants import Constants
from autos.exampleAuto import exampleAuto
from commands.TeleopSwerve import TeleopSwerve
from commands.PathFindToTag import PathFindToTag
from commands.DynamicShot import DynamicShot
from commands.ExecuteCommand import ExecuteCommand
from subsystems.Swerve import Swerve
from subsystems.intake import Intake
from subsystems.indexer import Indexer
from subsystems.Arm import Arm
from subsystems.Climber import Climber
from subsystems.Shooter import Shooter
from subsystems.Vision import Vision
from subsystems.Led import LED
# from subsystems.Climber import Climber
from commands.TurnInPlace import TurnInPlace
from commands.TurnToTag import TurnToTag
from commands.SysId import DriveSysId
from wpilib.shuffleboard import Shuffleboard, BuiltInWidgets, BuiltInLayouts
from wpilib import SendableChooser, RobotBase, DriverStation
from wpimath import applyDeadband
from autos.PathPlannerAutoRunner import PathPlannerAutoRunner
from pathplannerlib.auto import NamedCommands, PathConstraints, AutoBuilder
from pathplannerlib.controller import PPHolonomicDriveController
from robotState import RobotState
class RobotContainer:
ctreConfigs = CTREConfigs()
# Drive Controls
translationAxis = XboxController.Axis.kLeftY
strafeAxis = XboxController.Axis.kLeftX
rotationAxis = XboxController.Axis.kRightX
slowAxis = XboxController.Axis.kRightTrigger # This causes issues on certain controllers, where kRightTrigger is for some reason mapped to [5] instead of [3]
driver = CommandXboxController(0)
operator = CommandXboxController(1)
sysId = JoystickButton(driver, XboxController.Button.kY)
robotCentric_value = False
# Subsystems
s_Swerve : Swerve = Swerve()
s_Arm : Arm = Arm()
s_Intake : Intake = Intake()
s_Indexer : Indexer = Indexer()
s_Shooter : Shooter = Shooter()
s_Vision : Vision = Vision.getInstance()
# s_Climber : Climber = Climber()
#SysId
driveSysId = DriveSysId(s_Swerve)
s_Climber : Climber = Climber()
s_LED : LED = LED()
# The container for the robot. Contains subsystems, OI devices, and commands.
def __init__(self):
self.m_robotState : RobotState = RobotState()
self.m_robotState.initialize(
lambda: self.s_Swerve.getHeading().degrees(),
self.s_Arm.getDegrees,
self.s_Shooter.getVelocity
)
self.dynamicShot = DynamicShot(self.s_Swerve, self.s_Vision, self.s_Arm)
# PPHolonomicDriveController.setRotationTargetOverride(self.dynamicShot.getRotationTarget())
self.currentArmAngle = self.s_Arm.getDegrees()
# Driver Controls
self.zeroGyro = self.driver.back()
self.robotCentric = self.driver.start()
self.execute = self.driver.leftBumper()
self.shoot = self.driver.rightBumper()
self.intake = self.driver.leftTrigger()
self.fastTurn = self.driver.povUp()
self.climbUp = self.driver.y()
self.climbDown = self.driver.a()
# Slowmode is defined with the other Axis objects
# Operator Controls
self.autoHome = self.operator.rightTrigger()
# self.flywheel = self.operator.rightBumper()
self.systemReverse = self.operator.leftBumper()
self.opExec = self.operator.leftTrigger()
self.opShoot = self.operator.rightBumper()
self.emergencyArmUp = self.operator.povDown()
# Que Controls
self.queSubFront = self.operator.a()
self.quePodium = self.operator.y()
self.queSubRight = self.operator.b()
self.queSubLeft = self.operator.x()
self.queAmp = self.operator.povUp()
self.queDynamic = self.operator.povRight()
self.configureButtonBindings()
NamedCommands.registerCommand("RevShooter", self.s_Shooter.shoot().withTimeout(1.0).withName("AutoRevShooter"))
NamedCommands.registerCommand("Shoot", self.s_Indexer.indexerShoot().withTimeout(1.0).withName("AutoShoot"))
NamedCommands.registerCommand("ShooterOff", InstantCommand(self.s_Shooter.brake, self.s_Shooter).withName("AutoShooterBrake"))
NamedCommands.registerCommand("IndexerIntake", self.s_Indexer.indexerIntakeOnce().withName("AutoIndexerIntake"))
NamedCommands.registerCommand("ArmUp", self.s_Arm.servoArmToTarget(5.0).withTimeout(0.5))
NamedCommands.registerCommand("ArmDown", self.s_Arm.seekArmZero().withTimeout(1.0))
NamedCommands.registerCommand("IndexerOff", self.s_Indexer.instantStop().withName("AutoIndexerOff"))
NamedCommands.registerCommand("IntakeOn", self.s_Intake.intakeOnce().withName("AutoIntakeOn"))
NamedCommands.registerCommand("IntakeOff", self.s_Intake.instantStop().withName("AutoIntakeOff"))
NamedCommands.registerCommand("IndexerOut", self.s_Indexer.indexerOuttake().withTimeout(4.0))
NamedCommands.registerCommand("BringArmUp", self.bringArmUp())
NamedCommands.registerCommand("IntakeUntilBeamBreak", SequentialCommandGroup(
self.s_Indexer.indexerIntakeOnce(),
WaitUntilCommand(self.s_Indexer.getBeamBreakState).withTimeout(4.0).finallyDo(lambda interrupted: self.s_Indexer.stopMotor()),
self.s_Indexer.instantStop()
).withTimeout(5.0))
# Compiled Commands
NamedCommands.registerCommand("Full Shooter Rev", self.s_Shooter.shoot())
NamedCommands.registerCommand("Full Intake", self.s_Intake.intake().alongWith(self.s_Indexer.indexerIntake()).until(self.s_Indexer.getBeamBreakState).andThen(self.s_Indexer.instantStop()).andThen(self.s_Indexer.indexerOuttake().withTimeout(0.0005)).withName("AutoIntake").withTimeout(5.0))
NamedCommands.registerCommand("Full Shoot", self.s_Arm.servoArmToTarget(4.0).withTimeout(0.5).andThen(WaitCommand(0.7)).andThen(self.s_Indexer.indexerShoot().withTimeout(0.5).alongWith(self.s_Intake.intake().withTimeout(0.5)).withTimeout(1.0)).andThen(self.s_Arm.seekArmZero()))
NamedCommands.registerCommand("All Off", self.s_Intake.instantStop().alongWith(self.s_Indexer.instantStop(), self.s_Shooter.brake()).withName("AutoAllOff"))
NamedCommands.registerCommand("Combo Shot", self.autoModeShot(Constants.NextShot.SPEAKER_CENTER))
NamedCommands.registerCommand("Combo Podium Shot", self.autoModeShot(Constants.NextShot.CENTER_AUTO))
NamedCommands.registerCommand("Queue Speaker", self.autoExecuteShot(Constants.NextShot.SPEAKER_CENTER))
NamedCommands.registerCommand("Queue Podium", self.autoExecuteShot(Constants.NextShot.CENTER_AUTO))
NamedCommands.registerCommand("Queue Dynamic", self.autoDynamicShot()) #check this change with saranga
NamedCommands.registerCommand("Execute Shot", self.autoShootWhenReady())
NamedCommands.registerCommand("Bring Arm Down", self.bringArmDown())
self.auton_selector = AutoBuilder.buildAutoChooser("DO NOTHING")
Shuffleboard.getTab("Autonomous").add("Auton Selector", self.auton_selector)
Shuffleboard.getTab("Teleoperated").addString("QUEUED SHOT", self.getQueuedShot)
Shuffleboard.getTab("Teleoperated").addBoolean("Field Oriented", self.getFieldOriented)
Shuffleboard.getTab("Teleoperated").addBoolean("Zero Gyro", self.zeroGyro.getAsBoolean)
Shuffleboard.getTab("Teleoperated").addBoolean("Beam Break", self.s_Indexer.getBeamBreakState)
Shuffleboard.getTab("Teleoperated").addDouble("Shooter Speed", self.s_Shooter.getVelocity)
Shuffleboard.getTab("Teleoperated").addBoolean("Arm + Shooter Ready", lambda: self.m_robotState.isArmAndShooterReady())
Shuffleboard.getTab("Teleoperated").addDouble("Swerve Heading", lambda: self.s_Swerve.getHeading().degrees())
Shuffleboard.getTab("Teleoperated").addDouble("Front Right Module Speed", lambda: self.s_Swerve.mSwerveMods[1].getState().speed)
Shuffleboard.getTab("Teleoperated").addDouble("Swerve Pose X", lambda: self.s_Swerve.getPose().X())
Shuffleboard.getTab("Teleoperated").addDouble("Swerve Pose Y", lambda: self.s_Swerve.getPose().Y())
Shuffleboard.getTab("Teleoperated").addDouble("Swerve Pose Theta", lambda: self.s_Swerve.getPose().rotation().degrees())
Shuffleboard.getTab("Teleoperated").addDouble("Target Distance X", lambda: self.s_Vision.getDistanceVectorToSpeaker(self.s_Swerve.getPose()).X())
Shuffleboard.getTab("Teleoperated").addDouble("Target Distance Y", lambda: self.s_Vision.getDistanceVectorToSpeaker(self.s_Swerve.getPose()).Y())
Shuffleboard.getTab("Teleoperated").addDouble("Target Distance Norm", lambda: self.s_Vision.getDistanceVectorToSpeaker(self.s_Swerve.getPose()).norm())
Shuffleboard.getTab("Teleoperated").addDouble("Target Arm Angle", lambda: self.dynamicShot.getInterpolatedArmAngle())
Shuffleboard.getTab("Teleoperated").addDouble("Target Robot Angle", lambda: self.dynamicShot.getRobotAngle().degrees())
Shuffleboard.getTab("Teleoperated").addDouble("Target Arm Angle Trig", lambda: self.dynamicShot.getTrigArmAngle())
Shuffleboard.getTab("Teleoperated").addDouble("Target Distance Feet", lambda: Units.metersToFeet(self.s_Vision.getDistanceVectorToSpeaker(self.s_Swerve.getPose()).norm()) - (36.37 / 12.0) - (Constants.Swerve.robotLength / 2.0 / 12.0))
Shuffleboard.getTab("Teleoperated").addBoolean("PATH FLIP", self.s_Swerve.shouldFlipPath)
Shuffleboard.getTab("Teleoperated").addString("FMS ALLIANCE", self.getAllianceName)
Shuffleboard.getTab("Teleoperated").addDouble("Shooter Speed RPM", lambda: Conversions.MPSToRPS(self.s_Shooter.getVelocity(), self.s_Shooter.wheelCircumference) * 60.0)
def getAllianceName(self):
if DriverStation.getAlliance() is None:
return "NONE"
else:
return DriverStation.getAlliance().name
def autoModeShot(self, autoShot: Constants.NextShot) -> Command:
"""
Used during automode commands to shoot any Constants.NextShot.
"""
shotTimeoutSec = (autoShot.m_armAngle / 45.0) + 1.0
return SequentialCommandGroup(
InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(autoShot)),
ParallelDeadlineGroup(
WaitUntilCommand(lambda: self.m_robotState.isArmAndShooterReady())
.withTimeout(1.0)
.andThen(self.s_Indexer.indexerShoot()),
InstantCommand(
lambda: self.s_Shooter.setShooterVelocity(
autoShot.m_shooterVelocity
),
self.s_Shooter,
),
self.s_Arm.servoArmToTargetGravity(autoShot.m_armAngle)
),
self.s_Indexer.instantStop(),
self.s_Arm.seekArmZero().withTimeout(0.5)
)
def getDynamicShotCommand(self, translation, strafe, rotation, robotcentric) -> ParallelCommandGroup:
return ParallelCommandGroup(
self.s_Arm.servoArmToTargetDynamic(
lambda: self.dynamicShot.getInterpolatedArmAngle()
).repeatedly(),
InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(Constants.NextShot.DYNAMIC)),
self.s_Shooter.shootVelocityWithSupplier(
lambda: 35.0
).repeatedly(),
TurnInPlace(
self.s_Swerve,
lambda: self.dynamicShot.getRobotAngle(),
translation,
strafe,
rotation,
robotcentric
).repeatedly()
)
def autoDynamicShot(self) -> Command:
return DeferredCommand(
lambda:
ParallelDeadlineGroup(
WaitUntilCommand(lambda: self.m_robotState.isReadyDynamic(lambda: self.dynamicShot.getInterpolatedArmAngle()))
.withTimeout(1.0)
.andThen(self.s_Indexer.indexerShoot()),
self.s_Arm.servoArmToTargetDynamic(
lambda: self.dynamicShot.getInterpolatedArmAngle()
),
InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(Constants.NextShot.DYNAMIC)),
self.s_Shooter.shootVelocityWithSupplier(
lambda: 35.0
),
TurnInPlace(
self.s_Swerve,
lambda: self.dynamicShot.getRobotAngle(),
lambda: 0.0,
lambda: 0.0,
lambda: 0.0,
lambda: False
)
).andThen(self.s_Arm.seekArmZero().withTimeout(0.5))
)
def autoShootWhenReady(self) -> Command:
return DeferredCommand(
lambda: ConditionalCommand(
SequentialCommandGroup(
self.s_Indexer.indexerShoot(),
self.s_Indexer.instantStop(),
),
InstantCommand(),
lambda: self.s_Indexer.getBeamBreakState()
)
)
def bringArmDown(self) -> Command:
return DeferredCommand(lambda: self.s_Arm.seekArmZero().withTimeout(0.5))
def bringArmUp(self) -> Command:
return DeferredCommand(
lambda: ParallelDeadlineGroup(
WaitUntilCommand(lambda: abs(self.s_Swerve.getTranslationVelocity().norm() - 0.0) < 0.1),
ConditionalCommand(
self.s_Arm.servoArmToTargetDynamic(lambda: self.dynamicShot.getInterpolatedArmAngle()),
self.s_Arm.seekArmZero(),
lambda: self.s_Indexer.getBeamBreakState()
)
)
)
def autoExecuteShot(self, autoShot: Constants.NextShot) -> Command:
return ParallelCommandGroup(
InstantCommand(
lambda: self.s_Shooter.setShooterVelocity(
autoShot.m_shooterVelocity
),
self.s_Shooter,
),
self.s_Arm.servoArmToTargetGravity(autoShot.m_armAngle)
)
"""
* Use this method to define your button->command mappings. Buttons can be created by
* instantiating a {@link GenericHID} or one of its subclasses ({@link
* edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link
* edu.wpi.first.wpilibj2.command.button.JoystickButton}.
"""
def configureButtonBindings(self):
translation = lambda: -applyDeadband(self.driver.getRawAxis(self.translationAxis), 0.1)
strafe = lambda: -applyDeadband(self.driver.getRawAxis(self.strafeAxis), 0.1)
rotation = lambda: applyDeadband(self.driver.getRawAxis(self.rotationAxis), 0.1)
robotcentric = lambda: applyDeadband(self.robotCentric_value, 0.1)
slow = lambda: applyDeadband(self.driver.getRawAxis(self.slowAxis), 0.1)
# slow = lambda: 0.0
self.s_Swerve.setDefaultCommand(
TeleopSwerve(
self.s_Swerve,
translation,
strafe,
rotation,
robotcentric,
slow
)
)
# Arm Buttons
self.s_Arm.setDefaultCommand(self.s_Arm.holdPosition())
# Driver Buttons
self.zeroGyro.onTrue(InstantCommand(lambda: self.s_Swerve.zeroHeading()))
self.robotCentric.onTrue(InstantCommand(lambda: self.toggleFieldOriented()))
# Intake Buttons
self.s_Indexer.setDefaultCommand(self.s_Indexer.stopIndexer())
self.s_Intake.setDefaultCommand(self.s_Intake.stopIntake())
self.intake.whileTrue(self.s_Intake.intake().alongWith(self.s_Indexer.indexerIntake()).until(self.s_Indexer.getBeamBreakState).andThen(self.s_Indexer.instantStop()).andThen(self.s_Indexer.indexerIntake().withTimeout(0.0005)))
self.systemReverse.whileTrue(self.s_Intake.outtake().alongWith(self.s_Indexer.indexerOuttake(), self.s_Shooter.shootReverse()))
self.beamBreakTrigger = Trigger(self.s_Indexer.getBeamBreakState)
self.intakeBeamBreakTrigger = Trigger(self.s_Intake.getIntakeBeamBreakState)
self.beamBreakTrigger.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setHasNote(True))).onFalse(InstantCommand(lambda: self.m_robotState.m_gameState.setHasNote(False)))
self.intakeBeamBreakTrigger.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNoteInIntake(True)).alongWith(self.rumbleAll())).onFalse(InstantCommand(lambda: self.m_robotState.m_gameState.setNoteInIntake(False)))
# Que Buttons
self.queSubFront.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.SPEAKER_CENTER
)).andThen(self.s_Arm.seekArmZero()))
self.quePodium.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.PODIUM
)).andThen(self.s_Arm.seekArmZero()))
self.queSubRight.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.SPEAKER_AMP
)).andThen(self.s_Arm.seekArmZero()))
self.queSubLeft.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.SPEAKER_SOURCE
)).andThen(self.s_Arm.seekArmZero()))
self.queAmp.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.AMP
)).andThen(self.s_Arm.seekArmZero()))
self.queDynamic.onTrue(InstantCommand(lambda: self.m_robotState.m_gameState.setNextShot(
Constants.NextShot.DYNAMIC
)).andThen(self.s_Arm.seekArmZero()))
self.execute.or_(self.opExec.getAsBoolean).onTrue(
ConditionalCommand(
self.getDynamicShotCommand(translation, strafe, rotation, robotcentric),
self.s_Arm.servoArmToTargetWithSupplier(
lambda: self.m_robotState.m_gameState.getNextShot()
).alongWith(
self.s_Shooter.shootVelocityWithSupplier(
lambda: self.m_robotState.m_gameState.getNextShot().m_shooterVelocity
),
TurnInPlace(
self.s_Swerve,
lambda: Rotation2d.fromDegrees(
self.m_robotState.m_gameState.getNextShotRobotAngle()
),
translation,
strafe,
rotation,
robotcentric
).repeatedly()
),
lambda: self.m_robotState.m_gameState.getNextShot() == Constants.NextShot.DYNAMIC
)
)
self.fastTurn.whileTrue(InstantCommand(lambda: self.setFastTurn(True))).whileFalse(InstantCommand(lambda: self.setFastTurn(False)))
# LED Controls
self.s_LED.setDefaultCommand(self.s_LED.getStateCommand())
# Climber Buttons
self.s_Climber.setDefaultCommand(self.s_Climber.stopClimbers())
self.climbUp.whileTrue(self.s_Climber.runClimbersUp())
self.climbDown.whileTrue(self.s_Climber.runClimbersDown())
# Shooter Buttons
self.s_Shooter.setDefaultCommand(self.s_Shooter.stop())
self.shoot.or_(self.opShoot.getAsBoolean).whileTrue(cmd.parallel(self.s_Indexer.indexerTeleopShot(), self.s_Intake.intake(), self.s_Shooter.shootVelocityWithSupplier(lambda: self.m_robotState.m_gameState.getNextShot().m_shooterVelocity)))
self.autoHome.onTrue(self.s_Arm.seekArmZero())
self.emergencyArmUp.onTrue(
ConditionalCommand(
self.s_Arm.seekArmZero(),
self.s_Arm.servoArmToTargetGravity(90.0),
lambda: self.s_Arm.getDegrees() > 45.0
)
)
# self.emergencyArmUp.whileTrue(
# self.s_Shooter.shootVelocityWithSupplier(lambda: 35.0)
# )
def toggleFieldOriented(self):
self.robotCentric_value = not self.robotCentric_value
def getFieldOriented(self):
return not self.robotCentric_value
def getQueuedShot(self):
return self.m_robotState.m_gameState.getNextShot().name
def rumbleAll(self):
return ParallelCommandGroup(
self.rumbleDriver(),
self.rumbleOperator()
)
def rumbleDriver(self):
return InstantCommand(
lambda: self.driver.getHID().setRumble(XboxController.RumbleType.kLeftRumble, 1.0)
).andThen(WaitCommand(0.5)).andThen(InstantCommand(lambda: self.driver.getHID().setRumble(XboxController.RumbleType.kLeftRumble, 0.0))).withName("Rumble")
def rumbleOperator(self):
return InstantCommand(
lambda: self.operator.getHID().setRumble(XboxController.RumbleType.kLeftRumble, 1.0)
).andThen(WaitCommand(0.5)).andThen(InstantCommand(lambda: self.operator.getHID().setRumble(XboxController.RumbleType.kLeftRumble, 0.0))).withName("Rumble")
"""
* Use this to pass the autonomous command to the main {@link Robot} class.
*
* @return the command to run in autonomous
"""
def getAutonomousCommand(self) -> Command:
auto = self.auton_selector.getSelected()
return auto
def setFastTurn(self, value: bool):
if value:
Constants.Swerve.maxAngularVelocity = 2.5 * math.pi * 2.0
else:
Constants.Swerve.maxAngularVelocity = 2.5 * math.pi
| 22,363 | Python | 48.919643 | 297 | 0.672495 |
RoboEagles4828/rift2024/rio/srcrobot/robotState.py | import math
from gameState import GameState
class RobotState:
"""
The single robot can evaluate if the robot subsystems are ready to
execute a game task.
"""
kRobotHeadingTolerance = 2.0
kArmAngleTolerance = 1.0
kShooterVelocityTolerance = 3.0
m_gameState = GameState()
def __new__(cls):
"""
To initialize the singleton RobotState, call this from
RobotContainer soon after creating subsystems and
then immediately call initialize() the returned instance.
Other clients of the singleton only call this constructor.
"""
if not hasattr(cls, "instance"):
cls.instance = super(RobotState, cls).__new__(cls)
return cls.instance
def initialize(
self, robotHeadingSupplier, armAngleSupplier, shooterVelocitySupplier
):
"""
Only called from RobotContainer after the constructor to complete
initialization of the singleton.
:param robotHeadingSupplier: a supplier of the robots current heading.
:param armAngleSupplier: a supplier of the current arm angle.
:param shooterVelocitySupplier: a supplier of the current shooter velocity.
"""
self.m_robotHeadingSupplier = robotHeadingSupplier
self.m_armAngleSupplier = armAngleSupplier
self.m_shooterVelocitySupplier = shooterVelocitySupplier
def isclose(self, a, b, tolerance) -> bool:
return abs(a - b) < tolerance
def isShooterReady(self) -> bool:
"""
Return true if the current arm angle and shooter velocity are both within
tolerance for the needs of the next desired shot.
"""
shot = self.m_gameState.getNextShot()
return self.isclose(
shot.m_shooterVelocity,
self.m_shooterVelocitySupplier(),
self.kShooterVelocityTolerance,
)
def isArmReady(self) -> bool:
shot = self.m_gameState.getNextShot()
return self.isclose(
shot.m_armAngle,
self.m_armAngleSupplier(),
self.kArmAngleTolerance
)
def isArmAndShooterReady(self) -> bool:
return self.isShooterReady() and self.isArmReady()
def isRobotReady(self) -> bool:
"""
Return true if isShooterReady and the robot is turned correctly for the next shot.
"""
return self.isArmAndShooterReady() and self.isclose(
self.m_gameState.getNextShotRobotAngle(),
self.m_robotHeadingSupplier(),
self.kRobotHeadingTolerance,
)
def isReadyToIntake(self) -> bool:
"""
On our robot, the intake is physically dependent on the arm position for
intaking to work.
:return: True if we do not have a note and the arm is in the proper
intaking position.
"""
return (not self.m_gameState.hasNote()) and self.isclose(
0.0, self.m_armAngleSupplier(), self.kArmAngleTolerance
)
def isReadyDynamic(self, degreesSup) -> bool:
arm = self.isclose(
degreesSup(),
self.m_armAngleSupplier(),
self.kArmAngleTolerance
)
shooter = self.isclose(
35.0,
self.m_shooterVelocitySupplier(),
self.kShooterVelocityTolerance
)
return arm and shooter | 3,387 | Python | 30.962264 | 90 | 0.625627 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Swerve.py | from SwerveModule import SwerveModule
from constants import Constants
from subsystems.Vision import Vision
from wpimath.kinematics import ChassisSpeeds
from wpimath.kinematics import SwerveDrive4Kinematics
from wpimath.kinematics import SwerveDrive4Odometry
from wpimath.estimator import SwerveDrive4PoseEstimator
from wpimath.kinematics import SwerveModulePosition
from navx import AHRS
from wpimath.geometry import Pose2d
from wpimath.geometry import Rotation2d
from wpimath.geometry import Translation2d, Transform2d
from wpimath.kinematics import SwerveModuleState
from wpilib.shuffleboard import Shuffleboard, BuiltInWidgets
from commands2.subsystem import Subsystem
from wpilib.sysid import SysIdRoutineLog
from wpimath.units import volts
from pathplannerlib.auto import AutoBuilder, PathConstraints
from wpilib import DriverStation, RobotBase, Field2d
from wpiutil import Sendable, SendableBuilder
from sim.SwerveIMUSim import SwerveIMUSim
from sim.SwerveModuleSim import SwerveModuleSim
class Swerve(Subsystem):
def __init__(self):
if RobotBase.isSimulation():
self.gyro = SwerveIMUSim()
else:
self.gyro = AHRS.create_spi()
self.gyro.calibrate()
self.gyro.zeroYaw()
self.mSwerveMods = [
SwerveModule(0, Constants.Swerve.Mod0.constants),
SwerveModule(1, Constants.Swerve.Mod1.constants),
SwerveModule(2, Constants.Swerve.Mod2.constants),
SwerveModule(3, Constants.Swerve.Mod3.constants)
]
# self.swerveOdometry = SwerveDrive4Odometry(Constants.Swerve.swerveKinematics, self.getGyroYaw(), self.getModulePositions())
self.swerveOdometry = SwerveDrive4PoseEstimator(Constants.Swerve.swerveKinematics, self.getGyroYaw(), self.getModulePositions(), Pose2d(0, 0, Rotation2d()))
self.vision : Vision = Vision.getInstance()
self.field = Field2d()
AutoBuilder.configureHolonomic(
self.getPose,
self.setPose,
self.getRobotRelativeSpeeds,
self.driveRobotRelative,
Constants.Swerve.holonomicPathConfig,
self.shouldFlipPath,
self
)
Shuffleboard.getTab("Field").add(self.field)
self.alliance = Shuffleboard.getTab("Teleoperated").add("MANUAL ALLIANCE FLIP", False).getEntry()
def drive(self, translation: Translation2d, rotation, fieldRelative, isOpenLoop):
discreteSpeeds = ChassisSpeeds.discretize(translation.X(), translation.Y(), rotation, 0.02)
swerveModuleStates = Constants.Swerve.swerveKinematics.toSwerveModuleStates(
ChassisSpeeds.fromFieldRelativeSpeeds(
discreteSpeeds.vx,
discreteSpeeds.vy,
discreteSpeeds.omega,
self.getHeading()
)
) if fieldRelative else Constants.Swerve.swerveKinematics.toSwerveModuleStates(
ChassisSpeeds(translation.X(), translation.Y(), rotation)
)
SwerveDrive4Kinematics.desaturateWheelSpeeds(swerveModuleStates, Constants.Swerve.maxSpeed)
self.mSwerveMods[0].setDesiredState(swerveModuleStates[0], isOpenLoop)
self.mSwerveMods[1].setDesiredState(swerveModuleStates[1], isOpenLoop)
self.mSwerveMods[2].setDesiredState(swerveModuleStates[2], isOpenLoop)
self.mSwerveMods[3].setDesiredState(swerveModuleStates[3], isOpenLoop)
def driveRobotRelative(self, speeds: ChassisSpeeds):
self.drive(Translation2d(speeds.vx, speeds.vy), -speeds.omega, False, False)
def shouldFlipPath(self):
return DriverStation.getAlliance() == DriverStation.Alliance.kRed
def setModuleStates(self, desiredStates):
SwerveDrive4Kinematics.desaturateWheelSpeeds(desiredStates, Constants.Swerve.maxSpeed)
self.mSwerveMods[0].setDesiredState(desiredStates[0], False)
self.mSwerveMods[1].setDesiredState(desiredStates[1], False)
self.mSwerveMods[2].setDesiredState(desiredStates[2], False)
self.mSwerveMods[3].setDesiredState(desiredStates[3], False)
def getModuleStates(self):
states = list()
states.append(self.mSwerveMods[0].getState())
states.append(self.mSwerveMods[1].getState())
states.append(self.mSwerveMods[2].getState())
states.append(self.mSwerveMods[3].getState())
return states
def getModulePositions(self):
positions = list()
positions.append(self.mSwerveMods[0].getPosition())
positions.append(self.mSwerveMods[1].getPosition())
positions.append(self.mSwerveMods[2].getPosition())
positions.append(self.mSwerveMods[3].getPosition())
return positions
def getTranslationVelocity(self) -> Translation2d:
speed = self.getRobotRelativeSpeeds()
return Translation2d(speed.vx, speed.vy)
def getModules(self):
return self.mSwerveMods
def getPose(self):
return self.swerveOdometry.getEstimatedPosition()
def setPose(self, pose):
self.swerveOdometry.resetPosition(self.getGyroYaw(), tuple(self.getModulePositions()), pose)
def getHeading(self):
return self.getPose().rotation()
def setHeading(self, heading: Rotation2d):
self.swerveOdometry.resetPosition(self.getGyroYaw(), tuple(self.getModulePositions()), Pose2d(self.getPose().translation(), heading))
def zeroHeading(self):
self.swerveOdometry.resetPosition(self.getGyroYaw(), tuple(self.getModulePositions()), Pose2d(self.getPose().translation(), Rotation2d()))
def zeroYaw(self):
self.gyro.zeroYaw()
def getGyroYaw(self):
return Rotation2d.fromDegrees(self.gyro.getYaw()).__mul__(-1)
def resetModulesToAbsolute(self):
self.mSwerveMods[0].resetToAbsolute()
self.mSwerveMods[1].resetToAbsolute()
self.mSwerveMods[2].resetToAbsolute()
self.mSwerveMods[3].resetToAbsolute()
def resetModuleZero(self):
self.mSwerveMods[0].setDesiredStateNoOptimize(SwerveModuleState(0, Rotation2d(0)), False)
self.mSwerveMods[1].setDesiredStateNoOptimize(SwerveModuleState(0, Rotation2d(0)), False)
self.mSwerveMods[2].setDesiredStateNoOptimize(SwerveModuleState(0, Rotation2d(0)), False)
self.mSwerveMods[3].setDesiredStateNoOptimize(SwerveModuleState(0, Rotation2d(0)), False)
def getRobotRelativeSpeeds(self):
return Constants.Swerve.swerveKinematics.toChassisSpeeds(tuple(self.getModuleStates()))
def driveMotorsVoltage(self, volts):
self.mSwerveMods[0].driveMotorVoltage(volts)
self.mSwerveMods[1].driveMotorVoltage(volts)
self.mSwerveMods[2].driveMotorVoltage(volts)
self.mSwerveMods[3].driveMotorVoltage(volts)
def logDriveMotors(self, routineLog: SysIdRoutineLog):
for mod in self.mSwerveMods:
moduleName = "Module " + str(mod.moduleNumber)
routineLog.motor(moduleName)\
.voltage(mod.mDriveMotor.get_motor_voltage().value_as_double)\
.position(mod.getPosition().distance)\
.velocity(mod.getState().speed)
def pathFindToPose(self, pose: Pose2d, constraints: PathConstraints, goalEndVel: float):
return AutoBuilder.pathfindToPose(pose, constraints)
def getSwerveModulePoses(self, robot_pose: Pose2d):
poses = []
locations: list[Translation2d] = [
Constants.Swerve.frontLeftLocation,
Constants.Swerve.frontRightLocation,
Constants.Swerve.backLeftLocation,
Constants.Swerve.backRightLocation
]
for idx, module in enumerate(self.mSwerveMods):
loc = locations[idx]
poses.append(
robot_pose + Transform2d(loc, module.getState().angle)
)
return poses
def stop(self):
self.drive(Translation2d(), 0, False, True)
def periodic(self):
if RobotBase.isSimulation():
modulePoses = self.getSwerveModulePoses(self.getPose())
self.gyro.updateOdometry(Constants.Swerve.swerveKinematics, self.getModuleStates(), modulePoses, self.field)
self.field.getRobotObject().setPose(self.getPose())
self.swerveOdometry.update(self.getGyroYaw(), tuple(self.getModulePositions()))
optestimatedPose = self.vision.getEstimatedGlobalPose()
if optestimatedPose is not None:
estimatedPose = optestimatedPose
heading = estimatedPose.estimatedPose.toPose2d().rotation()
self.swerveOdometry.addVisionMeasurement(Pose2d(estimatedPose.estimatedPose.toPose2d().X(), estimatedPose.estimatedPose.toPose2d().Y(), self.getHeading()), estimatedPose.timestampSeconds)
| 8,794 | Python | 40.880952 | 199 | 0.699113 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/indexer.py | from constants import Constants
from commands2.subsystem import Subsystem
from commands2.cmd import waitSeconds
from phoenix5 import TalonSRX, TalonSRXConfiguration, TalonSRXControlMode, TalonSRXFeedbackDevice, NeutralMode, SupplyCurrentLimitConfiguration
from wpilib import DigitalInput
from commands2 import InstantCommand
from wpimath.filter import Debouncer
import math
class Indexer(Subsystem):
def __init__(self):
self.indexerMotor = TalonSRX(Constants.IndexerConstants.kIndexerMotorID)
self.indexerMotor.configFactoryDefault()
self.beamBreak = DigitalInput(Constants.IndexerConstants.kBeamBreakerID)
self.indexerMotor.setInverted(True)
self.indexerMotor.config_kP(0, 2.0)
self.indexerMotor.setNeutralMode(NeutralMode.Brake)
current_limit = 40
current_threshold = 60
current_threshold_time = 3.0
supply_configs = SupplyCurrentLimitConfiguration(True, current_limit, current_threshold, current_threshold_time)
self.indexerMotor.configSupplyCurrentLimit(supply_configs)
self.indexerDiameter = 0.031
self.indexerEncoderCPR = 2048.0
self.indexerIntakeVelocity = -(Constants.IndexerConstants.kIndexerIntakeSpeedMS/(math.pi*self.indexerDiameter))*self.indexerEncoderCPR
self.indexerShootVelocity = -(Constants.IndexerConstants.kIndexerMaxSpeedMS/(math.pi*self.indexerDiameter))*self.indexerEncoderCPR
self.debouncer = Debouncer(0.05, Debouncer.DebounceType.kBoth)
def getBeamBreakState(self):
return not bool(self.beamBreak.get())
def indexerIntake(self):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, self.indexerIntakeVelocity)).withName("Intake")
def indexerIntakeOnce(self):
return self.runOnce(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, self.indexerIntakeVelocity))
def indexerShoot(self):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, self.indexerShootVelocity)).until(lambda: not self.getBeamBreakState()).withTimeout(3.0).andThen(waitSeconds(0.3)).finallyDo(lambda interrupted: self.stopMotor()).withName("Shoot")
def indexerTeleopShot(self):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, self.indexerShootVelocity))
def indexerOuttake(self):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, -self.indexerIntakeVelocity)).withName("Outtake")
def setIndexerVelocity(self, velocity):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.Velocity, -(velocity/(math.pi*self.indexerDiameter))*self.indexerEncoderCPR)).withName("SetIndexerVelocity")
def levelIndexer(self):
return self.indexerIntake().withTimeout(0.005)\
.andThen(self.stopIndexer()).withName("LevelIndexer")
# .andThen(self.indexerOuttake().withTimeout(0.1))\
# .andThen(self.indexerIntake().until(self.getBeamBreakState))\
# .andThen(self.indexerOuttake().withTimeout(0.1))\
def stopMotor(self):
self.indexerMotor.set(TalonSRXControlMode.PercentOutput, 0.0)
def instantStop(self):
return InstantCommand(lambda: self.indexerMotor.set(TalonSRXControlMode.PercentOutput, 0.0)).withName("InstantStop")
def stopIndexer(self):
return self.run(lambda: self.indexerMotor.set(TalonSRXControlMode.PercentOutput, 0.0)).withName("StopIndexer")
| 3,497 | Python | 48.267605 | 264 | 0.750071 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Climber.py | from commands2.subsystem import Subsystem
from commands2.cmd import waitSeconds, waitUntil
import wpimath.filter
import wpimath
import wpilib
import phoenix6
from wpimath.geometry import Rotation2d, Pose3d, Pose2d, Rotation3d
from phoenix6.hardware.talon_fx import TalonFX
from phoenix6.controls import VelocityVoltage, VoltageOut, StrictFollower, DutyCycleOut, PositionVoltage
from phoenix6.signals import InvertedValue, NeutralModeValue
from lib.mathlib.conversions import Conversions
import math
from constants import Constants
from phoenix6.configs.talon_fx_configs import TalonFXConfiguration
from copy import deepcopy
from commands2 import InstantCommand
class Climber(Subsystem):
def __init__(self):
self.kLeftClimberCANID = 4
self.kRightClimberCANID = 15
self.leftClimber = TalonFX(self.kLeftClimberCANID)
self.rightClimber = TalonFX(self.kRightClimberCANID)
self.gearRatio = 1.0/14.2
self.wheelCircumference = 0.01905*math.pi
self.leftClimberConfig = TalonFXConfiguration()
self.rightClimberConfig = TalonFXConfiguration()
self.leftClimberConfig.slot0.k_p = 10.0
self.leftClimberConfig.slot0.k_i = 0.0
self.leftClimberConfig.slot0.k_d = 0.0
self.leftClimberConfig.motor_output.neutral_mode = NeutralModeValue.BRAKE
self.leftClimberConfig.current_limits.supply_current_limit_enable = True
self.leftClimberConfig.current_limits.supply_current_limit = 40
self.leftClimberConfig.current_limits.supply_current_threshold = 40
self.leftClimberConfig.current_limits.stator_current_limit_enable = True
self.leftClimberConfig.current_limits.stator_current_limit = 40
self.rightClimberConfig = deepcopy(self.leftClimberConfig)
self.rightClimberConfig.motor_output.inverted = InvertedValue.COUNTER_CLOCKWISE_POSITIVE
self.leftClimberConfig.motor_output.inverted = InvertedValue.COUNTER_CLOCKWISE_POSITIVE
self.rightClimberConfig.software_limit_switch.reverse_soft_limit_enable = True
self.rightClimberConfig.software_limit_switch.reverse_soft_limit_threshold = -97 # TODO: Change this value
self.rightClimberConfig.software_limit_switch.forward_soft_limit_enable = True
self.rightClimberConfig.software_limit_switch.forward_soft_limit_threshold = 0.0
self.leftClimberConfig.software_limit_switch.reverse_soft_limit_enable = True
self.leftClimberConfig.software_limit_switch.reverse_soft_limit_threshold = -97 # TODO: leftClimberConfig
self.leftClimberConfig.software_limit_switch.forward_soft_limit_enable = True
self.leftClimberConfig.software_limit_switch.forward_soft_limit_threshold = 0.0
self.leftClimber.configurator.apply(self.leftClimberConfig)
self.rightClimber.configurator.apply(self.rightClimberConfig)
self.dutyCycleControl = DutyCycleOut(0).with_enable_foc(True)
self.velocityControl = VelocityVoltage(0).with_enable_foc(True)
self.VoltageControl = VoltageOut(0).with_enable_foc(True)
self.leftClimbervelocitySupplier = self.leftClimber.get_velocity().as_supplier()
self.rightClimbervelocitySupplier = self.rightClimber.get_velocity().as_supplier()
self.ZeroingVelocityTolerance = 100.0
# Conversions.MPSToRPS(circumference=self.wheelCircumference, wheelMPS=velocity)*self.gearRatio)
def setClimbers(self, percentOutput):
self.leftClimber.set_control(self.dutyCycleControl.with_output(percentOutput))
self.rightClimber.set_control(self.dutyCycleControl.with_output(percentOutput))
# print(Conversions.MPSToRPS(velocity, self.wheelCircumference)*self.gearRatio)
def setClimbersLambda(self, climberAxis):
return self.run(lambda: self.setClimbers(climberAxis())).withName("Manual Climbers")
def runClimbersUp(self):
return self.run(lambda: self.setClimbers(-Constants.ClimberConstants.kClimberSpeed)).withName("Climbers Up")
# .andThen(
# self.detectStallAtHardStopLeft().alongWith(self.detectStallAtHardStopRight())
# )\
# .finallyDo(self.stopClimbers()).withName("Climbers Up")
def stopClimbers(self):
return self.run(lambda: self.setClimbers(0.0)).withName("Stop Climbers")
def runClimbersDown(self):
return self.run(lambda: self.setClimbers(Constants.ClimberConstants.kClimberSpeed)).withName("Climbers Down")
def isNear(self, a, b, tolerance):
# if abs(a - b) < tolerance:
# return True
return abs(a - b) < tolerance
def detectStallAtHardStopLeft(self):
stallDebouncer = wpimath.filter.Debouncer(1.0, wpimath.filter.Debouncer.DebounceType.kRising)
return waitUntil(lambda: stallDebouncer
.calculate(self.isNear(
0.0,
self.leftClimber.get_velocity().value_as_double,
self.ZeroingVelocityTolerance)
)
).finallyDo(lambda: self.leftClimber.set_control(self.VoltageControl.with_output(0.0)))
def detectStallAtHardStopRight(self):
stallDebouncer = wpimath.filter.Debouncer(1.0, wpimath.filter.Debouncer.DebounceType.kRising)
return waitUntil(lambda: stallDebouncer
.calculate(self.isNear(
0.0,
self.rightClimber.get_velocity(),
self.ZeroingVelocityTolerance)
)
).finallyDo(lambda: self.rightClimber.set_control(self.VoltageControl.with_output(0.0)))
| 5,557 | Python | 46.504273 | 117 | 0.725391 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Vision.py | from commands2 import Subsystem
from photonlibpy.photonCamera import PhotonCamera, VisionLEDMode, Packet
from photonlibpy.photonPoseEstimator import PhotonPoseEstimator, PoseStrategy
from photonlibpy.photonPipelineResult import PhotonPipelineResult
from lib.util.PhotonUtils import PhotonUtils
from robotpy_apriltag import AprilTagFieldLayout, AprilTagField, loadAprilTagLayoutField
from wpimath.geometry import Pose2d, Transform2d, Transform3d, Pose3d, Rotation2d, Rotation3d, Translation2d, Translation3d
import wpimath.units as Units
from constants import Constants
from wpilib import SmartDashboard, DriverStation
from typing import Callable
import math
class Vision(Subsystem):
instance = None
def __init__(self):
try:
self.camera : PhotonCamera | None = PhotonCamera("camera1")
except:
self.camera : PhotonCamera | None = None
print("========= NO PHOTON CAMERA FOUND =========")
self.aprilTagFieldLayout = loadAprilTagLayoutField(AprilTagField.k2024Crescendo)
self.speakerPositionBlue = Pose2d(Units.inchesToMeters(-1.50), Units.inchesToMeters(218.42), Rotation2d())
self.speakerPositionRed = Pose2d(Units.inchesToMeters(652.73), Units.inchesToMeters(218.42), Rotation2d.fromDegrees(180.0))
self.distanceSpeakerFieldToCamera = 0.0
# Right = 6.5 in
# Up = 11.5 in
# Froward = (frame / 2.0) - 1.25 in
self.robotToCamera = Transform3d(
Translation3d(-Units.inchesToMeters((31.125 / 2.0) - 1.25), -Units.inchesToMeters(6.5), Units.inchesToMeters(11.5)),
Rotation3d.fromDegrees(0.0, -45.0, 180.0)
)
self.fieldToCamera = Transform3d()
if self.camera is not None:
try:
self.photonPoseEstimator = PhotonPoseEstimator(
self.aprilTagFieldLayout,
PoseStrategy.MULTI_TAG_PNP_ON_COPROCESSOR,
self.camera,
self.robotToCamera
)
self.photonPoseEstimator.multiTagFallbackStrategy = PoseStrategy.LOWEST_AMBIGUITY
except:
self.photonPoseEstimator = None
print("===== PHOTON PROBLEM (POSE ESTIMATOR) =======")
self.CAMERA_HEIGHT_METERS = Units.inchesToMeters(11.5)
self.SPEAKER_HEIGHT_METERS = 1.45 # meters
self.CAMERA_PITCH_RADIANS = Rotation2d.fromDegrees(-45.0)
self.instance : Vision = None
@classmethod
def getInstance(cls):
if cls.instance == None:
cls.instance = Vision()
return cls.instance
def getEstimatedGlobalPose(self):
if self.camera is None or self.photonPoseEstimator is None:
return None
return self.photonPoseEstimator.update()
def getDistanceToSpeakerFieldToCameraFeet(self, fieldToCamera: Pose2d):
pose = fieldToCamera
speakerPos = self.speakerPositionBlue
if DriverStation.getAlliance() == DriverStation.Alliance.kRed:
speakerPos = self.speakerPositionRed
else:
speakerPos = self.speakerPositionBlue
distanceToSpeakerFieldToCamera = Units.metersToFeet(
PhotonUtils.getDistanceToPose(pose, speakerPos)
)
return distanceToSpeakerFieldToCamera - (36.37 / 12.0)
def getDistanceVectorToSpeaker(self, pose: Pose2d):
speakerPos = self.speakerPositionBlue
if DriverStation.getAlliance() == DriverStation.Alliance.kRed:
speakerPos = self.speakerPositionRed
else:
speakerPos = self.speakerPositionBlue
distanceVector = PhotonUtils.getDistanceVectorToPose(pose, speakerPos)
return distanceVector
def getAngleToSpeakerFieldToCamera(self, fieldToCamera: Pose2d):
pose = fieldToCamera
speakerPos = self.speakerPositionBlue
if DriverStation.getAlliance() == DriverStation.Alliance.kRed:
speakerPos = self.speakerPositionRed
else:
speakerPos = self.speakerPositionBlue
dx = speakerPos.X() - pose.X()
dy = speakerPos.Y() - pose.Y()
angleToSpeakerFieldToCamera = Rotation2d(math.atan2(dy, dx))
return angleToSpeakerFieldToCamera
def getCamera(self):
return self.camera
def hasTargetBooleanSupplier(self):
return lambda: self.camera.getLatestResult().hasTargets()
def takeSnapshot(self):
self.camera.takeInputSnapshot()
def setPipeline(self, pipelineIdx):
self.camera.setPipelineIndex(pipelineIdx)
def setTagMode(self):
self.setPipeline(0)
def getBestTarget(self, result : PhotonPipelineResult):
targets = result.getTargets()
# sort targets by area largest to smallest
targets.sort(key=lambda target: target.area, reverse=True)
if len(targets) <= 0:
return None
return targets[0]
def isTargetSeen(self, tagID) -> bool:
if self.camera is None:
return False
result = self.camera.getLatestResult()
if result.hasTargets() == False:
return False
best_target = self.getBestTarget(result)
return best_target.getFiducialId() == tagID
def isTargetSeenLambda(self, tagIDSupplier: Callable[[], int]) -> bool:
if self.camera is None:
return False
result = self.camera.getLatestResult()
if result.hasTargets() == False:
return False
best_target = self.getBestTarget(result)
return best_target.getFiducialId() == tagIDSupplier()
def getSortedTargetsList(self, result: PhotonPipelineResult):
targets = result.getTargets()
targets.sort(key=lambda target: target.area, reverse=True)
return targets
def getAngleToTag(self, tagIDSupplier: Callable[[], int]):
if self.camera is None:
return 0.0
if self.isTargetSeenLambda(tagIDSupplier):
result = self.camera.getLatestResult()
best_target = self.getBestTarget(result)
if best_target is not None:
return best_target.getYaw()
else:
return 0.0
else:
return 0.0
# def periodic(self):
# # if self.camera is not None:
# result = self.camera.getLatestResult()
# if result.multiTagResult.estimatedPose.isPresent:
# self.fieldToCamera = result.multiTagResult.estimatedPose.best
# hasTargets = result.hasTargets()
# if hasTargets:
# # get the best tag based on largest areaprint(f"================ {Units.inchesToMeters(self.s_Vision.getDistanceToSpeakerFieldToCameraInches(Transform3d(0.0, 0.0, 0.0, Rotation3d())))}")
# bestTarget = self.getBestTarget(result)
# if bestTarget is not None:
# SmartDashboard.putNumber("tag ID", bestTarget.getFiducialId())
# SmartDashboard.putNumber("pose ambiguity", bestTarget.getPoseAmbiguity())
# SmartDashboard.putNumber("tag transform X", bestTarget.getBestCameraToTarget().X())
# SmartDashboard.putNumber("tag transform Y", bestTarget.getBestCameraToTarget().Y())
# SmartDashboard.putNumber("tag transform Z", bestTarget.getBestCameraToTarget().Z())
# SmartDashboard.putNumber("tag transform angle", bestTarget.getBestCameraToTarget().rotation().angle_degrees)
# SmartDashboard.putNumber("tag yaw", bestTarget.getYaw())()
# SmartDashboard.putNumber("Vision Pose X", self.getEstimatedGlobalPose().estimatedPose.X())
# SmartDashboard.putNumber("Vision Pose Y", self.getEstimatedGlobalPose().estimatedPose.Y())
# SmartDashboard.putNumber("Vision Pose Angle", self.getEstimatedGlobalPose().estimatedPose.rotation().angle_degrees)
| 8,021 | Python | 35.967742 | 204 | 0.644184 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/intake.py | from constants import Constants
from commands2.subsystem import Subsystem
from phoenix5 import TalonSRX, TalonSRXConfiguration, TalonSRXControlMode, SupplyCurrentLimitConfiguration
from commands2 import InstantCommand
from wpilib import DigitalInput
from wpimath.filter import Debouncer
import math
class Intake(Subsystem):
def __init__(self):
self.intakeMotor = TalonSRX(Constants.IntakeConstants.kIntakeMotorID)
self.intakeMotor.configFactoryDefault()
current_limit = 40
current_threshold = 60
current_threshold_time = 3.0
supply_configs = SupplyCurrentLimitConfiguration(True, current_limit, current_threshold, current_threshold_time)
self.intakeMotor.configSupplyCurrentLimit(supply_configs)
self.intakeSpeed = 1.0
self.intakeBeam = DigitalInput(1)
# self.intakeMotor.configContinuousCurrentLimit(30)
# self.intakeMotor.enableCurrentLimit(True)
self.debouncer = Debouncer(0.05, Debouncer.DebounceType.kBoth)
def getIntakeBeamBreakState(self):
return not bool(self.intakeBeam.get())
def intake(self):
return self.run(lambda: self.intakeMotor.set(TalonSRXControlMode.PercentOutput, self.intakeSpeed)).withName("Intake")
def intakeOnce(self):
return self.runOnce(lambda: self.intakeMotor.set(TalonSRXControlMode.PercentOutput, self.intakeSpeed)).withName("IntakeOnce")
def outtake(self):
return self.run(lambda: self.intakeMotor.set(TalonSRXControlMode.PercentOutput, -self.intakeSpeed)).withName("Outtake")
def instantStop(self):
return InstantCommand(lambda: self.intakeMotor.set(TalonSRXControlMode.PercentOutput, 0.0)).withName("InstantStop")
def stopIntake(self):
return self.run(lambda: self.intakeMotor.set(TalonSRXControlMode.PercentOutput, 0.0)).withName("StopIntake") | 1,875 | Python | 39.782608 | 133 | 0.746133 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Shooter.py | from commands2.subsystem import Subsystem
import wpimath.filter
import wpimath
import wpilib
import phoenix6
from wpimath.geometry import Rotation2d, Pose3d, Pose2d, Rotation3d
from phoenix6.hardware.talon_fx import TalonFX
from phoenix6.controls import VelocityVoltage, VoltageOut, StrictFollower, DutyCycleOut
from phoenix6.signals import InvertedValue, NeutralModeValue
from lib.mathlib.conversions import Conversions
import math
from constants import Constants
from phoenix6.configs.talon_fx_configs import TalonFXConfiguration
from copy import deepcopy
from commands2 import InstantCommand, Command
class Shooter(Subsystem):
def __init__(self):
self.kBottomShooterCANID = 6
self.kTopShooterCANID = 13
self.bottomShooter = TalonFX(self.kBottomShooterCANID)
self.topShooter = TalonFX(self.kTopShooterCANID)
self.gearRatio = 1.0
self.wheelCircumference = 0.101*math.pi
self.topShooterConfig = TalonFXConfiguration()
self.topShooterConfig.slot0.k_v = (1/(Conversions.MPSToRPS(Constants.ShooterConstants.kPodiumShootSpeed, self.wheelCircumference)*self.gearRatio))
self.topShooterConfig.slot0.k_p = 1.5
self.topShooterConfig.slot0.k_i = 0.0
self.topShooterConfig.slot0.k_d = 0.0
self.topShooterConfig.motor_output.neutral_mode = NeutralModeValue.COAST
self.topShooterConfig.current_limits.supply_current_limit_enable = True
self.topShooterConfig.current_limits.supply_current_limit = 30
self.topShooterConfig.current_limits.supply_current_threshold = 50
self.topShooterConfig.current_limits.supply_time_threshold = Constants.Swerve.driveCurrentThresholdTime
self.topShooterConfig.current_limits.stator_current_limit_enable = True
self.topShooterConfig.current_limits.stator_current_limit = 50
self.bottomShooterConfig = deepcopy(self.topShooterConfig)
self.topShooterConfig.motor_output.inverted = InvertedValue.CLOCKWISE_POSITIVE
self.bottomShooterConfig.motor_output.inverted = InvertedValue.CLOCKWISE_POSITIVE
self.topShooter.configurator.apply(self.topShooterConfig)
self.bottomShooter.configurator.apply(self.bottomShooterConfig)
self.VelocityControl = VelocityVoltage(0).with_enable_foc(False)
self.VoltageControl = VoltageOut(0).with_enable_foc(False)
self.percentOutput = DutyCycleOut(0).with_enable_foc(False)
self.currentShotVelocity = 0.0
self.topShooterVelocitySupplier = self.topShooter.get_velocity().as_supplier()
self.bottomShooterVelocitySupplier = self.bottomShooter.get_velocity().as_supplier()
def setShooterVelocity(self, velocity):
self.topShooter.set_control(self.VelocityControl.with_velocity(Conversions.MPSToRPS(velocity, self.wheelCircumference)*self.gearRatio))
self.bottomShooter.set_control(self.VelocityControl.with_velocity(Conversions.MPSToRPS(velocity, self.wheelCircumference)*self.gearRatio))
self.currentShotVelocity = Conversions.MPSToRPS(velocity, self.wheelCircumference)*self.gearRatio
def shootVelocity(self, velocity) -> Command:
return self.run(lambda: self.setShooterVelocity(velocity)).withName("ShootVelocity")
def shootVelocityWithSupplier(self, velSup):
return self.run(lambda: self.setShooterVelocity(velSup())).withName("ShootVelocity")
def neutralizeShooter(self):
# self.topShooterConfig.motor_output.neutral_mode = NeutralModeValue.COAST
# self.bottomShooterConfig.motor_output.neutral_mode = NeutralModeValue.COAST
# self.topShooter.configurator.apply(self.topShooterConfig)
# self.bottomShooter.configurator.apply(self.bottomShooterConfig)
self.topShooter.set_control(self.VoltageControl.with_output(0).with_override_brake_dur_neutral(False))
self.bottomShooter.set_control(self.VoltageControl.with_output(0).with_override_brake_dur_neutral(False))
def idle(self):
return self.run(lambda: self.setShooterVelocity(Constants.ShooterConstants.kAmpShootSpeed)).withName("IdleShooter")
def shoot(self):
return self.run(lambda: self.setShooterVelocity(Constants.ShooterConstants.kSubwooferShootSpeed)).withName("Shoot")
def amp(self):
return self.run(lambda: self.setShooterVelocity(Constants.ShooterConstants.kAmpShootSpeed)).withName("Amp")
def shootReverse(self):
return self.run(lambda: self.setShooterVelocity(-Constants.ShooterConstants.kPodiumShootSpeed)).withName("ShootReverse")
def isShooterReady(self, isAuto=False):
if not isAuto:
topShooterReady = abs(self.topShooterVelocitySupplier() - self.currentShotVelocity) < 5
bottomShooterReady = abs(self.bottomShooterVelocitySupplier() - self.currentShotVelocity) < 5
else:
topShooterReady = abs(self.topShooterVelocitySupplier() - Conversions.MPSToRPS(Constants.ShooterConstants.kSubwooferShootSpeed, self.wheelCircumference)*self.gearRatio) < 5
bottomShooterReady = abs(self.bottomShooterVelocitySupplier() - self.currentShotVelocity) < 5
return topShooterReady and bottomShooterReady
def isShooterAtSubwooferSpeed(self):
if abs(self.topShooterVelocitySupplier() - Conversions.MPSToRPS(Constants.ShooterConstants.kSubwooferShootSpeed, self.wheelCircumference)*self.gearRatio) < 5:
return True
return False
def brake(self):
# self.topShooterConfig.motor_output.neutral_mode = NeutralModeValue.BRAKE
# self.topShooter.configurator.apply(self.topShooterConfig)
self.topShooter.set_control(self.VoltageControl.with_output(0).with_override_brake_dur_neutral(True))
# self.bottomShooterConfig.motor_output.neutral_mode = NeutralModeValue.BRAKE
# self.bottomShooter.configurator.apply(self.bottomShooterConfig)
self.bottomShooter.set_control(self.VoltageControl.with_output(0).with_override_brake_dur_neutral(True))
def stop(self):
return self.run(lambda: self.neutralizeShooter()).withName("StopShooter")
def getTargetVelocity(self):
return Conversions.RPSToMPS(self.currentShotVelocity, self.wheelCircumference)/self.gearRatio
def getVelocity(self):
return Conversions.RPSToMPS(self.topShooterVelocitySupplier(), self.wheelCircumference)/self.gearRatio | 6,419 | Python | 49.952381 | 185 | 0.753856 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Arm.py | from commands2.subsystem import Subsystem
# from commands2.subsystem import Command
from commands2 import WaitCommand
from commands2 import WaitUntilCommand
from commands2 import cmd
import wpimath.filter
import wpimath
import wpilib
from wpilib.shuffleboard import Shuffleboard
import phoenix5
from phoenix5 import TalonSRXControlMode, TalonSRXFeedbackDevice, SupplyCurrentLimitConfiguration, StatorCurrentLimitConfiguration
import math
class Arm(Subsystem):
#
# The motion magic parameters are configured in slot 0. Slot 1 is configured
# for velocity control for zeroing.
#
def __init__(self):
self.kArmMotorCANId = 5
self.kMeasuredTicksWhenHorizontal = 0
self.kEncoderTickPerEncoderRotation = 4096*2
self.kEncoderToArmGearRatio = 1.0
self.kEncoderTicksPerArmRotation = self.kEncoderTickPerEncoderRotation * self.kEncoderToArmGearRatio
self.kEncoderTicksPerDegreeOfArmMotion = self.kEncoderTicksPerArmRotation / 360.0
self.kMotionMagicSlot = 0
self.kVelocitySlot = 1
self.MaxGravityFF = 0.26 #0.26 # In percent output [1.0:1.0]
self.kF = 0.5
self.kPMotionMagic = 1.5 #4.0
self.kPVelocity = 1.0 #0.8
self.kIMotionMagic = 0.003
self.kIZoneMotionMagic = 3.0*self.kEncoderTicksPerDegreeOfArmMotion
self.kDMotionMagic = 0.4 #0.4
self.kCruiseVelocity = 1000.0 # ticks per 100ms
self.kMaxAccel = 1000.0 # Accel to cruise in 1 sec
self.kServoToleranceDegrees = 0.5 # +/- 1.0 for 2.0 degree window
# Velocity for safely zeroing arm encoder in native units (ticks) per 100ms
self.kZeroEncoderVelocity = -self.kEncoderTicksPerDegreeOfArmMotion * 6.5
self.kZeroingWaitForMoveSec = 2.0
self.ZeroingVelocityTolerance = 2.0
self.armMotor = phoenix5.TalonSRX(self.kArmMotorCANId)
# True when servo control active and false otherwise.
self.isServoControl = False
# The last requested servo target for target checking.
self.lastServoTarget = 0.0
self.kRestingAtZero = False
# Configure REV Through Bore Encoder as the arm's remote sensor
self.armMotor.configSelectedFeedbackSensor(TalonSRXFeedbackDevice.QuadEncoder)
self.armMotor.setSensorPhase(True)
self.armMotor.setInverted(False)
self.armMotor.config_kP(self.kMotionMagicSlot, self.kPMotionMagic)
self.armMotor.config_kI(self.kMotionMagicSlot, self.kIMotionMagic)
self.armMotor.config_IntegralZone(self.kMotionMagicSlot, self.kIZoneMotionMagic)
self.armMotor.config_kD(self.kMotionMagicSlot, self.kDMotionMagic)
self.armMotor.config_kF(self.kMotionMagicSlot, self.kF)
self.armMotor.configAllowableClosedloopError(self.kMotionMagicSlot, self.kServoToleranceDegrees*self.kEncoderTicksPerDegreeOfArmMotion)
self.armMotor.configMotionCruiseVelocity(self.kCruiseVelocity)
self.armMotor.configMotionAcceleration(self.kMaxAccel)
self.armMotor.config_kP(self.kVelocitySlot, self.kPVelocity)
self.armMotor.config_kI(self.kVelocitySlot, 0.002)
self.armMotor.config_kD(self.kVelocitySlot, 0.7)
self.armMotor.config_kF(self.kVelocitySlot, self.kF)
self.armMotor.config_IntegralZone(self.kVelocitySlot, self.kIZoneMotionMagic)
self.armMotor.configAllowableClosedloopError(self.kVelocitySlot, self.kServoToleranceDegrees*self.kEncoderTicksPerDegreeOfArmMotion)
current_limit = 20
current_threshold = 40
current_threshold_time = 0.1
supply_configs = SupplyCurrentLimitConfiguration(True, current_limit, current_threshold, current_threshold_time)
self.armMotor.configSupplyCurrentLimit(supply_configs)
Shuffleboard.getTab("Teleoperated").addDouble("Arm degrees", self.getDegrees)
# SmartDashboard.putData("Arm", self)
#
# Creates a command to seek the arm's zero position. This command is designed
# to always be used for returning to and settling at zero. It should be the
# subsystem's default command. The encoder will be reset to 0.
#
# @return a command that will move the arm toward 0, and stop when stalled.
#
def seekArmZero(self):
return self.runOnce(lambda: self.selectPIDSlot(self.kVelocitySlot))\
.andThen(self.servoArmToTarget(0.0).onlyIf(lambda: self.getDegrees() >= 15).withTimeout(2.5))\
.andThen(self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.Velocity,
self.kZeroEncoderVelocity)))\
.raceWith(cmd.waitSeconds(self.kZeroingWaitForMoveSec) \
.andThen(self.detectStallAtHardStop())) \
.andThen(self.restingAtZero()) \
.withName("seekArmZero")
# phoenix5.DemandType.ArbitraryFeedForward,
# self.calculateGravityFeedForward()))) \
# .andThen(self.servoArmToTarget(0.5).onlyIf(lambda: self.getDegrees() >= 15))\
def isNear(self, a, b, tolerance):
# if abs(a - b) < tolerance:
# return True
return abs(a - b) < tolerance
#
# Creates a command to detect stall at the hard stop during
# {@link #seekArmZero()}.
#
# @return the hard stop detection command.
#
def detectStallAtHardStop(self):
stallDebouncer = wpimath.filter.Debouncer(1.0, wpimath.filter.Debouncer.DebounceType.kRising)
return cmd.waitUntil(lambda: stallDebouncer
.calculate(self.isNear(
0.0,
self.armMotor.getSelectedSensorVelocity(self.kVelocitySlot),
self.ZeroingVelocityTolerance)
)
)
#
# Should only be called as the last step of {@link #seekArmZero()}. The encoder
# is reset to 0.
#
# @return a command to rest at the hard stop at 0 and on target.
#
def restingAtZero(self):
return self.runOnce(lambda: self.setRestingAtZero(True)) \
.andThen(self.run(lambda: self.armMotor.set(phoenix5.ControlMode.Velocity,0.0)).withTimeout(1.0)) \
.andThen(lambda: self.hardSetEncoderToZero() ) \
.andThen(self.run(lambda: self.armMotor.set(phoenix5.ControlMode.Velocity,-0.1))) \
.finallyDo(lambda interrupted: self.setRestingAtZero(False))
def setRestingAtZero(self, restAtZero):
self.kRestingAtZero = restAtZero
def hardSetEncoderToZero(self):
self.armMotor.setSelectedSensorPosition(0)
def holdPosition(self):
# return a command that will hold the arm in place
return self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.MotionMagic,
self.armMotor.getSelectedSensorPosition(),
phoenix5.DemandType.ArbitraryFeedForward,
self.calculateGravityFeedForward())) \
.withName("holdPosition")
#
# Creates a command to servo the arm to a desired angle. Note that 0 is
# parallel to the ground. The entire operation is run with
# {@link m_isServoControl} set to true to enable on target checking. See
# {@link #isServoOnTarget(double)}.
#
# <p>
# If the target is 0 or less, the command from {@link #seekArmZero()} is
# returned.
#
# @param degrees the target degrees from 0. Must be positive.
# @return a command that will servo the arm and will not end until interrupted
# by another command.
#
def servoArmToTarget(self, degrees):
targetSensorUnits = degrees * self.kEncoderTicksPerDegreeOfArmMotion
return self.runOnce(lambda: self.initializeServoArmToTarget(degrees)) \
.andThen(self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.MotionMagic,
targetSensorUnits))) \
.finallyDo(lambda interrupted: self.setServoControl(False)) \
.withName("servoArmToTarget: " + str(degrees))
#phoenix5.DemandType.ArbitraryFeedForward,
# self.calculateGravityFeedForward()
def servoArmToTargetGravity(self, degrees):
targetSensorUnits = degrees * self.kEncoderTicksPerDegreeOfArmMotion
return self.runOnce(lambda: self.initializeServoArmToTarget(degrees)) \
.andThen(self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.MotionMagic,
targetSensorUnits,
phoenix5.DemandType.ArbitraryFeedForward,
self.calculateGravityFeedForward()))) \
.finallyDo(lambda interrupted: self.setServoControl(False)) \
.withName("servoArmToTarget: " + str(degrees))
#phoenix5.DemandType.ArbitraryFeedForward,
# self.calculateGravityFeedForward()
def servoArmToTargetWithSupplier(self, degreesSup):
# if (degreesSup() <= 0.0):
# return self.seekArmZero()
return self.runOnce(lambda: self.initializeServoArmToTarget(degreesSup().m_armAngle)) \
.andThen(self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.MotionMagic,
degreesSup().m_armAngle * self.kEncoderTicksPerDegreeOfArmMotion,
phoenix5.DemandType.ArbitraryFeedForward,
self.calculateGravityFeedForward()))) \
.finallyDo(lambda interrupted: self.setServoControl(False)) \
.withName("servoArmToTarget: " + str(degreesSup().m_armAngle))
def servoArmToTargetDynamic(self, degreesSup):
return self.runOnce(lambda: self.initializeServoArmToTarget(degreesSup())) \
.andThen(self.run(lambda: self.armMotor.set(
phoenix5.ControlMode.MotionMagic,
degreesSup() * self.kEncoderTicksPerDegreeOfArmMotion,
phoenix5.DemandType.ArbitraryFeedForward,
self.calculateGravityFeedForward()))) \
.finallyDo(lambda interrupted: self.setServoControl(False)) \
.withName("servoArmToTarget: " + str(degreesSup()))
def initializeServoArmToTarget(self, degrees):
self.lastServoTarget = degrees
self.setServoControl(True)
if degrees > 45.0:
self.selectPIDSlot(self.kVelocitySlot)
else:
self.selectPIDSlot(self.kMotionMagicSlot)
def setServoControl(self, servoControl):
self.isServoControl = servoControl
#
# This method should rarely be used. It is for pure manual control (no encoder
# usage) which should be avoided.
#
# @param percentOutput the commanded output [-1.0..1.0]. Positive is up.
# @return a command that drives the arm via double supplier.
#
def moveArm(self, percentOutput):
return self.run(lambda: self.armMotor.set(TalonSRXControlMode.PercentOutput, -percentOutput() * 0.4)) \
.withName("moveArm")
#
# Assuming a properly zeroed arm (0 degrees is parallel to the ground), return
# the current angle adjusted gravity feed forward.
#
# @return the current angle adjusted gravity feed forward.
#
def calculateGravityFeedForward(self):
degrees = self.getDegrees()
radians = math.radians(degrees)
cosineScalar = math.cos(radians)
return self.MaxGravityFF * cosineScalar
#
# Assuming a properly zeroed arm (0 degrees is parallel to the ground), return
# the current arm angle.
#
# @return the current arm angle in degrees from 0.
#
def getDegrees(self):
currentPos = self.armMotor.getSelectedSensorPosition()
return (currentPos - self.kMeasuredTicksWhenHorizontal) / self.kEncoderTicksPerDegreeOfArmMotion
#
# Returns true if the arm is under servo control and we are close to the last
# requested target degrees.
#
# @return true if under servo control and close, false otherwise.
#
def isServoOnTarget(self):
return self.kRestingAtZero \
or (self.isServoControl \
and self.isNear(self.lastServoTarget, self.getDegrees(), self.kServoToleranceDegrees))
#
# Selects the specified slot for the next PID controlled arm movement. Always
# selected for primary closed loop control.
#
# @param slot the PID slot
#
def selectPIDSlot(self, slot):
self.armMotor.selectProfileSlot(slot, 0)
def stop(self):
return self.run(lambda: self.armMotor.set(TalonSRXControlMode.Velocity, 0.0)).withName("ArmStop")
#
# Updates the dashboard with critical arm data.
#
# def periodic(self) :
# # TODO reduce this to essentials.
# # wpilib.SmartDashboard.putNumber("Arm current", self.armMotor.getStatorCurrent())
# # wpilib.SmartDashboard.putBoolean("Arm on target", self.isServoOnTarget())
# # currentCommand = self.getCurrentCommand()
# # wpilib.SmartDashboard.putString("Arm command", currentCommand.getName() if currentCommand is not None else "<null>")
# # wpilib.SmartDashboard.putNumber("Arm zeroing velocity", self.armMotor.getSelectedSensorVelocity(self.kVelocitySlot))
# # wpilib.SmartDashboard.putBoolean("Arm resting", self.kRestingAtZero)
# # wpilib.SmartDashboard.putBoolean("Servo control", self.isServoControl)
# # wpilib.SmartDashboard.putBoolean("Arm is near", self.isNear(self.lastServoTarget, self.getDegrees(), self.kServoToleranceDegrees)) | 13,606 | Python | 42.472843 | 143 | 0.668529 |
RoboEagles4828/rift2024/rio/srcrobot/subsystems/Led.py | from commands2 import Subsystem, Command, FunctionalCommand
import wpilib
from wpilib import PneumaticsControlModule, Solenoid
from constants import Constants
from gameState import GameState
from robotState import RobotState
from wpilib import PneumaticsControlModule, Solenoid
from constants import Constants
# This subsystem will continued to be developed as the season progresses
class LED(Subsystem):
gameState = GameState()
robotState = RobotState()
def __init__(self):
self.kLedPort = 0
self.pcm = PneumaticsControlModule(self.kLedPort)
self.pcm.disableCompressor() # only using for leds, so don't even use the compressor
self.redChan = self.pcm.makeSolenoid(1)
self.greenChan = self.pcm.makeSolenoid(0)
self.blueChan = self.pcm.makeSolenoid(2)
# self.redChan = Solenoid(wpilib.PneumaticsModuleType.CTREPCM, 1)
# self.greenChan = Solenoid(wpilib.PneumaticsModuleType.CTREPCM, 0)
# self.blueChan = Solenoid(wpilib.PneumaticsModuleType.CTREPCM, 2)
self.BLACK = 0
self.OFF = 0
self.RED = 1
self.YELLOW = 2
self.GREEN = 3
self.TEAL = 4
self.BLUE = 5
self.PURPLE = 6
self.WHITE = 7
def set(self, color): # BLACK - 0, RED - 1, YELLOW - 2, GREEN - 3, TEAL - 4, BLUE - 5, PURPLE - 6, WHITE - 7
if color == 0: # BLACK / OFF
self.redChan.set(False)
self.greenChan.set(False)
self.blueChan.set(False)
elif color == 1: # RED
self.redChan.set(True)
self.greenChan.set(False)
self.blueChan.set(False)
elif color == 2: # YELLOW
self.redChan.set(True)
self.greenChan.set(True)
self.blueChan.set(False)
elif color == 3: # GREEN
self.redChan.set(False)
self.greenChan.set(True)
self.blueChan.set(False)
elif color == 4: # TEAL
self.redChan.set(False)
self.greenChan.set(True)
self.blueChan.set(True)
elif color == 5: # BLUE
self.redChan.set(False)
self.greenChan.set(False)
self.blueChan.set(True)
elif color == 6: # PURPLE
self.redChan.set(True)
self.greenChan.set(False)
self.blueChan.set(True)
elif color == 7: # WHITE / ON
self.redChan.set(True)
self.greenChan.set(True)
self.blueChan.set(True)
self.last = None
# The robot is empty, that is, it has no note.
def empty(self):
self.last = self.RED
self.refreshLast()
# The robot may have just gotten two notes!!!
def suspectTwoNotes(self):
self.last = self.YELLOW
self.refreshLast()
# A note has been detected in the indexer.
def noteDetected(self):
self.last = self.PURPLE
self.refreshLast()
# The shooter and arm are ready for the selected shot.
def readytoShoot(self):
self.last = self.GREEN
self.refreshLast()
def noteInIntake(self):
self.last = self.BLUE
self.refreshLast()
def getStateCommand(self) -> Command:
"""
Return the default command for the LED subsystem. It initializes to empty
and executes evaluating the game and robot states to set the LEDs for the
rest of the match.
"""
return FunctionalCommand(
self.empty, self.setNextLED, lambda _: None, lambda: False, self
)
def setNextLED(self):
if not self.gameState.hasNote():
if not self.gameState.getNoteInIntake():
self.empty()
else:
self.noteInIntake()
# elif self.gameState.getNoteInIntake():
# self.suspectTwoNotes()
elif self.robotState.isShooterReady():
self.readytoShoot()
else:
self.noteDetected()
def refreshLast(self):
self.set(self.last)
| 4,033 | Python | 31.015873 | 112 | 0.59633 |
RoboEagles4828/rift2024/rio/srcrobot/sim/SwerveModuleSim.py | from wpimath.geometry import Rotation2d
from wpimath.kinematics import SwerveModulePosition, SwerveModuleState
from wpilib import Timer
class SwerveModuleSim():
def __init__(self) -> None:
self.timer = Timer()
self.timer.start()
self.lastTime = self.timer.get()
self.state = SwerveModuleState(0.0, Rotation2d.fromDegrees(0.0))
self.fakeSpeed = 0.0
self.fakePos = 0.0
self.dt = 0.0
def updateStateAndPosition(self, desiredState : SwerveModuleState) -> None:
self.dt = self.timer.get() - self.lastTime
self.lastTime = self.timer.get()
self.state = desiredState
self.fakeSpeed = desiredState.speed
self.fakePos += self.fakeSpeed * self.dt
def getPosition(self) -> SwerveModulePosition:
return SwerveModulePosition(self.fakePos, self.state.angle)
def getState(self) -> SwerveModuleState:
return self.state | 939 | Python | 32.571427 | 79 | 0.667732 |
RoboEagles4828/rift2024/rio/srcrobot/sim/SwerveIMUSim.py | from wpimath.geometry import Rotation2d, Pose2d, Rotation3d, Translation3d
from wpimath.kinematics import SwerveDrive4Kinematics, SwerveModuleState
from wpilib import Timer
from wpilib import Field2d
class SwerveIMUSim():
def __init__(self) -> None:
self.timer = Timer()
self.timer.start()
self.lastTime = self.timer.get()
self.angle = 0.0
def getYaw(self) -> Rotation2d:
return Rotation2d(self.angle).degrees()
def getPitch(self) -> Rotation2d:
return Rotation2d()
def getRoll(self) -> Rotation2d:
return Rotation2d()
def updateOdometry(self, kinematics: SwerveDrive4Kinematics, states: list[SwerveModuleState], modulePoses: list[Pose2d], field: Field2d) -> None:
self.angle += kinematics.toChassisSpeeds(states).omega * (self.timer.get() - self.lastTime)
self.lastTime = self.timer.get()
field.getObject("XModules").setPoses(modulePoses)
def setAngle(self, angle : float):
self.angle = angle
def zeroYaw(self):
self.setAngle(0.0) | 1,070 | Python | 33.548386 | 149 | 0.675701 |
RoboEagles4828/rift2024/rio/srcrobot/autos/PathPlannerAutoRunner.py | from commands2 import SequentialCommandGroup, InstantCommand, WaitCommand
from pathplannerlib.auto import PathPlannerAuto
from subsystems.Swerve import Swerve
from wpimath.kinematics import ChassisSpeeds
from wpimath.geometry import Rotation2d
from wpimath.trajectory import Trajectory, TrajectoryGenerator, TrajectoryConfig
from pathplannerlib.path import *
class PathPlannerAutoRunner:
def __init__(self, pathplannerauto, swerve):
self.pathplannerauto: str = pathplannerauto
self.swerve: Swerve = swerve
self.auto = PathPlannerAuto(self.pathplannerauto)
def getCommand(self):
return SequentialCommandGroup(
InstantCommand(lambda: self.swerve.setPose(self.auto.getStartingPoseFromAutoFile(self.pathplannerauto)), self.swerve),
self.auto,
InstantCommand(lambda: self.swerve.stop(), self.swerve)
).withName(self.pathplannerauto) | 914 | Python | 42.571427 | 130 | 0.765864 |
RoboEagles4828/rift2024/rio/srcrobot/autos/exampleAuto.py | from constants import Constants
from subsystems.Swerve import Swerve
from wpimath.controller import PIDController
from wpimath.controller import ProfiledPIDControllerRadians, HolonomicDriveController
from wpimath.geometry import Pose2d;
from wpimath.geometry import Rotation2d;
from wpimath.geometry import Translation2d;
from wpimath.trajectory import Trajectory;
from wpimath.trajectory import TrajectoryConfig;
from wpimath.trajectory import TrajectoryGenerator;
from commands2 import InstantCommand
from commands2 import SequentialCommandGroup
from commands2 import SwerveControllerCommand
import math as Math
class exampleAuto:
def __init__(self, s_Swerve: Swerve):
config = \
TrajectoryConfig(
Constants.AutoConstants.kMaxSpeedMetersPerSecond,
Constants.AutoConstants.kMaxAccelerationMetersPerSecondSquared
)
config.setKinematics(Constants.Swerve.swerveKinematics)
self.s_Swerve = s_Swerve
# An example trajectory to follow. All units in meters.
self.exampleTrajectory = \
TrajectoryGenerator.generateTrajectory(
# Start at the origin facing the +X direction
Pose2d(0, 2, Rotation2d(0)),
# Pass through these two interior waypoints, making an 's' curve path
[Translation2d(1, 3), Translation2d(2, 1)],
# End 3 meters straight ahead of where we started, facing forward
Pose2d(3, 2, Rotation2d(0)),
config
)
thetaController = \
ProfiledPIDControllerRadians(
Constants.AutoConstants.kPThetaController, 0, 0, Constants.AutoConstants.kThetaControllerConstraints)
thetaController.enableContinuousInput(-Math.pi, Math.pi)
self.holonomicController = HolonomicDriveController(
PIDController(Constants.AutoConstants.kPXController, 0, 0),
PIDController(Constants.AutoConstants.kPYController, 0, 0),
thetaController
)
self.swerveControllerCommand = \
SwerveControllerCommand(
self.exampleTrajectory,
s_Swerve.getPose,
Constants.Swerve.swerveKinematics,
self.holonomicController,
s_Swerve.setModuleStates,
(s_Swerve,)
)
def getCommand(self):
return InstantCommand(lambda: self.s_Swerve.setPose(self.exampleTrajectory.initialPose()), (self.s_Swerve,)).andThen(self.swerveControllerCommand) | 2,572 | Python | 39.203124 | 154 | 0.677294 |
RoboEagles4828/rift2024/rio/srcrobot/commands/TurnToTag.py | from commands2 import Command
from constants import Constants
from wpimath.controller import ProfiledPIDControllerRadians, PIDController
from subsystems.Swerve import Swerve
from subsystems.Vision import Vision
from commands.TeleopSwerve import TeleopSwerve
from wpimath.geometry import Translation2d, Rotation2d
from wpimath.trajectory import TrapezoidProfile
import math
from typing import Callable
class TurnToTag(TeleopSwerve):
def __init__(self, s_Swerve, s_Vision: Vision, translationSup, strafeSup, rotationSup, robotCentricSup):
super().__init__(s_Swerve, translationSup, strafeSup, rotationSup, robotCentricSup)
self.turnPID = PIDController(16.0, 0.0, 0.0)
self.turnPID.enableContinuousInput(-math.pi, math.pi)
self.currentRotation = rotationSup
self.s_Vision = s_Vision
self.s_Swerve = s_Swerve
def initialize(self):
super().initialize()
self.start_angle = self.s_Swerve.getHeading().radians()
self.turnPID.reset()
self.turnPID.setTolerance(math.radians(1))
self.turnPID.setSetpoint(0.0)
def getRotationValue(self):
rotationStick = self.currentRotation()
if abs(rotationStick) > 0.0:
return rotationStick*Constants.Swerve.maxAngularVelocity
elif self.turnPID.atSetpoint():
return 0.0
else:
self.angularvelMRadiansPerSecond = self.turnPID.calculate(self.s_Vision.getAngleToSpeakerFieldToCamera(self.s_Swerve.getPose()).radians(), 0.0)
return self.angularvelMRadiansPerSecond
def isFinished(self) -> bool:
return self.turnPID.atSetpoint() | 1,643 | Python | 40.099999 | 155 | 0.719416 |
RoboEagles4828/rift2024/rio/srcrobot/commands/DynamicShot.py | from subsystems.Vision import Vision
from subsystems.Swerve import Swerve
from subsystems.Arm import Arm
from constants import Constants
import lib.mathlib.units as Units
import math
from wpimath.geometry import Rotation2d, Translation2d, Transform2d
from wpilib import DriverStation, RobotBase
from robotState import RobotState
class DynamicShot():
def __init__(self, swerve: Swerve, vision: Vision, arm: Arm):
self.swerve = swerve
self.arm = arm
self.vision = vision
self.speakerTargetHeightMeters = Units.inchesToMeters(80.5)
self.robotState = RobotState()
def getArmAngle(self):
# distanceFromSpeaker = self.vision.getDistanceVectorToSpeaker(self.swerve.getPose()).norm()
# robotVelocity = self.swerve.getTranslationVelocity().rotateBy(self.swerve.getHeading())
# return math.degrees(math.atan(
# (self.speakerTargetHeightMeters - Units.inchesToMeters(Constants.Swerve.robotHeight)) / (distanceFromSpeaker + robotVelocity.X()*0.02)
# )) - Constants.ShooterConstants.kMechanicalAngle
return Constants.NextShot.DYNAMIC.calculateInterpolatedArmAngle(Units.metersToFeet(self.vision.getDistanceVectorToSpeaker(self.swerve.getPose()).norm()) - (36.37 / 12.0) - (Constants.Swerve.robotLength / 2.0 / 12.0))
def getTrigArmAngle(self):
distanceFromSpeaker = self.vision.getDistanceVectorToSpeaker(self.swerve.getPose()).norm() - (Units.inchesToMeters(Constants.Swerve.robotLength / 2.0)) + Units.inchesToMeters(math.cos(math.radians(self.arm.getDegrees())) * Constants.Swerve.armLength)
robotVelocity = self.swerve.getTranslationVelocity().rotateBy(self.swerve.getHeading())
robotHeight = (math.sin(math.radians(self.arm.getDegrees())) * Constants.Swerve.armLength) + 16.5
denom = distanceFromSpeaker + robotVelocity.X()*0.02
if DriverStation.getAlliance() == DriverStation.Alliance.kRed:
denom = distanceFromSpeaker - robotVelocity.X()*0.02
return math.degrees(math.atan(
denom / (self.speakerTargetHeightMeters - Units.inchesToMeters(robotHeight))
)) - Constants.ShooterConstants.kMechanicalAngle
def getInterpolatedArmAngle(self):
robotVelocity = self.swerve.getTranslationVelocity().rotateBy(self.swerve.getHeading())
nextPose = self.swerve.getPose().__add__(Transform2d(robotVelocity.__mul__(-0.02), Rotation2d()))
distance = Units.metersToFeet(self.vision.getDistanceVectorToSpeaker(nextPose).norm()) - (36.37 / 12.0) - (Constants.Swerve.robotLength / 2.0 / 12.0)
return Constants.NextShot.DYNAMIC.calculateInterpolatedArmAngle(distance)
def getRobotAngle(self):
distanceVector = self.vision.getDistanceVectorToSpeaker(self.swerve.getPose())
robotVelocity = self.swerve.getTranslationVelocity().rotateBy(self.swerve.getHeading())
angle = 90.0 - math.degrees(math.atan(
(distanceVector.X() - robotVelocity.X()*0.02) / (distanceVector.Y() - robotVelocity.Y()*0.02)
))
if angle >= 90:
angle = angle - 180
if DriverStation.getAlliance() == DriverStation.Alliance.kRed and DriverStation.isAutonomous():
return Rotation2d.fromDegrees(angle).rotateBy(Rotation2d.fromDegrees(180.0))
return Rotation2d.fromDegrees(angle)
def getRotationTarget(self):
if self.robotState.m_gameState.getNextShot() == Constants.NextShot.DYNAMIC:
return self.getRobotAngle()
else:
return None
| 3,557 | Python | 51.323529 | 258 | 0.709306 |
RoboEagles4828/rift2024/rio/srcrobot/commands/TurnInPlace.py | from commands2 import Command
from constants import Constants
from wpimath.controller import ProfiledPIDControllerRadians, PIDController
from subsystems.Swerve import Swerve
from commands.TeleopSwerve import TeleopSwerve
from wpimath.geometry import Translation2d, Rotation2d
from wpimath.trajectory import TrapezoidProfile
import math
from typing import Callable
class TurnInPlace(TeleopSwerve):
def __init__(self, s_Swerve, desiredRotationSup: Callable[[], Rotation2d], translationSup, strafeSup, rotationSup, robotCentricSup):
super().__init__(s_Swerve, translationSup, strafeSup, rotationSup, robotCentricSup)
self.turnPID = PIDController(5.0, 0.001, 0.0)
self.turnPID.setIZone(math.radians(2.0))
self.turnPID.enableContinuousInput(-math.pi, math.pi)
self.desiredRotationSupplier = desiredRotationSup
self.angle = desiredRotationSup().radians()
self.currentRotation = rotationSup
def initialize(self):
super().initialize()
self.start_angle = self.s_Swerve.getHeading().radians()
self.turnPID.reset()
self.turnPID.setTolerance(math.radians(0.5))
self.turnPID.setSetpoint(self.angle)
def getRotationValue(self):
rotationStick = self.currentRotation()
if abs(rotationStick) > 0.0:
return rotationStick*Constants.Swerve.maxAngularVelocity
elif self.turnPID.atSetpoint():
return 0.0
else:
self.angularvelMRadiansPerSecond = -self.turnPID.calculate(self.s_Swerve.getHeading().radians(), self.desiredRotationSupplier().radians())
return self.angularvelMRadiansPerSecond
def isFinished(self) -> bool:
return self.turnPID.atSetpoint() | 1,733 | Python | 43.461537 | 150 | 0.723024 |
RoboEagles4828/rift2024/rio/srcrobot/commands/SysId.py | from commands2.sysid import SysIdRoutine
from commands2 import SequentialCommandGroup, InstantCommand, WaitCommand, Command
from subsystems.Swerve import Swerve
class DriveSysId():
routine: SysIdRoutine
def __init__(self, s_Swerve: Swerve):
self.routine = SysIdRoutine(
SysIdRoutine.Config(),
SysIdRoutine.Mechanism(
s_Swerve.driveMotorsVoltage,
s_Swerve.logDriveMotors,
s_Swerve,
name="SwerveDrive"
)
)
self.swerve = s_Swerve
self.quasiStaticForward = self.routine.quasistatic(SysIdRoutine.Direction.kForward)
self.quasiStaticReverse = self.routine.quasistatic(SysIdRoutine.Direction.kReverse)
self.dynamicForward = self.routine.dynamic(SysIdRoutine.Direction.kForward)
self.dynamicReverse = self.routine.dynamic(SysIdRoutine.Direction.kReverse)
self.resetAngleMotors = InstantCommand(lambda: (s_Swerve.resetModulesToAbsolute()), s_Swerve)
self.generalCommand = SequentialCommandGroup(
self.resetAngleMotors,
InstantCommand(lambda: (s_Swerve.stop()), s_Swerve),
)
self.quasiForwardCommand = SequentialCommandGroup(
self.quasiStaticForward,
InstantCommand(lambda: (s_Swerve.stop()), s_Swerve),
WaitCommand(2),
)
self.quasiReverseCommand = SequentialCommandGroup(
self.quasiStaticReverse,
InstantCommand(lambda: (s_Swerve.stop()), s_Swerve),
WaitCommand(2),
)
self.dynamicForwardCommand = SequentialCommandGroup(
self.dynamicForward,
InstantCommand(lambda: (s_Swerve.stop()), s_Swerve),
WaitCommand(2),
)
self.dynamicReverseCommand = SequentialCommandGroup(
self.dynamicReverse,
InstantCommand(lambda: (s_Swerve.stop()), s_Swerve),
WaitCommand(2),
)
def getQuasiForwardCommand(self):
return self.quasiForwardCommand
def getQuasiReverseCommand(self):
return self.quasiReverseCommand
def getDynamicForwardCommand(self):
return self.dynamicForwardCommand
def getDynamicReverseCommand(self):
return self.dynamicReverseCommand | 2,313 | Python | 33.029411 | 101 | 0.648508 |
RoboEagles4828/rift2024/rio/srcrobot/commands/ExecuteCommand.py | from commands2 import ParallelCommandGroup, RunCommand, InstantCommand
from commands.TurnInPlace import TurnInPlace
from subsystems.Arm import Arm
from subsystems.Shooter import Shooter
from subsystems.Swerve import Swerve
from wpimath.geometry import Rotation2d
from robotState import RobotState
class ExecuteCommand(ParallelCommandGroup):
def __init__(self, arm : Arm, shooter : Shooter, swerve : Swerve, translationSupplier, strafeSupplier, rotationSupplier, robotCentricSupplier):
super().__init__()
self.robotState = RobotState()
self.arm = arm
self.shooter = shooter
self.swerve = swerve
self.arm_angle = self.robotState.m_gameState.getNextShot().m_armAngle
self.shooter_velocity = self.robotState.m_gameState.getNextShot().m_shooterVelocity
self.robot_angle = self.robotState.m_gameState.getNextShotRobotAngle()
self.setName(f"Execute {self.robotState.m_gameState.getNextShot().name}")
self.addCommands(
self.arm.servoArmToTarget(self.arm_angle).withTimeout(2.0),
self.shooter.shootVelocity(self.shooter_velocity),
TurnInPlace(self.swerve, lambda: Rotation2d.fromDegrees(self.robot_angle), translationSupplier, strafeSupplier, rotationSupplier, robotCentricSupplier).repeatedly()
)
def initialize(self):
super().initialize()
self.robotState = RobotState()
self.arm_angle = self.robotState.m_gameState.getNextShot().m_armAngle
self.shooter_velocity = self.robotState.m_gameState.getNextShot().m_shooterVelocity
self.robot_angle = self.robotState.m_gameState.getNextShotRobotAngle()
self.setName(f"Execute {self.robotState.m_gameState.getNextShot().name}")
| 1,750 | Python | 43.897435 | 176 | 0.729714 |
RoboEagles4828/rift2024/rio/srcrobot/commands/TeleopSwerve.py | from constants import Constants
from subsystems.Swerve import Swerve
from wpimath.geometry import Translation2d
from commands2 import Command
from typing import Callable
import math
from wpimath import applyDeadband
from wpimath.controller import PIDController
class TeleopSwerve(Command):
s_Swerve: Swerve
translationSup: Callable[[], float]
strafeSup: Callable[[], float]
rotationSup: Callable[[], float]
robotCentricSup: Callable[[], bool]
slowSup: Callable[[], list[float]]
def __init__(self, s_Swerve, translationSup, strafeSup, rotationSup, robotCentricSup, slowSup=lambda: 0.0):
self.s_Swerve: Swerve = s_Swerve
self.addRequirements(s_Swerve)
self.translationSup = translationSup
self.strafeSup = strafeSup
self.rotationSup = rotationSup
self.robotCentricSup = robotCentricSup
self.slowSup = slowSup
self.lastHeading = self.s_Swerve.getHeading().radians()
self.headingPID = PIDController(4.0, 0.0, 0.0)
self.headingPID.enableContinuousInput(-math.pi, math.pi)
self.headingPID.reset()
self.headingPID.setTolerance(math.radians(1))
def initialize(self):
super().initialize()
self.lastHeading = self.s_Swerve.getHeading().radians()
def execute(self):
# Get Values, Deadband
# translationVal = math.copysign(self.translationSup()**2, self.translationSup())
# strafeVal = math.copysign(self.strafeSup()**2, self.strafeSup())
translationVal = self.translationSup()
strafeVal = self.strafeSup()
rotationVal = self.getRotationValue()
# Apply slowmode
slow = self.slowSup()
# TODO: REMOVE THIS IN PRODUCTION. THIS IS TO SAVE THE ROBOT DURING TESTING.
if slow < 0:
print("SLOWMODE ERROR: SLOW OFFSET IS NEGATIVE\nCheck that your controller axis mapping is correct and goes between [0, 1]!")
slow = 0
translationVal -= translationVal*slow*Constants.Swerve.slowMoveModifier
strafeVal -= strafeVal*slow*Constants.Swerve.slowMoveModifier
rotationVal -= rotationVal*slow*Constants.Swerve.slowTurnModifier
# Drive
self.s_Swerve.drive(
Translation2d(translationVal, strafeVal).__mul__(Constants.Swerve.maxSpeed),
rotationVal,
not self.robotCentricSup(),
True
)
def getRotationValue(self):
return self.rotationSup() * Constants.Swerve.maxAngularVelocity
# rotation = 0.0
#heading correction
# if abs(self.rotationSup()) > 0.0:
# # heading correction is disabled, record last heading
# self.lastHeading = self.s_Swerve.getHeading().radians()
# rotation = self.rotationSup() * Constants.Swerve.maxAngularVelocity
# elif abs(self.translationSup()) > 0.0 or abs(self.strafeSup()) > 0.0:
# # heading correction is enabled, calculate correction
# rotation = -self.headingPID.calculate(self.s_Swerve.getHeading().radians(), self.lastHeading)
# return rotation | 3,142 | Python | 35.546511 | 137 | 0.660089 |
RoboEagles4828/rift2024/rio/srcrobot/commands/PathFindToTag.py | from commands2 import Command, DeferredCommand, InstantCommand, SequentialCommandGroup
from subsystems.Vision import Vision
from subsystems.Swerve import Swerve
from wpilib import SmartDashboard
from photonlibpy.photonTrackedTarget import PhotonTrackedTarget
from pathplannerlib.auto import AutoBuilder
from pathplannerlib.path import PathConstraints
from wpimath.geometry import Pose3d, Rotation3d, Transform3d, Translation3d
import wpimath.units as Units
class PathFindToTag(SequentialCommandGroup):
def __init__(self, swerve : Swerve, vision : Vision, TAG_ID, frontOffsetInches):
super().__init__()
self.vision = vision
self.swerve = swerve
self.TAG_ID = TAG_ID
self.TAG_TO_GOAL = Transform3d(
Translation3d(Units.inchesToMeters(frontOffsetInches), 0.0, 0.0),
Rotation3d.fromDegrees(0.0, 0.0, 0.0)
)
self.targetToUse = None
self.addRequirements(self.swerve, self.vision)
self.addCommands(
DeferredCommand(lambda: self.getCommand(), swerve, vision),
InstantCommand(lambda: self.swerve.stop())
)
def getCommand(self):
robotToPose2d = self.swerve.getPose()
robotToPose3d = Pose3d(
robotToPose2d.X(),
robotToPose2d.Y(),
0.0,
Rotation3d(0.0, 0.0, robotToPose2d.rotation().radians())
)
result = self.vision.getCamera().getLatestResult()
if result.hasTargets() == False:
return InstantCommand()
else:
try:
allTargets = result.getTargets()
for target in allTargets:
if target.getFiducialId() == self.TAG_ID:
self.targetToUse = target
if self.targetToUse.getPoseAmbiguity() >= 0.2:
return InstantCommand()
camToTarget = self.targetToUse.getBestCameraToTarget()
cameraPose = robotToPose3d.transformBy(self.vision.robotToCamera)
targetPose = cameraPose.transformBy(camToTarget)
goalPose = targetPose.transformBy(self.TAG_TO_GOAL).toPose2d()
return AutoBuilder.pathfindToPose(goalPose, PathConstraints(
1.5, 1,
Units.degreesToRadians(540), Units.degreesToRadians(720), 0
))
except Exception as e:
print(e)
return InstantCommand()
| 2,520 | Python | 33.067567 | 86 | 0.610714 |
RoboEagles4828/rift2024/rio/srcrobot/tests/pyfrc_test.py | '''
This test module imports tests that come with pyfrc, and can be used
to test basic functionality of just about any robot.
'''
from pyfrc.tests import *
| 165 | Python | 22.714282 | 72 | 0.715152 |
RoboEagles4828/rift2024/rio/srcrobot/lib/util/InterpolatingTreeMap.py | from pytreemap import TreeMap
class InterpolatingTreeMap:
def __init__(self):
self.m_map = TreeMap()
def put(self,key, value):
self.m_map.put(key, value)
def get(self, key) -> float:
value = self.m_map.get(key)
if value == None:
ceilingKey = self.m_map.ceiling_key(key)
floorKey = self.m_map.floor_key(key)
if ceilingKey == None and floorKey == None:
return None
if ceilingKey == None:
return float(self.m_map.get(floorKey))
if floorKey == None:
return float(self.m_map.get(ceilingKey))
floor = self.m_map.get(floorKey)
ceiling = self.m_map.get(ceilingKey)
return self.interpolate(floor, ceiling, self.inverseInterpolate(ceilingKey, key, floorKey))
else:
return float(value)
def clear(self):
self.m_map.clear()
def interpolate(self, val1, val2, d: float) -> float:
dydx = float(val2)-float(val1)
return dydx*d+float(val1)
def inverseInterpolate(self, up, q, down) -> float:
uppertoLower = float(up)-float(down)
if uppertoLower <= 0:
return 0.0
querytoLower = float(q)-float(down)
if querytoLower <= 0:
return 0.0
return querytoLower/uppertoLower
| 1,380 | Python | 29.021738 | 103 | 0.560145 |
RoboEagles4828/rift2024/rio/srcrobot/lib/util/COTSTalonFXSwerveConstants.py | from phoenix6.signals import InvertedValue;
from phoenix6.signals import SensorDirectionValue;
import math
import lib.mathlib.units as Units
class COTSTalonFXSwerveConstants:
wheelDiameter: float
wheelCircumference: float
angleGearRatio: float
driveGearRatio: float
angleKP: float
angleKI: float
angleKD: float
driveMotorInvert: InvertedValue
angleMotorInvert: InvertedValue
cancoderInvert: SensorDirectionValue
def __init__(self, wheelDiameter, angleGearRatio, driveGearRatio, angleKP, angleKI, angleKD, driveMotorInvert, angleMotorInvert, cancoderInvert):
self.wheelDiameter = wheelDiameter
self.wheelCircumference = wheelDiameter * math.pi
self.angleGearRatio = angleGearRatio
self.driveGearRatio = driveGearRatio
self.angleKP = angleKP
self.angleKI = angleKI
self.angleKD = angleKD
self.driveMotorInvert = driveMotorInvert
self.angleMotorInvert = angleMotorInvert
self.cancoderInvert = cancoderInvert
# Swerve Drive Specialties - MK4i Module
class MK4i:
# Swerve Drive Specialties - MK4i Module (Falcon 500)
def Falcon500(driveGearRatio):
wheelDiameter = Units.inchesToMeters(4.0)
# (150 / 7) : 1
angleGearRatio = ((150.0 / 7.0) / 1.0)
angleKP = 100.0
angleKI = 0.0
angleKD = 0.0
driveMotorInvert = InvertedValue.COUNTER_CLOCKWISE_POSITIVE
angleMotorInvert = InvertedValue.CLOCKWISE_POSITIVE
cancoderInvert = SensorDirectionValue.COUNTER_CLOCKWISE_POSITIVE
return COTSTalonFXSwerveConstants(wheelDiameter, angleGearRatio, driveGearRatio, angleKP, angleKI, angleKD, driveMotorInvert, angleMotorInvert, cancoderInvert)
# Swerve Drive Specialties - MK4i Module (Kraken X60)
def KrakenX60(driveGearRatio):
wheelDiameter = Units.inchesToMeters(4.0)
# (150 / 7) : 1
angleGearRatio = ((150.0 / 7.0) / 1.0)
angleKP = 1.0
angleKI = 0.0
angleKD = 0.0
driveMotorInvert = InvertedValue.COUNTER_CLOCKWISE_POSITIVE
angleMotorInvert = InvertedValue.CLOCKWISE_POSITIVE
cancoderInvert = SensorDirectionValue.COUNTER_CLOCKWISE_POSITIVE
return COTSTalonFXSwerveConstants(wheelDiameter, angleGearRatio, driveGearRatio, angleKP, angleKI, angleKD, driveMotorInvert, angleMotorInvert, cancoderInvert)
class driveRatios:
# SDS MK4i - (8.14 : 1)
L1 = (8.14 / 1.0)
# SDS MK4i - (6.75 : 1)
L2 = (6.75 / 1.0)
# SDS MK4i - (6.12 : 1)
L3 = (6.12 / 1.0)
| 2,747 | Python | 36.643835 | 171 | 0.650892 |
RoboEagles4828/rift2024/rio/srcrobot/lib/util/SwerveModuleConstants.py | from wpimath.geometry import Rotation2d
class SwerveModuleConstants:
driveMotorID: int
angleMotorID: int
cancoderID: int
angleOffset: Rotation2d
def __init__(self, driveMotorID: int, angleMotorID: int, canCoderID: int, angleOffset: Rotation2d):
self.driveMotorID = driveMotorID
self.angleMotorID = angleMotorID
self.cancoderID = canCoderID
self.angleOffset = angleOffset | 424 | Python | 31.692305 | 103 | 0.721698 |
RoboEagles4828/rift2024/rio/srcrobot/lib/util/PhotonUtils.py | from wpimath.geometry import *
import math
class PhotonUtils:
@staticmethod
def calculateDistanceToTargetMeters(cameraHeightMeters, targetHeightMeters, cameraPitchRadians, targetPitchRadians):
return (targetHeightMeters - cameraHeightMeters) / math.tan(cameraPitchRadians + targetPitchRadians)
@staticmethod
def estimateCameraToTargetTranslation(targetDistanceMeters, yaw: Rotation2d):
return Translation2d(yaw.cos() * targetDistanceMeters, yaw.sin() * targetDistanceMeters);
@staticmethod
def estimateFieldToRobot(
cameraHeightMeters,
targetHeightMeters,
cameraPitchRadians,
targetPitchRadians,
targetYaw: Rotation2d,
gyroAngle: Rotation2d,
fieldToTarget: Pose2d,
cameraToRobot: Transform2d):
return PhotonUtils.estimateFieldToRobot(
PhotonUtils.estimateCameraToTarget(
PhotonUtils.estimateCameraToTargetTranslation(
PhotonUtils.calculateDistanceToTargetMeters(
cameraHeightMeters, targetHeightMeters, cameraPitchRadians, targetPitchRadians),
targetYaw),
fieldToTarget,
gyroAngle),
fieldToTarget,
cameraToRobot)
@staticmethod
def estimateCameraToTarget(
cameraToTargetTranslation: Translation2d, fieldToTarget: Pose2d, gyroAngle: Rotation2d):
return Transform2d(cameraToTargetTranslation, gyroAngle.__mul__(-1).__sub__(fieldToTarget.rotation()))
@staticmethod
def estimateFieldToRobot(
cameraToTarget: Transform2d, fieldToTarget: Pose2d, cameraToRobot: Transform2d):
return PhotonUtils.estimateFieldToCamera(cameraToTarget, fieldToTarget).transformBy(cameraToRobot)
@staticmethod
def estimateFieldToCamera(cameraToTarget: Transform2d, fieldToTarget: Pose2d):
targetToCamera = cameraToTarget.inverse()
return fieldToTarget.transformBy(targetToCamera)
@staticmethod
def estimateFieldToRobotAprilTag(
cameraToTarget: Transform3d, fieldRelativeTagPose: Pose3d, cameraToRobot: Transform3d):
return fieldRelativeTagPose.__add__(cameraToTarget.inverse()).__add__(cameraToRobot)
@staticmethod
def getYawToPose(robotPose: Pose2d, targetPose: Pose2d):
relativeTrl = targetPose.relativeTo(robotPose).translation()
angle = math.atan2(relativeTrl.Y(), relativeTrl.X())
return Rotation2d(angle)
@staticmethod
def getDistanceToPose(robotPose: Pose2d, targetPose: Pose2d):
robotTranslation = robotPose.translation()
return robotTranslation.distance(targetPose.translation())
@staticmethod
def getDistanceVectorToPose(robotPose: Pose2d, targetPose: Pose2d):
robotTranslation = robotPose.translation()
return targetPose.translation().__sub__(robotTranslation) | 3,013 | Python | 42.681159 | 120 | 0.688682 |
RoboEagles4828/rift2024/rio/srcrobot/lib/mathlib/conversions.py | class Conversions:
"""
:param wheelRPS: wheel rotations per second
:param circumference: wheel circumference
:returns: wheel meters per second
"""
@staticmethod
def RPSToMPS(wheelRPS: float, circumference: float):
wheelMPS = wheelRPS * circumference
return wheelMPS
"""
:param wheelMPS: wheel meters per second
:param circumference: wheel circumference
:returns: wheel rotations per second
"""
@staticmethod
def MPSToRPS(wheelMPS: float, circumference: float):
wheelRPS = wheelMPS / circumference
return wheelRPS
"""
:param wheelRotations: Wheel Position (in Rotations)
:param circumference: Wheel Circumference (in Meters)
:returns: Wheel Distance (in Meters)
"""
@staticmethod
def rotationsToMeters(wheelRotations: float, circumference: float):
wheelMeters = wheelRotations * circumference
return wheelMeters
"""
:param wheelMeters: Wheel Distance (in Meters)
:param circumference: Wheel Circumference (in Meters)
:returns: Wheel Position (in Rotations)
"""
@staticmethod
def metersToRotations(wheelMeters: float, circumference: float):
wheelRotations = wheelMeters / circumference
return wheelRotations
| 1,286 | Python | 29.642856 | 71 | 0.686625 |
RoboEagles4828/rift2024/rio/srcrobot/lib/mathlib/units.py | @staticmethod
def inchesToMeters(inches):
return inches * 0.0254
@staticmethod
def feetToMeters(feet):
return feet * 0.3048
@staticmethod
def mmToMeters(mm):
return mm * 0.001
@staticmethod
def metersToInches(meters):
return meters / 0.0254
@staticmethod
def metersToFeet(meters):
return meters / 0.3048
@staticmethod
def metersToMm(meters):
return meters / 0.001
@staticmethod
def inchesToFeet(inches):
return inches / 12
@staticmethod
def inchesToMm(inches):
return inches * 25.4
@staticmethod
def feetToInches(feet):
return feet * 12
@staticmethod
def feetToMm(feet):
return feet * 304.8
@staticmethod
def mmToInches(mm):
return mm / 25.4
@staticmethod
def mmToFeet(mm):
return mm / 304.8
| 751 | Python | 14.666666 | 27 | 0.716378 |
RoboEagles4828/rift2024/rio/dds/dds.py | import rticonnextdds_connector as rti
import logging
# Subscribe to DDS topics
class DDS_Subscriber:
def __init__(self, xml_path, participant_name, reader_name):
# Connectors are not thread safe, so we need to create a new one for each thread
self.connector = rti.Connector(config_name=participant_name, url=xml_path)
self.input = self.connector.get_input(reader_name)
def read(self) -> dict:
# Take the input data off of queue and read it
try:
self.input.take()
except rti.Error as e:
logging.warn("RTI Read Error", e.args)
# Return the first valid data sample
data = None
for sample in self.input.samples.valid_data_iter:
data = sample.get_dictionary()
break
return data
def close(self):
self.connector.close()
# Publish to DDS topics
class DDS_Publisher:
def __init__(self, xml_path, participant_name, writer_name):
self.connector = rti.Connector(config_name=participant_name, url=xml_path)
self.output = self.connector.get_output(writer_name)
def write(self, data) -> None:
if data:
self.output.instance.set_dictionary(data)
try:
self.output.write()
except rti.Error as e:
logging.warn("RTI Write Error", e.args)
# else:
# logging.warn("No data to write")
def close(self):
self.connector.close() | 1,491 | Python | 31.434782 | 88 | 0.608987 |
Virlus/OmniIsaacGymEnvs/setup.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Installation script for the 'isaacgymenvs' python package."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from setuptools import setup, find_packages
import os
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
"numpy==1.23.5",
"protobuf==3.20.2",
"omegaconf==2.3.0",
"hydra-core==1.3.2",
"urllib3==1.26.16",
"rl-games==1.6.1"
]
# Installation operation
setup(
name="omniisaacgymenvs",
author="NVIDIA",
version="2023.1.0b",
description="RL environments for robot learning in NVIDIA Isaac Sim.",
keywords=["robotics", "rl"],
include_package_data=True,
install_requires=INSTALL_REQUIRES,
packages=find_packages("."),
classifiers=["Natural Language :: English", "Programming Language :: Python :: 3.7, 3.8"],
zip_safe=False,
)
# EOF
| 2,452 | Python | 36.738461 | 94 | 0.743475 |
Virlus/OmniIsaacGymEnvs/README.md | # Omniverse Isaac Gym Reinforcement Learning Environments for Isaac Sim (With Customized Tasks)
## About this repository
This repository contains Reinforcement Learning examples that can be run with the latest release of [Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html). RL examples are trained using PPO from [rl_games](https://github.com/Denys88/rl_games) library and examples are built on top of Isaac Sim's `omni.isaac.core` and `omni.isaac.gym` frameworks.
Please see [release notes](docs/release_notes.md) for the latest updates.
<img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/> <img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/>
<img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="614" height="307"/>
## Installation
Follow the Isaac Sim [documentation](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html) to install the latest Isaac Sim release.
*Examples in this repository rely on features from the most recent Isaac Sim release. Please make sure to update any existing Isaac Sim build to the latest release version, 2023.1.0, to ensure examples work as expected.*
Note that the 2022.2.1 OmniIsaacGymEnvs release will no longer work with the latest Isaac Sim 2023.1.0 release. Due to a change in USD APIs, line 138 in rl_task.py is no longer valid. To run the previous OIGE release with the latest Isaac Sim release, please comment out lines 137 and 138 in rl_task.py or set `add_distant_light` to `False` in the task config file. No changes are required if running with the latest release of OmniIsaacGymEnvs.
Once installed, this repository can be used as a python module, `omniisaacgymenvs`, with the python executable provided in Isaac Sim.
To install `omniisaacgymenvs`, first clone this repository:
```bash
git clone https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs.git
```
Once cloned, locate the [python executable in Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_python.html). By default, this should be `python.sh`. We will refer to this path as `PYTHON_PATH`.
To set a `PYTHON_PATH` variable in the terminal that links to the python executable, we can run a command that resembles the following. Make sure to update the paths to your local path.
```
For Linux: alias PYTHON_PATH=~/.local/share/ov/pkg/isaac_sim-*/python.sh
For Windows: doskey PYTHON_PATH=C:\Users\user\AppData\Local\ov\pkg\isaac_sim-*\python.bat $*
For IsaacSim Docker: alias PYTHON_PATH=/isaac-sim/python.sh
```
Install `omniisaacgymenvs` as a python module for `PYTHON_PATH`:
```bash
PYTHON_PATH -m pip install -e .
```
The following error may appear during the initial installation. This error is harmless and can be ignored.
```
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
```
### Running the examples
*Note: All commands should be executed from `OmniIsaacGymEnvs/omniisaacgymenvs`.*
To train your first policy, run:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
An Isaac Sim app window should be launched. Once Isaac Sim initialization completes, the Cartpole scene will be constructed and simulation will start running automatically. The process will terminate once training finishes.
Note that by default, we show a Viewport window with rendering, which slows down training. You can choose to close the Viewport window during training for better performance. The Viewport window can be re-enabled by selecting `Window > Viewport` from the top menu bar.
To achieve maximum performance, launch training in `headless` mode as follows:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant headless=True
```
#### A Note on the Startup Time of the Simulation
Some of the examples could take a few minutes to load because the startup time scales based on the number of environments. The startup time will continually
be optimized in future releases.
### Extension Workflow
The extension workflow provides a simple user interface for creating and launching RL tasks. To launch Isaac Sim for the extension workflow, run:
```bash
./<isaac_sim_root>/isaac-sim.gym.sh --ext-folder </parent/directory/to/OIGE>
```
Note: `isaac_sim_root` should be located in the same directory as `python.sh`.
The UI window can be activated from `Isaac Examples > RL Examples` by navigating the top menu bar.
For more details on the extension workflow, please refer to the [documentation](docs/extension_workflow.md).
### Loading trained models // Checkpoints
Checkpoints are saved in the folder `runs/EXPERIMENT_NAME/nn` where `EXPERIMENT_NAME`
defaults to the task name, but can also be overridden via the `experiment` argument.
To load a trained checkpoint and continue training, use the `checkpoint` argument:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth
```
To load a trained checkpoint and only perform inference (no training), pass `test=True`
as an argument, along with the checkpoint name. To avoid rendering overhead, you may
also want to run with fewer environments using `num_envs=64`:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=runs/Ant/nn/Ant.pth test=True num_envs=64
```
Note that if there are special characters such as `[` or `=` in the checkpoint names,
you will need to escape them and put quotes around the string. For example,
`checkpoint="runs/Ant/nn/last_Antep\=501rew\[5981.31\].pth"`
We provide pre-trained checkpoints on the [Nucleus](https://docs.omniverse.nvidia.com/nucleus/latest/index.html) server under `Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints`. Run the following command
to launch inference with pre-trained checkpoint:
Localhost (To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html)):
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
Production server:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant checkpoint=http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth test=True num_envs=64
```
When running with a pre-trained checkpoint for the first time, we will automatically download the checkpoint file to `omniisaacgymenvs/checkpoints`. For subsequent runs, we will re-use the file that has already been downloaded, and will not overwrite existing checkpoints with the same name in the `checkpoints` folder.
## Runing from Docker
Latest Isaac Sim Docker image can be found on [NGC](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim). A utility script is provided at `docker/run_docker.sh` to help initialize this repository and launch the Isaac Sim docker container. The script can be run with:
```bash
./docker/run_docker.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py headless=True task=Ant
```
To run the Isaac Sim docker with UI, use the following script:
```bash
./docker/run_docker_viewer.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py task=Ant
```
To avoid re-installing OIGE each time a container is launched, we also provide a dockerfile that can be used to build an image with OIGE installed. To build the image, run:
```bash
docker build -t isaac-sim-oige -f docker/dockerfile .
```
Then, start a container with the built image:
```bash
./docker/run_dockerfile.sh
```
Then, training can be launched from the container with:
```bash
/isaac-sim/python.sh scripts/rlgames_train.py task=Ant headless=True
```
### Isaac Sim Automator
Cloud instances for AWS, Azure, or GCP can be setup using [IsaacSim Automator](https://github.com/NVIDIA-Omniverse/IsaacSim-Automator/tree/main#omniverse-isaac-gym).
## Livestream
OmniIsaacGymEnvs supports livestream through the [Omniverse Streaming Client](https://docs.omniverse.nvidia.com/app_streaming-client/app_streaming-client/overview.html). To enable this feature, add the commandline argument `enable_livestream=True`:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Ant headless=True enable_livestream=True
```
Connect from the Omniverse Streaming Client once the SimulationApp has been created. Note that enabling livestream is equivalent to training with the viewer enabled, thus the speed of training/inferencing will decrease compared to running in headless mode.
## Training Scripts
All scripts provided in `omniisaacgymenvs/scripts` can be launched directly with `PYTHON_PATH`.
To test out a task without RL in the loop, run the random policy script with:
```bash
PYTHON_PATH scripts/random_policy.py task=Cartpole
```
This script will sample random actions from the action space and apply these actions to your task without running any RL policies. Simulation should start automatically after launching the script, and will run indefinitely until terminated.
To run a simple form of PPO from `rl_games`, use the single-threaded training script:
```bash
PYTHON_PATH scripts/rlgames_train.py task=Cartpole
```
This script creates an instance of the PPO runner in `rl_games` and automatically launches training and simulation. Once training completes (the total number of iterations have been reached), the script will exit. If running inference with `test=True checkpoint=<path/to/checkpoint>`, the script will run indefinitely until terminated. Note that this script will have limitations on interaction with the UI.
### Configuration and command line arguments
We use [Hydra](https://hydra.cc/docs/intro/) to manage the config.
Common arguments for the training scripts are:
* `task=TASK` - Selects which task to use. Any of `AllegroHand`, `Ant`, `Anymal`, `AnymalTerrain`, `BallBalance`, `Cartpole`, `CartpoleCamera`, `Crazyflie`, `FactoryTaskNutBoltPick`, `FactoryTaskNutBoltPlace`, `FactoryTaskNutBoltScrew`, `FrankaCabinet`, `FrankaDeformable`, `Humanoid`, `Ingenuity`, `Quadcopter`, `ShadowHand`, `ShadowHandOpenAI_FF`, `ShadowHandOpenAI_LSTM` (these correspond to the config for each environment in the folder `omniisaacgymenvs/cfg/task`)
* `train=TRAIN` - Selects which training config to use. Will automatically default to the correct config for the environment (ie. `<TASK>PPO`).
* `num_envs=NUM_ENVS` - Selects the number of environments to use (overriding the default number of environments set in the task config).
* `seed=SEED` - Sets a seed value for randomization, and overrides the default seed in the task config
* `pipeline=PIPELINE` - Which API pipeline to use. Defaults to `gpu`, can also set to `cpu`. When using the `gpu` pipeline, all data stays on the GPU. When using the `cpu` pipeline, simulation can run on either CPU or GPU, depending on the `sim_device` setting, but a copy of the data is always made on the CPU at every step.
* `sim_device=SIM_DEVICE` - Device used for physics simulation. Set to `gpu` (default) to use GPU and to `cpu` for CPU.
* `device_id=DEVICE_ID` - Device ID for GPU to use for simulation and task. Defaults to `0`. This parameter will only be used if simulation runs on GPU.
* `rl_device=RL_DEVICE` - Which device / ID to use for the RL algorithm. Defaults to `cuda:0`, and follows PyTorch-like device syntax.
* `multi_gpu=MULTI_GPU` - Whether to train using multiple GPUs. Defaults to `False`. Note that this option is only available with `rlgames_train.py`.
* `test=TEST`- If set to `True`, only runs inference on the policy and does not do any training.
* `checkpoint=CHECKPOINT_PATH` - Path to the checkpoint to load for training or testing.
* `headless=HEADLESS` - Whether to run in headless mode.
* `enable_livestream=ENABLE_LIVESTREAM` - Whether to enable Omniverse streaming.
* `experiment=EXPERIMENT` - Sets the name of the experiment.
* `max_iterations=MAX_ITERATIONS` - Sets how many iterations to run for. Reasonable defaults are provided for the provided environments.
* `warp=WARP` - If set to True, launch the task implemented with Warp backend (Note: not all tasks have a Warp implementation).
* `kit_app=KIT_APP` - Specifies the absolute path to the kit app file to be used.
Hydra also allows setting variables inside config files directly as command line arguments. As an example, to set the minibatch size for a rl_games training run, you can use `train.params.config.minibatch_size=64`. Similarly, variables in task configs can also be set. For example, `task.env.episodeLength=100`.
#### Hydra Notes
Default values for each of these are found in the `omniisaacgymenvs/cfg/config.yaml` file.
The way that the `task` and `train` portions of the config works are through the use of config groups.
You can learn more about how these work [here](https://hydra.cc/docs/tutorials/structured_config/config_groups/)
The actual configs for `task` are in `omniisaacgymenvs/cfg/task/<TASK>.yaml` and for `train` in `omniisaacgymenvs/cfg/train/<TASK>PPO.yaml`.
In some places in the config you will find other variables referenced (for example,
`num_actors: ${....task.env.numEnvs}`). Each `.` represents going one level up in the config hierarchy.
This is documented fully [here](https://omegaconf.readthedocs.io/en/latest/usage.html#variable-interpolation).
### Tensorboard
Tensorboard can be launched during training via the following command:
```bash
PYTHON_PATH -m tensorboard.main --logdir runs/EXPERIMENT_NAME/summaries
```
## WandB support
You can run (WandB)[https://wandb.ai/] with OmniIsaacGymEnvs by setting `wandb_activate=True` flag from the command line. You can set the group, name, entity, and project for the run by setting the `wandb_group`, `wandb_name`, `wandb_entity` and `wandb_project` arguments. Make sure you have WandB installed in the Isaac Sim Python executable with `PYTHON_PATH -m pip install wandb` before activating.
## Training with Multiple GPUs
To train with multiple GPUs, use the following command, where `--proc_per_node` represents the number of available GPUs:
```bash
PYTHON_PATH -m torch.distributed.run --nnodes=1 --nproc_per_node=2 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
## Multi-Node Training
To train across multiple nodes/machines, it is required to launch an individual process on each node.
For the master node, use the following command, where `--proc_per_node` represents the number of available GPUs, and `--nnodes` represents the number of nodes:
```bash
PYTHON_PATH -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=localhost:5555 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
Note that the port (`5555`) can be replaced with any other available port.
For non-master nodes, use the following command, replacing `--node_rank` with the index of each machine:
```bash
PYTHON_PATH -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=ip_of_master_machine:5555 scripts/rlgames_train.py headless=True task=Ant multi_gpu=True
```
For more details on multi-node training with PyTorch, please visit [here](https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html). As mentioned in the PyTorch documentation, "multinode training is bottlenecked by inter-node communication latencies". When this latency is high, it is possible multi-node training will perform worse than running on a single node instance.
## Tasks
Source code for tasks can be found in `omniisaacgymenvs/tasks`.
Each task follows the frameworks provided in `omni.isaac.core` and `omni.isaac.gym` in Isaac Sim.
Refer to [docs/framework.md](docs/framework.md) for how to create your own tasks.
Full details on each of the tasks available can be found in the [RL examples documentation](docs/rl_examples.md).
## Demo
We provide an interactable demo based on the `AnymalTerrain` RL example. In this demo, you can click on any of
the ANYmals in the scene to go into third-person mode and manually control the robot with your keyboard as follows:
- `Up Arrow`: Forward linear velocity command
- `Down Arrow`: Backward linear velocity command
- `Left Arrow`: Leftward linear velocity command
- `Right Arrow`: Rightward linear velocity command
- `Z`: Counterclockwise yaw angular velocity command
- `X`: Clockwise yaw angular velocity command
- `C`: Toggles camera view between third-person and scene view while maintaining manual control
- `ESC`: Unselect a selected ANYmal and yields manual control
Launch this demo with the following command. Note that this demo limits the maximum number of ANYmals in the scene to 128.
```
PYTHON_PATH scripts/rlgames_demo.py task=AnymalTerrain num_envs=64 checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth
```
<img src="https://user-images.githubusercontent.com/34286328/184688654-6e7899b2-5847-4184-8944-2a96b129b1ff.gif" width="600" height="300"/>
| 18,657 | Markdown | 56.409231 | 469 | 0.776491 |
Virlus/OmniIsaacGymEnvs/config/extension.toml | [gym]
reloadable = true
[package]
version = "0.0.0"
category = "Simulation"
title = "Isaac Gym Envs"
description = "RL environments"
authors = ["Isaac Sim Team"]
repository = "https://gitlab-master.nvidia.com/carbon-gym/omniisaacgymenvs"
keywords = ["isaac"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
icon = "data/icon.png"
writeTarget.kit = true
[dependencies]
"omni.isaac.gym" = {}
"omni.isaac.core" = {}
"omni.isaac.cloner" = {}
"omni.isaac.ml_archive" = {} # torch
[[python.module]]
name = "omniisaacgymenvs"
| 532 | TOML | 20.319999 | 75 | 0.693609 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/extension.py | # Copyright (c) 2018-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 asyncio
import inspect
import os
import traceback
import weakref
from abc import abstractmethod
import hydra
import omni.ext
import omni.timeline
import omni.ui as ui
import omni.usd
from hydra import compose, initialize
from omegaconf import OmegaConf
from omni.isaac.cloner import GridCloner
from omni.isaac.core.utils.extensions import disable_extension, enable_extension
from omni.isaac.core.utils.torch.maths import set_seed
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.core.world import World
from omniisaacgymenvs.envs.vec_env_rlgames_mt import VecEnvRLGamesMT
from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig
from omniisaacgymenvs.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from omniisaacgymenvs.utils.rlgames.rlgames_train_mt import RLGTrainer, Trainer
from omniisaacgymenvs.utils.task_util import import_tasks, initialize_task
from omni.isaac.ui.callbacks import on_open_folder_clicked, on_open_IDE_clicked
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import (
btn_builder,
dropdown_builder,
get_style,
int_builder,
multi_btn_builder,
multi_cb_builder,
scrolling_frame_builder,
setup_ui_headers,
str_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.viewport.utility import get_active_viewport, get_viewport_from_window_name
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf
ext_instance = None
class RLExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
self._render_modes = ["Full render", "UI only", "None"]
self._env = None
self._task = None
self._ext_id = ext_id
ext_manager = omni.kit.app.get_app().get_extension_manager()
extension_path = ext_manager.get_extension_path(ext_id)
self._ext_path = os.path.dirname(extension_path) if os.path.isfile(extension_path) else extension_path
self._ext_file_path = os.path.abspath(__file__)
self._initialize_task_list()
self.start_extension(
"",
"",
"RL Examples",
"RL Examples",
"",
"A set of reinforcement learning examples.",
self._ext_file_path,
)
self._task_initialized = False
self._task_changed = False
self._is_training = False
self._render = True
self._resume = False
self._test = False
self._evaluate = False
self._checkpoint_path = ""
self._timeline = omni.timeline.get_timeline_interface()
self._viewport = get_active_viewport()
self._viewport.updates_enabled = True
global ext_instance
ext_instance = self
def _initialize_task_list(self):
self._task_map, _ = import_tasks()
self._task_list = list(self._task_map.keys())
self._task_list.sort()
self._task_list.remove("CartpoleCamera") # we cannot run camera-based training from extension workflow for now. it requires a specialized app file.
self._task_name = self._task_list[0]
self._parse_config(self._task_name)
self._update_task_file_paths(self._task_name)
def _update_task_file_paths(self, task):
self._task_file_path = os.path.abspath(inspect.getfile(self._task_map[task]))
self._task_cfg_file_path = os.path.join(os.path.dirname(self._ext_file_path), f"cfg/task/{task}.yaml")
self._train_cfg_file_path = os.path.join(os.path.dirname(self._ext_file_path), f"cfg/train/{task}PPO.yaml")
def _parse_config(self, task, num_envs=None, overrides=None):
hydra.core.global_hydra.GlobalHydra.instance().clear()
initialize(version_base=None, config_path="cfg")
overrides_list = [f"task={task}"]
if overrides is not None:
overrides_list += overrides
if num_envs is None:
self._cfg = compose(config_name="config", overrides=overrides_list)
else:
self._cfg = compose(config_name="config", overrides=overrides_list + [f"num_envs={num_envs}"])
self._cfg_dict = omegaconf_to_dict(self._cfg)
self._sim_config = SimConfig(self._cfg_dict)
def start_extension(
self,
menu_name: str,
submenu_name: str,
name: str,
title: str,
doc_link: str,
overview: str,
file_path: str,
number_of_extra_frames=1,
window_width=550,
keep_window_open=False,
):
window = ui.Workspace.get_window("Property")
if window:
window.visible = False
window = ui.Workspace.get_window("Render Settings")
if window:
window.visible = False
menu_items = [make_menu_item_description(self._ext_id, name, lambda a=weakref.proxy(self): a._menu_callback())]
if menu_name == "" or menu_name is None:
self._menu_items = menu_items
elif submenu_name == "" or submenu_name is None:
self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)]
else:
self._menu_items = [
MenuItemDescription(
name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)]
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._task_dropdown = None
self._cbs = None
self._build_ui(
name=name,
title=title,
doc_link=doc_link,
overview=overview,
file_path=file_path,
number_of_extra_frames=number_of_extra_frames,
window_width=window_width,
keep_window_open=keep_window_open,
)
return
def _build_ui(
self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width, keep_window_open
):
self._window = omni.ui.Window(
name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
self._main_stack = ui.VStack(spacing=5, height=0)
with self._main_stack:
setup_ui_headers(self._ext_id, file_path, title, doc_link, overview)
self._controls_frame = ui.CollapsableFrame(
title="World Controls",
width=ui.Fraction(1),
height=0,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with self._controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
with ui.HStack(style=get_style()):
with ui.VStack(style=get_style(), width=ui.Fraction(20)):
dict = {
"label": "Select Task",
"type": "dropdown",
"default_val": 0,
"items": self._task_list,
"tooltip": "Select a task",
"on_clicked_fn": self._on_task_select,
}
self._task_dropdown = dropdown_builder(**dict)
with ui.Frame(tooltip="Open Source Code"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_open_IDE_clicked(self._ext_path, self._task_file_path),
style=get_style()["IconButton.Image::OpenConfig"],
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Open in IDE",
)
with ui.Frame(tooltip="Open Task Config"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_open_IDE_clicked(self._ext_path, self._task_cfg_file_path),
style=get_style()["IconButton.Image::OpenConfig"],
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Open in IDE",
)
with ui.Frame(tooltip="Open Training Config"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_open_IDE_clicked(self._ext_path, self._train_cfg_file_path),
style=get_style()["IconButton.Image::OpenConfig"],
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Open in IDE",
)
dict = {
"label": "Number of environments",
"tooltip": "Enter the number of environments to construct",
"min": 0,
"max": 8192,
"default_val": self._cfg.task.env.numEnvs,
}
self._num_envs_int = int_builder(**dict)
dict = {
"label": "Load Environment",
"type": "button",
"text": "Load",
"tooltip": "Load Environment and Task",
"on_clicked_fn": self._on_load_world,
}
self._load_env_button = btn_builder(**dict)
dict = {
"label": "Rendering Mode",
"type": "dropdown",
"default_val": 0,
"items": self._render_modes,
"tooltip": "Select a rendering mode",
"on_clicked_fn": self._on_render_mode_select,
}
self._render_dropdown = dropdown_builder(**dict)
dict = {
"label": "Configure Training",
"count": 3,
"text": ["Resume from Checkpoint", "Test", "Evaluate"],
"default_val": [False, False, False],
"tooltip": [
"",
"Resume training from checkpoint",
"Play a trained policy",
"Evaluate a policy during training",
],
"on_clicked_fn": [
self._on_resume_cb_update,
self._on_test_cb_update,
self._on_evaluate_cb_update,
],
}
self._cbs = multi_cb_builder(**dict)
dict = {
"label": "Load Checkpoint",
"tooltip": "Enter path to checkpoint file",
"on_clicked_fn": self._on_checkpoint_update,
}
self._checkpoint_str = str_builder(**dict)
dict = {
"label": "Train/Test",
"count": 2,
"text": ["Start", "Stop"],
"tooltip": [
"",
"Launch new training/inference run",
"Terminate current training/inference run",
],
"on_clicked_fn": [self._on_train, self._on_train_stop],
}
self._buttons = multi_btn_builder(**dict)
return
def create_task(self):
headless = self._cfg.headless
enable_viewport = "enable_cameras" in self._cfg.task.sim and self._cfg.task.sim.enable_cameras
self._env = VecEnvRLGamesMT(
headless=headless,
sim_device=self._cfg.device_id,
enable_livestream=self._cfg.enable_livestream,
enable_viewport=enable_viewport,
launch_simulation_app=False,
)
self._task = initialize_task(self._cfg_dict, self._env, init_sim=False)
self._task_initialized = True
def _on_task_select(self, value):
if self._task_initialized and value != self._task_name:
self._task_changed = True
self._task_initialized = False
self._task_name = value
self._parse_config(self._task_name)
self._num_envs_int.set_value(self._cfg.task.env.numEnvs)
self._update_task_file_paths(self._task_name)
def _on_render_mode_select(self, value):
if value == self._render_modes[0]:
self._viewport.updates_enabled = True
window = ui.Workspace.get_window("Viewport")
window.visible = True
if self._env:
self._env._update_viewport = True
self._env._render_mode = 0
elif value == self._render_modes[1]:
self._viewport.updates_enabled = False
window = ui.Workspace.get_window("Viewport")
window.visible = False
if self._env:
self._env._update_viewport = False
self._env._render_mode = 1
elif value == self._render_modes[2]:
self._viewport.updates_enabled = False
window = ui.Workspace.get_window("Viewport")
window.visible = False
if self._env:
self._env._update_viewport = False
self._env._render_mode = 2
def _on_render_cb_update(self, value):
self._render = value
print("updates enabled", value)
self._viewport.updates_enabled = value
if self._env:
self._env._update_viewport = value
if value:
window = ui.Workspace.get_window("Viewport")
window.visible = True
else:
window = ui.Workspace.get_window("Viewport")
window.visible = False
def _on_single_env_cb_update(self, value):
visibility = "invisible" if value else "inherited"
stage = omni.usd.get_context().get_stage()
env_root = stage.GetPrimAtPath("/World/envs")
if env_root.IsValid():
for i, p in enumerate(env_root.GetChildren()):
p.GetAttribute("visibility").Set(visibility)
if value:
stage.GetPrimAtPath("/World/envs/env_0").GetAttribute("visibility").Set("inherited")
env_pos = self._task._env_pos[0].cpu().numpy().tolist()
camera_pos = [env_pos[0] + 10, env_pos[1] + 10, 3]
camera_target = [env_pos[0], env_pos[1], env_pos[2]]
else:
camera_pos = [10, 10, 3]
camera_target = [0, 0, 0]
camera_state = ViewportCameraState("/OmniverseKit_Persp", get_active_viewport())
camera_state.set_position_world(Gf.Vec3d(*camera_pos), True)
camera_state.set_target_world(Gf.Vec3d(*camera_target), True)
def _on_test_cb_update(self, value):
self._test = value
if value is True and self._checkpoint_path.strip() == "":
self._checkpoint_str.set_value(f"runs/{self._task_name}/nn/{self._task_name}.pth")
def _on_resume_cb_update(self, value):
self._resume = value
if value is True and self._checkpoint_path.strip() == "":
self._checkpoint_str.set_value(f"runs/{self._task_name}/nn/{self._task_name}.pth")
def _on_evaluate_cb_update(self, value):
self._evaluate = value
def _on_checkpoint_update(self, value):
self._checkpoint_path = value.get_value_as_string()
async def _on_load_world_async(self, use_existing_stage):
# initialize task if not initialized
if not self._task_initialized or not omni.usd.get_context().get_stage().GetPrimAtPath("/World/envs").IsValid():
self._parse_config(task=self._task_name, num_envs=self._num_envs_int.get_value_as_int())
self.create_task()
else:
# update config
self._parse_config(task=self._task_name, num_envs=self._num_envs_int.get_value_as_int())
self._task.update_config(self._sim_config)
# clear scene
# self._env._world.scene.clear()
self._env._world._sim_params = self._sim_config.get_physics_params()
await self._env._world.initialize_simulation_context_async()
set_camera_view(eye=[10, 10, 3], target=[0, 0, 0], camera_prim_path="/OmniverseKit_Persp")
if not use_existing_stage:
# clear scene
self._env._world.scene.clear()
# clear environments added to world
omni.usd.get_context().get_stage().RemovePrim("/World/collisions")
omni.usd.get_context().get_stage().RemovePrim("/World/envs")
# create scene
await self._env._world.reset_async_set_up_scene()
# update num_envs in envs
self._env.update_task_params()
else:
self._task.initialize_views(self._env._world.scene)
def _on_load_world(self):
# stop simulation before updating stage
self._timeline.stop()
asyncio.ensure_future(self._on_load_world_async(use_existing_stage=False))
def _on_train_stop(self):
if self._task_initialized:
asyncio.ensure_future(self._env._world.stop_async())
async def _on_train_async(self, overrides=None):
try:
# initialize task if not initialized
print("task initialized:", self._task_initialized)
if not self._task_initialized:
# if this is the first launch of the extension, we do not want to re-create stage if stage already exists
use_existing_stage = False
if omni.usd.get_context().get_stage().GetPrimAtPath("/World/envs").IsValid():
use_existing_stage = True
print(use_existing_stage)
await self._on_load_world_async(use_existing_stage)
# update config
self._parse_config(task=self._task_name, num_envs=self._num_envs_int.get_value_as_int(), overrides=overrides)
sim_config = SimConfig(self._cfg_dict)
self._task.update_config(sim_config)
cfg_dict = omegaconf_to_dict(self._cfg)
# sets seed. if seed is -1 will pick a random one
self._cfg.seed = set_seed(self._cfg.seed, torch_deterministic=self._cfg.torch_deterministic)
cfg_dict["seed"] = self._cfg.seed
self._checkpoint_path = self._checkpoint_str.get_value_as_string()
if self._resume or self._test:
self._cfg.checkpoint = self._checkpoint_path
self._cfg.test = self._test
self._cfg.evaluation = self._evaluate
cfg_dict["checkpoint"] = self._cfg.checkpoint
cfg_dict["test"] = self._cfg.test
cfg_dict["evaluation"] = self._cfg.evaluation
rlg_trainer = RLGTrainer(self._cfg, cfg_dict)
if not rlg_trainer._bad_checkpoint:
trainer = Trainer(rlg_trainer, self._env)
await self._env._world.reset_async_no_set_up_scene()
self._env._render_mode = self._render_dropdown.get_item_value_model().as_int
await self._env.run(trainer)
await omni.kit.app.get_app().next_update_async()
except Exception as e:
print(traceback.format_exc())
finally:
self._is_training = False
def _on_train(self):
# stop simulation if still running
self._timeline.stop()
self._on_render_mode_select(self._render_modes[self._render_dropdown.get_item_value_model().as_int])
if not self._is_training:
self._is_training = True
asyncio.ensure_future(self._on_train_async())
return
def _menu_callback(self):
self._window.visible = not self._window.visible
return
def _on_window(self, status):
return
def on_shutdown(self):
self._extra_frames = []
if self._menu_items is not None:
self._sample_window_cleanup()
self.shutdown_cleanup()
global ext_instance
ext_instance = None
return
def shutdown_cleanup(self):
return
def _sample_window_cleanup(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
self._menu_items = None
self._buttons = None
self._load_env_button = None
self._task_dropdown = None
self._cbs = None
self._checkpoint_str = None
return
def get_instance():
return ext_instance
| 22,236 | Python | 42.262646 | 155 | 0.533189 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/__init__.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import traceback
try:
from .extension import RLExtension, get_instance
# import omniisaacgymenvs.tests
except Exception as e:
pass
# print(e)
# print(traceback.format_exc())
| 1,753 | Python | 46.405404 | 80 | 0.775242 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/envs/vec_env_rlgames_mt.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
import torch
from omni.isaac.gym.vec_env import TaskStopException, VecEnvMT
from .vec_env_rlgames import VecEnvRLGames
# VecEnv Wrapper for RL training
class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT):
def _parse_data(self, data):
self._obs = data["obs"]
self._rew = data["rew"].to(self._task.rl_device)
self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device)
self._resets = data["reset"].to(self._task.rl_device)
self._extras = data["extras"]
def step(self, actions):
if self._stop:
raise TaskStopException()
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(
actions=actions, reset_buf=self._task.reset_buf
)
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device)
self.send_actions(actions)
data = self.get_data()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(
observations=self._obs.to(self._task.rl_device), reset_buf=self._task.reset_buf
)
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device)
obs_dict = {}
obs_dict["obs"] = self._obs
obs_dict["states"] = self._states
return obs_dict, self._rew, self._resets, self._extras
| 3,109 | Python | 42.194444 | 118 | 0.705693 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/envs/vec_env_rlgames.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from datetime import datetime
import numpy as np
import torch
from omni.isaac.gym.vec_env import VecEnvBase
# VecEnv Wrapper for RL training
class VecEnvRLGames(VecEnvBase):
def _process_data(self):
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device)
self._rew = self._rew.to(self._task.rl_device)
self._states = torch.clamp(self._states, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device)
self._resets = self._resets.to(self._task.rl_device)
self._extras = self._extras
def set_task(self, task, backend="numpy", sim_params=None, init_sim=True, rendering_dt=1.0 / 60.0) -> None:
super().set_task(task, backend, sim_params, init_sim, rendering_dt)
self.num_states = self._task.num_states
self.state_space = self._task.state_space
def step(self, actions):
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(
actions=actions, reset_buf=self._task.reset_buf
)
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device)
self._task.pre_physics_step(actions)
if (self.sim_frame_count + self._task.control_frequency_inv) % self._task.rendering_interval == 0:
for _ in range(self._task.control_frequency_inv - 1):
self._world.step(render=False)
self.sim_frame_count += 1
self._world.step(render=self._render)
self.sim_frame_count += 1
else:
for _ in range(self._task.control_frequency_inv):
self._world.step(render=False)
self.sim_frame_count += 1
self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(
observations=self._obs.to(device=self._task.rl_device), reset_buf=self._task.reset_buf
)
self._states = self._task.get_states()
self._process_data()
obs_dict = {"obs": self._obs, "states": self._states}
return obs_dict, self._rew, self._resets, self._extras
def reset(self, seed=None, options=None):
"""Resets the task and applies default zero actions to recompute observations and states."""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{now}] Running RL reset")
self._task.reset()
actions = torch.zeros((self.num_envs, self._task.num_actions), device=self._task.rl_device)
obs_dict, _, _, _ = self.step(actions)
return obs_dict
| 4,328 | Python | 43.628866 | 116 | 0.677218 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/allegro_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.allegro_hand import AllegroHand
from omniisaacgymenvs.robots.articulations.views.allegro_hand_view import AllegroHandView
from omniisaacgymenvs.tasks.shared.in_hand_manipulation import InHandManipulationTask
class AllegroHandTask(InHandManipulationTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
InHandManipulationTask.__init__(self, name=name, env=env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.object_type = self._task_cfg["env"]["objectType"]
assert self.object_type in ["block"]
self.obs_type = self._task_cfg["env"]["observationType"]
if not (self.obs_type in ["full_no_vel", "full"]):
raise Exception("Unknown type of observations!\nobservationType should be one of: [full_no_vel, full]")
print("Obs type:", self.obs_type)
self.num_obs_dict = {
"full_no_vel": 50,
"full": 72,
}
self.object_scale = torch.tensor([1.0, 1.0, 1.0])
self._num_observations = self.num_obs_dict[self.obs_type]
self._num_actions = 16
self._num_states = 0
InHandManipulationTask.update_config(self)
def get_starting_positions(self):
self.hand_start_translation = torch.tensor([0.0, 0.0, 0.5], device=self.device)
self.hand_start_orientation = torch.tensor([0.257551, 0.283045, 0.683330, -0.621782], device=self.device)
self.pose_dy, self.pose_dz = -0.2, 0.06
def get_hand(self):
allegro_hand = AllegroHand(
prim_path=self.default_zero_env_path + "/allegro_hand",
name="allegro_hand",
translation=self.hand_start_translation,
orientation=self.hand_start_orientation,
)
self._sim_config.apply_articulation_settings(
"allegro_hand",
get_prim_at_path(allegro_hand.prim_path),
self._sim_config.parse_actor_config("allegro_hand"),
)
allegro_hand_prim = self._stage.GetPrimAtPath(allegro_hand.prim_path)
allegro_hand.set_allegro_hand_properties(stage=self._stage, allegro_hand_prim=allegro_hand_prim)
allegro_hand.set_motor_control_mode(
stage=self._stage, allegro_hand_path=self.default_zero_env_path + "/allegro_hand"
)
def get_hand_view(self, scene):
return AllegroHandView(prim_paths_expr="/World/envs/.*/allegro_hand", name="allegro_hand_view")
def get_observations(self):
self.get_object_goal_observations()
self.hand_dof_pos = self._hands.get_joint_positions(clone=False)
self.hand_dof_vel = self._hands.get_joint_velocities(clone=False)
if self.obs_type == "full_no_vel":
self.compute_full_observations(True)
elif self.obs_type == "full":
self.compute_full_observations()
else:
print("Unkown observations type!")
observations = {self._hands.name: {"obs_buf": self.obs_buf}}
return observations
def compute_full_observations(self, no_vel=False):
if no_vel:
self.obs_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.obs_buf[:, 16:19] = self.object_pos
self.obs_buf[:, 19:23] = self.object_rot
self.obs_buf[:, 23:26] = self.goal_pos
self.obs_buf[:, 26:30] = self.goal_rot
self.obs_buf[:, 30:34] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 34:50] = self.actions
else:
self.obs_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.obs_buf[:, self.num_hand_dofs : 2 * self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 32:35] = self.object_pos
self.obs_buf[:, 35:39] = self.object_rot
self.obs_buf[:, 39:42] = self.object_linvel
self.obs_buf[:, 42:45] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 45:48] = self.goal_pos
self.obs_buf[:, 48:52] = self.goal_rot
self.obs_buf[:, 52:56] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 56:72] = self.actions
| 6,329 | Python | 42.655172 | 115 | 0.658872 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/ball_balance.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims import RigidPrim, RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.maths import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.balance_bot import BalanceBot
from pxr import PhysxSchema
class BallBalanceTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
self._num_observations = 12 + 12
self._num_actions = 3
self.anchored = False
RLTask.__init__(self, name, env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._dt = self._task_cfg["sim"]["dt"]
self._table_position = torch.tensor([0, 0, 0.56])
self._ball_position = torch.tensor([0.0, 0.0, 1.0])
self._ball_radius = 0.1
self._action_speed_scale = self._task_cfg["env"]["actionSpeedScale"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
def set_up_scene(self, scene) -> None:
self.get_balance_table()
self.add_ball()
super().set_up_scene(scene, replicate_physics=False)
self.set_up_table_anchors()
self._balance_bots = ArticulationView(
prim_paths_expr="/World/envs/.*/BalanceBot/tray", name="balance_bot_view", reset_xform_properties=False
)
scene.add(self._balance_bots)
self._balls = RigidPrimView(
prim_paths_expr="/World/envs/.*/Ball/ball", name="ball_view", reset_xform_properties=False
)
scene.add(self._balls)
return
def initialize_views(self, scene):
super().initialize_views(scene)
if scene.object_exists("balance_bot_view"):
scene.remove_object("balance_bot_view", registry_only=True)
if scene.object_exists("ball_view"):
scene.remove_object("ball_view", registry_only=True)
self._balance_bots = ArticulationView(
prim_paths_expr="/World/envs/.*/BalanceBot/tray", name="balance_bot_view", reset_xform_properties=False
)
scene.add(self._balance_bots)
self._balls = RigidPrimView(
prim_paths_expr="/World/envs/.*/Ball/ball", name="ball_view", reset_xform_properties=False
)
scene.add(self._balls)
def get_balance_table(self):
balance_table = BalanceBot(
prim_path=self.default_zero_env_path + "/BalanceBot", name="BalanceBot", translation=self._table_position
)
self._sim_config.apply_articulation_settings(
"table", get_prim_at_path(balance_table.prim_path), self._sim_config.parse_actor_config("table")
)
def add_ball(self):
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/Ball/ball",
translation=self._ball_position,
name="ball_0",
radius=self._ball_radius,
color=torch.tensor([0.9, 0.6, 0.2]),
)
self._sim_config.apply_articulation_settings(
"ball", get_prim_at_path(ball.prim_path), self._sim_config.parse_actor_config("ball")
)
def set_up_table_anchors(self):
from pxr import Gf
height = 0.08
stage = get_current_stage()
for i in range(self._num_envs):
base_path = f"{self.default_base_env_path}/env_{i}/BalanceBot"
for j, leg_offset in enumerate([(0.4, 0, height), (-0.2, 0.34641, 0), (-0.2, -0.34641, 0)]):
# fix the legs to ground
leg_path = f"{base_path}/lower_leg{j}"
ground_joint_path = leg_path + "_ground"
env_pos = stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}").GetAttribute("xformOp:translate").Get()
anchor_pos = env_pos + Gf.Vec3d(*leg_offset)
self.fix_to_ground(stage, ground_joint_path, leg_path, anchor_pos)
def fix_to_ground(self, stage, joint_path, prim_path, anchor_pos):
from pxr import UsdPhysics, Gf
# D6 fixed joint
d6FixedJoint = UsdPhysics.Joint.Define(stage, joint_path)
d6FixedJoint.CreateBody0Rel().SetTargets(["/World/defaultGroundPlane"])
d6FixedJoint.CreateBody1Rel().SetTargets([prim_path])
d6FixedJoint.CreateLocalPos0Attr().Set(anchor_pos)
d6FixedJoint.CreateLocalRot0Attr().Set(Gf.Quatf(1.0, Gf.Vec3f(0, 0, 0)))
d6FixedJoint.CreateLocalPos1Attr().Set(Gf.Vec3f(0, 0, 0.18))
d6FixedJoint.CreateLocalRot1Attr().Set(Gf.Quatf(1.0, Gf.Vec3f(0, 0, 0)))
# lock all DOF (lock - low is greater than high)
d6Prim = stage.GetPrimAtPath(joint_path)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transX")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transY")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transZ")
limitAPI.CreateLowAttr(1.0)
limitAPI.CreateHighAttr(-1.0)
def get_observations(self) -> dict:
ball_positions, ball_orientations = self._balls.get_world_poses(clone=False)
ball_positions = ball_positions[:, 0:3] - self._env_pos
ball_velocities = self._balls.get_velocities(clone=False)
ball_linvels = ball_velocities[:, 0:3]
ball_angvels = ball_velocities[:, 3:6]
dof_pos = self._balance_bots.get_joint_positions(clone=False)
dof_vel = self._balance_bots.get_joint_velocities(clone=False)
sensor_force_torques = self._balance_bots.get_measured_joint_forces(joint_indices=self._sensor_indices) # (num_envs, num_sensors, 6)
self.obs_buf[..., 0:3] = dof_pos[..., self.actuated_dof_indices]
self.obs_buf[..., 3:6] = dof_vel[..., self.actuated_dof_indices]
self.obs_buf[..., 6:9] = ball_positions
self.obs_buf[..., 9:12] = ball_linvels
self.obs_buf[..., 12:15] = sensor_force_torques[..., 0] / 20.0
self.obs_buf[..., 15:18] = sensor_force_torques[..., 3] / 20.0
self.obs_buf[..., 18:21] = sensor_force_torques[..., 4] / 20.0
self.obs_buf[..., 21:24] = sensor_force_torques[..., 5] / 20.0
self.ball_positions = ball_positions
self.ball_linvels = ball_linvels
observations = {"ball_balance": {"obs_buf": self.obs_buf}}
return observations
def pre_physics_step(self, actions) -> None:
if not self._env._world.is_playing():
return
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
# update position targets from actions
self.dof_position_targets[..., self.actuated_dof_indices] += (
self._dt * self._action_speed_scale * actions.to(self.device)
)
self.dof_position_targets[:] = tensor_clamp(
self.dof_position_targets, self.bbot_dof_lower_limits, self.bbot_dof_upper_limits
)
# reset position targets for reset envs
self.dof_position_targets[reset_env_ids] = 0
self._balance_bots.set_joint_position_targets(self.dof_position_targets) # .clone())
def reset_idx(self, env_ids):
num_resets = len(env_ids)
env_ids_32 = env_ids.type(torch.int32)
env_ids_64 = env_ids.type(torch.int64)
min_d = 0.001 # min horizontal dist from origin
max_d = 0.4 # max horizontal dist from origin
min_height = 1.0
max_height = 2.0
min_horizontal_speed = 0
max_horizontal_speed = 2
dists = torch_rand_float(min_d, max_d, (num_resets, 1), self._device)
dirs = torch_random_dir_2((num_resets, 1), self._device)
hpos = dists * dirs
speedscales = (dists - min_d) / (max_d - min_d)
hspeeds = torch_rand_float(min_horizontal_speed, max_horizontal_speed, (num_resets, 1), self._device)
hvels = -speedscales * hspeeds * dirs
vspeeds = -torch_rand_float(5.0, 5.0, (num_resets, 1), self._device).squeeze()
ball_pos = self.initial_ball_pos.clone()
ball_rot = self.initial_ball_rot.clone()
# position
ball_pos[env_ids_64, 0:2] += hpos[..., 0:2]
ball_pos[env_ids_64, 2] += torch_rand_float(min_height, max_height, (num_resets, 1), self._device).squeeze()
# rotation
ball_rot[env_ids_64, 0] = 1
ball_rot[env_ids_64, 1:] = 0
ball_velocities = self.initial_ball_velocities.clone()
# linear
ball_velocities[env_ids_64, 0:2] = hvels[..., 0:2]
ball_velocities[env_ids_64, 2] = vspeeds
# angular
ball_velocities[env_ids_64, 3:6] = 0
# reset root state for bbots and balls in selected envs
self._balls.set_world_poses(ball_pos[env_ids_64], ball_rot[env_ids_64], indices=env_ids_32)
self._balls.set_velocities(ball_velocities[env_ids_64], indices=env_ids_32)
# reset root pose and velocity
self._balance_bots.set_world_poses(
self.initial_bot_pos[env_ids_64].clone(), self.initial_bot_rot[env_ids_64].clone(), indices=env_ids_32
)
self._balance_bots.set_velocities(self.initial_bot_velocities[env_ids_64].clone(), indices=env_ids_32)
# reset DOF states for bbots in selected envs
self._balance_bots.set_joint_positions(self.initial_dof_positions[env_ids_64].clone(), indices=env_ids_32)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self):
dof_limits = self._balance_bots.get_dof_limits()
self.bbot_dof_lower_limits, self.bbot_dof_upper_limits = torch.t(dof_limits[0].to(device=self._device))
self.initial_dof_positions = self._balance_bots.get_joint_positions()
self.initial_bot_pos, self.initial_bot_rot = self._balance_bots.get_world_poses()
# self.initial_bot_pos[..., 2] = 0.559 # tray_height
self.initial_bot_velocities = self._balance_bots.get_velocities()
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
self.initial_ball_velocities = self._balls.get_velocities()
self.dof_position_targets = torch.zeros(
(self.num_envs, self._balance_bots.num_dof), dtype=torch.float32, device=self._device, requires_grad=False
)
actuated_joints = ["lower_leg0", "lower_leg1", "lower_leg2"]
self.actuated_dof_indices = torch.tensor(
[self._balance_bots._dof_indices[j] for j in actuated_joints], device=self._device, dtype=torch.long
)
force_links = ["upper_leg0", "upper_leg1", "upper_leg2"]
self._sensor_indices = torch.tensor(
[self._balance_bots._body_indices[j] for j in force_links], device=self._device, dtype=torch.long
)
def calculate_metrics(self) -> None:
ball_dist = torch.sqrt(
self.ball_positions[..., 0] * self.ball_positions[..., 0]
+ (self.ball_positions[..., 2] - 0.7) * (self.ball_positions[..., 2] - 0.7)
+ (self.ball_positions[..., 1]) * self.ball_positions[..., 1]
)
ball_speed = torch.sqrt(
self.ball_linvels[..., 0] * self.ball_linvels[..., 0]
+ self.ball_linvels[..., 1] * self.ball_linvels[..., 1]
+ self.ball_linvels[..., 2] * self.ball_linvels[..., 2]
)
pos_reward = 1.0 / (1.0 + ball_dist)
speed_reward = 1.0 / (1.0 + ball_speed)
self.rew_buf[:] = pos_reward * speed_reward
def is_done(self) -> None:
reset = torch.where(
self.progress_buf >= self._max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf
)
reset = torch.where(
self.ball_positions[..., 2] < self._ball_radius * 1.5, torch.ones_like(self.reset_buf), reset
)
self.reset_buf[:] = reset
| 13,958 | Python | 44.174757 | 140 | 0.630391 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/cartpole_camera.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from gym import spaces
import numpy as np
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.tasks.cartpole import CartpoleTask
from omniisaacgymenvs.robots.articulations.cartpole import Cartpole
class CartpoleCameraTask(CartpoleTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
self._max_episode_length = 500
self._num_observations = self.camera_width * self.camera_height * 3
self._num_actions = 1
# use multi-dimensional observation for camera RGB
self.observation_space = spaces.Box(
np.ones((self.camera_width, self.camera_height, 3), dtype=np.float32) * -np.Inf,
np.ones((self.camera_width, self.camera_height, 3), dtype=np.float32) * np.Inf)
RLTask.__init__(self, name, env)
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._cartpole_positions = torch.tensor([0.0, 0.0, 2.0])
self._reset_dist = self._task_cfg["env"]["resetDist"]
self._max_push_effort = self._task_cfg["env"]["maxEffort"]
self.camera_type = self._task_cfg["env"].get("cameraType", 'rgb')
self.camera_width = self._task_cfg["env"]["cameraWidth"]
self.camera_height = self._task_cfg["env"]["cameraHeight"]
self.camera_channels = 3
self._export_images = self._task_cfg["env"]["exportImages"]
def cleanup(self) -> None:
# initialize remaining buffers
RLTask.cleanup(self)
# override observation buffer for camera data
self.obs_buf = torch.zeros(
(self.num_envs, self.camera_width, self.camera_height, 3), device=self.device, dtype=torch.float)
def set_up_scene(self, scene) -> None:
self.get_cartpole()
RLTask.set_up_scene(self, scene)
# start replicator to capture image data
self.rep.orchestrator._orchestrator._is_started = True
# set up cameras
self.render_products = []
env_pos = self._env_pos.cpu()
for i in range(self._num_envs):
camera = self.rep.create.camera(
position=(-4.2 + env_pos[i][0], env_pos[i][1], 3.0), look_at=(env_pos[i][0], env_pos[i][1], 2.55))
render_product = self.rep.create.render_product(camera, resolution=(self.camera_width, self.camera_height))
self.render_products.append(render_product)
# initialize pytorch writer for vectorized collection
self.pytorch_listener = self.PytorchListener()
self.pytorch_writer = self.rep.WriterRegistry.get("PytorchWriter")
self.pytorch_writer.initialize(listener=self.pytorch_listener, device="cuda")
self.pytorch_writer.attach(self.render_products)
self._cartpoles = ArticulationView(
prim_paths_expr="/World/envs/.*/Cartpole", name="cartpole_view", reset_xform_properties=False
)
scene.add(self._cartpoles)
return
def get_observations(self) -> dict:
dof_pos = self._cartpoles.get_joint_positions(clone=False)
dof_vel = self._cartpoles.get_joint_velocities(clone=False)
self.cart_pos = dof_pos[:, self._cart_dof_idx]
self.cart_vel = dof_vel[:, self._cart_dof_idx]
self.pole_pos = dof_pos[:, self._pole_dof_idx]
self.pole_vel = dof_vel[:, self._pole_dof_idx]
# retrieve RGB data from all render products
images = self.pytorch_listener.get_rgb_data()
if images is not None:
if self._export_images:
from torchvision.utils import save_image, make_grid
img = images/255
save_image(make_grid(img, nrows = 2), 'cartpole_export.png')
self.obs_buf = torch.swapaxes(images, 1, 3).clone().float()/255.0
else:
print("Image tensor is NONE!")
return self.obs_buf
| 5,865 | Python | 41.817518 | 119 | 0.673998 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/anymal_terrain.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.anymal import Anymal
from omniisaacgymenvs.robots.articulations.views.anymal_view import AnymalView
from omniisaacgymenvs.tasks.utils.anymal_terrain_generator import *
from omniisaacgymenvs.utils.terrain_utils.terrain_utils import *
from pxr import UsdLux, UsdPhysics
class AnymalTerrainTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.height_samples = None
self.custom_origins = False
self.init_done = False
self._env_spacing = 0.0
self._num_observations = 188
self._num_actions = 12
self.update_config(sim_config)
RLTask.__init__(self, name, env)
self.height_points = self.init_height_points()
self.measured_heights = None
# joint positions offsets
self.default_dof_pos = torch.zeros(
(self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False
)
# reward episode sums
torch_zeros = lambda: torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {
"lin_vel_xy": torch_zeros(),
"lin_vel_z": torch_zeros(),
"ang_vel_z": torch_zeros(),
"ang_vel_xy": torch_zeros(),
"orient": torch_zeros(),
"torques": torch_zeros(),
"joint_acc": torch_zeros(),
"base_height": torch_zeros(),
"air_time": torch_zeros(),
"collision": torch_zeros(),
"stumble": torch_zeros(),
"action_rate": torch_zeros(),
"hip": torch_zeros(),
}
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# normalization
self.lin_vel_scale = self._task_cfg["env"]["learn"]["linearVelocityScale"]
self.ang_vel_scale = self._task_cfg["env"]["learn"]["angularVelocityScale"]
self.dof_pos_scale = self._task_cfg["env"]["learn"]["dofPositionScale"]
self.dof_vel_scale = self._task_cfg["env"]["learn"]["dofVelocityScale"]
self.height_meas_scale = self._task_cfg["env"]["learn"]["heightMeasurementScale"]
self.action_scale = self._task_cfg["env"]["control"]["actionScale"]
# reward scales
self.rew_scales = {}
self.rew_scales["termination"] = self._task_cfg["env"]["learn"]["terminalReward"]
self.rew_scales["lin_vel_xy"] = self._task_cfg["env"]["learn"]["linearVelocityXYRewardScale"]
self.rew_scales["lin_vel_z"] = self._task_cfg["env"]["learn"]["linearVelocityZRewardScale"]
self.rew_scales["ang_vel_z"] = self._task_cfg["env"]["learn"]["angularVelocityZRewardScale"]
self.rew_scales["ang_vel_xy"] = self._task_cfg["env"]["learn"]["angularVelocityXYRewardScale"]
self.rew_scales["orient"] = self._task_cfg["env"]["learn"]["orientationRewardScale"]
self.rew_scales["torque"] = self._task_cfg["env"]["learn"]["torqueRewardScale"]
self.rew_scales["joint_acc"] = self._task_cfg["env"]["learn"]["jointAccRewardScale"]
self.rew_scales["base_height"] = self._task_cfg["env"]["learn"]["baseHeightRewardScale"]
self.rew_scales["action_rate"] = self._task_cfg["env"]["learn"]["actionRateRewardScale"]
self.rew_scales["hip"] = self._task_cfg["env"]["learn"]["hipRewardScale"]
self.rew_scales["fallen_over"] = self._task_cfg["env"]["learn"]["fallenOverRewardScale"]
# command ranges
self.command_x_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_x"]
self.command_y_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_y"]
self.command_yaw_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["yaw"]
# base init state
pos = self._task_cfg["env"]["baseInitState"]["pos"]
rot = self._task_cfg["env"]["baseInitState"]["rot"]
v_lin = self._task_cfg["env"]["baseInitState"]["vLinear"]
v_ang = self._task_cfg["env"]["baseInitState"]["vAngular"]
self.base_init_state = pos + rot + v_lin + v_ang
# default joint positions
self.named_default_joint_angles = self._task_cfg["env"]["defaultJointAngles"]
# other
self.decimation = self._task_cfg["env"]["control"]["decimation"]
self.dt = self.decimation * self._task_cfg["sim"]["dt"]
self.max_episode_length_s = self._task_cfg["env"]["learn"]["episodeLength_s"]
self.max_episode_length = int(self.max_episode_length_s / self.dt + 0.5)
self.push_interval = int(self._task_cfg["env"]["learn"]["pushInterval_s"] / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
self.curriculum = self._task_cfg["env"]["terrain"]["curriculum"]
self.base_threshold = 0.2
self.knee_threshold = 0.1
for key in self.rew_scales.keys():
self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._task_cfg["sim"]["default_physics_material"]["static_friction"] = self._task_cfg["env"]["terrain"][
"staticFriction"
]
self._task_cfg["sim"]["default_physics_material"]["dynamic_friction"] = self._task_cfg["env"]["terrain"][
"dynamicFriction"
]
self._task_cfg["sim"]["default_physics_material"]["restitution"] = self._task_cfg["env"]["terrain"][
"restitution"
]
self._task_cfg["sim"]["add_ground_plane"] = False
def _get_noise_scale_vec(self, cfg):
noise_vec = torch.zeros_like(self.obs_buf[0])
self.add_noise = self._task_cfg["env"]["learn"]["addNoise"]
noise_level = self._task_cfg["env"]["learn"]["noiseLevel"]
noise_vec[:3] = self._task_cfg["env"]["learn"]["linearVelocityNoise"] * noise_level * self.lin_vel_scale
noise_vec[3:6] = self._task_cfg["env"]["learn"]["angularVelocityNoise"] * noise_level * self.ang_vel_scale
noise_vec[6:9] = self._task_cfg["env"]["learn"]["gravityNoise"] * noise_level
noise_vec[9:12] = 0.0 # commands
noise_vec[12:24] = self._task_cfg["env"]["learn"]["dofPositionNoise"] * noise_level * self.dof_pos_scale
noise_vec[24:36] = self._task_cfg["env"]["learn"]["dofVelocityNoise"] * noise_level * self.dof_vel_scale
noise_vec[36:176] = (
self._task_cfg["env"]["learn"]["heightMeasurementNoise"] * noise_level * self.height_meas_scale
)
noise_vec[176:188] = 0.0 # previous actions
return noise_vec
def init_height_points(self):
# 1mx1.6m rectangle (without center line)
y = 0.1 * torch.tensor(
[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5], device=self.device, requires_grad=False
) # 10-50cm on each side
x = 0.1 * torch.tensor(
[-8, -7, -6, -5, -4, -3, -2, 2, 3, 4, 5, 6, 7, 8], device=self.device, requires_grad=False
) # 20-80cm on each side
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
self.num_height_points = grid_x.numel()
points = torch.zeros(self.num_envs, self.num_height_points, 3, device=self.device, requires_grad=False)
points[:, :, 0] = grid_x.flatten()
points[:, :, 1] = grid_y.flatten()
return points
def _create_trimesh(self, create_mesh=True):
self.terrain = Terrain(self._task_cfg["env"]["terrain"], num_robots=self.num_envs)
vertices = self.terrain.vertices
triangles = self.terrain.triangles
position = torch.tensor([-self.terrain.border_size, -self.terrain.border_size, 0.0])
if create_mesh:
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position)
self.height_samples = (
torch.tensor(self.terrain.heightsamples).view(self.terrain.tot_rows, self.terrain.tot_cols).to(self.device)
)
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self.get_terrain()
self.get_anymal()
super().set_up_scene(scene, collision_filter_global_paths=["/World/terrain"])
self._anymals = AnymalView(
prim_paths_expr="/World/envs/.*/anymal", name="anymal_view", track_contact_forces=True
)
scene.add(self._anymals)
scene.add(self._anymals._knees)
scene.add(self._anymals._base)
def initialize_views(self, scene):
# initialize terrain variables even if we do not need to re-create the terrain mesh
self.get_terrain(create_mesh=False)
super().initialize_views(scene)
if scene.object_exists("anymal_view"):
scene.remove_object("anymal_view", registry_only=True)
if scene.object_exists("knees_view"):
scene.remove_object("knees_view", registry_only=True)
if scene.object_exists("base_view"):
scene.remove_object("base_view", registry_only=True)
self._anymals = AnymalView(
prim_paths_expr="/World/envs/.*/anymal", name="anymal_view", track_contact_forces=True
)
scene.add(self._anymals)
scene.add(self._anymals._knees)
scene.add(self._anymals._base)
def get_terrain(self, create_mesh=True):
self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
if not self.curriculum:
self._task_cfg["env"]["terrain"]["maxInitMapLevel"] = self._task_cfg["env"]["terrain"]["numLevels"] - 1
self.terrain_levels = torch.randint(
0, self._task_cfg["env"]["terrain"]["maxInitMapLevel"] + 1, (self.num_envs,), device=self.device
)
self.terrain_types = torch.randint(
0, self._task_cfg["env"]["terrain"]["numTerrains"], (self.num_envs,), device=self.device
)
self._create_trimesh(create_mesh=create_mesh)
self.terrain_origins = torch.from_numpy(self.terrain.env_origins).to(self.device).to(torch.float)
def get_anymal(self):
anymal_translation = torch.tensor([0.0, 0.0, 0.66])
anymal_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0])
anymal = Anymal(
prim_path=self.default_zero_env_path + "/anymal",
name="anymal",
translation=anymal_translation,
orientation=anymal_orientation,
)
self._sim_config.apply_articulation_settings(
"anymal", get_prim_at_path(anymal.prim_path), self._sim_config.parse_actor_config("anymal")
)
anymal.set_anymal_properties(self._stage, anymal.prim)
anymal.prepare_contacts(self._stage, anymal.prim)
self.dof_names = anymal.dof_names
for i in range(self.num_actions):
name = self.dof_names[i]
angle = self.named_default_joint_angles[name]
self.default_dof_pos[:, i] = angle
def post_reset(self):
self.base_init_state = torch.tensor(
self.base_init_state, dtype=torch.float, device=self.device, requires_grad=False
)
self.timeout_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# initialize some data used later on
self.up_axis_idx = 2
self.common_step_counter = 0
self.extras = {}
self.noise_scale_vec = self._get_noise_scale_vec(self._task_cfg)
self.commands = torch.zeros(
self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False
) # x vel, y vel, yaw vel, heading
self.commands_scale = torch.tensor(
[self.lin_vel_scale, self.lin_vel_scale, self.ang_vel_scale],
device=self.device,
requires_grad=False,
)
self.gravity_vec = torch.tensor(
get_axis_params(-1.0, self.up_axis_idx), dtype=torch.float, device=self.device
).repeat((self.num_envs, 1))
self.forward_vec = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float, device=self.device).repeat(
(self.num_envs, 1)
)
self.torques = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.last_actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.feet_air_time = torch.zeros(self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False)
self.last_dof_vel = torch.zeros((self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False)
for i in range(self.num_envs):
self.env_origins[i] = self.terrain_origins[self.terrain_levels[i], self.terrain_types[i]]
self.num_dof = self._anymals.num_dof
self.dof_pos = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.dof_vel = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.base_pos = torch.zeros((self.num_envs, 3), dtype=torch.float, device=self.device)
self.base_quat = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device)
self.base_velocities = torch.zeros((self.num_envs, 6), dtype=torch.float, device=self.device)
self.knee_pos = torch.zeros((self.num_envs * 4, 3), dtype=torch.float, device=self.device)
self.knee_quat = torch.zeros((self.num_envs * 4, 4), dtype=torch.float, device=self.device)
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
self.init_done = True
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
positions_offset = torch_rand_float(0.5, 1.5, (len(env_ids), self.num_dof), device=self.device)
velocities = torch_rand_float(-0.1, 0.1, (len(env_ids), self.num_dof), device=self.device)
self.dof_pos[env_ids] = self.default_dof_pos[env_ids] * positions_offset
self.dof_vel[env_ids] = velocities
self.update_terrain_level(env_ids)
self.base_pos[env_ids] = self.base_init_state[0:3]
self.base_pos[env_ids, 0:3] += self.env_origins[env_ids]
self.base_pos[env_ids, 0:2] += torch_rand_float(-0.5, 0.5, (len(env_ids), 2), device=self.device)
self.base_quat[env_ids] = self.base_init_state[3:7]
self.base_velocities[env_ids] = self.base_init_state[7:]
self._anymals.set_world_poses(
positions=self.base_pos[env_ids].clone(), orientations=self.base_quat[env_ids].clone(), indices=indices
)
self._anymals.set_velocities(velocities=self.base_velocities[env_ids].clone(), indices=indices)
self._anymals.set_joint_positions(positions=self.dof_pos[env_ids].clone(), indices=indices)
self._anymals.set_joint_velocities(velocities=self.dof_vel[env_ids].clone(), indices=indices)
self.commands[env_ids, 0] = torch_rand_float(
self.command_x_range[0], self.command_x_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 1] = torch_rand_float(
self.command_y_range[0], self.command_y_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 3] = torch_rand_float(
self.command_yaw_range[0], self.command_yaw_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids] *= (torch.norm(self.commands[env_ids, :2], dim=1) > 0.25).unsqueeze(
1
) # set small commands to zero
self.last_actions[env_ids] = 0.0
self.last_dof_vel[env_ids] = 0.0
self.feet_air_time[env_ids] = 0.0
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 1
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"]["rew_" + key] = (
torch.mean(self.episode_sums[key][env_ids]) / self.max_episode_length_s
)
self.episode_sums[key][env_ids] = 0.0
self.extras["episode"]["terrain_level"] = torch.mean(self.terrain_levels.float())
def update_terrain_level(self, env_ids):
if not self.init_done or not self.curriculum:
# do not change on initial reset
return
root_pos, _ = self._anymals.get_world_poses(clone=False)
distance = torch.norm(root_pos[env_ids, :2] - self.env_origins[env_ids, :2], dim=1)
self.terrain_levels[env_ids] -= 1 * (
distance < torch.norm(self.commands[env_ids, :2]) * self.max_episode_length_s * 0.25
)
self.terrain_levels[env_ids] += 1 * (distance > self.terrain.env_length / 2)
self.terrain_levels[env_ids] = torch.clip(self.terrain_levels[env_ids], 0) % self.terrain.env_rows
self.env_origins[env_ids] = self.terrain_origins[self.terrain_levels[env_ids], self.terrain_types[env_ids]]
def refresh_dof_state_tensors(self):
self.dof_pos = self._anymals.get_joint_positions(clone=False)
self.dof_vel = self._anymals.get_joint_velocities(clone=False)
def refresh_body_state_tensors(self):
self.base_pos, self.base_quat = self._anymals.get_world_poses(clone=False)
self.base_velocities = self._anymals.get_velocities(clone=False)
self.knee_pos, self.knee_quat = self._anymals._knees.get_world_poses(clone=False)
def pre_physics_step(self, actions):
if not self._env._world.is_playing():
return
self.actions = actions.clone().to(self.device)
for i in range(self.decimation):
if self._env._world.is_playing():
torques = torch.clip(
self.Kp * (self.action_scale * self.actions + self.default_dof_pos - self.dof_pos)
- self.Kd * self.dof_vel,
-80.0,
80.0,
)
self._anymals.set_joint_efforts(torques)
self.torques = torques
SimulationContext.step(self._env._world, render=False)
self.refresh_dof_state_tensors()
def post_physics_step(self):
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.refresh_dof_state_tensors()
self.refresh_body_state_tensors()
self.common_step_counter += 1
if self.common_step_counter % self.push_interval == 0:
self.push_robots()
# prepare quantities
self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3])
self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6])
self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec)
forward = quat_apply(self.base_quat, self.forward_vec)
heading = torch.atan2(forward[:, 1], forward[:, 0])
self.commands[:, 2] = torch.clip(0.5 * wrap_to_pi(self.commands[:, 3] - heading), -1.0, 1.0)
self.check_termination()
self.get_states()
self.calculate_metrics()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = self.dof_vel[:]
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
def push_robots(self):
self.base_velocities[:, 0:2] = torch_rand_float(
-1.0, 1.0, (self.num_envs, 2), device=self.device
) # lin vel x/y
self._anymals.set_velocities(self.base_velocities)
def check_termination(self):
self.timeout_buf = torch.where(
self.progress_buf >= self.max_episode_length - 1,
torch.ones_like(self.timeout_buf),
torch.zeros_like(self.timeout_buf),
)
knee_contact = (
torch.norm(self._anymals._knees.get_net_contact_forces(clone=False).view(self._num_envs, 4, 3), dim=-1)
> 1.0
)
self.has_fallen = (torch.norm(self._anymals._base.get_net_contact_forces(clone=False), dim=1) > 1.0) | (
torch.sum(knee_contact, dim=-1) > 1.0
)
self.reset_buf = self.has_fallen.clone()
self.reset_buf = torch.where(self.timeout_buf.bool(), torch.ones_like(self.reset_buf), self.reset_buf)
def calculate_metrics(self):
# velocity tracking reward
lin_vel_error = torch.sum(torch.square(self.commands[:, :2] - self.base_lin_vel[:, :2]), dim=1)
ang_vel_error = torch.square(self.commands[:, 2] - self.base_ang_vel[:, 2])
rew_lin_vel_xy = torch.exp(-lin_vel_error / 0.25) * self.rew_scales["lin_vel_xy"]
rew_ang_vel_z = torch.exp(-ang_vel_error / 0.25) * self.rew_scales["ang_vel_z"]
# other base velocity penalties
rew_lin_vel_z = torch.square(self.base_lin_vel[:, 2]) * self.rew_scales["lin_vel_z"]
rew_ang_vel_xy = torch.sum(torch.square(self.base_ang_vel[:, :2]), dim=1) * self.rew_scales["ang_vel_xy"]
# orientation penalty
rew_orient = torch.sum(torch.square(self.projected_gravity[:, :2]), dim=1) * self.rew_scales["orient"]
# base height penalty
rew_base_height = torch.square(self.base_pos[:, 2] - 0.52) * self.rew_scales["base_height"]
# torque penalty
rew_torque = torch.sum(torch.square(self.torques), dim=1) * self.rew_scales["torque"]
# joint acc penalty
rew_joint_acc = torch.sum(torch.square(self.last_dof_vel - self.dof_vel), dim=1) * self.rew_scales["joint_acc"]
# fallen over penalty
rew_fallen_over = self.has_fallen * self.rew_scales["fallen_over"]
# action rate penalty
rew_action_rate = (
torch.sum(torch.square(self.last_actions - self.actions), dim=1) * self.rew_scales["action_rate"]
)
# cosmetic penalty for hip motion
rew_hip = (
torch.sum(torch.abs(self.dof_pos[:, 0:4] - self.default_dof_pos[:, 0:4]), dim=1) * self.rew_scales["hip"]
)
# total reward
self.rew_buf = (
rew_lin_vel_xy
+ rew_ang_vel_z
+ rew_lin_vel_z
+ rew_ang_vel_xy
+ rew_orient
+ rew_base_height
+ rew_torque
+ rew_joint_acc
+ rew_action_rate
+ rew_hip
+ rew_fallen_over
)
self.rew_buf = torch.clip(self.rew_buf, min=0.0, max=None)
# add termination reward
self.rew_buf += self.rew_scales["termination"] * self.reset_buf * ~self.timeout_buf
# log episode reward sums
self.episode_sums["lin_vel_xy"] += rew_lin_vel_xy
self.episode_sums["ang_vel_z"] += rew_ang_vel_z
self.episode_sums["lin_vel_z"] += rew_lin_vel_z
self.episode_sums["ang_vel_xy"] += rew_ang_vel_xy
self.episode_sums["orient"] += rew_orient
self.episode_sums["torques"] += rew_torque
self.episode_sums["joint_acc"] += rew_joint_acc
self.episode_sums["action_rate"] += rew_action_rate
self.episode_sums["base_height"] += rew_base_height
self.episode_sums["hip"] += rew_hip
def get_observations(self):
self.measured_heights = self.get_heights()
heights = (
torch.clip(self.base_pos[:, 2].unsqueeze(1) - 0.5 - self.measured_heights, -1, 1.0) * self.height_meas_scale
)
self.obs_buf = torch.cat(
(
self.base_lin_vel * self.lin_vel_scale,
self.base_ang_vel * self.ang_vel_scale,
self.projected_gravity,
self.commands[:, :3] * self.commands_scale,
self.dof_pos * self.dof_pos_scale,
self.dof_vel * self.dof_vel_scale,
heights,
self.actions,
),
dim=-1,
)
def get_ground_heights_below_knees(self):
points = self.knee_pos.reshape(self.num_envs, 4, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_ground_heights_below_base(self):
points = self.base_pos.reshape(self.num_envs, 1, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_heights(self, env_ids=None):
if env_ids:
points = quat_apply_yaw(
self.base_quat[env_ids].repeat(1, self.num_height_points), self.height_points[env_ids]
) + (self.base_pos[env_ids, 0:3]).unsqueeze(1)
else:
points = quat_apply_yaw(self.base_quat.repeat(1, self.num_height_points), self.height_points) + (
self.base_pos[:, 0:3]
).unsqueeze(1)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
@torch.jit.script
def quat_apply_yaw(quat, vec):
quat_yaw = quat.clone().view(-1, 4)
quat_yaw[:, 1:3] = 0.0
quat_yaw = normalize(quat_yaw)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def wrap_to_pi(angles):
angles %= 2 * np.pi
angles -= 2 * np.pi * (angles > np.pi)
return angles
def get_axis_params(value, axis_idx, x_value=0.0, dtype=float, n_dims=3):
"""construct arguments to `Vec` according to axis index."""
zs = np.zeros((n_dims,))
assert axis_idx < n_dims, "the axis dim should be within the vector dimensions"
zs[axis_idx] = 1.0
params = np.where(zs == 1.0, value, zs)
params[0] = x_value
return list(params.astype(dtype))
| 29,337 | Python | 45.568254 | 120 | 0.609128 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/shadow_hand.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.shadow_hand import ShadowHand
from omniisaacgymenvs.robots.articulations.views.shadow_hand_view import ShadowHandView
from omniisaacgymenvs.tasks.shared.in_hand_manipulation import InHandManipulationTask
class ShadowHandTask(InHandManipulationTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
InHandManipulationTask.__init__(self, name=name, env=env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self.object_type = self._task_cfg["env"]["objectType"]
assert self.object_type in ["block"]
self.obs_type = self._task_cfg["env"]["observationType"]
if not (self.obs_type in ["openai", "full_no_vel", "full", "full_state"]):
raise Exception(
"Unknown type of observations!\nobservationType should be one of: [openai, full_no_vel, full, full_state]"
)
print("Obs type:", self.obs_type)
self.num_obs_dict = {
"openai": 42,
"full_no_vel": 77,
"full": 157,
"full_state": 187,
}
self.asymmetric_obs = self._task_cfg["env"]["asymmetric_observations"]
self.use_vel_obs = False
self.fingertip_obs = True
self.fingertips = [
"robot0:ffdistal",
"robot0:mfdistal",
"robot0:rfdistal",
"robot0:lfdistal",
"robot0:thdistal",
]
self.num_fingertips = len(self.fingertips)
self.object_scale = torch.tensor([1.0, 1.0, 1.0])
self.force_torque_obs_scale = 10.0
num_states = 0
if self.asymmetric_obs:
num_states = 187
self._num_observations = self.num_obs_dict[self.obs_type]
self._num_actions = 20
self._num_states = num_states
InHandManipulationTask.update_config(self)
def get_starting_positions(self):
self.hand_start_translation = torch.tensor([0.0, 0.0, 0.5], device=self.device)
self.hand_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
self.pose_dy, self.pose_dz = -0.39, 0.10
def get_hand(self):
shadow_hand = ShadowHand(
prim_path=self.default_zero_env_path + "/shadow_hand",
name="shadow_hand",
translation=self.hand_start_translation,
orientation=self.hand_start_orientation,
)
self._sim_config.apply_articulation_settings(
"shadow_hand",
get_prim_at_path(shadow_hand.prim_path),
self._sim_config.parse_actor_config("shadow_hand"),
)
shadow_hand.set_shadow_hand_properties(stage=self._stage, shadow_hand_prim=shadow_hand.prim)
shadow_hand.set_motor_control_mode(stage=self._stage, shadow_hand_path=shadow_hand.prim_path)
def get_hand_view(self, scene):
hand_view = ShadowHandView(prim_paths_expr="/World/envs/.*/shadow_hand", name="shadow_hand_view")
scene.add(hand_view._fingers)
return hand_view
def get_observations(self):
self.get_object_goal_observations()
self.fingertip_pos, self.fingertip_rot = self._hands._fingers.get_world_poses(clone=False)
self.fingertip_pos -= self._env_pos.repeat((1, self.num_fingertips)).reshape(
self.num_envs * self.num_fingertips, 3
)
self.fingertip_velocities = self._hands._fingers.get_velocities(clone=False)
self.hand_dof_pos = self._hands.get_joint_positions(clone=False)
self.hand_dof_vel = self._hands.get_joint_velocities(clone=False)
if self.obs_type == "full_state" or self.asymmetric_obs:
self.vec_sensor_tensor = self._hands.get_measured_joint_forces(
joint_indices=self._hands._sensor_indices
).view(self._num_envs, -1)
if self.obs_type == "openai":
self.compute_fingertip_observations(True)
elif self.obs_type == "full_no_vel":
self.compute_full_observations(True)
elif self.obs_type == "full":
self.compute_full_observations()
elif self.obs_type == "full_state":
self.compute_full_state(False)
else:
print("Unkown observations type!")
if self.asymmetric_obs:
self.compute_full_state(True)
observations = {self._hands.name: {"obs_buf": self.obs_buf}}
return observations
def compute_fingertip_observations(self, no_vel=False):
if no_vel:
# Per https://arxiv.org/pdf/1808.00177.pdf Table 2
# Fingertip positions
# Object Position, but not orientation
# Relative target orientation
# 3*self.num_fingertips = 15
self.obs_buf[:, 0:15] = self.fingertip_pos.reshape(self.num_envs, 15)
self.obs_buf[:, 15:18] = self.object_pos
self.obs_buf[:, 18:22] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 22:42] = self.actions
else:
# 13*self.num_fingertips = 65
self.obs_buf[:, 0:65] = self.fingertip_state.reshape(self.num_envs, 65)
self.obs_buf[:, 0:15] = self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips)
self.obs_buf[:, 15:35] = self.fingertip_rot.reshape(self.num_envs, 4 * self.num_fingertips)
self.obs_buf[:, 35:65] = self.fingertip_velocities.reshape(self.num_envs, 6 * self.num_fingertips)
self.obs_buf[:, 65:68] = self.object_pos
self.obs_buf[:, 68:72] = self.object_rot
self.obs_buf[:, 72:75] = self.object_linvel
self.obs_buf[:, 75:78] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 78:81] = self.goal_pos
self.obs_buf[:, 81:85] = self.goal_rot
self.obs_buf[:, 85:89] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 89:109] = self.actions
def compute_full_observations(self, no_vel=False):
if no_vel:
self.obs_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.obs_buf[:, 24:37] = self.object_pos
self.obs_buf[:, 27:31] = self.object_rot
self.obs_buf[:, 31:34] = self.goal_pos
self.obs_buf[:, 34:38] = self.goal_rot
self.obs_buf[:, 38:42] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
self.obs_buf[:, 42:57] = self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips)
self.obs_buf[:, 57:77] = self.actions
else:
self.obs_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.obs_buf[:, self.num_hand_dofs : 2 * self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 48:51] = self.object_pos
self.obs_buf[:, 51:55] = self.object_rot
self.obs_buf[:, 55:58] = self.object_linvel
self.obs_buf[:, 58:61] = self.vel_obs_scale * self.object_angvel
self.obs_buf[:, 61:64] = self.goal_pos
self.obs_buf[:, 64:68] = self.goal_rot
self.obs_buf[:, 68:72] = quat_mul(self.object_rot, quat_conjugate(self.goal_rot))
# (7+6)*self.num_fingertips = 65
self.obs_buf[:, 72:87] = self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips)
self.obs_buf[:, 87:107] = self.fingertip_rot.reshape(self.num_envs, 4 * self.num_fingertips)
self.obs_buf[:, 107:137] = self.fingertip_velocities.reshape(self.num_envs, 6 * self.num_fingertips)
self.obs_buf[:, 137:157] = self.actions
def compute_full_state(self, asymm_obs=False):
if asymm_obs:
self.states_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.states_buf[:, self.num_hand_dofs : 2 * self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
# self.states_buf[:, 2*self.num_hand_dofs:3*self.num_hand_dofs] = self.force_torque_obs_scale * self.dof_force_tensor
obj_obs_start = 2 * self.num_hand_dofs # 48
self.states_buf[:, obj_obs_start : obj_obs_start + 3] = self.object_pos
self.states_buf[:, obj_obs_start + 3 : obj_obs_start + 7] = self.object_rot
self.states_buf[:, obj_obs_start + 7 : obj_obs_start + 10] = self.object_linvel
self.states_buf[:, obj_obs_start + 10 : obj_obs_start + 13] = self.vel_obs_scale * self.object_angvel
goal_obs_start = obj_obs_start + 13 # 61
self.states_buf[:, goal_obs_start : goal_obs_start + 3] = self.goal_pos
self.states_buf[:, goal_obs_start + 3 : goal_obs_start + 7] = self.goal_rot
self.states_buf[:, goal_obs_start + 7 : goal_obs_start + 11] = quat_mul(
self.object_rot, quat_conjugate(self.goal_rot)
)
# fingertip observations, state(pose and vel) + force-torque sensors
num_ft_states = 13 * self.num_fingertips # 65
num_ft_force_torques = 6 * self.num_fingertips # 30
fingertip_obs_start = goal_obs_start + 11 # 72
self.states_buf[
:, fingertip_obs_start : fingertip_obs_start + 3 * self.num_fingertips
] = self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips)
self.states_buf[
:, fingertip_obs_start + 3 * self.num_fingertips : fingertip_obs_start + 7 * self.num_fingertips
] = self.fingertip_rot.reshape(self.num_envs, 4 * self.num_fingertips)
self.states_buf[
:, fingertip_obs_start + 7 * self.num_fingertips : fingertip_obs_start + 13 * self.num_fingertips
] = self.fingertip_velocities.reshape(self.num_envs, 6 * self.num_fingertips)
self.states_buf[
:, fingertip_obs_start + num_ft_states : fingertip_obs_start + num_ft_states + num_ft_force_torques
] = (self.force_torque_obs_scale * self.vec_sensor_tensor)
# obs_end = 72 + 65 + 30 = 167
# obs_total = obs_end + num_actions = 187
obs_end = fingertip_obs_start + num_ft_states + num_ft_force_torques
self.states_buf[:, obs_end : obs_end + self.num_actions] = self.actions
else:
self.obs_buf[:, 0 : self.num_hand_dofs] = unscale(
self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits
)
self.obs_buf[:, self.num_hand_dofs : 2 * self.num_hand_dofs] = self.vel_obs_scale * self.hand_dof_vel
self.obs_buf[:, 2 * self.num_hand_dofs : 3 * self.num_hand_dofs] = (
self.force_torque_obs_scale * self.dof_force_tensor
)
obj_obs_start = 3 * self.num_hand_dofs # 48
self.obs_buf[:, obj_obs_start : obj_obs_start + 3] = self.object_pos
self.obs_buf[:, obj_obs_start + 3 : obj_obs_start + 7] = self.object_rot
self.obs_buf[:, obj_obs_start + 7 : obj_obs_start + 10] = self.object_linvel
self.obs_buf[:, obj_obs_start + 10 : obj_obs_start + 13] = self.vel_obs_scale * self.object_angvel
goal_obs_start = obj_obs_start + 13 # 61
self.obs_buf[:, goal_obs_start : goal_obs_start + 3] = self.goal_pos
self.obs_buf[:, goal_obs_start + 3 : goal_obs_start + 7] = self.goal_rot
self.obs_buf[:, goal_obs_start + 7 : goal_obs_start + 11] = quat_mul(
self.object_rot, quat_conjugate(self.goal_rot)
)
# fingertip observations, state(pose and vel) + force-torque sensors
num_ft_states = 13 * self.num_fingertips # 65
num_ft_force_torques = 6 * self.num_fingertips # 30
fingertip_obs_start = goal_obs_start + 11 # 72
self.obs_buf[
:, fingertip_obs_start : fingertip_obs_start + 3 * self.num_fingertips
] = self.fingertip_pos.reshape(self.num_envs, 3 * self.num_fingertips)
self.obs_buf[
:, fingertip_obs_start + 3 * self.num_fingertips : fingertip_obs_start + 7 * self.num_fingertips
] = self.fingertip_rot.reshape(self.num_envs, 4 * self.num_fingertips)
self.obs_buf[
:, fingertip_obs_start + 7 * self.num_fingertips : fingertip_obs_start + 13 * self.num_fingertips
] = self.fingertip_velocities.reshape(self.num_envs, 6 * self.num_fingertips)
self.obs_buf[
:, fingertip_obs_start + num_ft_states : fingertip_obs_start + num_ft_states + num_ft_force_torques
] = (self.force_torque_obs_scale * self.vec_sensor_tensor)
# obs_end = 96 + 65 + 30 = 167
# obs_total = obs_end + num_actions = 187
obs_end = fingertip_obs_start + num_ft_states + num_ft_force_torques
self.obs_buf[:, obs_end : obs_end + self.num_actions] = self.actions
| 15,107 | Python | 48.211726 | 129 | 0.609188 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/franka_cabinet.py | # Copyright (c) 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.
#
import math
import numpy as np
import torch
from omni.isaac.cloner import Cloner
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.prims import RigidPrim, RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.utils.torch.transformations import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.cabinet import Cabinet
from omniisaacgymenvs.robots.articulations.franka import Franka
from omniisaacgymenvs.robots.articulations.views.cabinet_view import CabinetView
from omniisaacgymenvs.robots.articulations.views.franka_view import FrankaView
from pxr import Usd, UsdGeom
class FrankaCabinetTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
self.distX_offset = 0.04
self.dt = 1 / 60.0
self._num_observations = 23
self._num_actions = 9
RLTask.__init__(self, name, env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["episodeLength"]
self.action_scale = self._task_cfg["env"]["actionScale"]
self.start_position_noise = self._task_cfg["env"]["startPositionNoise"]
self.start_rotation_noise = self._task_cfg["env"]["startRotationNoise"]
self.num_props = self._task_cfg["env"]["numProps"]
self.dof_vel_scale = self._task_cfg["env"]["dofVelocityScale"]
self.dist_reward_scale = self._task_cfg["env"]["distRewardScale"]
self.rot_reward_scale = self._task_cfg["env"]["rotRewardScale"]
self.around_handle_reward_scale = self._task_cfg["env"]["aroundHandleRewardScale"]
self.open_reward_scale = self._task_cfg["env"]["openRewardScale"]
self.finger_dist_reward_scale = self._task_cfg["env"]["fingerDistRewardScale"]
self.action_penalty_scale = self._task_cfg["env"]["actionPenaltyScale"]
self.finger_close_reward_scale = self._task_cfg["env"]["fingerCloseRewardScale"]
def set_up_scene(self, scene) -> None:
self.get_franka()
self.get_cabinet()
if self.num_props > 0:
self.get_props()
super().set_up_scene(scene, filter_collisions=False)
self._frankas = FrankaView(prim_paths_expr="/World/envs/.*/franka", name="franka_view")
self._cabinets = CabinetView(prim_paths_expr="/World/envs/.*/cabinet", name="cabinet_view")
scene.add(self._frankas)
scene.add(self._frankas._hands)
scene.add(self._frankas._lfingers)
scene.add(self._frankas._rfingers)
scene.add(self._cabinets)
scene.add(self._cabinets._drawers)
if self.num_props > 0:
self._props = RigidPrimView(
prim_paths_expr="/World/envs/.*/prop/.*", name="prop_view", reset_xform_properties=False
)
scene.add(self._props)
self.init_data()
return
def initialize_views(self, scene):
super().initialize_views(scene)
if scene.object_exists("franka_view"):
scene.remove_object("franka_view", registry_only=True)
if scene.object_exists("hands_view"):
scene.remove_object("hands_view", registry_only=True)
if scene.object_exists("lfingers_view"):
scene.remove_object("lfingers_view", registry_only=True)
if scene.object_exists("rfingers_view"):
scene.remove_object("rfingers_view", registry_only=True)
if scene.object_exists("cabinet_view"):
scene.remove_object("cabinet_view", registry_only=True)
if scene.object_exists("drawers_view"):
scene.remove_object("drawers_view", registry_only=True)
if scene.object_exists("prop_view"):
scene.remove_object("prop_view", registry_only=True)
self._frankas = FrankaView(prim_paths_expr="/World/envs/.*/franka", name="franka_view")
self._cabinets = CabinetView(prim_paths_expr="/World/envs/.*/cabinet", name="cabinet_view")
scene.add(self._frankas)
scene.add(self._frankas._hands)
scene.add(self._frankas._lfingers)
scene.add(self._frankas._rfingers)
scene.add(self._cabinets)
scene.add(self._cabinets._drawers)
if self.num_props > 0:
self._props = RigidPrimView(
prim_paths_expr="/World/envs/.*/prop/.*", name="prop_view", reset_xform_properties=False
)
scene.add(self._props)
self.init_data()
def get_franka(self):
franka = Franka(prim_path=self.default_zero_env_path + "/franka", name="franka")
self._sim_config.apply_articulation_settings(
"franka", get_prim_at_path(franka.prim_path), self._sim_config.parse_actor_config("franka")
)
def get_cabinet(self):
cabinet = Cabinet(self.default_zero_env_path + "/cabinet", name="cabinet")
self._sim_config.apply_articulation_settings(
"cabinet", get_prim_at_path(cabinet.prim_path), self._sim_config.parse_actor_config("cabinet")
)
def get_props(self):
prop_cloner = Cloner()
drawer_pos = torch.tensor([0.0515, 0.0, 0.7172])
prop_color = torch.tensor([0.2, 0.4, 0.6])
props_per_row = int(math.ceil(math.sqrt(self.num_props)))
prop_size = 0.08
prop_spacing = 0.09
xmin = -0.5 * prop_spacing * (props_per_row - 1)
zmin = -0.5 * prop_spacing * (props_per_row - 1)
prop_count = 0
prop_pos = []
for j in range(props_per_row):
prop_up = zmin + j * prop_spacing
for k in range(props_per_row):
if prop_count >= self.num_props:
break
propx = xmin + k * prop_spacing
prop_pos.append([propx, prop_up, 0.0])
prop_count += 1
prop = DynamicCuboid(
prim_path=self.default_zero_env_path + "/prop/prop_0",
name="prop",
color=prop_color,
size=prop_size,
density=100.0,
)
self._sim_config.apply_articulation_settings(
"prop", get_prim_at_path(prop.prim_path), self._sim_config.parse_actor_config("prop")
)
prop_paths = [f"{self.default_zero_env_path}/prop/prop_{j}" for j in range(self.num_props)]
prop_cloner.clone(
source_prim_path=self.default_zero_env_path + "/prop/prop_0",
prim_paths=prop_paths,
positions=np.array(prop_pos) + drawer_pos.numpy(),
replicate_physics=False,
)
def init_data(self) -> None:
def get_env_local_pose(env_pos, xformable, device):
"""Compute pose in env-local coordinates"""
world_transform = xformable.ComputeLocalToWorldTransform(0)
world_pos = world_transform.ExtractTranslation()
world_quat = world_transform.ExtractRotationQuat()
px = world_pos[0] - env_pos[0]
py = world_pos[1] - env_pos[1]
pz = world_pos[2] - env_pos[2]
qx = world_quat.imaginary[0]
qy = world_quat.imaginary[1]
qz = world_quat.imaginary[2]
qw = world_quat.real
return torch.tensor([px, py, pz, qw, qx, qy, qz], device=device, dtype=torch.float)
stage = get_current_stage()
hand_pose = get_env_local_pose(
self._env_pos[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_link7")),
self._device,
)
lfinger_pose = get_env_local_pose(
self._env_pos[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_leftfinger")),
self._device,
)
rfinger_pose = get_env_local_pose(
self._env_pos[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/franka/panda_rightfinger")),
self._device,
)
finger_pose = torch.zeros(7, device=self._device)
finger_pose[0:3] = (lfinger_pose[0:3] + rfinger_pose[0:3]) / 2.0
finger_pose[3:7] = lfinger_pose[3:7]
hand_pose_inv_rot, hand_pose_inv_pos = tf_inverse(hand_pose[3:7], hand_pose[0:3])
grasp_pose_axis = 1
franka_local_grasp_pose_rot, franka_local_pose_pos = tf_combine(
hand_pose_inv_rot, hand_pose_inv_pos, finger_pose[3:7], finger_pose[0:3]
)
franka_local_pose_pos += torch.tensor([0, 0.04, 0], device=self._device)
self.franka_local_grasp_pos = franka_local_pose_pos.repeat((self._num_envs, 1))
self.franka_local_grasp_rot = franka_local_grasp_pose_rot.repeat((self._num_envs, 1))
drawer_local_grasp_pose = torch.tensor([0.3, 0.01, 0.0, 1.0, 0.0, 0.0, 0.0], device=self._device)
self.drawer_local_grasp_pos = drawer_local_grasp_pose[0:3].repeat((self._num_envs, 1))
self.drawer_local_grasp_rot = drawer_local_grasp_pose[3:7].repeat((self._num_envs, 1))
self.gripper_forward_axis = torch.tensor([0, 0, 1], device=self._device, dtype=torch.float).repeat(
(self._num_envs, 1)
)
self.drawer_inward_axis = torch.tensor([-1, 0, 0], device=self._device, dtype=torch.float).repeat(
(self._num_envs, 1)
)
self.gripper_up_axis = torch.tensor([0, 1, 0], device=self._device, dtype=torch.float).repeat(
(self._num_envs, 1)
)
self.drawer_up_axis = torch.tensor([0, 0, 1], device=self._device, dtype=torch.float).repeat(
(self._num_envs, 1)
)
self.franka_default_dof_pos = torch.tensor(
[1.157, -1.066, -0.155, -2.239, -1.841, 1.003, 0.469, 0.035, 0.035], device=self._device
)
self.actions = torch.zeros((self._num_envs, self.num_actions), device=self._device)
def get_observations(self) -> dict:
hand_pos, hand_rot = self._frankas._hands.get_world_poses(clone=False)
drawer_pos, drawer_rot = self._cabinets._drawers.get_world_poses(clone=False)
franka_dof_pos = self._frankas.get_joint_positions(clone=False)
franka_dof_vel = self._frankas.get_joint_velocities(clone=False)
self.cabinet_dof_pos = self._cabinets.get_joint_positions(clone=False)
self.cabinet_dof_vel = self._cabinets.get_joint_velocities(clone=False)
self.franka_dof_pos = franka_dof_pos
(
self.franka_grasp_rot,
self.franka_grasp_pos,
self.drawer_grasp_rot,
self.drawer_grasp_pos,
) = self.compute_grasp_transforms(
hand_rot,
hand_pos,
self.franka_local_grasp_rot,
self.franka_local_grasp_pos,
drawer_rot,
drawer_pos,
self.drawer_local_grasp_rot,
self.drawer_local_grasp_pos,
)
self.franka_lfinger_pos, self.franka_lfinger_rot = self._frankas._lfingers.get_world_poses(clone=False)
self.franka_rfinger_pos, self.franka_rfinger_rot = self._frankas._lfingers.get_world_poses(clone=False)
dof_pos_scaled = (
2.0
* (franka_dof_pos - self.franka_dof_lower_limits)
/ (self.franka_dof_upper_limits - self.franka_dof_lower_limits)
- 1.0
)
to_target = self.drawer_grasp_pos - self.franka_grasp_pos
self.obs_buf = torch.cat(
(
dof_pos_scaled,
franka_dof_vel * self.dof_vel_scale,
to_target,
self.cabinet_dof_pos[:, 3].unsqueeze(-1),
self.cabinet_dof_vel[:, 3].unsqueeze(-1),
),
dim=-1,
)
observations = {self._frankas.name: {"obs_buf": self.obs_buf}}
return observations
def pre_physics_step(self, actions) -> None:
if not self._env._world.is_playing():
return
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
self.actions = actions.clone().to(self._device)
targets = self.franka_dof_targets + self.franka_dof_speed_scales * self.dt * self.actions * self.action_scale
self.franka_dof_targets[:] = tensor_clamp(targets, self.franka_dof_lower_limits, self.franka_dof_upper_limits)
env_ids_int32 = torch.arange(self._frankas.count, dtype=torch.int32, device=self._device)
self._frankas.set_joint_position_targets(self.franka_dof_targets, indices=env_ids_int32)
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
num_indices = len(indices)
# reset franka
pos = tensor_clamp(
self.franka_default_dof_pos.unsqueeze(0)
+ 0.25 * (torch.rand((len(env_ids), self.num_franka_dofs), device=self._device) - 0.5),
self.franka_dof_lower_limits,
self.franka_dof_upper_limits,
)
dof_pos = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_vel = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_pos[:, :] = pos
self.franka_dof_targets[env_ids, :] = pos
self.franka_dof_pos[env_ids, :] = pos
# reset cabinet
self._cabinets.set_joint_positions(
torch.zeros_like(self._cabinets.get_joint_positions(clone=False)[env_ids]), indices=indices
)
self._cabinets.set_joint_velocities(
torch.zeros_like(self._cabinets.get_joint_velocities(clone=False)[env_ids]), indices=indices
)
# reset props
if self.num_props > 0:
self._props.set_world_poses(
self.default_prop_pos[self.prop_indices[env_ids].flatten()],
self.default_prop_rot[self.prop_indices[env_ids].flatten()],
self.prop_indices[env_ids].flatten().to(torch.int32),
)
self._frankas.set_joint_position_targets(self.franka_dof_targets[env_ids], indices=indices)
self._frankas.set_joint_positions(dof_pos, indices=indices)
self._frankas.set_joint_velocities(dof_vel, indices=indices)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self):
self.num_franka_dofs = self._frankas.num_dof
self.franka_dof_pos = torch.zeros((self.num_envs, self.num_franka_dofs), device=self._device)
dof_limits = self._frankas.get_dof_limits()
self.franka_dof_lower_limits = dof_limits[0, :, 0].to(device=self._device)
self.franka_dof_upper_limits = dof_limits[0, :, 1].to(device=self._device)
self.franka_dof_speed_scales = torch.ones_like(self.franka_dof_lower_limits)
self.franka_dof_speed_scales[self._frankas.gripper_indices] = 0.1
self.franka_dof_targets = torch.zeros(
(self._num_envs, self.num_franka_dofs), dtype=torch.float, device=self._device
)
if self.num_props > 0:
self.default_prop_pos, self.default_prop_rot = self._props.get_world_poses()
self.prop_indices = torch.arange(self._num_envs * self.num_props, device=self._device).view(
self._num_envs, self.num_props
)
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
self.rew_buf[:] = self.compute_franka_reward(
self.reset_buf,
self.progress_buf,
self.actions,
self.cabinet_dof_pos,
self.franka_grasp_pos,
self.drawer_grasp_pos,
self.franka_grasp_rot,
self.drawer_grasp_rot,
self.franka_lfinger_pos,
self.franka_rfinger_pos,
self.gripper_forward_axis,
self.drawer_inward_axis,
self.gripper_up_axis,
self.drawer_up_axis,
self._num_envs,
self.dist_reward_scale,
self.rot_reward_scale,
self.around_handle_reward_scale,
self.open_reward_scale,
self.finger_dist_reward_scale,
self.action_penalty_scale,
self.distX_offset,
self._max_episode_length,
self.franka_dof_pos,
self.finger_close_reward_scale,
)
def is_done(self) -> None:
# reset if drawer is open or max length reached
self.reset_buf = torch.where(self.cabinet_dof_pos[:, 3] > 0.39, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(
self.progress_buf >= self._max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf
)
def compute_grasp_transforms(
self,
hand_rot,
hand_pos,
franka_local_grasp_rot,
franka_local_grasp_pos,
drawer_rot,
drawer_pos,
drawer_local_grasp_rot,
drawer_local_grasp_pos,
):
global_franka_rot, global_franka_pos = tf_combine(
hand_rot, hand_pos, franka_local_grasp_rot, franka_local_grasp_pos
)
global_drawer_rot, global_drawer_pos = tf_combine(
drawer_rot, drawer_pos, drawer_local_grasp_rot, drawer_local_grasp_pos
)
return global_franka_rot, global_franka_pos, global_drawer_rot, global_drawer_pos
def compute_franka_reward(
self,
reset_buf,
progress_buf,
actions,
cabinet_dof_pos,
franka_grasp_pos,
drawer_grasp_pos,
franka_grasp_rot,
drawer_grasp_rot,
franka_lfinger_pos,
franka_rfinger_pos,
gripper_forward_axis,
drawer_inward_axis,
gripper_up_axis,
drawer_up_axis,
num_envs,
dist_reward_scale,
rot_reward_scale,
around_handle_reward_scale,
open_reward_scale,
finger_dist_reward_scale,
action_penalty_scale,
distX_offset,
max_episode_length,
joint_positions,
finger_close_reward_scale,
):
# type: (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, float, float, float, float, float, float, float, float, Tensor) -> Tuple[Tensor, Tensor]
# distance from hand to the drawer
d = torch.norm(franka_grasp_pos - drawer_grasp_pos, p=2, dim=-1)
dist_reward = 1.0 / (1.0 + d**2)
dist_reward *= dist_reward
dist_reward = torch.where(d <= 0.02, dist_reward * 2, dist_reward)
axis1 = tf_vector(franka_grasp_rot, gripper_forward_axis)
axis2 = tf_vector(drawer_grasp_rot, drawer_inward_axis)
axis3 = tf_vector(franka_grasp_rot, gripper_up_axis)
axis4 = tf_vector(drawer_grasp_rot, drawer_up_axis)
dot1 = (
torch.bmm(axis1.view(num_envs, 1, 3), axis2.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1)
) # alignment of forward axis for gripper
dot2 = (
torch.bmm(axis3.view(num_envs, 1, 3), axis4.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1)
) # alignment of up axis for gripper
# reward for matching the orientation of the hand to the drawer (fingers wrapped)
rot_reward = 0.5 * (torch.sign(dot1) * dot1**2 + torch.sign(dot2) * dot2**2)
# bonus if left finger is above the drawer handle and right below
around_handle_reward = torch.zeros_like(rot_reward)
around_handle_reward = torch.where(
franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(
franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2], around_handle_reward + 0.5, around_handle_reward
),
around_handle_reward,
)
# reward for distance of each finger from the drawer
finger_dist_reward = torch.zeros_like(rot_reward)
lfinger_dist = torch.abs(franka_lfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
rfinger_dist = torch.abs(franka_rfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
finger_dist_reward = torch.where(
franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(
franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2],
(0.04 - lfinger_dist) + (0.04 - rfinger_dist),
finger_dist_reward,
),
finger_dist_reward,
)
finger_close_reward = torch.zeros_like(rot_reward)
finger_close_reward = torch.where(
d <= 0.03, (0.04 - joint_positions[:, 7]) + (0.04 - joint_positions[:, 8]), finger_close_reward
)
# regularization on the actions (summed for each environment)
action_penalty = torch.sum(actions**2, dim=-1)
# how far the cabinet has been opened out
open_reward = cabinet_dof_pos[:, 3] * around_handle_reward + cabinet_dof_pos[:, 3] # drawer_top_joint
rewards = (
dist_reward_scale * dist_reward
+ rot_reward_scale * rot_reward
+ around_handle_reward_scale * around_handle_reward
+ open_reward_scale * open_reward
+ finger_dist_reward_scale * finger_dist_reward
- action_penalty_scale * action_penalty
+ finger_close_reward * finger_close_reward_scale
)
# bonus for opening drawer properly
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.01, rewards + 0.5, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.2, rewards + around_handle_reward, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.39, rewards + (2.0 * around_handle_reward), rewards)
# # prevent bad style in opening drawer
# rewards = torch.where(franka_lfinger_pos[:, 0] < drawer_grasp_pos[:, 0] - distX_offset,
# torch.ones_like(rewards) * -1, rewards)
# rewards = torch.where(franka_rfinger_pos[:, 0] < drawer_grasp_pos[:, 0] - distX_offset,
# torch.ones_like(rewards) * -1, rewards)
return rewards
| 22,939 | Python | 41.324723 | 222 | 0.599895 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/crazyflie.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
import torch
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.crazyflie import Crazyflie
from omniisaacgymenvs.robots.articulations.views.crazyflie_view import CrazyflieView
EPS = 1e-6 # small constant to avoid divisions by 0 and log(0)
class CrazyflieTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
self._num_observations = 18
self._num_actions = 4
self._crazyflie_position = torch.tensor([0, 0, 1.0])
self._ball_position = torch.tensor([0, 0, 1.0])
RLTask.__init__(self, name=name, env=env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["maxEpisodeLength"]
self.dt = self._task_cfg["sim"]["dt"]
# parameters for the crazyflie
self.arm_length = 0.05
# parameters for the controller
self.motor_damp_time_up = 0.15
self.motor_damp_time_down = 0.15
# I use the multiplier 4, since 4*T ~ time for a step response to finish, where
# T is a time constant of the first-order filter
self.motor_tau_up = 4 * self.dt / (self.motor_damp_time_up + EPS)
self.motor_tau_down = 4 * self.dt / (self.motor_damp_time_down + EPS)
# thrust max
self.mass = 0.028
self.thrust_to_weight = 1.9
self.motor_assymetry = np.array([1.0, 1.0, 1.0, 1.0])
# re-normalizing to sum-up to 4
self.motor_assymetry = self.motor_assymetry * 4.0 / np.sum(self.motor_assymetry)
self.grav_z = -1.0 * self._task_cfg["sim"]["gravity"][2]
def set_up_scene(self, scene) -> None:
self.get_crazyflie()
self.get_target()
RLTask.set_up_scene(self, scene)
self._copters = CrazyflieView(prim_paths_expr="/World/envs/.*/Crazyflie", name="crazyflie_view")
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/ball", name="ball_view")
scene.add(self._copters)
scene.add(self._balls)
for i in range(4):
scene.add(self._copters.physics_rotors[i])
return
def initialize_views(self, scene):
super().initialize_views(scene)
if scene.object_exists("crazyflie_view"):
scene.remove_object("crazyflie_view", registry_only=True)
if scene.object_exists("ball_view"):
scene.remove_object("ball_view", registry_only=True)
for i in range(1, 5):
scene.remove_object(f"m{i}_prop_view", registry_only=True)
self._copters = CrazyflieView(prim_paths_expr="/World/envs/.*/Crazyflie", name="crazyflie_view")
self._balls = RigidPrimView(prim_paths_expr="/World/envs/.*/ball", name="ball_view")
scene.add(self._copters)
scene.add(self._balls)
for i in range(4):
scene.add(self._copters.physics_rotors[i])
def get_crazyflie(self):
copter = Crazyflie(
prim_path=self.default_zero_env_path + "/Crazyflie", name="crazyflie", translation=self._crazyflie_position
)
self._sim_config.apply_articulation_settings(
"crazyflie", get_prim_at_path(copter.prim_path), self._sim_config.parse_actor_config("crazyflie")
)
def get_target(self):
radius = 0.2
color = torch.tensor([1, 0, 0])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings(
"ball", get_prim_at_path(ball.prim_path), self._sim_config.parse_actor_config("ball")
)
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
self.root_pos, self.root_rot = self._copters.get_world_poses(clone=False)
self.root_velocities = self._copters.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
rot_x = quat_axis(root_quats, 0)
rot_y = quat_axis(root_quats, 1)
rot_z = quat_axis(root_quats, 2)
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = self.target_positions - root_positions
self.obs_buf[..., 3:6] = rot_x
self.obs_buf[..., 6:9] = rot_y
self.obs_buf[..., 9:12] = rot_z
self.obs_buf[..., 12:15] = root_linvels
self.obs_buf[..., 15:18] = root_angvels
observations = {self._copters.name: {"obs_buf": self.obs_buf}}
return observations
def pre_physics_step(self, actions) -> None:
if not self._env._world.is_playing():
return
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
actions = actions.clone().to(self._device)
self.actions = actions
# clamp to [-1.0, 1.0]
thrust_cmds = torch.clamp(actions, min=-1.0, max=1.0)
# scale to [0.0, 1.0]
thrust_cmds = (thrust_cmds + 1.0) / 2.0
# filtering the thruster and adding noise
motor_tau = self.motor_tau_up * torch.ones((self._num_envs, 4), dtype=torch.float32, device=self._device)
motor_tau[thrust_cmds < self.thrust_cmds_damp] = self.motor_tau_down
motor_tau[motor_tau > 1.0] = 1.0
# Since NN commands thrusts we need to convert to rot vel and back
thrust_rot = thrust_cmds**0.5
self.thrust_rot_damp = motor_tau * (thrust_rot - self.thrust_rot_damp) + self.thrust_rot_damp
self.thrust_cmds_damp = self.thrust_rot_damp**2
## Adding noise
thrust_noise = 0.01 * torch.randn(4, dtype=torch.float32, device=self._device)
thrust_noise = thrust_cmds * thrust_noise
self.thrust_cmds_damp = torch.clamp(self.thrust_cmds_damp + thrust_noise, min=0.0, max=1.0)
thrusts = self.thrust_max * self.thrust_cmds_damp
# thrusts given rotation
root_quats = self.root_rot
rot_x = quat_axis(root_quats, 0)
rot_y = quat_axis(root_quats, 1)
rot_z = quat_axis(root_quats, 2)
rot_matrix = torch.cat((rot_x, rot_y, rot_z), 1).reshape(-1, 3, 3)
force_x = torch.zeros(self._num_envs, 4, dtype=torch.float32, device=self._device)
force_y = torch.zeros(self._num_envs, 4, dtype=torch.float32, device=self._device)
force_xy = torch.cat((force_x, force_y), 1).reshape(-1, 4, 2)
thrusts = thrusts.reshape(-1, 4, 1)
thrusts = torch.cat((force_xy, thrusts), 2)
thrusts_0 = thrusts[:, 0]
thrusts_0 = thrusts_0[:, :, None]
thrusts_1 = thrusts[:, 1]
thrusts_1 = thrusts_1[:, :, None]
thrusts_2 = thrusts[:, 2]
thrusts_2 = thrusts_2[:, :, None]
thrusts_3 = thrusts[:, 3]
thrusts_3 = thrusts_3[:, :, None]
mod_thrusts_0 = torch.matmul(rot_matrix, thrusts_0)
mod_thrusts_1 = torch.matmul(rot_matrix, thrusts_1)
mod_thrusts_2 = torch.matmul(rot_matrix, thrusts_2)
mod_thrusts_3 = torch.matmul(rot_matrix, thrusts_3)
self.thrusts[:, 0] = torch.squeeze(mod_thrusts_0)
self.thrusts[:, 1] = torch.squeeze(mod_thrusts_1)
self.thrusts[:, 2] = torch.squeeze(mod_thrusts_2)
self.thrusts[:, 3] = torch.squeeze(mod_thrusts_3)
# clear actions for reset envs
self.thrusts[reset_env_ids] = 0
# spin spinning rotors
prop_rot = self.thrust_cmds_damp * self.prop_max_rot
self.dof_vel[:, 0] = prop_rot[:, 0]
self.dof_vel[:, 1] = -1.0 * prop_rot[:, 1]
self.dof_vel[:, 2] = prop_rot[:, 2]
self.dof_vel[:, 3] = -1.0 * prop_rot[:, 3]
self._copters.set_joint_velocities(self.dof_vel)
# apply actions
for i in range(4):
self._copters.physics_rotors[i].apply_forces(self.thrusts[:, i], indices=self.all_indices)
def post_reset(self):
thrust_max = self.grav_z * self.mass * self.thrust_to_weight * self.motor_assymetry / 4.0
self.thrusts = torch.zeros((self._num_envs, 4, 3), dtype=torch.float32, device=self._device)
self.thrust_cmds_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.thrust_rot_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.thrust_max = torch.tensor(thrust_max, device=self._device, dtype=torch.float32)
self.motor_linearity = 1.0
self.prop_max_rot = 433.3
self.target_positions = torch.zeros((self._num_envs, 3), device=self._device, dtype=torch.float32)
self.target_positions[:, 2] = 1
self.actions = torch.zeros((self._num_envs, 4), device=self._device, dtype=torch.float32)
self.all_indices = torch.arange(self._num_envs, dtype=torch.int32, device=self._device)
# Extra info
self.extras = {}
torch_zeros = lambda: torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {
"rew_pos": torch_zeros(),
"rew_orient": torch_zeros(),
"rew_effort": torch_zeros(),
"rew_spin": torch_zeros(),
"raw_dist": torch_zeros(),
"raw_orient": torch_zeros(),
"raw_effort": torch_zeros(),
"raw_spin": torch_zeros(),
}
self.root_pos, self.root_rot = self._copters.get_world_poses()
self.root_velocities = self._copters.get_velocities()
self.dof_pos = self._copters.get_joint_positions()
self.dof_vel = self._copters.get_joint_velocities()
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses(clone=False)
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# control parameters
self.thrusts = torch.zeros((self._num_envs, 4, 3), dtype=torch.float32, device=self._device)
self.thrust_cmds_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.thrust_rot_damp = torch.zeros((self._num_envs, 4), dtype=torch.float32, device=self._device)
self.set_targets(self.all_indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (0, 0) and z in (2)
self.target_positions[envs_long, 0:2] = torch.zeros((num_sets, 2), device=self._device)
self.target_positions[envs_long, 2] = torch.ones(num_sets, device=self._device) * 2.0
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
ball_pos[:, 2] += 0.0
self._balls.set_world_poses(ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
self.dof_pos[env_ids, :] = torch_rand_float(-0.0, 0.0, (num_resets, self._copters.num_dof), device=self._device)
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(-0.0, 0.0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._copters.set_joint_positions(self.dof_pos[env_ids], indices=env_ids)
self._copters.set_joint_velocities(self.dof_vel[env_ids], indices=env_ids)
self._copters.set_world_poses(root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._copters.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
self.thrust_cmds_damp[env_ids] = 0
self.thrust_rot_damp[env_ids] = 0
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"][key] = torch.mean(self.episode_sums[key][env_ids]) / self._max_episode_length
self.episode_sums[key][env_ids] = 0.0
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_angvels = self.root_velocities[:, 3:]
# pos reward
target_dist = torch.sqrt(torch.square(self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
# orient reward
ups = quat_axis(root_quats, 2)
self.orient_z = ups[..., 2]
up_reward = torch.clamp(ups[..., 2], min=0.0, max=1.0)
# effort reward
effort = torch.square(self.actions).sum(-1)
effort_reward = 0.05 * torch.exp(-0.5 * effort)
# spin reward
spin = torch.square(root_angvels).sum(-1)
spin_reward = 0.01 * torch.exp(-1.0 * spin)
# combined reward
self.rew_buf[:] = pos_reward + pos_reward * (up_reward + spin_reward) - effort_reward
# log episode reward sums
self.episode_sums["rew_pos"] += pos_reward
self.episode_sums["rew_orient"] += up_reward
self.episode_sums["rew_effort"] += effort_reward
self.episode_sums["rew_spin"] += spin_reward
# log raw info
self.episode_sums["raw_dist"] += target_dist
self.episode_sums["raw_orient"] += ups[..., 2]
self.episode_sums["raw_effort"] += effort
self.episode_sums["raw_spin"] += spin
def is_done(self) -> None:
# resets due to misbehavior
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 5.0, ones, die)
# z >= 0.5 & z <= 5.0 & up > 0
die = torch.where(self.root_positions[..., 2] < 0.5, ones, die)
die = torch.where(self.root_positions[..., 2] > 5.0, ones, die)
die = torch.where(self.orient_z < 0.0, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(self.progress_buf >= self._max_episode_length - 1, ones, die)
| 16,830 | Python | 41.502525 | 120 | 0.61937 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/aliengo_terrain.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.aliengo import Aliengo
from omniisaacgymenvs.robots.articulations.views.aliengo_view import AliengoView
from omniisaacgymenvs.tasks.utils.anymal_terrain_generator import *
from omniisaacgymenvs.utils.terrain_utils.terrain_utils import *
from pxr import UsdLux, UsdPhysics
import time
class AliengoTerrainTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.height_samples = None
self.custom_origins = False
self.init_done = False
self._env_spacing = 0.0
self._num_observations = 188
self._num_actions = 12
self.update_config(sim_config)
RLTask.__init__(self, name, env)
self.height_points = self.init_height_points()
self.measured_heights = None
# joint positions offsets
self.default_dof_pos = torch.zeros(
(self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False
)
# reward episode sums
torch_zeros = lambda: torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {
"lin_vel_xy": torch_zeros(),
"lin_vel_z": torch_zeros(),
"ang_vel_z": torch_zeros(),
"ang_vel_xy": torch_zeros(),
"orient": torch_zeros(),
"torques": torch_zeros(),
"joint_acc": torch_zeros(),
"base_height": torch_zeros(),
"air_time": torch_zeros(),
"collision": torch_zeros(),
"stumble": torch_zeros(),
"action_rate": torch_zeros(),
"hip": torch_zeros(),
"foot_clearance": torch_zeros(),
"joint_power": torch_zeros(),
"smoothness": torch_zeros(),
"power_distribution": torch_zeros(),
}
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# normalization
self.lin_vel_scale = self._task_cfg["env"]["learn"]["linearVelocityScale"]
self.ang_vel_scale = self._task_cfg["env"]["learn"]["angularVelocityScale"]
self.dof_pos_scale = self._task_cfg["env"]["learn"]["dofPositionScale"]
self.dof_vel_scale = self._task_cfg["env"]["learn"]["dofVelocityScale"]
self.height_meas_scale = self._task_cfg["env"]["learn"]["heightMeasurementScale"]
self.action_scale = self._task_cfg["env"]["control"]["actionScale"]
# reward scales
self.rew_scales = {}
self.rew_scales["termination"] = self._task_cfg["env"]["learn"]["terminalReward"]
self.rew_scales["lin_vel_xy"] = self._task_cfg["env"]["learn"]["linearVelocityXYRewardScale"]
self.rew_scales["lin_vel_z"] = self._task_cfg["env"]["learn"]["linearVelocityZRewardScale"]
self.rew_scales["ang_vel_z"] = self._task_cfg["env"]["learn"]["angularVelocityZRewardScale"]
self.rew_scales["ang_vel_xy"] = self._task_cfg["env"]["learn"]["angularVelocityXYRewardScale"]
self.rew_scales["orient"] = self._task_cfg["env"]["learn"]["orientationRewardScale"]
self.rew_scales["torque"] = self._task_cfg["env"]["learn"]["torqueRewardScale"]
self.rew_scales["joint_acc"] = self._task_cfg["env"]["learn"]["jointAccRewardScale"]
self.rew_scales["base_height"] = self._task_cfg["env"]["learn"]["baseHeightRewardScale"]
self.rew_scales["action_rate"] = self._task_cfg["env"]["learn"]["actionRateRewardScale"]
self.rew_scales["hip"] = self._task_cfg["env"]["learn"]["hipRewardScale"]
self.rew_scales["fallen_over"] = self._task_cfg["env"]["learn"]["fallenOverRewardScale"]
self.rew_scales["foot_clearance"] = self._task_cfg["env"]["learn"]["footClearanceRewardScale"]
self.rew_scales["joint_power"] = self._task_cfg["env"]["learn"]["jointPowerRewardScale"]
self.rew_scales["smoothness"] = self._task_cfg["env"]["learn"]["smoothnessRewardScale"]
self.rew_scales["power_distribution"] = self._task_cfg["env"]["learn"]["powerDistributionRewardScale"]
# command ranges
self.command_x_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_x"]
self.command_y_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_y"]
self.command_yaw_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["yaw"]
# base init state
pos = self._task_cfg["env"]["baseInitState"]["pos"]
rot = self._task_cfg["env"]["baseInitState"]["rot"]
v_lin = self._task_cfg["env"]["baseInitState"]["vLinear"]
v_ang = self._task_cfg["env"]["baseInitState"]["vAngular"]
self.base_init_state = pos + rot + v_lin + v_ang
# default joint positions
self.named_default_joint_angles = self._task_cfg["env"]["defaultJointAngles"]
# other
self.decimation = self._task_cfg["env"]["control"]["decimation"]
self.dt = self.decimation * self._task_cfg["sim"]["dt"]
self.max_episode_length_s = self._task_cfg["env"]["learn"]["episodeLength_s"]
self.max_episode_length = int(self.max_episode_length_s / self.dt + 0.5)
self.push_interval = int(self._task_cfg["env"]["learn"]["pushInterval_s"] / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
self.curriculum = self._task_cfg["env"]["terrain"]["curriculum"]
self.base_threshold = 0.2
self.knee_threshold = 0.1
for key in self.rew_scales.keys():
self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._task_cfg["sim"]["default_physics_material"]["static_friction"] = self._task_cfg["env"]["terrain"][
"staticFriction"
]
self._task_cfg["sim"]["default_physics_material"]["dynamic_friction"] = self._task_cfg["env"]["terrain"][
"dynamicFriction"
]
self._task_cfg["sim"]["default_physics_material"]["restitution"] = self._task_cfg["env"]["terrain"][
"restitution"
]
self._task_cfg["sim"]["add_ground_plane"] = False
def _get_noise_scale_vec(self, cfg):
noise_vec = torch.zeros_like(self.obs_buf[0])
self.add_noise = self._task_cfg["env"]["learn"]["addNoise"]
noise_level = self._task_cfg["env"]["learn"]["noiseLevel"]
noise_vec[:3] = self._task_cfg["env"]["learn"]["linearVelocityNoise"] * noise_level * self.lin_vel_scale
noise_vec[3:6] = self._task_cfg["env"]["learn"]["angularVelocityNoise"] * noise_level * self.ang_vel_scale
noise_vec[6:9] = self._task_cfg["env"]["learn"]["gravityNoise"] * noise_level
noise_vec[9:12] = 0.0 # commands
noise_vec[12:24] = self._task_cfg["env"]["learn"]["dofPositionNoise"] * noise_level * self.dof_pos_scale
noise_vec[24:36] = self._task_cfg["env"]["learn"]["dofVelocityNoise"] * noise_level * self.dof_vel_scale
noise_vec[36:176] = (
self._task_cfg["env"]["learn"]["heightMeasurementNoise"] * noise_level * self.height_meas_scale
)
noise_vec[176:188] = 0.0 # previous actions
return noise_vec
def init_height_points(self):
# 1mx1.6m rectangle (without center line)
y = 0.1 * torch.tensor(
[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5], device=self.device, requires_grad=False
) # 10-50cm on each side
x = 0.1 * torch.tensor(
[-8, -7, -6, -5, -4, -3, -2, 2, 3, 4, 5, 6, 7, 8], device=self.device, requires_grad=False
) # 20-80cm on each side
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
self.num_height_points = grid_x.numel()
points = torch.zeros(self.num_envs, self.num_height_points, 3, device=self.device, requires_grad=False)
points[:, :, 0] = grid_x.flatten()
points[:, :, 1] = grid_y.flatten()
return points
def _create_trimesh(self, create_mesh=True):
self.terrain = Terrain(self._task_cfg["env"]["terrain"], num_robots=self.num_envs)
vertices = self.terrain.vertices
triangles = self.terrain.triangles
position = torch.tensor([-self.terrain.border_size, -self.terrain.border_size, 0.0])
if create_mesh:
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position)
self.height_samples = (
torch.tensor(self.terrain.heightsamples).view(self.terrain.tot_rows, self.terrain.tot_cols).to(self.device)
)
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self.get_terrain()
# self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
# self.height_samples = (
# torch.zeros((1200, 2000)).to(self.device)
# )
self.get_aliengo()
super().set_up_scene(scene, collision_filter_global_paths=["/World/terrain"])
# super().set_up_scene(scene)
self._aliengos = AliengoView(
prim_paths_expr="/World/envs/.*/aliengo", name="aliengo_view", track_contact_forces=True, stage = self._stage
)
scene.add(self._aliengos)
scene.add(self._aliengos._knees)
scene.add(self._aliengos._base)
# scene.add_default_ground_plane(prim_path = "/World/defaultGroundPlane")
def initialize_views(self, scene):
# initialize terrain variables even if we do not need to re-create the terrain mesh
self.get_terrain(create_mesh=False)
super().initialize_views(scene)
if scene.object_exists("aliengo_view"):
scene.remove_object("aliengo_view", registry_only=True)
if scene.object_exists("knees_view"):
scene.remove_object("knees_view", registry_only=True)
if scene.object_exists("base_view"):
scene.remove_object("base_view", registry_only=True)
self._aliengos = AliengoView(
prim_paths_expr="/World/envs/.*/aliengo", name="aliengo_view", track_contact_forces=True
)
scene.add(self._aliengos)
scene.add(self._aliengos._knees)
scene.add(self._aliengos._base)
def get_terrain(self, create_mesh=True):
self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
if not self.curriculum:
self._task_cfg["env"]["terrain"]["maxInitMapLevel"] = self._task_cfg["env"]["terrain"]["numLevels"] - 1
self.terrain_levels = torch.randint(
0, self._task_cfg["env"]["terrain"]["maxInitMapLevel"] + 1, (self.num_envs,), device=self.device
)
self.terrain_types = torch.randint(
0, self._task_cfg["env"]["terrain"]["numTerrains"], (self.num_envs,), device=self.device
)
self._create_trimesh(create_mesh=create_mesh)
self.terrain_origins = torch.from_numpy(self.terrain.env_origins).to(self.device).to(torch.float)
def get_aliengo(self):
aliengo_translation = torch.tensor([0.0, 0.0, 0.42])
aliengo_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0])
aliengo = Aliengo(
prim_path=self.default_zero_env_path + "/aliengo",
name="aliengo",
usd_path="./robots/models/aliengo/urdf/aliengo/aliengo.usd",
translation=aliengo_translation,
orientation=aliengo_orientation,
)
self._sim_config.apply_articulation_settings(
"aliengo", get_prim_at_path(aliengo.prim_path), self._sim_config.parse_actor_config("aliengo")
)
aliengo.set_aliengo_properties(self._stage, aliengo.prim)
aliengo.prepare_contacts(self._stage, aliengo.prim)
self.dof_names = aliengo.dof_names
for i in range(self.num_actions):
name = self.dof_names[i]
angle = self.named_default_joint_angles[name]
self.default_dof_pos[:, i] = angle
def post_reset(self):
self.base_init_state = torch.tensor(
self.base_init_state, dtype=torch.float, device=self.device, requires_grad=False
)
self.timeout_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# initialize some data used later on
self.up_axis_idx = 2
self.common_step_counter = 0
self.extras = {}
self.noise_scale_vec = self._get_noise_scale_vec(self._task_cfg)
self.commands = torch.zeros(
self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False
) # x vel, y vel, yaw vel, heading
self.commands_scale = torch.tensor(
[self.lin_vel_scale, self.lin_vel_scale, self.ang_vel_scale],
device=self.device,
requires_grad=False,
)
self.gravity_vec = torch.tensor(
get_axis_params(-1.0, self.up_axis_idx), dtype=torch.float, device=self.device
).repeat((self.num_envs, 1))
self.forward_vec = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float, device=self.device).repeat(
(self.num_envs, 1)
)
self.torques = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.last_actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.last_last_actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.feet_air_time = torch.zeros(self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False)
self.last_dof_vel = torch.zeros((self.num_envs, 12), dtype=torch.float, device=self.device, requires_grad=False)
for i in range(self.num_envs):
self.env_origins[i] = self.terrain_origins[self.terrain_levels[i], self.terrain_types[i]]
# self.env_origins[i] = torch.tensor([0.0, 0.0, 0.0]).cuda()
self.num_dof = self._aliengos.num_dof
self.dof_pos = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.dof_vel = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.base_pos = torch.zeros((self.num_envs, 3), dtype=torch.float, device=self.device)
self.base_quat = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device)
self.base_velocities = torch.zeros((self.num_envs, 6), dtype=torch.float, device=self.device)
self.knee_pos = torch.zeros((self.num_envs * 4, 3), dtype=torch.float, device=self.device)
self.knee_quat = torch.zeros((self.num_envs * 4, 4), dtype=torch.float, device=self.device)
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
self.init_done = True
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
positions_offset = torch_rand_float(0.5, 1.5, (len(env_ids), self.num_dof), device=self.device)
velocities = torch_rand_float(-0.1, 0.1, (len(env_ids), self.num_dof), device=self.device)
self.dof_pos[env_ids] = self.default_dof_pos[env_ids] * positions_offset
self.dof_vel[env_ids] = velocities
self.update_terrain_level(env_ids)
self.base_pos[env_ids] = self.base_init_state[0:3]
self.base_pos[env_ids, 0:3] += self.env_origins[env_ids]
self.base_pos[env_ids, 0:2] += torch_rand_float(-0.5, 0.5, (len(env_ids), 2), device=self.device)
self.base_quat[env_ids] = self.base_init_state[3:7]
self.base_velocities[env_ids] = self.base_init_state[7:]
self._aliengos.set_world_poses(
positions=self.base_pos[env_ids].clone(), orientations=self.base_quat[env_ids].clone(), indices=indices
)
self._aliengos.set_velocities(velocities=self.base_velocities[env_ids].clone(), indices=indices)
self._aliengos.set_joint_positions(positions=self.dof_pos[env_ids].clone(), indices=indices)
self._aliengos.set_joint_velocities(velocities=self.dof_vel[env_ids].clone(), indices=indices)
self.commands[env_ids, 0] = torch_rand_float(
self.command_x_range[0], self.command_x_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 1] = torch_rand_float(
self.command_y_range[0], self.command_y_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 3] = torch_rand_float(
self.command_yaw_range[0], self.command_yaw_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids] *= (torch.norm(self.commands[env_ids, :2], dim=1) > 0.25).unsqueeze(
1
) # set small commands to zero
self.last_actions[env_ids] = 0.0
self.last_last_actions[env_ids] = 0.0
self.last_dof_vel[env_ids] = 0.0
self.feet_air_time[env_ids] = 0.0
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 1
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"]["rew_" + key] = (
torch.mean(self.episode_sums[key][env_ids]) / self.max_episode_length_s
)
self.episode_sums[key][env_ids] = 0.0
self.extras["episode"]["terrain_level"] = torch.mean(self.terrain_levels.float())
def update_terrain_level(self, env_ids):
if not self.init_done or not self.curriculum:
# do not change on initial reset
return
root_pos, _ = self._aliengos.get_world_poses(clone=False)
distance = torch.norm(root_pos[env_ids, :2] - self.env_origins[env_ids, :2], dim=1)
self.terrain_levels[env_ids] -= 1 * (
distance < torch.norm(self.commands[env_ids, :2]) * self.max_episode_length_s * 0.25
)
self.terrain_levels[env_ids] += 1 * (distance > self.terrain.env_length / 2)
self.terrain_levels[env_ids] = torch.clip(self.terrain_levels[env_ids], 0) % self.terrain.env_rows
self.env_origins[env_ids] = self.terrain_origins[self.terrain_levels[env_ids], self.terrain_types[env_ids]]
def refresh_dof_state_tensors(self):
self.dof_pos = self._aliengos.get_joint_positions(clone=False)
self.dof_vel = self._aliengos.get_joint_velocities(clone=False)
def refresh_body_state_tensors(self):
self.base_pos, self.base_quat = self._aliengos.get_world_poses(clone=False)
self.base_velocities = self._aliengos.get_velocities(clone=False)
self.knee_pos, self.knee_quat = self._aliengos._knees.get_world_poses(clone=False)
self.feet_pos, self.feet_quat = self._aliengos._feet.get_world_poses(clone = False)
self.feet_vel = self._aliengos._feet.get_velocities(clone = False)
self.feet_pos = self.feet_pos.reshape(self._num_envs, 4, 3)
self.feet_vel = self.feet_vel.reshape(self._num_envs, 4, 6)
def pre_physics_step(self, actions):
if not self._env._world.is_playing():
return
self.actions = actions.clone().to(self.device)
for i in range(self.decimation):
if self._env._world.is_playing():
torques = torch.clip(
self.Kp * (self.action_scale * self.actions + self.default_dof_pos - self.dof_pos)
- self.Kd * self.dof_vel,
-80.0,
80.0,
)
self._aliengos.set_joint_efforts(torques)
self.torques = torques
SimulationContext.step(self._env._world, render=False)
self.refresh_dof_state_tensors()
def post_physics_step(self):
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.refresh_dof_state_tensors()
self.refresh_body_state_tensors()
self.common_step_counter += 1
if self.common_step_counter % self.push_interval == 0:
self.push_robots()
# prepare quantities
self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3])
self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6])
# Foot clearance reward needed
curr_footpos_translated = self.feet_pos - self.base_pos.unsqueeze(1)
curr_footvel_translated = self.feet_vel[:, :, 0:3] - self.base_velocities[:, 0:3].unsqueeze(1)
self.foot_pos_body_frame = torch.zeros(self._num_envs, 4, 3, device = self._device)
self.foot_vel_body_frame = torch.zeros(self._num_envs, 4, 3, device = self._device)
for i in range(4):
self.foot_pos_body_frame[:, i, :] = quat_rotate_inverse(self.base_quat, curr_footpos_translated[:, i, :])
self.foot_vel_body_frame[:, i, :] = quat_rotate_inverse(self.base_quat, curr_footvel_translated[:, i, :])
# Resume preparing quantities
self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec)
forward = quat_apply(self.base_quat, self.forward_vec)
heading = torch.atan2(forward[:, 1], forward[:, 0])
self.commands[:, 2] = torch.clip(0.5 * wrap_to_pi(self.commands[:, 3] - heading), -1.0, 1.0)
self.check_termination()
self.get_states()
self.calculate_metrics()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
self.last_last_actions[:] = self.last_actions[:]
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = self.dof_vel[:]
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
def push_robots(self):
self.base_velocities[:, 0:2] = torch_rand_float(
-1.0, 1.0, (self.num_envs, 2), device=self.device
) # lin vel x/y
self._aliengos.set_velocities(self.base_velocities)
def check_termination(self):
self.timeout_buf = torch.where(
self.progress_buf >= self.max_episode_length - 1,
torch.ones_like(self.timeout_buf),
torch.zeros_like(self.timeout_buf),
)
knee_contact = (
torch.norm(self._aliengos._knees.get_net_contact_forces(clone=False).view(self._num_envs, 4, 3), dim=-1)
> 1.0
)
self.has_fallen = (torch.norm(self._aliengos._base.get_net_contact_forces(clone=False), dim=1) > 1.0) | (
torch.sum(knee_contact, dim=-1) > 1.0
)
self.reset_buf = self.has_fallen.clone()
self.reset_buf = torch.where(self.timeout_buf.bool(), torch.ones_like(self.reset_buf), self.reset_buf)
def calculate_metrics(self):
# velocity tracking reward
lin_vel_error = torch.sum(torch.square(self.commands[:, :2] - self.base_lin_vel[:, :2]), dim=1)
ang_vel_error = torch.square(self.commands[:, 2] - self.base_ang_vel[:, 2])
rew_lin_vel_xy = torch.exp(-lin_vel_error / 0.25) * self.rew_scales["lin_vel_xy"]
rew_ang_vel_z = torch.exp(-ang_vel_error / 0.25) * self.rew_scales["ang_vel_z"]
# other base velocity penalties
rew_lin_vel_z = torch.square(self.base_lin_vel[:, 2]) * self.rew_scales["lin_vel_z"]
rew_ang_vel_xy = torch.sum(torch.square(self.base_ang_vel[:, :2]), dim=1) * self.rew_scales["ang_vel_xy"]
# orientation penalty
rew_orient = torch.sum(torch.square(self.projected_gravity[:, :2]), dim=1) * self.rew_scales["orient"]
# base height penalty
rew_base_height = torch.square(self.base_pos[:, 2] - 0.40) * self.rew_scales["base_height"]
# torque penalty
rew_torque = torch.sum(torch.square(self.torques), dim=1) * self.rew_scales["torque"]
# joint acc penalty
rew_joint_acc = torch.sum(torch.square(self.last_dof_vel - self.dof_vel), dim=1) * self.rew_scales["joint_acc"]
# joint power penalty
rew_joint_power = torch.sum(torch.abs(self.dof_vel) * torch.abs(self.torques), dim = 1) * self.rew_scales["joint_power"]
# fallen over penalty
rew_fallen_over = self.has_fallen * self.rew_scales["fallen_over"]
# foot clearance penalty
height_error = torch.square(self.foot_pos_body_frame[:, :, 2] + 0.22).view(self._num_envs, -1)
foot_lateral_vel = torch.sqrt(torch.sum(torch.square(self.foot_vel_body_frame[:, :, :2]), dim = 2)).view(self._num_envs, -1)
rew_foot_clearance = torch.sum(height_error * foot_lateral_vel, dim = 1) * self.rew_scales["foot_clearance"]
# action rate penalty
rew_action_rate = (
torch.sum(torch.square(self.last_actions - self.actions), dim=1) * self.rew_scales["action_rate"]
)
# smoothness penalty
rew_smoothness = (
torch.sum(torch.square(self.actions - self.last_actions * 2.0 + self.last_last_actions), dim = 1) * self.rew_scales["smoothness"]
)
# power distribution penalty
rew_power_distribution = (
torch.var(torch.abs(self.dof_vel) * torch.abs(self.torques), dim = 1) * self.rew_scales["power_distribution"]
)
# cosmetic penalty for hip motion
rew_hip = (
torch.sum(torch.abs(self.dof_pos[:, 0:4] - self.default_dof_pos[:, 0:4]), dim=1) * self.rew_scales["hip"]
)
# total reward
self.rew_buf = (
rew_lin_vel_xy
+ rew_ang_vel_z
+ rew_lin_vel_z
+ rew_ang_vel_xy
+ rew_orient
+ rew_base_height
+ rew_torque
+ rew_joint_acc
+ rew_action_rate
+ rew_hip
+ rew_fallen_over
+ rew_foot_clearance
+ rew_joint_power
+ rew_smoothness
+ rew_power_distribution
)
# self.rew_buf = torch.clip(self.rew_buf, min=0.0, max=None)
# add termination reward
self.rew_buf += self.rew_scales["termination"] * self.reset_buf * ~self.timeout_buf
# log episode reward sums
self.episode_sums["lin_vel_xy"] += rew_lin_vel_xy
self.episode_sums["ang_vel_z"] += rew_ang_vel_z
self.episode_sums["lin_vel_z"] += rew_lin_vel_z
self.episode_sums["ang_vel_xy"] += rew_ang_vel_xy
self.episode_sums["orient"] += rew_orient
self.episode_sums["torques"] += rew_torque
self.episode_sums["joint_acc"] += rew_joint_acc
self.episode_sums["action_rate"] += rew_action_rate
self.episode_sums["base_height"] += rew_base_height
self.episode_sums["hip"] += rew_hip
self.episode_sums["foot_clearance"] += rew_foot_clearance
self.episode_sums["joint_power"] += rew_joint_power
self.episode_sums["smoothness"] += rew_smoothness
self.episode_sums["power_distribution"] += rew_power_distribution
def get_observations(self):
self.measured_heights = self.get_heights()
heights = (
torch.clip(self.base_pos[:, 2].unsqueeze(1) - 0.5 - self.measured_heights, -1, 1.0) * self.height_meas_scale
)
self.obs_buf = torch.cat(
(
self.base_lin_vel * self.lin_vel_scale,
self.base_ang_vel * self.ang_vel_scale,
self.projected_gravity,
self.commands[:, :3] * self.commands_scale,
self.dof_pos * self.dof_pos_scale,
self.dof_vel * self.dof_vel_scale,
heights,
self.actions,
),
dim=-1,
)
def get_ground_heights_below_knees(self):
points = self.knee_pos.reshape(self.num_envs, 4, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_ground_heights_below_base(self):
points = self.base_pos.reshape(self.num_envs, 1, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_heights(self, env_ids=None):
if env_ids:
points = quat_apply_yaw(
self.base_quat[env_ids].repeat(1, self.num_height_points), self.height_points[env_ids]
) + (self.base_pos[env_ids, 0:3]).unsqueeze(1)
else:
points = quat_apply_yaw(self.base_quat.repeat(1, self.num_height_points), self.height_points) + (
self.base_pos[:, 0:3]
).unsqueeze(1)
points += self.terrain.border_size
# points += 20
points = (points / self.terrain.horizontal_scale).long()
# points = (points / 0.1).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
# return heights.view(self.num_envs, -1) * 0.005
@torch.jit.script
def quat_apply_yaw(quat, vec):
quat_yaw = quat.clone().view(-1, 4)
quat_yaw[:, 1:3] = 0.0
quat_yaw = normalize(quat_yaw)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def wrap_to_pi(angles):
angles %= 2 * np.pi
angles -= 2 * np.pi * (angles > np.pi)
return angles
def get_axis_params(value, axis_idx, x_value=0.0, dtype=float, n_dims=3):
"""construct arguments to `Vec` according to axis index."""
zs = np.zeros((n_dims,))
assert axis_idx < n_dims, "the axis dim should be within the vector dimensions"
zs[axis_idx] = 1.0
params = np.where(zs == 1.0, value, zs)
params[0] = x_value
return list(params.astype(dtype))
| 33,261 | Python | 46.858993 | 141 | 0.609483 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/humanoid.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.maths import tensor_clamp, torch_rand_float, unscale
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.humanoid import Humanoid
from omniisaacgymenvs.tasks.shared.locomotion import LocomotionTask
from pxr import PhysxSchema
class HumanoidLocomotionTask(LocomotionTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
self._num_observations = 87
self._num_actions = 21
self._humanoid_positions = torch.tensor([0, 0, 1.34])
LocomotionTask.__init__(self, name=name, env=env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
LocomotionTask.update_config(self)
def set_up_scene(self, scene) -> None:
self.get_humanoid()
RLTask.set_up_scene(self, scene)
self._humanoids = ArticulationView(
prim_paths_expr="/World/envs/.*/Humanoid/torso", name="humanoid_view", reset_xform_properties=False
)
scene.add(self._humanoids)
return
def initialize_views(self, scene):
RLTask.initialize_views(self, scene)
if scene.object_exists("humanoid_view"):
scene.remove_object("humanoid_view", registry_only=True)
self._humanoids = ArticulationView(
prim_paths_expr="/World/envs/.*/Humanoid/torso", name="humanoid_view", reset_xform_properties=False
)
scene.add(self._humanoids)
def get_humanoid(self):
humanoid = Humanoid(
prim_path=self.default_zero_env_path + "/Humanoid", name="Humanoid", translation=self._humanoid_positions
)
self._sim_config.apply_articulation_settings(
"Humanoid", get_prim_at_path(humanoid.prim_path), self._sim_config.parse_actor_config("Humanoid")
)
def get_robot(self):
return self._humanoids
def post_reset(self):
self.joint_gears = torch.tensor(
[
67.5000, # lower_waist
67.5000, # lower_waist
67.5000, # right_upper_arm
67.5000, # right_upper_arm
67.5000, # left_upper_arm
67.5000, # left_upper_arm
67.5000, # pelvis
45.0000, # right_lower_arm
45.0000, # left_lower_arm
45.0000, # right_thigh: x
135.0000, # right_thigh: y
45.0000, # right_thigh: z
45.0000, # left_thigh: x
135.0000, # left_thigh: y
45.0000, # left_thigh: z
90.0000, # right_knee
90.0000, # left_knee
22.5, # right_foot
22.5, # right_foot
22.5, # left_foot
22.5, # left_foot
],
device=self._device,
)
self.max_motor_effort = torch.max(self.joint_gears)
self.motor_effort_ratio = self.joint_gears / self.max_motor_effort
dof_limits = self._humanoids.get_dof_limits()
self.dof_limits_lower = dof_limits[0, :, 0].to(self._device)
self.dof_limits_upper = dof_limits[0, :, 1].to(self._device)
force_links = ["left_foot", "right_foot"]
self._sensor_indices = torch.tensor(
[self._humanoids._body_indices[j] for j in force_links], device=self._device, dtype=torch.long
)
LocomotionTask.post_reset(self)
def get_dof_at_limit_cost(self):
return get_dof_at_limit_cost(self.obs_buf, self.motor_effort_ratio, self.joints_at_limit_cost_scale)
@torch.jit.script
def get_dof_at_limit_cost(obs_buf, motor_effort_ratio, joints_at_limit_cost_scale):
# type: (Tensor, Tensor, float) -> Tensor
scaled_cost = joints_at_limit_cost_scale * (torch.abs(obs_buf[:, 12:33]) - 0.98) / 0.02
dof_at_limit_cost = torch.sum(
(torch.abs(obs_buf[:, 12:33]) > 0.98) * scaled_cost * motor_effort_ratio.unsqueeze(0), dim=-1
)
return dof_at_limit_cost
| 5,980 | Python | 41.119718 | 117 | 0.651003 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/franka_deformable.py | # Copyright (c) 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 omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.franka import Franka
from omniisaacgymenvs.robots.articulations.views.franka_view import FrankaView
from omni.isaac.core.prims import RigidPrim, RigidPrimView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage, add_reference_to_stage
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.torch.transformations import *
from omni.isaac.core.utils.torch.rotations import *
import omni.isaac.core.utils.deformable_mesh_utils as deformableMeshUtils
from omni.isaac.core.materials.deformable_material import DeformableMaterial
from omni.isaac.core.prims.soft.deformable_prim import DeformablePrim
from omni.isaac.core.prims.soft.deformable_prim_view import DeformablePrimView
from omni.physx.scripts import deformableUtils, physicsUtils
import numpy as np
import torch
import math
from pxr import Usd, UsdGeom, Gf, UsdPhysics, PhysxSchema
class FrankaDeformableTask(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
self.update_config(sim_config)
self.dt = 1/60.
self._num_observations = 39
self._num_actions = 9
RLTask.__init__(self, name, env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["episodeLength"]
self.dof_vel_scale = self._task_cfg["env"]["dofVelocityScale"]
self.action_scale = self._task_cfg["env"]["actionScale"]
def set_up_scene(self, scene) -> None:
self.stage = get_current_stage()
self.assets_root_path = get_assets_root_path()
if self.assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self.get_franka()
self.get_beaker()
self.get_deformable_tube()
super().set_up_scene(scene=scene, replicate_physics=False)
self._frankas = FrankaView(prim_paths_expr="/World/envs/.*/franka", name="franka_view")
self.deformableView = DeformablePrimView(
prim_paths_expr="/World/envs/.*/deformableTube/tube/mesh", name="deformabletube_view"
)
scene.add(self.deformableView)
scene.add(self._frankas)
scene.add(self._frankas._hands)
scene.add(self._frankas._lfingers)
scene.add(self._frankas._rfingers)
return
def initialize_views(self, scene):
super().initialize_views(scene)
if scene.object_exists("franka_view"):
scene.remove_object("franka_view", registry_only=True)
if scene.object_exists("hands_view"):
scene.remove_object("hands_view", registry_only=True)
if scene.object_exists("lfingers_view"):
scene.remove_object("lfingers_view", registry_only=True)
if scene.object_exists("rfingers_view"):
scene.remove_object("rfingers_view", registry_only=True)
if scene.object_exists("deformabletube_view"):
scene.remove_object("deformabletube_view", registry_only=True)
self._frankas = FrankaView(
prim_paths_expr="/World/envs/.*/franka", name="franka_view"
)
self.deformableView = DeformablePrimView(
prim_paths_expr="/World/envs/.*/deformableTube/tube/mesh", name="deformabletube_view"
)
scene.add(self._frankas)
scene.add(self._frankas._hands)
scene.add(self._frankas._lfingers)
scene.add(self._frankas._rfingers)
scene.add(self.deformableView)
def get_franka(self):
franka = Franka(
prim_path=self.default_zero_env_path + "/franka",
name="franka",
orientation=torch.tensor([1.0, 0.0, 0.0, 0.0]),
translation=torch.tensor([0.0, 0.0, 0.0]),
)
self._sim_config.apply_articulation_settings(
"franka", get_prim_at_path(franka.prim_path), self._sim_config.parse_actor_config("franka")
)
franka.set_franka_properties(stage=self.stage, prim=franka.prim)
def get_beaker(self):
_usd_path = self.assets_root_path + "/Isaac/Props/Beaker/beaker_500ml.usd"
mesh_path = self.default_zero_env_path + "/beaker"
add_reference_to_stage(_usd_path, mesh_path)
beaker = RigidPrim(
prim_path=mesh_path+"/beaker",
name="beaker",
position=torch.tensor([0.5, 0.2, 0.095]),
)
self._sim_config.apply_articulation_settings("beaker", beaker.prim, self._sim_config.parse_actor_config("beaker"))
def get_deformable_tube(self):
_usd_path = self.assets_root_path + "/Isaac/Props/DeformableTube/tube.usd"
mesh_path = self.default_zero_env_path + "/deformableTube/tube"
add_reference_to_stage(_usd_path, mesh_path)
skin_mesh = get_prim_at_path(mesh_path)
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
physicsUtils.set_or_add_translate_op(skin_mesh, (0.6, 0.0, 0.005))
physicsUtils.set_or_add_orient_op(skin_mesh, Gf.Rotation(Gf.Vec3d([0, 0, 1]), 90).GetQuat())
def get_observations(self) -> dict:
franka_dof_pos = self._frankas.get_joint_positions(clone=False)
franka_dof_vel = self._frankas.get_joint_velocities(clone=False)
self.franka_dof_pos = franka_dof_pos
dof_pos_scaled = (
2.0 * (franka_dof_pos - self.franka_dof_lower_limits)
/ (self.franka_dof_upper_limits - self.franka_dof_lower_limits)
- 1.0
)
self.lfinger_pos, _ = self._frankas._lfingers.get_world_poses(clone=False)
self.rfinger_pos, _ = self._frankas._rfingers.get_world_poses(clone=False)
self.gripper_site_pos = (self.lfinger_pos + self.rfinger_pos)/2 - self._env_pos
tube_positions = self.deformableView.get_simulation_mesh_nodal_positions(clone=False)
tube_velocities = self.deformableView.get_simulation_mesh_nodal_velocities(clone=False)
self.tube_front_positions = tube_positions[:, 200, :] - self._env_pos
self.tube_front_velocities = tube_velocities[:, 200, :]
self.tube_back_positions = tube_positions[:, -1, :] - self._env_pos
self.tube_back_velocities = tube_velocities[:, -1, :]
front_to_gripper = self.tube_front_positions - self.gripper_site_pos
to_front_goal = self.front_goal_pos - self.tube_front_positions
to_back_goal = self.back_goal_pos - self.tube_back_positions
self.obs_buf = torch.cat(
(
dof_pos_scaled,
franka_dof_vel * self.dof_vel_scale,
front_to_gripper,
to_front_goal,
to_back_goal,
self.tube_front_positions,
self.tube_front_velocities,
self.tube_back_positions,
self.tube_back_velocities,
),
dim=-1,
)
observations = {
self._frankas.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
if not self._env._world.is_playing():
return
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
self.actions = actions.clone().to(self._device)
targets = self.franka_dof_targets + self.franka_dof_speed_scales * self.dt * self.actions * self.action_scale
self.franka_dof_targets[:] = tensor_clamp(targets, self.franka_dof_lower_limits, self.franka_dof_upper_limits)
self.franka_dof_targets[:, -1] = self.franka_dof_targets[:, -2]
env_ids_int32 = torch.arange(self._frankas.count, dtype=torch.int32, device=self._device)
self._frankas.set_joint_position_targets(self.franka_dof_targets, indices=env_ids_int32)
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
num_indices = len(indices)
pos = self.franka_default_dof_pos
dof_pos = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_vel = torch.zeros((num_indices, self._frankas.num_dof), device=self._device)
dof_pos[:, :] = pos
self.franka_dof_targets[env_ids, :] = pos
self.franka_dof_pos[env_ids, :] = pos
self._frankas.set_joint_position_targets(self.franka_dof_targets[env_ids], indices=indices)
self._frankas.set_joint_positions(dof_pos, indices=indices)
self._frankas.set_joint_velocities(dof_vel, indices=indices)
self.deformableView.set_simulation_mesh_nodal_positions(self.initial_tube_positions[env_ids], indices)
self.deformableView.set_simulation_mesh_nodal_velocities(self.initial_tube_velocities[env_ids], indices)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
def post_reset(self):
self.franka_default_dof_pos = torch.tensor(
[0.00, 0.63, 0.00, -2.15, 0.00, 2.76, 0.75, 0.02, 0.02], device=self._device
)
self.actions = torch.zeros((self._num_envs, self.num_actions), device=self._device)
self.front_goal_pos = torch.tensor([0.36, 0.0, 0.23], device=self._device).repeat((self._num_envs, 1))
self.back_goal_pos = torch.tensor([0.5, 0.2, 0.0], device=self._device).repeat((self._num_envs, 1))
self.goal_hand_rot = torch.tensor([0.0, 1.0, 0.0, 0.0], device=self._device).repeat((self.num_envs, 1))
self.lfinger_pos, _ = self._frankas._lfingers.get_world_poses(clone=False)
self.rfinger_pos, _ = self._frankas._rfingers.get_world_poses(clone=False)
self.gripper_site_pos = (self.lfinger_pos + self.rfinger_pos)/2 - self._env_pos
self.initial_tube_positions = self.deformableView.get_simulation_mesh_nodal_positions()
self.initial_tube_velocities = self.deformableView.get_simulation_mesh_nodal_velocities()
self.tube_front_positions = self.initial_tube_positions[:, 0, :] - self._env_pos
self.tube_front_velocities = self.initial_tube_velocities[:, 0, :]
self.tube_back_positions = self.initial_tube_positions[:, -1, :] - self._env_pos
self.tube_back_velocities = self.initial_tube_velocities[:, -1, :]
self.num_franka_dofs = self._frankas.num_dof
self.franka_dof_pos = torch.zeros((self.num_envs, self.num_franka_dofs), device=self._device)
dof_limits = self._frankas.get_dof_limits()
self.franka_dof_lower_limits = dof_limits[0, :, 0].to(device=self._device)
self.franka_dof_upper_limits = dof_limits[0, :, 1].to(device=self._device)
self.franka_dof_speed_scales = torch.ones_like(self.franka_dof_lower_limits)
self.franka_dof_speed_scales[self._frankas.gripper_indices] = 0.1
self.franka_dof_targets = torch.zeros(
(self._num_envs, self.num_franka_dofs), dtype=torch.float, device=self._device
)
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
goal_distance_error = torch.norm(self.tube_back_positions[:, 0:2] - self.back_goal_pos[:, 0:2], p = 2, dim = -1)
goal_dist_reward = 1.0 / (5*goal_distance_error + .025)
current_z_level = self.tube_back_positions[:, 2:3]
z_lift_level = torch.where(
goal_distance_error < 0.07, torch.zeros_like(current_z_level), torch.ones_like(current_z_level)*0.18
)
front_lift_error = torch.norm(current_z_level - z_lift_level, p = 2, dim = -1)
front_lift_reward = 1.0 / (5*front_lift_error + .025)
rewards = goal_dist_reward + 4*front_lift_reward
self.rew_buf[:] = rewards
def is_done(self) -> None:
self.reset_buf = torch.where(self.progress_buf >= self._max_episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(self.tube_front_positions[:, 0] < 0, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(self.tube_front_positions[:, 0] > 1.0, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(self.tube_front_positions[:, 1] < -1.0, torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = torch.where(self.tube_front_positions[:, 1] > 1.0, torch.ones_like(self.reset_buf), self.reset_buf)
| 13,322 | Python | 42.825658 | 136 | 0.641045 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/go1widow_terrain.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.rotations import *
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.go1widow import Go1Widow
from omniisaacgymenvs.robots.articulations.views.go1widow_view import Go1WidowView
from omniisaacgymenvs.tasks.utils.anymal_terrain_generator import *
from omniisaacgymenvs.utils.terrain_utils.terrain_utils import *
from pxr import UsdLux, UsdPhysics
import time
class Go1WidowTerrainTask(RLTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.height_samples = None
self.custom_origins = False
self.init_done = False
self._env_spacing = 0.0
self._num_observations = 204
self._num_actions = 12
self.num_joints = 20
self.update_config(sim_config)
RLTask.__init__(self, name, env)
self.height_points = self.init_height_points()
self.measured_heights = None
# joint positions offsets
self.default_dof_pos = torch.zeros(
(self.num_envs, self.num_joints), dtype=torch.float, device=self.device, requires_grad=False
)
# reward episode sums
torch_zeros = lambda: torch.zeros(self.num_envs, dtype=torch.float, device=self.device, requires_grad=False)
self.episode_sums = {
"lin_vel_xy": torch_zeros(),
"lin_vel_z": torch_zeros(),
"ang_vel_z": torch_zeros(),
"ang_vel_xy": torch_zeros(),
"orient": torch_zeros(),
"torques": torch_zeros(),
"joint_acc": torch_zeros(),
"base_height": torch_zeros(),
"air_time": torch_zeros(),
"collision": torch_zeros(),
"stumble": torch_zeros(),
"action_rate": torch_zeros(),
"hip": torch_zeros(),
}
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# normalization
self.lin_vel_scale = self._task_cfg["env"]["learn"]["linearVelocityScale"]
self.ang_vel_scale = self._task_cfg["env"]["learn"]["angularVelocityScale"]
self.dof_pos_scale = self._task_cfg["env"]["learn"]["dofPositionScale"]
self.dof_vel_scale = self._task_cfg["env"]["learn"]["dofVelocityScale"]
self.height_meas_scale = self._task_cfg["env"]["learn"]["heightMeasurementScale"]
self.action_scale = self._task_cfg["env"]["control"]["actionScale"]
# reward scales
self.rew_scales = {}
self.rew_scales["termination"] = self._task_cfg["env"]["learn"]["terminalReward"]
self.rew_scales["lin_vel_xy"] = self._task_cfg["env"]["learn"]["linearVelocityXYRewardScale"]
self.rew_scales["lin_vel_z"] = self._task_cfg["env"]["learn"]["linearVelocityZRewardScale"]
self.rew_scales["ang_vel_z"] = self._task_cfg["env"]["learn"]["angularVelocityZRewardScale"]
self.rew_scales["ang_vel_xy"] = self._task_cfg["env"]["learn"]["angularVelocityXYRewardScale"]
self.rew_scales["orient"] = self._task_cfg["env"]["learn"]["orientationRewardScale"]
self.rew_scales["torque"] = self._task_cfg["env"]["learn"]["torqueRewardScale"]
self.rew_scales["joint_acc"] = self._task_cfg["env"]["learn"]["jointAccRewardScale"]
self.rew_scales["base_height"] = self._task_cfg["env"]["learn"]["baseHeightRewardScale"]
self.rew_scales["action_rate"] = self._task_cfg["env"]["learn"]["actionRateRewardScale"]
self.rew_scales["hip"] = self._task_cfg["env"]["learn"]["hipRewardScale"]
self.rew_scales["fallen_over"] = self._task_cfg["env"]["learn"]["fallenOverRewardScale"]
# command ranges
self.command_x_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_x"]
self.command_y_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["linear_y"]
self.command_yaw_range = self._task_cfg["env"]["randomCommandVelocityRanges"]["yaw"]
# base init state
pos = self._task_cfg["env"]["baseInitState"]["pos"]
rot = self._task_cfg["env"]["baseInitState"]["rot"]
v_lin = self._task_cfg["env"]["baseInitState"]["vLinear"]
v_ang = self._task_cfg["env"]["baseInitState"]["vAngular"]
self.base_init_state = pos + rot + v_lin + v_ang
# default joint positions
self.named_default_joint_angles = self._task_cfg["env"]["defaultJointAngles"]
# other
self.decimation = self._task_cfg["env"]["control"]["decimation"]
self.dt = self.decimation * self._task_cfg["sim"]["dt"]
self.max_episode_length_s = self._task_cfg["env"]["learn"]["episodeLength_s"]
self.max_episode_length = int(self.max_episode_length_s / self.dt + 0.5)
self.push_interval = int(self._task_cfg["env"]["learn"]["pushInterval_s"] / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
self.curriculum = self._task_cfg["env"]["terrain"]["curriculum"]
self.base_threshold = 0.2
self.knee_threshold = 0.1
for key in self.rew_scales.keys():
self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._task_cfg["sim"]["default_physics_material"]["static_friction"] = self._task_cfg["env"]["terrain"][
"staticFriction"
]
self._task_cfg["sim"]["default_physics_material"]["dynamic_friction"] = self._task_cfg["env"]["terrain"][
"dynamicFriction"
]
self._task_cfg["sim"]["default_physics_material"]["restitution"] = self._task_cfg["env"]["terrain"][
"restitution"
]
self._task_cfg["sim"]["add_ground_plane"] = False
def _get_noise_scale_vec(self, cfg):
noise_vec = torch.zeros_like(self.obs_buf[0])
self.add_noise = self._task_cfg["env"]["learn"]["addNoise"]
noise_level = self._task_cfg["env"]["learn"]["noiseLevel"]
noise_vec[:3] = self._task_cfg["env"]["learn"]["linearVelocityNoise"] * noise_level * self.lin_vel_scale
noise_vec[3:6] = self._task_cfg["env"]["learn"]["angularVelocityNoise"] * noise_level * self.ang_vel_scale
noise_vec[6:9] = self._task_cfg["env"]["learn"]["gravityNoise"] * noise_level
noise_vec[9:12] = 0.0 # commands
noise_vec[12:24] = self._task_cfg["env"]["learn"]["dofPositionNoise"] * noise_level * self.dof_pos_scale
noise_vec[24:36] = self._task_cfg["env"]["learn"]["dofVelocityNoise"] * noise_level * self.dof_vel_scale
noise_vec[36:176] = (
self._task_cfg["env"]["learn"]["heightMeasurementNoise"] * noise_level * self.height_meas_scale
)
noise_vec[176:188] = 0.0 # previous actions
return noise_vec
def init_height_points(self):
# 1mx1.6m rectangle (without center line)
y = 0.1 * torch.tensor(
[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5], device=self.device, requires_grad=False
) # 10-50cm on each side
x = 0.1 * torch.tensor(
[-8, -7, -6, -5, -4, -3, -2, 2, 3, 4, 5, 6, 7, 8], device=self.device, requires_grad=False
) # 20-80cm on each side
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
self.num_height_points = grid_x.numel()
points = torch.zeros(self.num_envs, self.num_height_points, 3, device=self.device, requires_grad=False)
points[:, :, 0] = grid_x.flatten()
points[:, :, 1] = grid_y.flatten()
return points
def _create_trimesh(self, create_mesh=True):
self.terrain = Terrain(self._task_cfg["env"]["terrain"], num_robots=self.num_envs)
vertices = self.terrain.vertices
triangles = self.terrain.triangles
position = torch.tensor([-self.terrain.border_size, -self.terrain.border_size, 0.0])
if create_mesh:
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position)
self.height_samples = (
torch.tensor(self.terrain.heightsamples).view(self.terrain.tot_rows, self.terrain.tot_cols).to(self.device)
)
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self.get_terrain()
# self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
# self.height_samples = (
# torch.zeros((1200, 2000)).to(self.device)
# )
self.get_go1widow()
super().set_up_scene(scene, collision_filter_global_paths=["/World/terrain"])
# super().set_up_scene(scene)
self._go1widow = Go1WidowView(
prim_paths_expr="/World/envs/.*/go1widow", name="go1widow_view", track_contact_forces=True, stage = self._stage
)
scene.add(self._go1widow)
scene.add(self._go1widow._knees)
scene.add(self._go1widow._base)
# scene.add_default_ground_plane(prim_path = "/World/defaultGroundPlane")
def initialize_views(self, scene):
# initialize terrain variables even if we do not need to re-create the terrain mesh
self.get_terrain(create_mesh=False)
super().initialize_views(scene)
if scene.object_exists("go1widow_view"):
scene.remove_object("go1widow_view", registry_only=True)
if scene.object_exists("knees_view"):
scene.remove_object("knees_view", registry_only=True)
if scene.object_exists("base_view"):
scene.remove_object("base_view", registry_only=True)
self._go1wiow = Go1WidowView(
prim_paths_expr="/World/envs/.*/go1widow", name="go1widow_view", track_contact_forces=True
)
scene.add(self._go1widow)
scene.add(self._go1widow._knees)
scene.add(self._go1widow._base)
def get_terrain(self, create_mesh=True):
self.env_origins = torch.zeros((self.num_envs, 3), device=self.device, requires_grad=False)
if not self.curriculum:
self._task_cfg["env"]["terrain"]["maxInitMapLevel"] = self._task_cfg["env"]["terrain"]["numLevels"] - 1
self.terrain_levels = torch.randint(
0, self._task_cfg["env"]["terrain"]["maxInitMapLevel"] + 1, (self.num_envs,), device=self.device
)
self.terrain_types = torch.randint(
0, self._task_cfg["env"]["terrain"]["numTerrains"], (self.num_envs,), device=self.device
)
self._create_trimesh(create_mesh=create_mesh)
self.terrain_origins = torch.from_numpy(self.terrain.env_origins).to(self.device).to(torch.float)
def get_go1widow(self):
go1widow_translation = torch.tensor([0.0, 0.0, 0.45])
go1widow_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0])
go1widow = Go1Widow(
prim_path=self.default_zero_env_path + "/go1widow",
name="go1widow",
usd_path="/home/elgceben/OmniIsaacGymEnvs/resources/widowGo1/urdf/widowGo1/widowGo1.usd",
# usd_path="omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.0/Isaac/Robots/Unitree/go1.usd",
translation=go1widow_translation,
orientation=go1widow_orientation,
)
self._sim_config.apply_articulation_settings(
"go1widow", get_prim_at_path(go1widow.prim_path), self._sim_config.parse_actor_config("go1widow")
)
go1widow.set_go1widow_properties(self._stage, go1widow.prim)
go1widow.prepare_contacts(self._stage, go1widow.prim)
self.dof_names = go1widow.dof_names
for i in range(self.num_actions):
name = self.dof_names[i]
angle = self.named_default_joint_angles[name]
self.default_dof_pos[:, i] = angle
def _keep_arm_fixed(self):
self.dof_pos[:, self.num_actions:] = self.default_dof_pos[:, self.num_actions:]
self.dof_vel[:, self.num_actions:] = 0.0
self._go1widow.set_joint_positions(positions=self.dof_pos[:].clone(),
indices=torch.arange(self.num_envs, device=self.device))
self._go1widow.set_joint_velocities(velocities=self.dof_vel[:].clone(),
indices=torch.arange(self.num_envs, device=self.device))
def post_reset(self):
self.base_init_state = torch.tensor(
self.base_init_state, dtype=torch.float, device=self.device, requires_grad=False
)
self.timeout_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# initialize some data used later on
self.up_axis_idx = 2
self.common_step_counter = 0
self.extras = {}
self.noise_scale_vec = self._get_noise_scale_vec(self._task_cfg)
self.commands = torch.zeros(
self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False
) # x vel, y vel, yaw vel, heading
self.commands_scale = torch.tensor(
[self.lin_vel_scale, self.lin_vel_scale, self.ang_vel_scale],
device=self.device,
requires_grad=False,
)
self.gravity_vec = torch.tensor(
get_axis_params(-1.0, self.up_axis_idx), dtype=torch.float, device=self.device
).repeat((self.num_envs, 1))
self.forward_vec = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float, device=self.device).repeat(
(self.num_envs, 1)
)
self.torques = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.last_actions = torch.zeros(
self.num_envs, self.num_actions, dtype=torch.float, device=self.device, requires_grad=False
)
self.feet_air_time = torch.zeros(self.num_envs, 4, dtype=torch.float, device=self.device, requires_grad=False)
self.last_dof_vel = torch.zeros((self.num_envs, self.num_joints), dtype=torch.float, device=self.device, requires_grad=False)
for i in range(self.num_envs):
self.env_origins[i] = self.terrain_origins[self.terrain_levels[i], self.terrain_types[i]]
# self.env_origins[i] = torch.tensor([0.0, 0.0, 0.0]).cuda()
self.num_dof = self._go1widow.num_dof
self.dof_pos = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.dof_vel = torch.zeros((self.num_envs, self.num_dof), dtype=torch.float, device=self.device)
self.base_pos = torch.zeros((self.num_envs, 3), dtype=torch.float, device=self.device)
self.base_quat = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device)
self.base_velocities = torch.zeros((self.num_envs, 6), dtype=torch.float, device=self.device)
self.knee_pos = torch.zeros((self.num_envs * 4, 3), dtype=torch.float, device=self.device)
self.knee_quat = torch.zeros((self.num_envs * 4, 4), dtype=torch.float, device=self.device)
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
self.init_done = True
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
positions_offset = torch_rand_float(0.5, 1.5, (len(env_ids), self.num_dof), device=self.device)
velocities = torch_rand_float(-0.1, 0.1, (len(env_ids), self.num_dof), device=self.device)
self.dof_pos[env_ids] = self.default_dof_pos[env_ids] * positions_offset
self.dof_vel[env_ids] = velocities
self.update_terrain_level(env_ids)
self.base_pos[env_ids] = self.base_init_state[0:3]
self.base_pos[env_ids, 0:3] += self.env_origins[env_ids]
self.base_pos[env_ids, 0:2] += torch_rand_float(-0.5, 0.5, (len(env_ids), 2), device=self.device)
self.base_quat[env_ids] = self.base_init_state[3:7]
self.base_velocities[env_ids] = self.base_init_state[7:]
self._go1widow.set_world_poses(
positions=self.base_pos[env_ids].clone(), orientations=self.base_quat[env_ids].clone(), indices=indices
)
self._go1widow.set_velocities(velocities=self.base_velocities[env_ids].clone(), indices=indices)
self._go1widow.set_joint_positions(positions=self.dof_pos[env_ids].clone(), indices=indices)
self._go1widow.set_joint_velocities(velocities=self.dof_vel[env_ids].clone(), indices=indices)
self.commands[env_ids, 0] = torch_rand_float(
self.command_x_range[0], self.command_x_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 1] = torch_rand_float(
self.command_y_range[0], self.command_y_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids, 3] = torch_rand_float(
self.command_yaw_range[0], self.command_yaw_range[1], (len(env_ids), 1), device=self.device
).squeeze()
self.commands[env_ids] *= (torch.norm(self.commands[env_ids, :2], dim=1) > 0.25).unsqueeze(
1
) # set small commands to zero
self.last_actions[env_ids] = 0.0
self.last_dof_vel[env_ids] = 0.0
self.feet_air_time[env_ids] = 0.0
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 1
# fill extras
self.extras["episode"] = {}
for key in self.episode_sums.keys():
self.extras["episode"]["rew_" + key] = (
torch.mean(self.episode_sums[key][env_ids]) / self.max_episode_length_s
)
self.episode_sums[key][env_ids] = 0.0
self.extras["episode"]["terrain_level"] = torch.mean(self.terrain_levels.float())
def update_terrain_level(self, env_ids):
if not self.init_done or not self.curriculum:
# do not change on initial reset
return
root_pos, _ = self._go1widow.get_world_poses(clone=False)
distance = torch.norm(root_pos[env_ids, :2] - self.env_origins[env_ids, :2], dim=1)
self.terrain_levels[env_ids] -= 1 * (
distance < torch.norm(self.commands[env_ids, :2]) * self.max_episode_length_s * 0.25
)
self.terrain_levels[env_ids] += 1 * (distance > self.terrain.env_length / 2)
self.terrain_levels[env_ids] = torch.clip(self.terrain_levels[env_ids], 0) % self.terrain.env_rows
self.env_origins[env_ids] = self.terrain_origins[self.terrain_levels[env_ids], self.terrain_types[env_ids]]
def refresh_dof_state_tensors(self):
self.dof_pos = self._go1widow.get_joint_positions(clone=False)
self.dof_vel = self._go1widow.get_joint_velocities(clone=False)
def refresh_body_state_tensors(self):
self.base_pos, self.base_quat = self._go1widow.get_world_poses(clone=False)
self.base_velocities = self._go1widow.get_velocities(clone=False)
self.knee_pos, self.knee_quat = self._go1widow._knees.get_world_poses(clone=False)
def pre_physics_step(self, actions):
if not self._env._world.is_playing():
return
# self._keep_arm_fixed()
self.actions = actions.clone().to(self.device)
actions = torch.cat((self.actions, self.default_dof_pos[:, self.num_actions:]), dim=1)
for i in range(self.decimation):
if self._env._world.is_playing():
torques = torch.clip(
self.Kp * (self.action_scale * actions + self.default_dof_pos - self.dof_pos)
- self.Kd * self.dof_vel,
-80.0,
80.0,
)
self._go1widow.set_joint_efforts(torques)
self.torques = torques
SimulationContext.step(self._env._world, render=False)
self.refresh_dof_state_tensors()
def post_physics_step(self):
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.refresh_dof_state_tensors()
self.refresh_body_state_tensors()
self.common_step_counter += 1
if self.common_step_counter % self.push_interval == 0:
self.push_robots()
# prepare quantities
self.base_lin_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 0:3])
self.base_ang_vel = quat_rotate_inverse(self.base_quat, self.base_velocities[:, 3:6])
self.projected_gravity = quat_rotate_inverse(self.base_quat, self.gravity_vec)
forward = quat_apply(self.base_quat, self.forward_vec)
heading = torch.atan2(forward[:, 1], forward[:, 0])
self.commands[:, 2] = torch.clip(0.5 * wrap_to_pi(self.commands[:, 3] - heading), -1.0, 1.0)
self.check_termination()
self.get_states()
self.calculate_metrics()
env_ids = self.reset_buf.nonzero(as_tuple=False).flatten()
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.get_observations()
if self.add_noise:
self.obs_buf += (2 * torch.rand_like(self.obs_buf) - 1) * self.noise_scale_vec
self.last_actions[:] = self.actions[:]
self.last_dof_vel[:] = self.dof_vel[:]
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
def push_robots(self):
self.base_velocities[:, 0:2] = torch_rand_float(
-1.0, 1.0, (self.num_envs, 2), device=self.device
) # lin vel x/y
self._go1widow.set_velocities(self.base_velocities)
def check_termination(self):
self.timeout_buf = torch.where(
self.progress_buf >= self.max_episode_length - 1,
torch.ones_like(self.timeout_buf),
torch.zeros_like(self.timeout_buf),
)
knee_contact = (
torch.norm(self._go1widow._knees.get_net_contact_forces(clone=False).view(self._num_envs, 4, 3), dim=-1)
> 1.0
)
self.has_fallen = (torch.norm(self._go1widow._base.get_net_contact_forces(clone=False), dim=1) > 1.0) | (
torch.sum(knee_contact, dim=-1) > 1.0
)
self.reset_buf = self.has_fallen.clone()
self.reset_buf = torch.where(self.timeout_buf.bool(), torch.ones_like(self.reset_buf), self.reset_buf)
self.reset_buf = self.timeout_buf
def calculate_metrics(self):
# velocity tracking reward
lin_vel_error = torch.sum(torch.square(self.commands[:, :2] - self.base_lin_vel[:, :2]), dim=1)
ang_vel_error = torch.square(self.commands[:, 2] - self.base_ang_vel[:, 2])
rew_lin_vel_xy = torch.exp(-lin_vel_error / 0.25) * self.rew_scales["lin_vel_xy"]
rew_ang_vel_z = torch.exp(-ang_vel_error / 0.25) * self.rew_scales["ang_vel_z"]
# other base velocity penalties
rew_lin_vel_z = torch.square(self.base_lin_vel[:, 2]) * self.rew_scales["lin_vel_z"]
rew_ang_vel_xy = torch.sum(torch.square(self.base_ang_vel[:, :2]), dim=1) * self.rew_scales["ang_vel_xy"]
# orientation penalty
rew_orient = torch.sum(torch.square(self.projected_gravity[:, :2]), dim=1) * self.rew_scales["orient"]
# base height penalty
rew_base_height = torch.square(self.base_pos[:, 2] - 0.52) * self.rew_scales["base_height"]
# torque penalty
rew_torque = torch.sum(torch.square(self.torques), dim=1) * self.rew_scales["torque"]
# joint acc penalty
rew_joint_acc = torch.sum(torch.square(self.last_dof_vel - self.dof_vel), dim=1) * self.rew_scales["joint_acc"]
# fallen over penalty
rew_fallen_over = self.has_fallen * self.rew_scales["fallen_over"]
# action rate penalty
rew_action_rate = (
torch.sum(torch.square(self.last_actions - self.actions), dim=1) * self.rew_scales["action_rate"]
)
# cosmetic penalty for hip motion
rew_hip = (
torch.sum(torch.abs(self.dof_pos[:, 0:4] - self.default_dof_pos[:, 0:4]), dim=1) * self.rew_scales["hip"]
)
# total reward
self.rew_buf = (
rew_lin_vel_xy
+ rew_ang_vel_z
+ rew_lin_vel_z
+ rew_ang_vel_xy
+ rew_orient
+ rew_base_height
+ rew_torque
+ rew_joint_acc
+ rew_action_rate
+ rew_hip
+ rew_fallen_over
)
self.rew_buf = torch.clip(self.rew_buf, min=0.0, max=None)
# add termination reward
self.rew_buf += self.rew_scales["termination"] * self.reset_buf * ~self.timeout_buf
# log episode reward sums
self.episode_sums["lin_vel_xy"] += rew_lin_vel_xy
self.episode_sums["ang_vel_z"] += rew_ang_vel_z
self.episode_sums["lin_vel_z"] += rew_lin_vel_z
self.episode_sums["ang_vel_xy"] += rew_ang_vel_xy
self.episode_sums["orient"] += rew_orient
self.episode_sums["torques"] += rew_torque
self.episode_sums["joint_acc"] += rew_joint_acc
self.episode_sums["action_rate"] += rew_action_rate
self.episode_sums["base_height"] += rew_base_height
self.episode_sums["hip"] += rew_hip
def get_observations(self):
self.measured_heights = self.get_heights()
heights = (
torch.clip(self.base_pos[:, 2].unsqueeze(1) - 0.5 - self.measured_heights, -1, 1.0) * self.height_meas_scale
)
self.obs_buf = torch.cat(
(
self.base_lin_vel * self.lin_vel_scale,
self.base_ang_vel * self.ang_vel_scale,
self.projected_gravity,
self.commands[:, :3] * self.commands_scale,
self.dof_pos * self.dof_pos_scale,
self.dof_vel * self.dof_vel_scale,
heights,
self.actions,
),
dim=-1,
)
def get_ground_heights_below_knees(self):
points = self.knee_pos.reshape(self.num_envs, 4, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_ground_heights_below_base(self):
points = self.base_pos.reshape(self.num_envs, 1, 3)
points += self.terrain.border_size
points = (points / self.terrain.horizontal_scale).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
def get_heights(self, env_ids=None):
if env_ids:
points = quat_apply_yaw(
self.base_quat[env_ids].repeat(1, self.num_height_points), self.height_points[env_ids]
) + (self.base_pos[env_ids, 0:3]).unsqueeze(1)
else:
points = quat_apply_yaw(self.base_quat.repeat(1, self.num_height_points), self.height_points) + (
self.base_pos[:, 0:3]
).unsqueeze(1)
points += self.terrain.border_size
# points += 20
points = (points / self.terrain.horizontal_scale).long()
# points = (points / 0.1).long()
px = points[:, :, 0].view(-1)
py = points[:, :, 1].view(-1)
px = torch.clip(px, 0, self.height_samples.shape[0] - 2)
py = torch.clip(py, 0, self.height_samples.shape[1] - 2)
heights1 = self.height_samples[px, py]
heights2 = self.height_samples[px + 1, py + 1]
heights = torch.min(heights1, heights2)
return heights.view(self.num_envs, -1) * self.terrain.vertical_scale
# return heights.view(self.num_envs, -1) * 0.005
@torch.jit.script
def quat_apply_yaw(quat, vec):
quat_yaw = quat.clone().view(-1, 4)
quat_yaw[:, 1:3] = 0.0
quat_yaw = normalize(quat_yaw)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def wrap_to_pi(angles):
angles %= 2 * np.pi
angles -= 2 * np.pi * (angles > np.pi)
return angles
def get_axis_params(value, axis_idx, x_value=0.0, dtype=float, n_dims=3):
"""construct arguments to `Vec` according to axis index."""
zs = np.zeros((n_dims,))
assert axis_idx < n_dims, "the axis dim should be within the vector dimensions"
zs[axis_idx] = 1.0
params = np.where(zs == 1.0, value, zs)
params[0] = x_value
return list(params.astype(dtype))
| 30,931 | Python | 46.224427 | 133 | 0.609389 |
Virlus/OmniIsaacGymEnvs/omniisaacgymenvs/tasks/ant.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import torch
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.maths import tensor_clamp, torch_rand_float, unscale
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omniisaacgymenvs.tasks.base.rl_task import RLTask
from omniisaacgymenvs.robots.articulations.ant import Ant
from omniisaacgymenvs.tasks.shared.locomotion import LocomotionTask
from pxr import PhysxSchema
class AntLocomotionTask(LocomotionTask):
def __init__(self, name, sim_config, env, offset=None) -> None:
self.update_config(sim_config)
LocomotionTask.__init__(self, name=name, env=env)
return
def update_config(self, sim_config):
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
self._num_observations = 60
self._num_actions = 8
self._ant_positions = torch.tensor([0, 0, 0.5])
LocomotionTask.update_config(self)
def set_up_scene(self, scene) -> None:
self.get_ant()
RLTask.set_up_scene(self, scene)
self._ants = ArticulationView(
prim_paths_expr="/World/envs/.*/Ant/torso", name="ant_view", reset_xform_properties=False
)
scene.add(self._ants)
return
def initialize_views(self, scene):
RLTask.initialize_views(self, scene)
if scene.object_exists("ant_view"):
scene.remove_object("ant_view", registry_only=True)
self._ants = ArticulationView(
prim_paths_expr="/World/envs/.*/Ant/torso", name="ant_view", reset_xform_properties=False
)
scene.add(self._ants)
def get_ant(self):
ant = Ant(prim_path=self.default_zero_env_path + "/Ant", name="Ant", translation=self._ant_positions)
self._sim_config.apply_articulation_settings(
"Ant", get_prim_at_path(ant.prim_path), self._sim_config.parse_actor_config("Ant")
)
def get_robot(self):
return self._ants
def post_reset(self):
self.joint_gears = torch.tensor([15, 15, 15, 15, 15, 15, 15, 15], dtype=torch.float32, device=self._device)
dof_limits = self._ants.get_dof_limits()
self.dof_limits_lower = dof_limits[0, :, 0].to(self._device)
self.dof_limits_upper = dof_limits[0, :, 1].to(self._device)
self.motor_effort_ratio = torch.ones_like(self.joint_gears, device=self._device)
force_links = ["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"]
self._sensor_indices = torch.tensor(
[self._ants._body_indices[j] for j in force_links], device=self._device, dtype=torch.long
)
LocomotionTask.post_reset(self)
def get_dof_at_limit_cost(self):
return get_dof_at_limit_cost(self.obs_buf, self._ants.num_dof)
@torch.jit.script
def get_dof_at_limit_cost(obs_buf, num_dof):
# type: (Tensor, int) -> Tensor
return torch.sum(obs_buf[:, 12 : 12 + num_dof] > 0.99, dim=-1)
| 4,691 | Python | 41.654545 | 115 | 0.69708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.