file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
RoboEagles4828/rift2024/src/zed_object_hardware_interface/zed_object_hardware_interface/zed_conversion.py | import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from zed_interfaces.msg import ObjectsStamped
class ZedConversion(Node):
def __init__(self):
super().__init__('zed_conversion')
self.zed_objects_subscriber = self.create_subscription(ObjectsStamped, '/real/zed/obj_det/objects', self.zed_objects_callback, 10)
self.pose_publisher = self.create_publisher(String, '/real/obj_det_pose', 10)
self.OKGREEN = '\033[92m'
self.ENDC = '\033[0m'
self.pose = String()
self.get_logger().info(self.OKGREEN + "Configured and Activated Zed Conversion" + self.ENDC)
def zed_objects_callback(self, objects: ObjectsStamped):
if objects == None:
self.get_logger().warn("Objects message recieved was null")
else:
if len(objects.objects) <= 0:
self.get_logger().warn("NO OBJECTS DETECTED")
empty = String()
empty.data = "0.0|0.0|0.0"
self.pose_publisher.publish(empty)
else:
x = objects.objects[0].position[0]
y = objects.objects[0].position[1]
z = objects.objects[0].position[2]
self.pose.data = f"{float(x)}|{float(y)}|{float(z)}"
print(self.pose)
self.pose_publisher.publish(self.pose)
def main(args=None):
rclpy.init(args=args)
zed_conversion = ZedConversion()
rclpy.spin(zed_conversion)
zed_conversion.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,638 | Python | 34.630434 | 138 | 0.571429 |
RoboEagles4828/rift2024/src/rift_bringup/launch/isaac-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 }
isaac_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','isaac.launch.py'
)]))
rtab_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','rtab.launch.py'
)]))
delay_rtab_layer = TimerAction(period=8.0, actions=[rtab_layer])
pysim_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','isaac_pysim.launch.py'
)]))
rviz = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','rviz.launch.py'
)]))
# Launch!
return LaunchDescription([
isaac_layer,
pysim_layer,
# rviz,
delay_rtab_layer,
])
| 1,592 | Python | 34.399999 | 91 | 0.643216 |
RoboEagles4828/rift2024/src/rift_bringup/launch/gym.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import RegisterEventHandler, DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, Command, PythonExpression
from launch_ros.actions import Node
from launch.conditions import IfCondition
# Easy use of namespace since args are not strings
# 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')
policy = Node(
package='policy_runner',
executable='runner',
name='policy_runner_node',
parameters=[{
'use_sim_time': use_sim_time,
'odom_topic': '/saranga/zed/odom',
'target_topic': '/real/obj_det_pose',
}]
)
# Launch!
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
policy
]) | 1,094 | Python | 32.181817 | 93 | 0.667276 |
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/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/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.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/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/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 |
2820207922/isaac_ws/main.py | #launch Isaac Sim before any other imports
#default first two lines in any standalone application
from omni.isaac.kit import SimulationApp
# This sample enables a livestream server to connect to when running headless
KIT_CONFIG = {
"width": 1280,
"height": 720,
"window_width": 1920,
"window_height": 1080,
"headless": True,
"renderer": "RayTracedLighting",
"display_options": 3286, # Set display options to show default grid
}
kit = SimulationApp(KIT_CONFIG)
from omni.isaac.core.articulations import Articulation
from omni.isaac.sensor import IMUSensor
from omni.importer.urdf import _urdf
from omni.isaac.dynamic_control import _dynamic_control
from pxr import Gf, PhysxSchema, Sdf, UsdLux, UsdPhysics, Tf
import omni.kit.commands
import numpy as np
import math
def quaternion_to_euler(q):
"""
Convert a quaternion into euler angles (yaw, roll, pitch)
Quaternion format: [w, x, y, z]
Euler angles order: yaw (Z), roll (X), pitch (Y)
"""
# Extract the values from quaternion
w, x, y, z = q
# Pre-calculate common terms
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x**2 + y**2)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = np.clip(t2, a_min=-1.0, a_max=1.0)
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y**2 + z**2)
yaw_z = math.atan2(t3, t4)
return yaw_z, roll_x, pitch_y # Order: yaw, roll, pitch
# Acquire the URDF extension interface
urdf_interface = _urdf.acquire_urdf_interface()
# Set the settings in the import config
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.import_inertia_tensor = True
import_config.distance_scale = 1.0
import_config.density = 0.0
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.default_drive_strength = 0.0
import_config.default_position_drive_damping = 0.0
import_config.convex_decomp = False
import_config.self_collision = False
import_config.create_physics_scene = True
import_config.make_default_prim = False
# Get path to extension data:
URDF_PATH = "balance_infantry/model.urdf"
DEST_PATH = "balance_infantry/model/model.usd"
# Import URDF, stage_path contains the path the path to the usd prim in the stage.
status, stage_path = omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=URDF_PATH,
import_config=import_config,
get_articulation_root=True,
)
# Get stage handle
stage = omni.usd.get_context().get_stage()
# Enable physics
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
# Set gravity
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# Set solver settings
PhysxSchema.PhysxSceneAPI.Apply(stage.GetPrimAtPath("/physicsScene"))
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Get(stage, "/physicsScene")
physxSceneAPI.CreateEnableCCDAttr(True)
physxSceneAPI.CreateEnableStabilizationAttr(True)
physxSceneAPI.CreateEnableGPUDynamicsAttr(False)
physxSceneAPI.CreateBroadphaseTypeAttr("MBP")
physxSceneAPI.CreateSolverTypeAttr("TGS")
# Set limit
LOWER_LIMIT_ANGLE = 0
UPPER_LIMIT_ANGLE = 70
left_front_joint_prim = UsdPhysics.RevoluteJoint.Get(stage, "/balance_infantry/base_link/joint1")
left_front_joint_prim.GetLowerLimitAttr().Set(LOWER_LIMIT_ANGLE)
left_front_joint_prim.GetUpperLimitAttr().Set(UPPER_LIMIT_ANGLE)
left_back_joint_prim = UsdPhysics.RevoluteJoint.Get(stage, "/balance_infantry/base_link/joint2")
left_back_joint_prim.GetLowerLimitAttr().Set(-UPPER_LIMIT_ANGLE)
left_back_joint_prim.GetUpperLimitAttr().Set(-LOWER_LIMIT_ANGLE)
right_front_joint_prim = UsdPhysics.RevoluteJoint.Get(stage, "/balance_infantry/base_link/joint7")
right_front_joint_prim.GetLowerLimitAttr().Set(LOWER_LIMIT_ANGLE)
right_front_joint_prim.GetUpperLimitAttr().Set(UPPER_LIMIT_ANGLE)
right_back_joint_prim = UsdPhysics.RevoluteJoint.Get(stage, "/balance_infantry/base_link/joint6")
right_back_joint_prim.GetLowerLimitAttr().Set(-UPPER_LIMIT_ANGLE)
right_back_joint_prim.GetUpperLimitAttr().Set(-LOWER_LIMIT_ANGLE)
# Set constraint
left_wheel_link = stage.GetPrimAtPath("/balance_infantry/left_wheel_link")
left_hole_link = stage.GetPrimAtPath("/balance_infantry/left_hole_link")
left_constraint = UsdPhysics.RevoluteJoint.Define(stage, "/balance_infantry/base_link/left_constraint")
left_constraint.CreateBody0Rel().SetTargets([left_wheel_link.GetPath()])
left_constraint.CreateBody1Rel().SetTargets([left_hole_link.GetPath()])
left_constraint.CreateAxisAttr().Set("X")
left_constraint.CreateLocalPos0Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
left_constraint.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
left_constraint.CreateExcludeFromArticulationAttr().Set(True)
right_wheel_link = stage.GetPrimAtPath("/balance_infantry/right_wheel_link")
right_hole_link = stage.GetPrimAtPath("/balance_infantry/right_hole_link")
right_constraint = UsdPhysics.RevoluteJoint.Define(stage, "/balance_infantry/base_link/right_constraint")
right_constraint.CreateBody0Rel().SetTargets([right_wheel_link.GetPath()])
right_constraint.CreateBody1Rel().SetTargets([right_hole_link.GetPath()])
right_constraint.CreateAxisAttr().Set("X")
right_constraint.CreateLocalPos0Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
right_constraint.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
right_constraint.CreateExcludeFromArticulationAttr().Set(True)
# Add ground plane
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=stage,
planePath="/groundPlane",
axis="Z",
size=150.0,
position=Gf.Vec3f(0, 0, -0.3),
color=Gf.Vec3f(0.3),
)
# Add lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
# Start simulation
omni.timeline.get_timeline_interface().play()
# perform one simulation step so physics is loaded and dynamic control works.
kit.update()
art = Articulation(prim_path=stage_path)
art.initialize()
if not art.handles_initialized:
print(f"{stage_path} is not an articulation")
else:
print(f"Got articulation {stage_path} with handle {art.articulation_handle}")
dc = _dynamic_control.acquire_dynamic_control_interface()
dc.wake_up_articulation(art.articulation_handle)
dof_properties = _dynamic_control.DofProperties()
dof_properties.damping = 0.0
dof_properties.stiffness = 0.0
dof_properties.max_effort = 100.0
dof_properties.max_velocity = 10.0
left_constraint = dc.find_articulation_dof(art.articulation_handle, "left_constraint")
right_constraint = dc.find_articulation_dof(art.articulation_handle, "right_constraint")
dc.set_dof_properties(left_constraint, dof_properties)
dc.set_dof_properties(right_constraint, dof_properties)
dof_properties.damping = 100.0
dof_properties.stiffness = 0.0
dof_properties.max_effort = 100.0
dof_properties.max_velocity = 10.0
left_wheel_joint = dc.find_articulation_dof(art.articulation_handle, "joint4")
right_wheel_joint = dc.find_articulation_dof(art.articulation_handle, "joint9")
dc.set_dof_properties(left_wheel_joint, dof_properties)
dc.set_dof_properties(right_wheel_joint, dof_properties)
left_front_joint = dc.find_articulation_dof(art.articulation_handle, "joint1")
left_back_joint = dc.find_articulation_dof(art.articulation_handle, "joint2")
right_front_joint = dc.find_articulation_dof(art.articulation_handle, "joint7")
right_back_joint = dc.find_articulation_dof(art.articulation_handle, "joint6")
dc.set_dof_properties(left_front_joint, dof_properties)
dc.set_dof_properties(left_back_joint, dof_properties)
dc.set_dof_properties(right_front_joint, dof_properties)
dc.set_dof_properties(right_back_joint, dof_properties)
# Set IMU sensor
# imu_sensor = IMUSensor(
# prim_path="/balance_infantry/base_link/imu_sensor",
# name="imu",
# frequency=100,
# translation=np.array([0.0, -0.2, 0.1]),
# )
# imu_sensor.initialize()
if not stage:
print("Stage could not be used.")
else:
for prim in stage.Traverse():
prim_path = prim.GetPath()
prim_type = prim.GetTypeName()
print(f"prim_path: {prim_path}, prim_type: {prim_type}")
k = 0
torque = 10
# perform simulation
while kit._app.is_running() and not kit.is_exiting():
# Run in realtime mode, we don't specify the step size
k = k + 1
if k // 500 % 2 == 1:
dc.set_dof_effort(left_front_joint, torque)
dc.set_dof_effort(left_back_joint, -torque)
dc.set_dof_effort(right_front_joint, torque)
dc.set_dof_effort(right_back_joint, -torque)
else:
dc.set_dof_effort(left_front_joint, -torque)
dc.set_dof_effort(left_back_joint, torque)
dc.set_dof_effort(right_front_joint, -torque)
dc.set_dof_effort(right_back_joint, torque)
# imu_data = imu_sensor.get_current_frame()
# quaternion = imu_data['orientation']
# # quaternion = [1.0, 0.0, 0.0, 0.0]
# rotation = quaternion_to_euler(quaternion)
# euler_angles_deg = np.degrees(rotation)
# print(f"quaternion: {quaternion}, angle: {euler_angles_deg}")
kit.update()
# Shutdown and exit
omni.timeline.get_timeline_interface().stop()
kit.close()
| 9,170 | Python | 37.860169 | 105 | 0.735333 |
2820207922/isaac_ws/balance_train.py | from omni.isaac.gym.vec_env import VecEnvBase
env = VecEnvBase(headless=True, enable_livestream=True)
# env = VecEnvBase(headless=True)
from balance_task import BalanceTask
task = BalanceTask(name="Balance")
env.set_task(task, backend="torch")
from stable_baselines3 import PPO
import torch
# create agent from stable baselines
# model = PPO(
# "MlpPolicy",
# env,
# n_steps=1000,
# batch_size=1000,
# n_epochs=10,
# learning_rate=0.005,
# gamma=0.99,
# device="cuda:0",
# ent_coef=0.0,
# vf_coef=0.5,
# max_grad_norm=1.0,
# verbose=1,
# tensorboard_log="./balance_tensorboard"
# )
# torch.save(model.state_dict(),"model.pth")
model = PPO.load(
"models/ppo/ppo_balance0",
env=env,
device="cuda:0"
)
model.learn(total_timesteps=300000)
model.save("models/ppo/ppo_balance1")
env.close() | 856 | Python | 20.974358 | 55 | 0.661215 |
2820207922/isaac_ws/balance_play.py | # create isaac environment
from omni.isaac.gym.vec_env import VecEnvBase
env = VecEnvBase(headless=True, enable_livestream=True)
# create task and register task
from balance_task import BalanceTask
task = BalanceTask(name="Balance")
env.set_task(task, backend="torch")
# import stable baselines
from stable_baselines3 import PPO
# Run inference on the trained policy
model = PPO.load("models/ppo/ppo_balance0")
env._world.reset()
obs, _ = env.reset()
while env._simulation_app.is_running():
action, _states = model.predict(obs)
obs, rewards, terminated, truncated, info = env.step(action[0])
# print(f"obs: {obs}")
# print(f"action: {action}")
# print(f"obs: {obs}, rewards: {rewards}, terminated: {terminated}, truncated: {truncated}, info: {info}")
env.close() | 786 | Python | 31.791665 | 110 | 0.717557 |
2820207922/isaac_ws/balance_task.py | from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.tasks.base_task import BaseTask
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import create_prim
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.core.materials.deformable_material import DeformableMaterial
from pxr import Gf, PhysxSchema, Sdf, UsdLux, UsdPhysics, Tf, UsdShade
from omni.importer.urdf import _urdf
import omni.kit.commands
from gymnasium import spaces
import numpy as np
import torch
import math
class BalanceTask(BaseTask):
def __init__(
self,
name,
offset=None
) -> None:
# print("running: __init__")
# task-specific parameters
self._reward_cnt = 0
self._orders = [0, 1, 2, 3]
self._left_wheel_target = 0.0
self._right_wheel_target = 0.0
self._angle_limit = 90.0 * math.pi / 180
self._vel_wheel_limit = 50.0
self._effort_leg_limit = 10.0
self._effort_wheel_limit = 20.0
# values used for defining RL buffers
self._num_observations = 15
self._num_actions = 6
self._device = "cpu"
self.num_envs = 1
# a few class buffers to store RL-related states
self.obs = torch.zeros((self.num_envs, self._num_observations))
self.obs_last = torch.zeros((self.num_envs, self._num_observations))
self.resets = torch.zeros((self.num_envs, 1))
# set the action and observation space for RL
self.action_space = spaces.Box(
np.ones(self._num_actions, dtype=np.float32) * -1.0, np.ones(self._num_actions, dtype=np.float32) * 1.0
)
self.observation_space = spaces.Box(
np.ones(self._num_observations, dtype=np.float32) * -np.Inf,
np.ones(self._num_observations, dtype=np.float32) * np.Inf,
)
# trigger __init__ of parent class
BaseTask.__init__(self, name=name, offset=offset)
def set_up_scene(self, scene) -> None:
# print("running: set_up_scene")
# retrieve file path for the Cartpole USD file
# usd_path = "balance_infantry/model/balance_infantry_no_constraint.usd"
# add the Cartpole USD to our stage
# Set the settings in the import config
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.import_inertia_tensor = True
import_config.distance_scale = 1.0
import_config.density = 0.0
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.default_drive_strength = 0.0
import_config.default_position_drive_damping = 0.0
import_config.convex_decomp = False
import_config.self_collision = False
import_config.create_physics_scene = True
import_config.make_default_prim = False
urdf_path = "balance_infantry/model.urdf"
status, robot_path = omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config,
# get_articulation_root=True,
)
add_reference_to_stage(robot_path, "/World")
# Get stage handle
self.stage = omni.usd.get_context().get_stage()
if not self.stage:
print("Stage could not be used.")
else:
for prim in self.stage.Traverse():
prim_path = prim.GetPath()
prim_type = prim.GetTypeName()
print(f"prim_path: {prim_path}, prim_type: {prim_type}")
# Set material
self.wheel_material = DeformableMaterial(
prim_path="/World/balance_infantry/base_link/wheel_material",
name="wheel_material",
dynamic_friction=0.5,
youngs_modulus=6e6,
poissons_ratio=0.47,
elasticity_damping=0.00784,
damping_scale=0.1,
)
# print("wheel_material: ", self.wheel_material)
wheel_material_prim = self.stage.GetPrimAtPath("/World/balance_infantry/base_link/wheel_material")
# print("wheel_material_prim: ", wheel_material_prim)
wheel_material_shade = UsdShade.Material(wheel_material_prim)
# print("wheel_material_shade: ", wheel_material_shade)
left_wheel_link = self.stage.GetPrimAtPath("/World/balance_infantry/left_wheel_link")
right_wheel_link = self.stage.GetPrimAtPath("/World/balance_infantry/right_wheel_link")
UsdShade.MaterialBindingAPI(left_wheel_link).Bind(wheel_material_shade, UsdShade.Tokens.strongerThanDescendants)
UsdShade.MaterialBindingAPI(right_wheel_link).Bind(wheel_material_shade, UsdShade.Tokens.strongerThanDescendants)
# create an ArticulationView wrapper for our cartpole - this can be extended towards accessing multiple cartpoles
self._robots = ArticulationView(prim_paths_expr="/World/balance_infantry/base_link*", name="robot_view")
scene.add(self._robots)
# scene.add_default_ground_plane()
# Add ground plane
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=self.stage,
planePath="/groundPlane",
axis="Z",
size=150.0,
position=Gf.Vec3f(0, 0, -0.2),
color=Gf.Vec3f(0.2),
)
# set default camera viewport position and target
self.set_initial_camera_params()
def set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]):
set_camera_view(eye=camera_position, target=camera_target, camera_prim_path="/OmniverseKit_Persp")
def post_reset(self):
# print("running: post_reset")
self.robot_init()
# randomize all envs
indices = torch.arange(self._robots.count, dtype=torch.int64, device=self._device)
self.reset(indices)
def robot_init(self):
self._height_lower_limit = self.calc_height(torch.tensor([0.0]), torch.tensor([0.0]))
self._height_upper_limit = self.calc_height(torch.tensor([1.2217]), torch.tensor([1.2217]))
self._height_target = 0.2
# Get joint index
self._base_link_idx = self._robots.get_body_index("base_link")
self._joint1_idx = self._robots.get_dof_index("joint1")
self._joint2_idx = self._robots.get_dof_index("joint2")
self._joint6_idx = self._robots.get_dof_index("joint6")
self._joint7_idx = self._robots.get_dof_index("joint7")
self._joint4_idx = self._robots.get_dof_index("joint4")
self._joint9_idx = self._robots.get_dof_index("joint9")
# print("base_link_idx: ", self._base_link_idx)
# print("joint1_idx: ", self._joint1_idx)
# print("joint2_idx: ", self._joint2_idx)
# print("joint4_idx: ", self._joint4_idx)
# print("joint6_idx: ", self._joint6_idx)
# print("joint7_idx: ", self._joint7_idx)
# print("joint9_idx: ", self._joint9_idx)
# Set limit
LOWER_LIMIT_ANGLE = 0
UPPER_LIMIT_ANGLE = 70
left_front_joint_prim = UsdPhysics.RevoluteJoint.Get(self.stage, "/World/balance_infantry/base_link/joint1")
left_front_joint_prim.GetLowerLimitAttr().Set(LOWER_LIMIT_ANGLE)
left_front_joint_prim.GetUpperLimitAttr().Set(UPPER_LIMIT_ANGLE)
left_back_joint_prim = UsdPhysics.RevoluteJoint.Get(self.stage, "/World/balance_infantry/base_link/joint2")
left_back_joint_prim.GetLowerLimitAttr().Set(-UPPER_LIMIT_ANGLE)
left_back_joint_prim.GetUpperLimitAttr().Set(-LOWER_LIMIT_ANGLE)
right_front_joint_prim = UsdPhysics.RevoluteJoint.Get(self.stage, "/World/balance_infantry/base_link/joint7")
right_front_joint_prim.GetLowerLimitAttr().Set(LOWER_LIMIT_ANGLE)
right_front_joint_prim.GetUpperLimitAttr().Set(UPPER_LIMIT_ANGLE)
right_back_joint_prim = UsdPhysics.RevoluteJoint.Get(self.stage, "/World/balance_infantry/base_link/joint6")
right_back_joint_prim.GetLowerLimitAttr().Set(-UPPER_LIMIT_ANGLE)
right_back_joint_prim.GetUpperLimitAttr().Set(-LOWER_LIMIT_ANGLE)
# Set constraint
left_wheel_link = self.stage.GetPrimAtPath("/World/balance_infantry/left_wheel_link")
left_hole_link = self.stage.GetPrimAtPath("/World/balance_infantry/left_hole_link")
left_constraint = UsdPhysics.RevoluteJoint.Define(self.stage, "/World/balance_infantry/base_link/left_constraint")
left_constraint.CreateBody0Rel().SetTargets([left_wheel_link.GetPath()])
left_constraint.CreateBody1Rel().SetTargets([left_hole_link.GetPath()])
left_constraint.CreateAxisAttr().Set("X")
left_constraint.CreateLocalPos0Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
left_constraint.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
left_constraint.CreateExcludeFromArticulationAttr().Set(True)
right_wheel_link = self.stage.GetPrimAtPath("/World/balance_infantry/right_wheel_link")
right_hole_link = self.stage.GetPrimAtPath("/World/balance_infantry/right_hole_link")
right_constraint = UsdPhysics.RevoluteJoint.Define(self.stage, "/World/balance_infantry/base_link/right_constraint")
right_constraint.CreateBody0Rel().SetTargets([right_wheel_link.GetPath()])
right_constraint.CreateBody1Rel().SetTargets([right_hole_link.GetPath()])
right_constraint.CreateAxisAttr().Set("X")
right_constraint.CreateLocalPos0Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
right_constraint.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
right_constraint.CreateExcludeFromArticulationAttr().Set(True)
def reset(self, env_ids=None):
# print("running: reset")
if env_ids is None:
env_ids = torch.arange(self.num_envs, device=self._device)
num_resets = len(env_ids)
if self._orders[0] == 0:
self._left_wheel_target = 0.0
self._right_wheel_target = 0.0
self._height_target = 0.2
elif self._orders[0] == 1:
uniform_num = 1.0 * (1.0 - 2.0 * torch.rand(2, device=self._device))
self._left_wheel_target = uniform_num[0]
self._right_wheel_target = uniform_num[1]
self._height_target = 0.2
elif self._orders[0] == 2:
uniform_num = 1.0 * (1.0 - 2.0 * torch.rand(1, device=self._device))
self._left_wheel_target = 0.0
self._right_wheel_target = 0.0
self._height_target = uniform_num[0]
elif self._orders[0] == 3:
uniform_num = 1.0 * (1.0 - 2.0 * torch.rand(2, device=self._device))
self._left_wheel_target = uniform_num[0]
self._right_wheel_target = uniform_num[1]
uniform_num = 1.0 * (1.0 - 2.0 * torch.rand(1, device=self._device))
self._height_target = uniform_num[0]
print(f"left_wheel_target: {self._left_wheel_target}, right_wheel_target: {self._right_wheel_target}, height_target: {self._height_target}")
self._robots.post_reset()
# bookkeeping
self.resets[env_ids] = 0
def pre_physics_step(self, actions) -> None:
# print("running: pre_physics_step")
reset_env_ids = self.resets.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset(reset_env_ids)
# print("actions: ", actions)
forces = torch.zeros((self._robots.count, 6), dtype=torch.float32, device=self._device)
forces[:, 0] = self._effort_leg_limit * actions[0]
forces[:, 1] = self._effort_leg_limit * actions[1]
forces[:, 2] = self._effort_leg_limit * actions[2]
forces[:, 3] = self._effort_leg_limit * actions[3]
forces[:, 4] = self._effort_wheel_limit * actions[4]
forces[:, 5] = self._effort_wheel_limit * actions[5]
indices = torch.arange(self._robots.count, dtype=torch.int32, device=self._device)
self._robots.set_joint_efforts(forces, indices=indices, joint_indices=torch.tensor([self._joint1_idx, self._joint2_idx, self._joint6_idx, self._joint7_idx, self._joint4_idx, self._joint9_idx]))
def get_observations(self):
# print("running: get_observations")
positions, orientations = self._robots.get_world_poses()
# positions_check = torch.where(positions[:, 2] > 10.0, 1, 0)
# if positions_check.item() == 1:
# self.reset()
# return
# if torch.isnan(positions).any() or torch.isnan(orientations).any():
# self.reset()
# return
# print("positions: ", positions)
# print("orientations: ", orientations)
angle = self.quaternion_to_euler_zxy(orientations)
# print(f"roll_x: {angle[:, 1] * 180 / math.pi}, picth_y: {angle[:, 2] * 180 / math.pi}")
if torch.isnan(angle).any():
return
# collect joint positions and velocities for observation
dof_pos = self._robots.get_joint_positions()
dof_vel = self._robots.get_joint_velocities()
if torch.isnan(dof_pos).any() or torch.isnan(dof_vel).any():
return
joint1_pos = dof_pos[:, self._joint1_idx]
joint1_vel = dof_vel[:, self._joint1_idx]
joint2_pos = dof_pos[:, self._joint2_idx]
joint2_vel = dof_vel[:, self._joint2_idx]
joint6_pos = dof_pos[:, self._joint6_idx]
joint6_vel = dof_vel[:, self._joint6_idx]
joint7_pos = dof_pos[:, self._joint7_idx]
joint7_vel = dof_vel[:, self._joint7_idx]
joint4_vel = dof_vel[:, self._joint4_idx]
joint9_vel = dof_vel[:, self._joint9_idx]
self.obs_last = self.obs.clone()
self.obs[:, 0] = self._left_wheel_target
self.obs[:, 1] = self._right_wheel_target
self.obs[:, 2] = self._height_target
self.obs[:, 3] = angle[:, 1]
self.obs[:, 4] = angle[:, 2]
self.obs[:, 5] = joint1_pos
self.obs[:, 6] = joint2_pos
self.obs[:, 7] = joint6_pos
self.obs[:, 8] = joint7_pos
self.obs[:, 9] = joint1_vel
self.obs[:, 10] = joint2_vel
self.obs[:, 11] = joint6_vel
self.obs[:, 12] = joint7_vel
self.obs[:, 13] = joint4_vel
self.obs[:, 14] = joint9_vel
# print("obs: ", self.obs)
return self.obs
def quaternion_to_euler_zxy(self, q):
# q = torch.tensor(q)
quat = torch.zeros((self._robots.count, 4), dtype=torch.float32, device=self._device)
angle = torch.zeros((self._robots.count, 3), dtype=torch.float32, device=self._device)
quat[:, 0] = q[:, 0]
quat[:, 1] = q[:, 1]
quat[:, 2] = q[:, 2]
quat[:, 3] = q[:, 3]
angle[:, 1] = torch.atan2(2.0 * (quat[:, 0] * quat[:, 1] + quat[:, 2] * quat[:, 3]), 1.0 - 2.0 * (quat[:, 1] * quat[:, 1] + quat[:, 2] * quat[:, 2]))
angle[:, 2] = torch.asin(torch.clamp(2.0 * (quat[:, 0] * quat[:, 2] - quat[:, 3] * quat[:, 1]), min=-1.0, max=1.0))
angle[:, 0] = torch.atan2(2.0 * (quat[:, 0] * quat[:, 3] + quat[:, 1] * quat[:, 2]), 1.0 - 2.0 * (quat[:, 2] * quat[:, 2] + quat[:, 3] * quat[:, 3]))
# angle = angle * 180 / math.pi
return angle
def calculate_metrics(self) -> None:
# print("running: calculate_metrics")
left_wheel_target = self.obs[:, 0]
right_wheel_target = self.obs[:, 1]
height_target = self.obs[:, 2]
# print(f"left_wheel_target: {left_wheel_target}, right_wheel_target: {right_wheel_target}, height_target: {height_target}")
roll_x = self.obs[:, 3]
pitch_y = self.obs[:, 4]
joint1_pos = self.obs[:, 5]
joint2_pos = self.obs[:, 6]
joint6_pos = self.obs[:, 7]
joint7_pos = self.obs[:, 8]
joint1_vel = self.obs[:, 9]
joint2_vel = self.obs[:, 10]
joint6_vel = self.obs[:, 11]
joint7_vel = self.obs[:, 12]
joint4_vel = self.obs[:, 13]
joint9_vel = self.obs[:, 14]
# print(f"joint4_vel: {joint4_vel}, joint9_vel: {joint9_vel}")
roll_x_last = self.obs_last[:, 3]
pitch_y_last = self.obs_last[:, 4]
joint1_pos_last = self.obs_last[:, 5]
joint2_pos_last = self.obs_last[:, 6]
joint6_pos_last = self.obs_last[:, 7]
joint7_pos_last = self.obs_last[:, 8]
left_height = self.calc_height(joint1_pos, joint2_pos)
right_height = self.calc_height(joint6_pos, joint7_pos)
height_current = (left_height + right_height) / 2
left_height_last = self.calc_height(joint1_pos_last, joint2_pos_last)
right_height_last = self.calc_height(joint6_pos_last, joint7_pos_last)
height_last = (left_height_last + right_height_last) / 2
reward_roll_x = -0.8 * torch.abs(roll_x / self._angle_limit + (roll_x - roll_x_last) / self._angle_limit)
reward_pitch_y = -0.5 * torch.abs(pitch_y / self._angle_limit + (pitch_y - pitch_y_last) / self._angle_limit)
reward_wheel_vel = -0.3 * (torch.abs(left_wheel_target - joint4_vel / self._vel_wheel_limit) + torch.abs(right_wheel_target - joint9_vel / self._vel_wheel_limit))
reward_height = -0.5 * torch.abs(height_target - height_current / (self._height_upper_limit - self._height_lower_limit))
reward = 1.5 + reward_roll_x + reward_pitch_y + reward_wheel_vel + reward_height
# print(f"reward: {reward.item()}")
if reward.item() > 0.0:
self._reward_cnt = self._reward_cnt + int(reward.item() * 10)
# print("reward_cnt: ", self._reward_cnt)
return reward.item()
def calc_height(self, a, b):
l1 = 0.075
l2 = 0.15
l3 = 0.27
d = 15 * math.pi / 180
p1 = torch.zeros((self._robots.count, 2), dtype=torch.float32, device=self._device)
p2 = torch.zeros((self._robots.count, 2), dtype=torch.float32, device=self._device)
p3 = torch.zeros((self._robots.count, 2), dtype=torch.float32, device=self._device)
res = torch.zeros((self._robots.count, 1), dtype=torch.float32, device=self._device)
a = torch.abs(a)
b = torch.abs(b)
p1[:, 0] = -l2 * torch.cos(a - d) - l1
p1[:, 1] = l2 * torch.sin(a - d)
p2[:, 0] = l2 * torch.cos(b - d) + l1
p2[:, 1] = l2 * torch.sin(b - d)
p3[:, 0] = (p1[:, 0] + p2[:, 0]) / 2
p3[:, 1] = (p1[:, 1] + p2[:, 1]) / 2
res[:, 0] = l3 * l3 - torch.pow(p2[:, 0] - p3[:, 0], 2) - torch.pow(p2[:, 1] - p3[:, 1], 2)
res[:, 0] = torch.sqrt(res[:, 0] * torch.pow(p2[:, 0]- p1[:, 0], 2) / (torch.pow(p2[:, 0]- p1[:, 0], 2) + torch.pow(p2[:, 1]- p1[:, 1], 2)))
return res
def is_done(self) -> None:
# print("running: is_done")
roll_x = self.obs[:, 3]
pitch_y = self.obs[:, 4]
joint1_pos = self.obs[:, 5]
joint2_pos = self.obs[:, 6]
joint6_pos = self.obs[:, 7]
joint7_pos = self.obs[:, 8]
joint1_vel = self.obs[:, 9]
joint2_vel = self.obs[:, 10]
joint6_vel = self.obs[:, 11]
joint7_vel = self.obs[:, 12]
joint4_vel = self.obs[:, 13]
joint9_vel = self.obs[:, 14]
# reset the robot if cart has reached reset_dist or pole is too far from upright
resets = torch.where(torch.abs(roll_x) > self._angle_limit, 1, 0)
resets = torch.where(torch.abs(pitch_y) > self._angle_limit, 1, resets)
resets = torch.where(torch.tensor([self._reward_cnt]) > 1000, 1, resets)
if self._reward_cnt > 1000:
order = self._orders.pop(0)
self._orders.append(order)
self._reward_cnt = 0
# print("order: ", order)
self.resets = resets
# print("resets: ", resets.item())
return resets.item()
| 19,987 | Python | 42.546841 | 201 | 0.592835 |
2820207922/isaac_ws/README.md | # Servicer Deployment Guide | 27 | Markdown | 26.999973 | 27 | 0.851852 |
2820207922/isaac_ws/standalone_examples/replicator/amr_navigation.py | # Copyright (c) 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.
"""Generate synthetic data from an AMR navigating to random locations
"""
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp(launch_config={"headless": False})
import argparse
import builtins
import os
import random
from itertools import cycle
import carb.settings
import omni.client
import omni.kit.app
import omni.replicator.core as rep
import omni.timeline
import omni.usd
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage, create_new_stage
from pxr import Gf, PhysxSchema, UsdGeom, UsdLux, UsdPhysics
class NavSDGDemo:
CARTER_URL = "/Isaac/Samples/Replicator/OmniGraph/nova_carter_nav_only.usd"
DOLLY_URL = "/Isaac/Props/Dolly/dolly_physics.usd"
PROPS_URL = "/Isaac/Props/YCB/Axis_Aligned_Physics"
LEFT_CAMERA_PATH = "/NavWorld/CarterNav/chassis_link/front_hawk/left/camera_left"
RIGHT_CAMERA_PATH = "/NavWorld/CarterNav/chassis_link/front_hawk/right/camera_right"
def __init__(self):
self._carter_chassis = None
self._carter_nav_target = None
self._dolly = None
self._dolly_light = None
self._props = []
self._cycled_env_urls = None
self._env_interval = 1
self._timeline = None
self._timeline_sub = None
self._stage_event_sub = None
self._stage = None
self._trigger_distance = 2.0
self._num_frames = 0
self._frame_counter = 0
self._writer = None
self._out_dir = None
self._render_products = []
self._use_temp_rp = False
self._in_running_state = False
def start(
self,
num_frames=10,
out_dir=None,
env_urls=[],
env_interval=3,
use_temp_rp=False,
seed=None,
):
print(f"[NavSDGDemo] Starting")
if seed is not None:
random.seed(seed)
self._num_frames = num_frames
self._out_dir = out_dir if out_dir is not None else os.path.join(os.getcwd(), "_out_nav_sdg_demo")
self._cycled_env_urls = cycle(env_urls)
self._env_interval = env_interval
self._use_temp_rp = use_temp_rp
self._frame_counter = 0
self._trigger_distance = 2.0
self._load_env()
self._randomize_dolly_pose()
self._randomize_dolly_light()
self._randomize_prop_poses()
self._setup_sdg()
self._timeline = omni.timeline.get_timeline_interface()
self._timeline.play()
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED), self._on_timeline_event
)
self._stage_event_sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop_by_type(int(omni.usd.StageEventType.CLOSING), self._on_stage_closing_event)
)
self._in_running_state = True
def clear(self):
self._cycled_env_urls = None
self._carter_chassis = None
self._carter_nav_target = None
self._dolly = None
self._dolly_light = None
self._timeline = None
self._frame_counter = 0
if self._stage_event_sub:
self._stage_event_sub.unsubscribe()
self._stage_event_sub = None
if self._timeline_sub:
self._timeline_sub.unsubscribe()
self._timeline_sub = None
self._destroy_render_products()
self._stage = None
self._in_running_state = False
def is_running(self):
return self._in_running_state
def _is_running_in_script_editor(self):
return builtins.ISAAC_LAUNCHED_FROM_TERMINAL is True
def _on_stage_closing_event(self, e: carb.events.IEvent):
self.clear()
def _load_env(self):
# Fresh stage with custom physics scene for carter's navigation
create_new_stage()
self._stage = omni.usd.get_context().get_stage()
self._add_physics_scene()
# Environment
assets_root_path = get_assets_root_path()
add_reference_to_stage(usd_path=assets_root_path + next(self._cycled_env_urls), prim_path="/Environment")
# Carter
add_reference_to_stage(usd_path=assets_root_path + self.CARTER_URL, prim_path="/NavWorld/CarterNav")
self._carter_nav_target = self._stage.GetPrimAtPath("/NavWorld/CarterNav/targetXform")
self._carter_chassis = self._stage.GetPrimAtPath("/NavWorld/CarterNav/chassis_link")
# Dolly
add_reference_to_stage(usd_path=assets_root_path + self.DOLLY_URL, prim_path="/NavWorld/Dolly")
self._dolly = self._stage.GetPrimAtPath("/NavWorld/Dolly")
if not self._dolly.GetAttribute("xformOp:translate"):
UsdGeom.Xformable(self._dolly).AddTranslateOp()
if not self._dolly.GetAttribute("xformOp:rotateXYZ"):
UsdGeom.Xformable(self._dolly).AddRotateXYZOp()
# Light
light = UsdLux.SphereLight.Define(self._stage, f"/NavWorld/DollyLight")
light.CreateRadiusAttr(0.5)
light.CreateIntensityAttr(35000)
light.CreateColorAttr(Gf.Vec3f(1.0, 1.0, 1.0))
self._dolly_light = light.GetPrim()
if not self._dolly_light.GetAttribute("xformOp:translate"):
UsdGeom.Xformable(self._dolly_light).AddTranslateOp()
# Props
props_urls = []
props_folder_path = assets_root_path + self.PROPS_URL
result, entries = omni.client.list(props_folder_path)
if result != omni.client.Result.OK:
carb.log_error(f"Could not list assets in path: {props_folder_path}")
return
for entry in entries:
_, ext = os.path.splitext(entry.relative_path)
if ext == ".usd":
props_urls.append(f"{props_folder_path}/{entry.relative_path}")
cycled_props_url = cycle(props_urls)
for i in range(15):
prop_url = next(cycled_props_url)
prop_name = os.path.splitext(os.path.basename(prop_url))[0]
path = f"/NavWorld/Props/Prop_{prop_name}_{i}"
prim = self._stage.DefinePrim(path, "Xform")
prim.GetReferences().AddReference(prop_url)
self._props.append(prim)
def _add_physics_scene(self):
# Physics setup specific for the navigation graph
physics_scene = UsdPhysics.Scene.Define(self._stage, "/physicsScene")
physx_scene = PhysxSchema.PhysxSceneAPI.Apply(self._stage.GetPrimAtPath("/physicsScene"))
physx_scene.GetEnableCCDAttr().Set(True)
physx_scene.GetEnableGPUDynamicsAttr().Set(False)
physx_scene.GetBroadphaseTypeAttr().Set("MBP")
def _randomize_dolly_pose(self):
min_dist_from_carter = 4
carter_loc = self._carter_chassis.GetAttribute("xformOp:translate").Get()
for _ in range(100):
x, y = random.uniform(-6, 6), random.uniform(-6, 6)
dist = (Gf.Vec2f(x, y) - Gf.Vec2f(carter_loc[0], carter_loc[1])).GetLength()
if dist > min_dist_from_carter:
self._dolly.GetAttribute("xformOp:translate").Set((x, y, 0))
self._carter_nav_target.GetAttribute("xformOp:translate").Set((x, y, 0))
break
self._dolly.GetAttribute("xformOp:rotateXYZ").Set((0, 0, random.uniform(-180, 180)))
def _randomize_dolly_light(self):
dolly_loc = self._dolly.GetAttribute("xformOp:translate").Get()
self._dolly_light.GetAttribute("xformOp:translate").Set(dolly_loc + (0, 0, 2.5))
self._dolly_light.GetAttribute("inputs:color").Set(
(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1))
)
def _randomize_prop_poses(self):
spawn_loc = self._dolly.GetAttribute("xformOp:translate").Get()
spawn_loc[2] = spawn_loc[2] + 0.5
for prop in self._props:
prop.GetAttribute("xformOp:translate").Set(spawn_loc + (random.uniform(-1, 1), random.uniform(-1, 1), 0))
spawn_loc[2] = spawn_loc[2] + 0.2
def _setup_sdg(self):
# Disable capture on play and async rendering
carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False)
carb.settings.get_settings().set("/omni/replicator/asyncRendering", False)
carb.settings.get_settings().set("/app/asyncRendering", False)
# Set camera sensors fStop to 0.0 to get well lit sharp images
left_camera_prim = self._stage.GetPrimAtPath(self.LEFT_CAMERA_PATH)
left_camera_prim.GetAttribute("fStop").Set(0.0)
right_camera_prim = self._stage.GetPrimAtPath(self.RIGHT_CAMERA_PATH)
right_camera_prim.GetAttribute("fStop").Set(0.0)
self._writer = rep.WriterRegistry.get("BasicWriter")
self._writer.initialize(output_dir=self._out_dir, rgb=True)
# If no temporary render products are requested, create them once here and destroy them only at the end
if not self._use_temp_rp:
self._setup_render_products()
def _setup_render_products(self):
print(f"[NavSDGDemo] Creating render products")
rp_left = rep.create.render_product(
self.LEFT_CAMERA_PATH,
(512, 512),
name="left_sensor",
force_new=True,
)
rp_right = rep.create.render_product(
self.RIGHT_CAMERA_PATH,
(512, 512),
name="right_sensor",
force_new=True,
)
self._render_products = [rp_left, rp_right]
self._writer.attach(self._render_products)
rep.orchestrator.preview()
def _destroy_render_products(self):
print(f"[NavSDGDemo] Destroying render products")
if self._writer:
self._writer.detach()
for rp in self._render_products:
rp.destroy()
self._render_products.clear()
if self._stage.GetPrimAtPath("/Replicator"):
omni.kit.commands.execute("DeletePrimsCommand", paths=["/Replicator"])
def _run_sdg(self):
if self._use_temp_rp:
self._setup_render_products()
rep.orchestrator.step(rt_subframes=16, pause_timeline=False)
rep.orchestrator.wait_until_complete()
if self._use_temp_rp:
self._destroy_render_products()
async def _run_sdg_async(self):
if self._use_temp_rp:
self._setup_render_products()
await rep.orchestrator.step_async(rt_subframes=16, pause_timeline=False)
await rep.orchestrator.wait_until_complete_async()
if self._use_temp_rp:
self._destroy_render_products()
def _load_next_env(self):
if self._stage.GetPrimAtPath("/Environment"):
omni.kit.commands.execute("DeletePrimsCommand", paths=["/Environment"])
assets_root_path = get_assets_root_path()
add_reference_to_stage(usd_path=assets_root_path + next(self._cycled_env_urls), prim_path="/Environment")
def _on_sdg_done(self, task):
self._setup_next_frame()
def _setup_next_frame(self):
self._frame_counter += 1
if self._frame_counter >= self._num_frames:
print(f"[NavSDGDemo] Finished")
self.clear()
return
self._randomize_dolly_pose()
self._randomize_dolly_light()
self._randomize_prop_poses()
if self._frame_counter % self._env_interval == 0:
self._load_next_env()
# Set a new random distance from which to take capture the next frame
self._trigger_distance = random.uniform(1.75, 2.5)
self._timeline.play()
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED), self._on_timeline_event
)
def _on_timeline_event(self, e: carb.events.IEvent):
carter_loc = self._carter_chassis.GetAttribute("xformOp:translate").Get()
dolly_loc = self._dolly.GetAttribute("xformOp:translate").Get()
dist = (Gf.Vec2f(dolly_loc[0], dolly_loc[1]) - Gf.Vec2f(carter_loc[0], carter_loc[1])).GetLength()
if dist < self._trigger_distance:
print(f"[NavSDGDemo] Capturing frame no. {self._frame_counter}")
self._timeline.pause()
self._timeline_sub.unsubscribe()
if self._is_running_in_script_editor():
import asyncio
task = asyncio.ensure_future(self._run_sdg_async())
task.add_done_callback(self._on_sdg_done)
else:
self._run_sdg()
self._setup_next_frame()
ENV_URLS = [
"/Isaac/Environments/Grid/default_environment.usd",
"/Isaac/Environments/Simple_Warehouse/warehouse.usd",
"/Isaac/Environments/Grid/gridroom_black.usd",
]
parser = argparse.ArgumentParser()
parser.add_argument("--use_temp_rp", action="store_true", help="Create and destroy render products for each SDG frame")
parser.add_argument("--num_frames", type=int, default=9, help="The number of frames to capture")
parser.add_argument("--env_interval", type=int, default=3, help="Interval at which to change the environments")
args, unknown = parser.parse_known_args()
out_dir = os.path.join(os.getcwd(), "_out_nav_sdg_demo", "")
nav_demo = NavSDGDemo()
nav_demo.start(
num_frames=args.num_frames,
out_dir=out_dir,
env_urls=ENV_URLS,
env_interval=args.env_interval,
use_temp_rp=args.use_temp_rp,
seed=124,
)
while simulation_app.is_running() and nav_demo.is_running():
simulation_app.update()
simulation_app.close()
| 14,064 | Python | 39.768116 | 119 | 0.630475 |
2820207922/isaac_ws/standalone_examples/replicator/online_generation/generate_shapenet.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""Dataset with online randomized scene generation for Instance Segmentation training.
Use OmniKit to generate a simple scene. At each iteration, the scene is populated by
adding assets from the user-specified classes with randomized pose and colour.
The camera position is also randomized before capturing groundtruth consisting of
an RGB rendered image, Tight 2D Bounding Boxes and Instance Segmentation masks.
"""
import glob
import os
import signal
import sys
import carb
import numpy as np
import torch
from omni.isaac.kit import SimulationApp
LABEL_TO_SYNSET = {
"table": "04379243",
"monitor": "03211117",
"phone": "04401088",
"watercraft": "04530566",
"chair": "03001627",
"lamp": "03636649",
"speaker": "03691459",
"bench": "02828884",
"plane": "02691156",
"bathtub": "02808440",
"bookcase": "02871439",
"bag": "02773838",
"basket": "02801938",
"bowl": "02880940",
"bus": "02924116",
"cabinet": "02933112",
"camera": "02942699",
"car": "02958343",
"dishwasher": "03207941",
"file": "03337140",
"knife": "03624134",
"laptop": "03642806",
"mailbox": "03710193",
"microwave": "03761084",
"piano": "03928116",
"pillow": "03938244",
"pistol": "03948459",
"printer": "04004475",
"rocket": "04099429",
"sofa": "04256520",
"washer": "04554684",
"rifle": "04090263",
"can": "02946921",
"bottle": "02876657",
"bowl": "02880940",
"earphone": "03261776",
"mug": "03797390",
}
SYNSET_TO_LABEL = {v: k for k, v in LABEL_TO_SYNSET.items()}
# Setup default variables
RESOLUTION = (1024, 1024)
OBJ_LOC_MIN = (-50, 5, -50)
OBJ_LOC_MAX = (50, 5, 50)
CAM_LOC_MIN = (100, 0, -100)
CAM_LOC_MAX = (100, 100, 100)
SCALE_MIN = 15
SCALE_MAX = 40
# Default rendering parameters
RENDER_CONFIG = {"headless": False}
class RandomObjects(torch.utils.data.IterableDataset):
"""Dataset of random ShapeNet objects.
Objects are randomly chosen from selected categories and are positioned, rotated and coloured
randomly in an empty room. RGB, BoundingBox2DTight and Instance Segmentation are captured by moving a
camera aimed at the centre of the scene which is positioned at random at a fixed distance from the centre.
This dataset is intended for use with ShapeNet but will function with any dataset of USD models
structured as `root/category/**/*.usd. One note is that this is designed for assets without materials
attached. This is to avoid requiring to compile MDLs and load textures while training.
Args:
categories (tuple of str): Tuple or list of categories. For ShapeNet, these will be the synset IDs.
max_asset_size (int): Maximum asset file size that will be loaded. This prevents out of memory errors
due to loading large meshes.
num_assets_min (int): Minimum number of assets populated in the scene.
num_assets_max (int): Maximum number of assets populated in the scene.
split (float): Fraction of the USDs found to use for training.
train (bool): If true, use the first training split and generate infinite random scenes.
"""
def __init__(
self, root, categories, max_asset_size=None, num_assets_min=3, num_assets_max=5, split=0.7, train=True
):
assert len(categories) > 1
assert (split > 0) and (split <= 1.0)
self.kit = SimulationApp(RENDER_CONFIG)
import omni.replicator.core as rep
import warp as wp
self.rep = rep
self.wp = wp
from omni.isaac.core.utils.nucleus import get_assets_root_path
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")
return
# If ShapeNet categories are specified with their names, convert to synset ID
# Remove this if using with a different dataset than ShapeNet
category_ids = [LABEL_TO_SYNSET.get(c, c) for c in categories]
self.categories = category_ids
self.range_num_assets = (num_assets_min, max(num_assets_min, num_assets_max))
try:
self.references = self._find_usd_assets(root, category_ids, max_asset_size, split, train)
except ValueError as err:
carb.log_error(str(err))
self.kit.close()
sys.exit()
# Setup the scene, lights, walls, camera, etc.
self.setup_scene()
# Setup replicator randomizer graph
self.setup_replicator()
self.cur_idx = 0
self.exiting = False
signal.signal(signal.SIGINT, self._handle_exit)
def _get_textures(self):
return [
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/checkered.png",
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/marble_tile.png",
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/picture_a.png",
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/picture_b.png",
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/textured_wall.png",
self.assets_root_path + "/Isaac/Samples/DR/Materials/Textures/checkered_color.png",
]
def _handle_exit(self, *args, **kwargs):
print("exiting dataset generation...")
self.exiting = True
def close(self):
self.rep.orchestrator.stop()
self.kit.close()
def setup_scene(self):
from omni.isaac.core.utils.prims import create_prim
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core.utils.stage import set_stage_up_axis
"""Setup lights, walls, floor, ceiling and camera"""
# Set stage up axis to Y-up
set_stage_up_axis("y")
# In a practical setting, the room parameters should attempt to match those of the
# target domain. Here, we instead opt for simplicity.
create_prim("/World/Room", "Sphere", attributes={"radius": 1e3, "primvars:displayColor": [(1.0, 1.0, 1.0)]})
create_prim(
"/World/Ground",
"Cylinder",
position=np.array([0.0, -0.5, 0.0]),
orientation=euler_angles_to_quat(np.array([90.0, 0.0, 0.0]), degrees=True),
attributes={"height": 1, "radius": 1e4, "primvars:displayColor": [(1.0, 1.0, 1.0)]},
)
create_prim("/World/Asset", "Xform")
self.camera = self.rep.create.camera()
self.render_product = self.rep.create.render_product(self.camera, RESOLUTION)
# Setup annotators that will report groundtruth
self.rgb = self.rep.AnnotatorRegistry.get_annotator("rgb")
self.bbox_2d_tight = self.rep.AnnotatorRegistry.get_annotator("bounding_box_2d_tight")
self.instance_seg = self.rep.AnnotatorRegistry.get_annotator("instance_segmentation")
self.rgb.attach(self.render_product)
self.bbox_2d_tight.attach(self.render_product)
self.instance_seg.attach(self.render_product)
self.kit.update()
def _find_usd_assets(self, root, categories, max_asset_size, split, train=True):
"""Look for USD files under root/category for each category specified.
For each category, generate a list of all USD files found and select
assets up to split * len(num_assets) if `train=True`, otherwise select the
remainder.
"""
references = {}
for category in categories:
all_assets = glob.glob(os.path.join(root, category, "*/*.usd"), recursive=True)
print(os.path.join(root, category, "*/*.usd"))
# Filter out large files (which can prevent OOM errors during training)
if max_asset_size is None:
assets_filtered = all_assets
else:
assets_filtered = []
for a in all_assets:
if os.stat(a).st_size > max_asset_size * 1e6:
print(f"{a} skipped as it exceeded the max size {max_asset_size} MB.")
else:
assets_filtered.append(a)
num_assets = len(assets_filtered)
if num_assets == 0:
raise ValueError(f"No USDs found for category {category} under max size {max_asset_size} MB.")
if train:
references[category] = assets_filtered[: int(num_assets * split)]
else:
references[category] = assets_filtered[int(num_assets * split) :]
return references
def _instantiate_category(self, category, references):
with self.rep.randomizer.instantiate(references, size=1, mode="reference"):
self.rep.modify.semantics([("class", category)])
self.rep.modify.pose(
position=self.rep.distribution.uniform(OBJ_LOC_MIN, OBJ_LOC_MAX),
rotation=self.rep.distribution.uniform((0, -180, 0), (0, 180, 0)),
scale=self.rep.distribution.uniform(SCALE_MIN, SCALE_MAX),
)
self.rep.randomizer.texture(self._get_textures(), project_uvw=True)
def setup_replicator(self):
"""Setup the replicator graph with various attributes."""
# Create two sphere lights
light1 = self.rep.create.light(light_type="sphere", position=(-450, 350, 350), scale=100, intensity=30000.0)
light2 = self.rep.create.light(light_type="sphere", position=(450, 350, 350), scale=100, intensity=30000.0)
with self.rep.new_layer():
with self.rep.trigger.on_frame():
# Randomize light colors
with self.rep.create.group([light1, light2]):
self.rep.modify.attribute("color", self.rep.distribution.uniform((0.1, 0.1, 0.1), (1.0, 1.0, 1.0)))
# Randomize camera position
with self.camera:
self.rep.modify.pose(
position=self.rep.distribution.uniform(CAM_LOC_MIN, CAM_LOC_MAX), look_at=(0, 0, 0)
)
# Randomize asset positions and textures
for category, references in self.references.items():
self._instantiate_category(category, references)
# Run replicator for a single iteration without triggering any writes
self.rep.orchestrator.preview()
def __iter__(self):
return self
def __next__(self):
# Step - trigger a randomization and a render
self.rep.orchestrator.step(rt_subframes=4)
# Collect Groundtruth
gt = {
"rgb": self.rgb.get_data(device="cuda"),
"boundingBox2DTight": self.bbox_2d_tight.get_data(device="cpu"),
"instanceSegmentation": self.instance_seg.get_data(device="cuda"),
}
# RGB
# Drop alpha channel
image = self.wp.to_torch(gt["rgb"])[..., :3]
# Normalize between 0. and 1. and change order to channel-first.
image = image.float() / 255.0
image = image.permute(2, 0, 1)
# Bounding Box
gt_bbox = gt["boundingBox2DTight"]["data"]
# Create mapping from categories to index
bboxes = torch.tensor(gt_bbox[["x_min", "y_min", "x_max", "y_max"]].tolist(), device="cuda")
id_to_labels = gt["boundingBox2DTight"]["info"]["idToLabels"]
prim_paths = gt["boundingBox2DTight"]["info"]["primPaths"]
# For each bounding box, map semantic label to label index
cat_to_id = {cat: i + 1 for i, cat in enumerate(self.categories)}
semantic_labels_mapping = {int(k): v.get("class", "") for k, v in id_to_labels.items()}
semantic_labels = [cat_to_id[semantic_labels_mapping[i]] for i in gt_bbox["semanticId"]]
labels = torch.tensor(semantic_labels, device="cuda")
# Calculate bounding box area for each area
areas = (bboxes[:, 2] - bboxes[:, 0]) * (bboxes[:, 3] - bboxes[:, 1])
# Identify invalid bounding boxes to filter final output
valid_areas = (areas > 0.0) * (areas < (image.shape[1] * image.shape[2]))
# Instance Segmentation
instance_data = self.wp.to_torch(gt["instanceSegmentation"]["data"].view(self.wp.int32)).squeeze()
path_to_instance_id = {v: int(k) for k, v in gt["instanceSegmentation"]["info"]["idToLabels"].items()}
instance_list = [im[0] for im in gt_bbox]
masks = torch.zeros((len(instance_list), *instance_data.shape), dtype=bool, device="cuda")
# Filter for the mask of each object
for i, prim_path in enumerate(prim_paths):
# Merge child instances of prim_path as one instance
for instance in path_to_instance_id:
if prim_path in instance:
masks[i] += torch.isin(instance_data, path_to_instance_id[instance])
target = {
"boxes": bboxes[valid_areas],
"labels": labels[valid_areas],
"masks": masks[valid_areas],
"image_id": torch.LongTensor([self.cur_idx]),
"area": areas[valid_areas],
"iscrowd": torch.BoolTensor([False] * len(bboxes[valid_areas])), # Assume no crowds
}
self.cur_idx += 1
return image, target
if __name__ == "__main__":
"Typical usage"
import argparse
import struct
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser("Dataset test")
parser.add_argument("--categories", type=str, nargs="+", required=True, help="List of object classes to use")
parser.add_argument(
"--max_asset_size",
type=float,
default=10.0,
help="Maximum asset size to use in MB. Larger assets will be skipped.",
)
parser.add_argument(
"--num_test_images", type=int, default=10, help="number of test images to generate when executing main"
)
parser.add_argument(
"--root",
type=str,
default=None,
help="Root directory containing USDs. If not specified, use {SHAPENET_LOCAL_DIR}_mat as root.",
)
args, unknown_args = parser.parse_known_args()
# If root is not specified use the environment variable SHAPENET_LOCAL_DIR with the _mat suffix as root
if args.root is None:
if "SHAPENET_LOCAL_DIR" in os.environ:
shapenet_local_dir = f"{os.path.abspath(os.environ['SHAPENET_LOCAL_DIR'])}_mat"
if os.path.exists(shapenet_local_dir):
args.root = shapenet_local_dir
if args.root is None:
print(
"root argument not specified and SHAPENET_LOCAL_DIR environment variable was not set or the path did not exist"
)
exit()
dataset = RandomObjects(args.root, args.categories, max_asset_size=args.max_asset_size)
from omni.replicator.core import random_colours
categories = [LABEL_TO_SYNSET.get(c, c) for c in args.categories]
# Iterate through dataset and visualize the output
plt.ion()
_, axes = plt.subplots(1, 2, figsize=(10, 5))
plt.tight_layout()
# Directory to save the example images to
out_dir = os.path.join(os.getcwd(), "_out_gen_imgs", "")
os.makedirs(out_dir, exist_ok=True)
image_num = 0
for image, target in dataset:
for ax in axes:
ax.clear()
ax.axis("off")
np_image = image.permute(1, 2, 0).cpu().numpy()
axes[0].imshow(np_image)
num_instances = len(target["boxes"])
# Create random colors for each instance as rgb float lists
colours = random_colours(num_instances, num_channels=3)
colours = colours.astype(float) / 255.0
colours = colours.tolist()
overlay = np.zeros_like(np_image)
for mask, colour in zip(target["masks"].cpu().numpy(), colours):
overlay[mask, :3] = colour
axes[1].imshow(overlay)
mapping = {i + 1: cat for i, cat in enumerate(categories)}
labels = [SYNSET_TO_LABEL[mapping[label.item()]] for label in target["labels"]]
for bb, label, colour in zip(target["boxes"].tolist(), labels, colours):
maxint = 2 ** (struct.Struct("i").size * 8 - 1) - 1
# if a bbox is not visible, do not draw
if bb[0] != maxint and bb[1] != maxint:
x = bb[0]
y = bb[1]
w = bb[2] - x
h = bb[3] - y
box = plt.Rectangle((x, y), w, h, fill=False, edgecolor=colour)
ax.add_patch(box)
ax.text(bb[0], bb[1], label, fontdict={"family": "sans-serif", "color": colour, "size": 10})
plt.draw()
plt.pause(0.01)
fig_name = os.path.join(out_dir, f"domain_randomization_test_image_{image_num}.png")
plt.savefig(fig_name)
image_num += 1
if dataset.exiting or (image_num >= args.num_test_images):
break
# cleanup
dataset.close()
| 17,377 | Python | 39.226852 | 127 | 0.61449 |
2820207922/isaac_ws/standalone_examples/replicator/online_generation/train_shapenet.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""Instance Segmentation Training Demonstration
Use a PyTorch dataloader together with OmniKit to generate scenes and groundtruth to
train a [Mask-RCNN](https://arxiv.org/abs/1703.06870) model.
"""
import os
import signal
import matplotlib.pyplot as plt
import numpy as np
from generate_shapenet import LABEL_TO_SYNSET, SYNSET_TO_LABEL, RandomObjects
def main(args):
device = "cuda"
train_set = RandomObjects(
args.root, args.categories, num_assets_min=3, num_assets_max=5, max_asset_size=args.max_asset_size
)
def handle_exit(self, *args, **kwargs):
print("exiting dataset generation...")
train_set.exiting = True
signal.signal(signal.SIGINT, handle_exit)
import struct
import torch
import torchvision
from omni.replicator.core import random_colours
from torch.utils.data import DataLoader
# Setup data
train_loader = DataLoader(train_set, batch_size=2, collate_fn=lambda x: tuple(zip(*x)))
# Setup Model
model = torchvision.models.detection.maskrcnn_resnet50_fpn(weights=None, num_classes=1 + len(args.categories))
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
if args.visualize:
plt.ion()
fig, axes = plt.subplots(1, 2, figsize=(14, 7))
# Directory to save the train images to
out_dir = os.path.join(os.getcwd(), "_out_train_imgs", "")
os.makedirs(out_dir, exist_ok=True)
for i, train_batch in enumerate(train_loader):
if i > args.max_iters or train_set.exiting:
print("Exiting ...")
train_set.close()
break
model.train()
images, targets = train_batch
images = [i.to(device) for i in images]
targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
loss_dict = model(images, targets)
loss = sum(loss for loss in loss_dict.values())
print(f"ITER {i} | {loss:.6f}")
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i % 10 == 0:
model.eval()
with torch.no_grad():
predictions = model(images[:1])
if args.visualize:
idx = 0
score_thresh = 0.5
mask_thresh = 0.5
pred = predictions[idx]
np_image = images[idx].permute(1, 2, 0).cpu().numpy()
for ax in axes:
fig.suptitle(f"Iteration {i:05}", fontsize=14)
ax.cla()
ax.axis("off")
ax.imshow(np_image)
axes[0].set_title("Input")
axes[1].set_title("Input + Predictions")
score_filter = [i for i in range(len(pred["scores"])) if pred["scores"][i] > score_thresh]
num_instances = len(score_filter)
# Create random colors for each instance as rgb float lists
colours = random_colours(num_instances, num_channels=3)
colours = colours.astype(float) / 255.0
colours = colours.tolist()
overlay = np.zeros_like(np_image)
for mask, colour in zip(pred["masks"], colours):
overlay[mask.squeeze().cpu().numpy() > mask_thresh, :3] = colour
axes[1].imshow(overlay, alpha=0.5)
# If ShapeNet categories are specified with their names, convert to synset ID
# Remove this if using with a different dataset than ShapeNet
args.categories = [LABEL_TO_SYNSET.get(c, c) for c in args.categories]
mapping = {i + 1: cat for i, cat in enumerate(args.categories)}
labels = [SYNSET_TO_LABEL[mapping[label.item()]] for label in pred["labels"]]
for bb, label, colour in zip(pred["boxes"].cpu().numpy(), labels, colours):
maxint = 2 ** (struct.Struct("i").size * 8 - 1) - 1
# if a bbox is not visible, do not draw
if bb[0] != maxint and bb[1] != maxint:
x = bb[0]
y = bb[1]
w = bb[2] - x
h = bb[3] - y
box = plt.Rectangle((x, y), w, h, fill=False, edgecolor=colour)
ax.add_patch(box)
ax.text(bb[0], bb[1], label, fontdict={"family": "sans-serif", "color": colour, "size": 10})
plt.draw()
fig_name = os.path.join(out_dir, f"train_image_{i}.png")
plt.savefig(fig_name)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser("Dataset test")
parser.add_argument(
"--root",
type=str,
default=None,
help="Root directory containing ShapeNet USDs. If not specified, use {SHAPENET_LOCAL_DIR}_nomat as root.",
)
parser.add_argument(
"--categories", type=str, nargs="+", required=True, help="List of ShapeNet categories to use (space seperated)."
)
parser.add_argument(
"--max_asset_size",
type=float,
default=10.0,
help="Maximum asset size to use in MB. Larger assets will be skipped.",
)
parser.add_argument("-lr", "--learning_rate", type=float, default=1e-4, help="Learning rate")
parser.add_argument("--max_iters", type=float, default=1000, help="Number of training iterations.")
parser.add_argument("--visualize", action="store_true", help="Visualize predicted masks during training.")
args, unknown_args = parser.parse_known_args()
# If root is not specified use the environment variable SHAPENET_LOCAL_DIR with the _nomat suffix as root
if args.root is None:
if "SHAPENET_LOCAL_DIR" in os.environ:
shapenet_local_dir = f"{os.path.abspath(os.environ['SHAPENET_LOCAL_DIR'])}_nomat"
if os.path.exists(shapenet_local_dir):
args.root = shapenet_local_dir
if args.root is None:
print(
"root argument not specified and SHAPENET_LOCAL_DIR environment variable was not set or the path did not exist"
)
exit()
main(args)
| 6,668 | Python | 37.549133 | 127 | 0.586083 |
2820207922/isaac_ws/standalone_examples/replicator/offline_generation/offline_generation_utils.py | # Copyright (c) 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 math
import random
import numpy as np
import omni
import omni.replicator.core as rep
from omni.isaac.core import World
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.utils import prims
from omni.isaac.core.utils.bounds import compute_combined_aabb, compute_obb, create_bbox_cache, get_obb_corners
from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles
from omni.isaac.core.utils.semantics import remove_all_semantics
from pxr import Gf
# Clear any previous semantic data in the stage
def remove_previous_semantics(stage, recursive: bool = False):
prims = stage.Traverse()
for prim in prims:
remove_all_semantics(prim, recursive)
# Run a simulation
def simulate_falling_objects(forklift_prim, assets_root_path, config, max_sim_steps=250, num_boxes=8):
# Create the isaac sim world to run any physics simulations
world = World(physics_dt=1.0 / 90.0, stage_units_in_meters=1.0)
# Set a random relative offset to the pallet using the forklift transform as a base frame
forklift_tf = omni.usd.get_world_transform_matrix(forklift_prim)
pallet_offset_tf = Gf.Matrix4d().SetTranslate(Gf.Vec3d(random.uniform(-1, 1), random.uniform(-4, -3.6), 0))
pallet_pos = (pallet_offset_tf * forklift_tf).ExtractTranslation()
# Spawn pallet prim at a relative random offset to the forklift
pallet_prim_name = "SimulatedPallet"
pallet_prim = prims.create_prim(
prim_path=f"/World/{pallet_prim_name}",
usd_path=assets_root_path + config["pallet"]["url"],
semantic_label=config["pallet"]["class"],
translation=pallet_pos,
orientation=euler_angles_to_quat([0, 0, random.uniform(0, math.pi)]),
)
# Wrap the pallet as a simulation ready rigid prim a
pallet_rigid_prim = RigidPrim(prim_path=str(pallet_prim.GetPrimPath()), name=pallet_prim_name)
# Enable physics and add to isaacsim world scene
pallet_rigid_prim.enable_rigid_body_physics()
world.scene.add(pallet_rigid_prim)
# Use the height of the pallet as a spawn base for the boxes
bb_cache = create_bbox_cache()
spawn_height = bb_cache.ComputeLocalBound(pallet_prim).GetRange().GetSize()[2] * 1.1
# Spawn boxes falling on the pallet
for i in range(num_boxes):
# Spawn box prim
cardbox_prim_name = f"SimulatedCardbox_{i}"
box_prim = prims.create_prim(
prim_path=f"/World/{cardbox_prim_name}",
usd_path=assets_root_path + config["cardbox"]["url"],
semantic_label=config["cardbox"]["class"],
)
# Get the next spawn height for the box
spawn_height += bb_cache.ComputeLocalBound(box_prim).GetRange().GetSize()[2] * 1.1
# Wrap the cardbox prim into a rigid prim to be able to simulate it
box_rigid_prim = RigidPrim(
prim_path=str(box_prim.GetPrimPath()),
name=cardbox_prim_name,
position=pallet_pos + Gf.Vec3d(random.uniform(-0.2, 0.2), random.uniform(-0.2, 0.2), spawn_height),
orientation=euler_angles_to_quat([0, 0, random.uniform(0, math.pi)]),
)
# Make sure physics are enabled on the rigid prim
box_rigid_prim.enable_rigid_body_physics()
# Register rigid prim with the scene
world.scene.add(box_rigid_prim)
# Reset the world to handle the physics of the newly created rigid prims
world.reset()
# Simulate the world for the given number of steps or until the highest box stops moving
last_box = world.scene.get_object(f"SimulatedCardbox_{num_boxes - 1}")
for i in range(max_sim_steps):
world.step(render=False)
if last_box and np.linalg.norm(last_box.get_linear_velocity()) < 0.001:
print(f"Falling objects simulation finished at step {i}..")
break
# Register the boxes and materials randomizer graph
def register_scatter_boxes(pallet_prim, assets_root_path, config):
# Calculate the bounds of the prim to create a scatter plane of its size
bb_cache = create_bbox_cache()
bbox3d_gf = bb_cache.ComputeLocalBound(pallet_prim)
prim_tf_gf = omni.usd.get_world_transform_matrix(pallet_prim)
# Calculate the bounds of the prim
bbox3d_gf.Transform(prim_tf_gf)
range_size = bbox3d_gf.GetRange().GetSize()
# Get the quaterion of the prim in xyzw format from usd
prim_quat_gf = prim_tf_gf.ExtractRotation().GetQuaternion()
prim_quat_xyzw = (prim_quat_gf.GetReal(), *prim_quat_gf.GetImaginary())
# Create a plane on the pallet to scatter the boxes on
plane_scale = (range_size[0] * 0.8, range_size[1] * 0.8, 1)
plane_pos_gf = prim_tf_gf.ExtractTranslation() + Gf.Vec3d(0, 0, range_size[2])
plane_rot_euler_deg = quat_to_euler_angles(np.array(prim_quat_xyzw), degrees=True)
scatter_plane = rep.create.plane(
scale=plane_scale, position=plane_pos_gf, rotation=plane_rot_euler_deg, visible=False
)
cardbox_mats = [
f"{assets_root_path}/Isaac/Environments/Simple_Warehouse/Materials/MI_PaperNotes_01.mdl",
f"{assets_root_path}/Isaac/Environments/Simple_Warehouse/Materials/MI_CardBoxB_05.mdl",
]
def scatter_boxes():
cardboxes = rep.create.from_usd(
assets_root_path + config["cardbox"]["url"], semantics=[("class", config["cardbox"]["class"])], count=5
)
with cardboxes:
rep.randomizer.scatter_2d(scatter_plane, check_for_collisions=True)
rep.randomizer.materials(cardbox_mats)
return cardboxes.node
rep.randomizer.register(scatter_boxes)
# Register the place cones randomizer graph
def register_cone_placement(forklift_prim, assets_root_path, config):
# Get the bottom corners of the oriented bounding box (OBB) of the forklift
bb_cache = create_bbox_cache()
centroid, axes, half_extent = compute_obb(bb_cache, forklift_prim.GetPrimPath())
larger_xy_extent = (half_extent[0] * 1.3, half_extent[1] * 1.3, half_extent[2])
obb_corners = get_obb_corners(centroid, axes, larger_xy_extent)
bottom_corners = [
obb_corners[0].tolist(),
obb_corners[2].tolist(),
obb_corners[4].tolist(),
obb_corners[6].tolist(),
]
# Orient the cone using the OBB (Oriented Bounding Box)
obb_quat = Gf.Matrix3d(axes).ExtractRotation().GetQuaternion()
obb_quat_xyzw = (obb_quat.GetReal(), *obb_quat.GetImaginary())
obb_euler = quat_to_euler_angles(np.array(obb_quat_xyzw), degrees=True)
def place_cones():
cones = rep.create.from_usd(
assets_root_path + config["cone"]["url"], semantics=[("class", config["cone"]["class"])]
)
with cones:
rep.modify.pose(position=rep.distribution.sequence(bottom_corners), rotation_z=obb_euler[2])
return cones.node
rep.randomizer.register(place_cones)
# Register light randomization graph
def register_lights_placement(forklift_prim, pallet_prim):
bb_cache = create_bbox_cache()
combined_range_arr = compute_combined_aabb(bb_cache, [forklift_prim.GetPrimPath(), pallet_prim.GetPrimPath()])
pos_min = (combined_range_arr[0], combined_range_arr[1], 6)
pos_max = (combined_range_arr[3], combined_range_arr[4], 7)
def randomize_lights():
lights = rep.create.light(
light_type="Sphere",
color=rep.distribution.uniform((0.2, 0.1, 0.1), (0.9, 0.8, 0.8)),
intensity=rep.distribution.uniform(500, 2000),
position=rep.distribution.uniform(pos_min, pos_max),
scale=rep.distribution.uniform(5, 10),
count=3,
)
return lights.node
rep.randomizer.register(randomize_lights)
| 8,124 | Python | 41.763158 | 115 | 0.679468 |
2820207922/isaac_ws/standalone_examples/replicator/offline_generation/offline_generation.py | # Copyright (c) 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.
"""Generate offline synthetic dataset
"""
import argparse
import json
import math
import os
import random
import carb
import yaml
from omni.isaac.kit import SimulationApp
# Default config (will be updated/extended by any other passed config arguments)
config = {
"launch_config": {
"renderer": "RayTracedLighting",
"headless": False,
},
"resolution": [1024, 1024],
"rt_subframes": 2,
"num_frames": 20,
"env_url": "/Isaac/Environments/Simple_Warehouse/full_warehouse.usd",
"scope_name": "/MyScope",
"writer": "BasicWriter",
"writer_config": {
"output_dir": "_out_offline_generation",
"rgb": True,
"bounding_box_2d_tight": True,
"semantic_segmentation": True,
"distance_to_image_plane": True,
"bounding_box_3d": True,
"occlusion": True,
},
"clear_previous_semantics": True,
"forklift": {
"url": "/Isaac/Props/Forklift/forklift.usd",
"class": "Forklift",
},
"cone": {
"url": "/Isaac/Environments/Simple_Warehouse/Props/S_TrafficCone.usd",
"class": "TrafficCone",
},
"pallet": {
"url": "/Isaac/Environments/Simple_Warehouse/Props/SM_PaletteA_01.usd",
"class": "Pallet",
},
"cardbox": {
"url": "/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxD_04.usd",
"class": "Cardbox",
},
}
# Check if there are any config files (yaml or json) are passed as arguments
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=False, help="Include specific config parameters (json or yaml))")
args, unknown = parser.parse_known_args()
args_config = {}
if args.config and os.path.isfile(args.config):
print("File exist")
with open(args.config, "r") as f:
if args.config.endswith(".json"):
args_config = json.load(f)
elif args.config.endswith(".yaml"):
args_config = yaml.safe_load(f)
else:
carb.log_warn(f"File {args.config} is not json or yaml, will use default config")
else:
print(f"File {args.config} does not exist, will use default config")
carb.log_warn(f"File {args.config} does not exist, will use default config")
# If there are specific writer parameters in the input config file make sure they are not mixed with the default ones
if "writer_config" in args_config:
config["writer_config"].clear()
# Update the default config dictionay with any new parameters or values from the config file
config.update(args_config)
# Create the simulation app with the given launch_config
simulation_app = SimulationApp(launch_config=config["launch_config"])
import offline_generation_utils
# Late import of runtime modules (the SimulationApp needs to be created before loading the modules)
import omni.replicator.core as rep
import omni.usd
from omni.isaac.core.utils import prims
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core.utils.stage import get_current_stage, open_stage
from pxr import Gf
# Get server path
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not get nucleus server path, closing application..")
simulation_app.close()
# Open the given environment in a new stage
print(f"Loading Stage {config['env_url']}")
if not open_stage(assets_root_path + config["env_url"]):
carb.log_error(f"Could not open stage{config['env_url']}, closing application..")
simulation_app.close()
# Disable capture on play and async rendering
carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False)
carb.settings.get_settings().set("/omni/replicator/asyncRendering", False)
carb.settings.get_settings().set("/app/asyncRendering", False)
if config["clear_previous_semantics"]:
stage = get_current_stage()
offline_generation_utils.remove_previous_semantics(stage)
# Spawn a new forklift at a random pose
forklift_prim = prims.create_prim(
prim_path="/World/Forklift",
position=(random.uniform(-20, -2), random.uniform(-1, 3), 0),
orientation=euler_angles_to_quat([0, 0, random.uniform(0, math.pi)]),
usd_path=assets_root_path + config["forklift"]["url"],
semantic_label=config["forklift"]["class"],
)
# Spawn the pallet in front of the forklift with a random offset on the Y (pallet's forward) axis
forklift_tf = omni.usd.get_world_transform_matrix(forklift_prim)
pallet_offset_tf = Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, random.uniform(-1.2, -1.8), 0))
pallet_pos_gf = (pallet_offset_tf * forklift_tf).ExtractTranslation()
forklift_quat_gf = forklift_tf.ExtractRotationQuat()
forklift_quat_xyzw = (forklift_quat_gf.GetReal(), *forklift_quat_gf.GetImaginary())
pallet_prim = prims.create_prim(
prim_path="/World/Pallet",
position=pallet_pos_gf,
orientation=forklift_quat_xyzw,
usd_path=assets_root_path + config["pallet"]["url"],
semantic_label=config["pallet"]["class"],
)
# Register randomizers graphs
offline_generation_utils.register_scatter_boxes(pallet_prim, assets_root_path, config)
offline_generation_utils.register_cone_placement(forklift_prim, assets_root_path, config)
offline_generation_utils.register_lights_placement(forklift_prim, pallet_prim)
# Spawn a camera in the driver's location looking at the pallet
foklift_pos_gf = forklift_tf.ExtractTranslation()
driver_cam_pos_gf = foklift_pos_gf + Gf.Vec3d(0.0, 0.0, 1.9)
driver_cam = rep.create.camera(
focus_distance=400.0, focal_length=24.0, clipping_range=(0.1, 10000000.0), name="DriverCam"
)
# Camera looking at the pallet
pallet_cam = rep.create.camera(name="PalletCam")
# Camera looking at the forklift from a top view with large min clipping to see the scene through the ceiling
top_view_cam = rep.create.camera(clipping_range=(6.0, 1000000.0), name="TopCam")
# Generate graph nodes to be triggered every frame
with rep.trigger.on_frame():
rep.randomizer.scatter_boxes()
rep.randomizer.place_cones()
rep.randomizer.randomize_lights()
pallet_cam_min = (pallet_pos_gf[0] - 2, pallet_pos_gf[1] - 2, 2)
pallet_cam_max = (pallet_pos_gf[0] + 2, pallet_pos_gf[1] + 2, 4)
with pallet_cam:
rep.modify.pose(
position=rep.distribution.uniform(pallet_cam_min, pallet_cam_max),
look_at=str(pallet_prim.GetPrimPath()),
)
driver_cam_min = (driver_cam_pos_gf[0], driver_cam_pos_gf[1], driver_cam_pos_gf[2] - 0.25)
driver_cam_max = (driver_cam_pos_gf[0], driver_cam_pos_gf[1], driver_cam_pos_gf[2] + 0.25)
with driver_cam:
rep.modify.pose(
position=rep.distribution.uniform(driver_cam_min, driver_cam_max),
look_at=str(pallet_prim.GetPrimPath()),
)
# Generate graph nodes to be triggered only at the given interval
with rep.trigger.on_frame(interval=4):
top_view_cam_min = (foklift_pos_gf[0], foklift_pos_gf[1], 9)
top_view_cam_max = (foklift_pos_gf[0], foklift_pos_gf[1], 11)
with top_view_cam:
rep.modify.pose(
position=rep.distribution.uniform(top_view_cam_min, top_view_cam_max),
rotation=rep.distribution.uniform((0, -90, -30), (0, -90, 30)),
)
# If output directory is relative, set it relative to the current working directory
if config["writer_config"]["output_dir"] and not os.path.isabs(config["writer_config"]["output_dir"]):
config["writer_config"]["output_dir"] = os.path.join(os.getcwd(), config["writer_config"]["output_dir"])
print(f"Output directory={config['writer_config']['output_dir']}")
# Setup the writer
writer = rep.WriterRegistry.get(config["writer"])
writer.initialize(**config["writer_config"])
forklift_rp = rep.create.render_product(top_view_cam, config["resolution"], name="TopView")
driver_rp = rep.create.render_product(driver_cam, config["resolution"], name="DriverView")
pallet_rp = rep.create.render_product(pallet_cam, config["resolution"], name="PalletView")
writer.attach([forklift_rp, driver_rp, pallet_rp])
# Run a simulation before generating data
offline_generation_utils.simulate_falling_objects(forklift_prim, assets_root_path, config)
# Increase subframes if materials are not loaded on time or ghosting rendering artifacts appear on quickly moving objects,
# see: https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/subframes_examples.html
if config["rt_subframes"] > 1:
rep.settings.carb_settings("/omni/replicator/RTSubframes", config["rt_subframes"])
else:
carb.log_warn("RTSubframes is set to 1, consider increasing it if materials are not loaded on time")
# Run the SDG
rep.orchestrator.run_until_complete(num_frames=config["num_frames"])
simulation_app.close()
| 9,138 | Python | 39.799107 | 122 | 0.706281 |
2820207922/isaac_ws/standalone_examples/replicator/offline_generation/config/config_kitti_writer.yaml | launch_config:
renderer: RayTracedLighting
headless: true
resolution: [512, 512]
num_frames: 5
clear_previous_semantics: false
writer: KittiWriter
writer_config:
output_dir: _out_kitti
colorize_instance_segmentation: true | 229 | YAML | 21.999998 | 38 | 0.786026 |
2820207922/isaac_ws/standalone_examples/replicator/offline_generation/config/config_basic_writer.yaml | launch_config:
renderer: RayTracedLighting
headless: false
resolution: [512, 512]
env_url: "/Isaac/Environments/Grid/default_environment.usd"
rt_subframes: 32
writer: BasicWriter
writer_config:
output_dir: _out_basicwriter
rgb: true | 240 | YAML | 23.099998 | 59 | 0.775 |
2820207922/isaac_ws/standalone_examples/replicator/augmentation/annotator_augmentation.py | # Copyright (c) 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.
"""Generate augmented synthetic data from annotators
"""
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp(launch_config={"headless": False})
import argparse
import os
import time
import carb.settings
import numpy as np
import omni.replicator.core as rep
import warp as wp
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import open_stage
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument("--num_frames", type=int, default=25, help="The number of frames to capture")
parser.add_argument("--use_warp", action="store_true", help="Use warp augmentations instead of numpy")
args, unknown = parser.parse_known_args()
NUM_FRAMES = args.num_frames
USE_WARP = args.use_warp
ENV_URL = "/Isaac/Environments/Grid/default_environment.usd"
# Enable scripts
carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True)
# Illustrative augmentation switching red and blue channels in rgb data using numpy (CPU) and warp (GPU)
def rgb_to_bgr_np(data_in):
data_in[:, :, [0, 2]] = data_in[:, :, [2, 0]]
return data_in
@wp.kernel
def rgb_to_bgr_wp(data_in: wp.array3d(dtype=wp.uint8), data_out: wp.array3d(dtype=wp.uint8)):
i, j = wp.tid()
data_out[i, j, 0] = data_in[i, j, 2]
data_out[i, j, 1] = data_in[i, j, 1]
data_out[i, j, 2] = data_in[i, j, 0]
data_out[i, j, 3] = data_in[i, j, 3]
# Gaussian noise augmentation on depth data in numpy (CPU) and warp (GPU)
def gaussian_noise_depth_np(data_in, sigma: float, seed: int):
np.random.seed(seed)
return data_in + np.random.randn(*data_in.shape) * sigma
rep.AnnotatorRegistry.register_augmentation(
"gn_depth_np", rep.annotators.Augmentation.from_function(gaussian_noise_depth_np, sigma=0.1, seed=None)
)
@wp.kernel
def gaussian_noise_depth_wp(
data_in: wp.array2d(dtype=wp.float32), data_out: wp.array2d(dtype=wp.float32), sigma: float, seed: int
):
i, j = wp.tid()
state = wp.rand_init(seed, wp.tid())
data_out[i, j] = data_in[i, j] + sigma * wp.randn(state)
rep.AnnotatorRegistry.register_augmentation(
"gn_depth_wp", rep.annotators.Augmentation.from_function(gaussian_noise_depth_wp, sigma=0.1, seed=None)
)
# Helper functions for writing images from annotator data
def write_rgb(data, path):
rgb_img = Image.fromarray(data, mode="RGBA")
rgb_img.save(path + ".png")
def write_depth(data, path):
# Convert to numpy (if warp), normalize, handle any nan values, and convert to from float32 to 8-bit int array
if isinstance(data, wp.array):
data = data.numpy()
# Replace any -inf and inf values with nan, then calculate the mean value and replace nan with the mean
data[np.isinf(data)] = np.nan
data = np.nan_to_num(data, nan=np.nanmean(data), copy=False)
normalized_array = (data - np.min(data)) / (np.max(data) - np.min(data))
integer_array = (normalized_array * 255).astype(np.uint8)
depth_img = Image.fromarray(integer_array, mode="L")
depth_img.save(path + ".png")
# Setup the environment
assets_root_path = get_assets_root_path()
open_stage(assets_root_path + ENV_URL)
# Disable capture on play and async rendering
carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False)
carb.settings.get_settings().set("/omni/replicator/asyncRendering", False)
carb.settings.get_settings().set("/app/asyncRendering", False)
# Create a red cube and a render product from a camera looking at the cube from the top
red_mat = rep.create.material_omnipbr(diffuse=(1, 0, 0))
red_cube = rep.create.cube(position=(0, 0, 0.71), material=red_mat)
cam = rep.create.camera(position=(0, 0, 5), look_at=(0, 0, 0))
rp = rep.create.render_product(cam, (512, 512))
# Update the app a couple of times to fully load texture/materials
for _ in range(5):
simulation_app.update()
# Get the local augmentations, either from function or from the registry
rgb_to_bgr_augm = None
gn_depth_augm = None
if USE_WARP:
rgb_to_bgr_augm = rep.annotators.Augmentation.from_function(rgb_to_bgr_wp)
gn_depth_augm = rep.AnnotatorRegistry.get_augmentation("gn_depth_wp")
else:
rgb_to_bgr_augm = rep.annotators.Augmentation.from_function(rgb_to_bgr_np)
gn_depth_augm = rep.AnnotatorRegistry.get_augmentation("gn_depth_np")
# Output directories
out_dir = os.path.join(os.getcwd(), "_out_augm_annot")
print(f"Writing data to: {out_dir}")
os.makedirs(out_dir, exist_ok=True)
# Register the annotator together with its augmentation
rep.annotators.register(
name="rgb_to_bgr_augm",
annotator=rep.annotators.augment(
source_annotator=rep.AnnotatorRegistry.get_annotator("rgb"),
augmentation=rgb_to_bgr_augm,
),
)
rgb_to_bgr_annot = rep.AnnotatorRegistry.get_annotator("rgb_to_bgr_augm")
depth_annot_1 = rep.AnnotatorRegistry.get_annotator("distance_to_camera")
depth_annot_1.augment(gn_depth_augm)
depth_annot_2 = rep.AnnotatorRegistry.get_annotator("distance_to_camera")
depth_annot_2.augment(gn_depth_augm, sigma=0.5)
rgb_to_bgr_annot.attach(rp)
depth_annot_1.attach(rp)
depth_annot_2.attach(rp)
# Generate a replicator graph to rotate the cube every capture frame
with rep.trigger.on_frame():
with red_cube:
rep.randomizer.rotation()
# Evaluate the graph
rep.orchestrator.preview()
# Measure the duration of capturing the data
start_time = time.time()
# The `step()` function will trigger the randomization graph, feed annotators with new data, and trigger the writers
for i in range(NUM_FRAMES):
rep.orchestrator.step()
rgb_data = rgb_to_bgr_annot.get_data()
depth_data_1 = depth_annot_1.get_data()
depth_data_2 = depth_annot_2.get_data()
write_rgb(rgb_data, os.path.join(out_dir, f"annot_rgb_{i}"))
write_depth(depth_data_1, os.path.join(out_dir, f"annot_depth_1_{i}"))
write_depth(depth_data_2, os.path.join(out_dir, f"annot_depth_2_{i}"))
print(
f"The duration for capturing {NUM_FRAMES} frames using '{'warp' if USE_WARP else 'numpy'}' was: {time.time() - start_time:.4f} seconds, with an average of {(time.time() - start_time) / NUM_FRAMES:.4f} seconds per frame."
)
simulation_app.close()
| 6,579 | Python | 35.759776 | 224 | 0.716978 |
2820207922/isaac_ws/standalone_examples/replicator/augmentation/writer_augmentation.py | # Copyright (c) 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.
"""Generate augmented synthetic from a writer
"""
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp(launch_config={"headless": False})
import argparse
import os
import time
import carb.settings
import numpy as np
import omni.replicator.core as rep
import warp as wp
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import open_stage
parser = argparse.ArgumentParser()
parser.add_argument("--num_frames", type=int, default=25, help="The number of frames to capture")
parser.add_argument("--use_warp", action="store_true", help="Use warp augmentations instead of numpy")
args, unknown = parser.parse_known_args()
NUM_FRAMES = args.num_frames
USE_WARP = args.use_warp
ENV_URL = "/Isaac/Environments/Grid/default_environment.usd"
# Enable scripts
carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True)
# Gaussian noise augmentation on rgba data in numpy (CPU) and warp (GPU)
def gaussian_noise_rgb_np(data_in, sigma: float, seed: int):
np.random.seed(seed)
data_in[:, :, 0] = data_in[:, :, 0] + np.random.randn(*data_in.shape[:-1]) * sigma
data_in[:, :, 1] = data_in[:, :, 1] + np.random.randn(*data_in.shape[:-1]) * sigma
data_in[:, :, 2] = data_in[:, :, 2] + np.random.randn(*data_in.shape[:-1]) * sigma
return data_in
@wp.kernel
def gaussian_noise_rgb_wp(
data_in: wp.array3d(dtype=wp.uint8), data_out: wp.array3d(dtype=wp.uint8), sigma: float, seed: int
):
i, j = wp.tid()
state = wp.rand_init(seed, wp.tid())
data_out[i, j, 0] = wp.uint8(wp.int32(data_in[i, j, 0]) + wp.int32(sigma * wp.randn(state)))
data_out[i, j, 1] = wp.uint8(wp.int32(data_in[i, j, 1]) + wp.int32(sigma * wp.randn(state)))
data_out[i, j, 2] = wp.uint8(wp.int32(data_in[i, j, 2]) + wp.int32(sigma * wp.randn(state)))
data_out[i, j, 3] = data_in[i, j, 3]
# Gaussian noise augmentation on depth data in numpy (CPU) and warp (GPU)
def gaussian_noise_depth_np(data_in, sigma: float, seed: int):
np.random.seed(seed)
return data_in + np.random.randn(*data_in.shape) * sigma
rep.AnnotatorRegistry.register_augmentation(
"gn_depth_np", rep.annotators.Augmentation.from_function(gaussian_noise_depth_np, sigma=0.1, seed=None)
)
@wp.kernel
def gaussian_noise_depth_wp(
data_in: wp.array2d(dtype=wp.float32), data_out: wp.array2d(dtype=wp.float32), sigma: float, seed: int
):
i, j = wp.tid()
state = wp.rand_init(seed, wp.tid())
data_out[i, j] = data_in[i, j] + sigma * wp.randn(state)
rep.AnnotatorRegistry.register_augmentation(
"gn_depth_wp", rep.annotators.Augmentation.from_function(gaussian_noise_depth_wp, sigma=0.1, seed=None)
)
# Setup the environment
assets_root_path = get_assets_root_path()
open_stage(assets_root_path + ENV_URL)
# Disable capture on play and async rendering
carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False)
carb.settings.get_settings().set("/omni/replicator/asyncRendering", False)
carb.settings.get_settings().set("/app/asyncRendering", False)
# Create a red cube and a render product from a camera looking at the cube from the top
red_mat = rep.create.material_omnipbr(diffuse=(1, 0, 0))
red_cube = rep.create.cube(position=(0, 0, 0.71), material=red_mat)
cam = rep.create.camera(position=(0, 0, 5), look_at=(0, 0, 0))
rp = rep.create.render_product(cam, (512, 512))
# Update the app a couple of times to fully load texture/materials
for _ in range(5):
simulation_app.update()
# Access default annotators from replicator
rgb_to_hsv_augm = rep.annotators.Augmentation.from_function(rep.augmentations_default.aug_rgb_to_hsv)
hsv_to_rgb_augm = rep.annotators.Augmentation.from_function(rep.augmentations_default.aug_hsv_to_rgb)
# Access the custom annotators as functions or from the registry
gn_rgb_augm = None
gn_depth_augm = None
if USE_WARP:
gn_rgb_augm = rep.annotators.Augmentation.from_function(gaussian_noise_rgb_wp, sigma=6.0, seed=None)
gn_depth_augm = rep.AnnotatorRegistry.get_augmentation("gn_depth_wp")
else:
gn_rgb_augm = rep.annotators.Augmentation.from_function(gaussian_noise_rgb_np, sigma=6.0, seed=None)
gn_depth_augm = rep.AnnotatorRegistry.get_augmentation("gn_depth_np")
# Create a writer and apply the augmentations to its corresponding annotators
out_dir = os.path.join(os.getcwd(), "_out_augm_writer")
print(f"Writing data to: {out_dir}")
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir=out_dir, rgb=True, distance_to_camera=True)
augmented_rgb_annot = rep.annotators.get("rgb").augment_compose(
[rgb_to_hsv_augm, gn_rgb_augm, hsv_to_rgb_augm], name="rgb"
)
writer.add_annotator(augmented_rgb_annot)
writer.augment_annotator("distance_to_camera", gn_depth_augm)
# Attach render product to writer
writer.attach([rp])
# Generate a replicator graph randomizing the cube's rotation every frame
with rep.trigger.on_frame():
with red_cube:
rep.randomizer.rotation()
# Evaluate the graph
rep.orchestrator.preview()
# Measure the duration of capturing the data
start_time = time.time()
# The `step()` function will trigger the randomization graph, feed annotators with new data, and trigger the writers
for i in range(NUM_FRAMES):
rep.orchestrator.step()
print(
f"The duration for capturing {NUM_FRAMES} frames using '{'warp' if USE_WARP else 'numpy'}' was: {time.time() - start_time:.4f} seconds, with an average of {(time.time() - start_time) / NUM_FRAMES:.4f} seconds per frame."
)
simulation_app.close()
| 5,949 | Python | 38.144737 | 224 | 0.722642 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/offline_pose_generation.py | # Copyright (c) 2021-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.
#
"""Generate a [YCBVideo, DOPE] synthetic datasets
"""
import argparse
import os
import signal
import carb
import numpy as np
import torch
import yaml
from omni.isaac.kit import SimulationApp
parser = argparse.ArgumentParser("Pose Generation data generator")
parser.add_argument("--num_mesh", type=int, default=30, help="Number of frames to record similar to MESH dataset")
parser.add_argument("--num_dome", type=int, default=30, help="Number of frames to record similar to DOME dataset")
parser.add_argument(
"--dome_interval",
type=int,
default=1,
help="Number of frames to capture before switching DOME background. When generating large datasets, increasing this interval will reduce time taken. A good value to set is 10.",
)
parser.add_argument("--output_folder", "-o", type=str, default="output", help="Output directory.")
parser.add_argument("--use_s3", action="store_true", help="Saves output to s3 bucket. Only supported by DOPE writer.")
parser.add_argument(
"--bucket",
type=str,
default=None,
help="Bucket name to store output in. See naming rules: https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html",
)
parser.add_argument("--s3_region", type=str, default="us-east-1", help="s3 region.")
parser.add_argument("--endpoint", type=str, default=None, help="s3 endpoint to write to.")
parser.add_argument(
"--writer",
type=str,
default="YCBVideo",
help="Which writer to use to output data. Choose between: [YCBVideo, DOPE]",
)
parser.add_argument(
"--test",
action="store_true",
help="Generates data for testing. Hardcodes the pose of the object to compare output data with expected data to ensure that generation is correct.",
)
args, unknown_args = parser.parse_known_args()
# Do not write to s3 if in test mode
if args.test:
args.use_s3 = False
if args.use_s3 and (args.endpoint is None or args.bucket is None):
raise Exception("To use s3, --endpoint and --bucket must be specified.")
CONFIG_FILES = {"dope": "config/dope_config.yaml", "ycbvideo": "config/ycb_config.yaml"}
TEST_CONFIG_FILES = {"dope": "tests/dope/test_dope_config.yaml", "ycbvideo": "tests/ycbvideo/test_ycb_config.yaml"}
# Path to config file:
cf_map = TEST_CONFIG_FILES if args.test else CONFIG_FILES
CONFIG_FILE = cf_map[args.writer.lower()]
CONFIG_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), CONFIG_FILE)
with open(CONFIG_FILE_PATH) as f:
config_data = yaml.full_load(f)
OBJECTS_TO_GENERATE = config_data["OBJECTS_TO_GENERATE"]
kit = SimulationApp(launch_config=config_data["CONFIG"])
import math
import omni.replicator.core as rep
from omni.isaac.core import World
from omni.isaac.core.prims.xform_prim import XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.core.utils.semantics import add_update_semantics
from omni.replicator.isaac.scripts.writers import DOPEWriter, YCBVideoWriter
# Since the simulation is mostly collision checking, a larger physics dt can be used to speed up the object movements
world = World(physics_dt=1.0 / 30.0)
world.reset()
from flying_distractors.collision_box import CollisionBox
from flying_distractors.dynamic_object import DynamicObject
from flying_distractors.dynamic_object_set import DynamicObjectSet
from flying_distractors.dynamic_shape_set import DynamicShapeSet
from flying_distractors.flying_distractors import FlyingDistractors
from omni.isaac.core.utils.random import get_random_world_pose_in_view
from omni.isaac.core.utils.transformations import get_world_pose_from_relative
from tests.test_utils import clean_output_dir, run_pose_generation_test
class RandomScenario(torch.utils.data.IterableDataset):
def __init__(
self,
num_mesh,
num_dome,
dome_interval,
output_folder,
use_s3=False,
endpoint="",
s3_region="us-east-1",
writer="ycbvideo",
bucket="",
test=False,
):
self.test = test
if writer == "ycbvideo":
self.writer_helper = YCBVideoWriter
elif writer == "dope":
self.writer_helper = DOPEWriter
else:
raise Exception("Invalid writer specified. Choose between [DOPE, YCBVideo].")
self.result = True
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self.result = False
return
self.dome_texture_path = assets_root_path + "/NVIDIA/Assets/Skies/"
self.ycb_asset_path = assets_root_path + "/Isaac/Props/YCB/Axis_Aligned/"
self.asset_path = assets_root_path + "/Isaac/Props/YCB/Axis_Aligned/"
self.train_parts = []
self.train_part_mesh_path_to_prim_path_map = {}
self.mesh_distractors = FlyingDistractors()
self.dome_distractors = FlyingDistractors()
self.current_distractors = None
self.data_writer = None
self.num_mesh = max(0, num_mesh) if not self.test else 5
self.num_dome = max(0, num_dome) if not self.test else 0
self.train_size = self.num_mesh + self.num_dome
self.dome_interval = dome_interval
self._output_folder = output_folder if use_s3 else os.path.join(os.getcwd(), output_folder)
self.use_s3 = use_s3
self.endpoint = endpoint
self.s3_region = s3_region
self.bucket = bucket
self.writer_config = {
"output_folder": self._output_folder,
"use_s3": self.use_s3,
"bucket_name": self.bucket,
"endpoint_url": self.endpoint,
"s3_region": self.s3_region,
"train_size": self.train_size,
}
self._setup_world()
self.cur_idx = 0
self.exiting = False
self.last_frame_reached = False
# Clean up output folder ahead of test
if not self.use_s3 and self.test:
clean_output_dir(self._output_folder)
# Disable capture on play and async rendering
self._carb_settings = carb.settings.get_settings()
self._carb_settings.set("/omni/replicator/captureOnPlay", False)
self._carb_settings.set("/app/asyncRendering", False)
self._carb_settings.set("/omni/replicator/asyncRendering", False)
signal.signal(signal.SIGINT, self._handle_exit)
def _handle_exit(self, *args, **kwargs):
print("Exiting dataset generation..")
self.exiting = True
def _setup_world(self):
"""Populate scene with assets and prepare for synthetic data generation."""
self._setup_camera()
rep.settings.set_render_rtx_realtime()
# Allow flying distractors to float
world.get_physics_context().set_gravity(0.0)
collision_box = self._setup_collision_box()
world.scene.add(collision_box)
self._setup_distractors(collision_box)
self._setup_train_objects()
if not self.test:
self._setup_randomizers()
# Update the app a few times to make sure the materials are fully loaded and world scene objects are registered
for _ in range(5):
kit.app.update()
# Setup writer
self.writer_helper.register_pose_annotator(config_data=config_data)
self.writer = self.writer_helper.setup_writer(config_data=config_data, writer_config=self.writer_config)
self.writer.attach([self.render_product])
self.dome_distractors.set_visible(False)
# Generate the replicator graphs without triggering any writing
rep.orchestrator.preview()
def _setup_camera(self):
focal_length = config_data["HORIZONTAL_APERTURE"] * config_data["F_X"] / config_data["WIDTH"]
# Setup camera and render product
self.camera = rep.create.camera(
position=(0, 0, 0),
rotation=np.array(config_data["CAMERA_RIG_ROTATION"]),
focal_length=focal_length,
clipping_range=(0.01, 10000),
)
self.render_product = rep.create.render_product(self.camera, (config_data["WIDTH"], config_data["HEIGHT"]))
camera_rig_path = str(rep.utils.get_node_targets(self.camera.node, "inputs:primsIn")[0])
self.camera_path = camera_rig_path + "/Camera"
with rep.get.prims(prim_types=["Camera"]):
rep.modify.pose(
rotation=rep.distribution.uniform(
np.array(config_data["CAMERA_ROTATION"]), np.array(config_data["CAMERA_ROTATION"])
)
)
self.rig = XFormPrim(prim_path=camera_rig_path)
def _setup_collision_box(self):
# Create a collision box in view of the camera, allowing distractors placed in the box to be within
# [MIN_DISTANCE, MAX_DISTANCE] of the camera. The collision box will be placed in front of the camera,
# regardless of CAMERA_ROTATION or CAMERA_RIG_ROTATION.
self.fov_x = 2 * math.atan(config_data["WIDTH"] / (2 * config_data["F_X"]))
self.fov_y = 2 * math.atan(config_data["HEIGHT"] / (2 * config_data["F_Y"]))
theta_x = self.fov_x / 2.0
theta_y = self.fov_y / 2.0
# Collision box dimensions lower than 1.3 do not work properly
collision_box_width = max(2 * config_data["MAX_DISTANCE"] * math.tan(theta_x), 1.3)
collision_box_height = max(2 * config_data["MAX_DISTANCE"] * math.tan(theta_y), 1.3)
collision_box_depth = config_data["MAX_DISTANCE"] - config_data["MIN_DISTANCE"]
collision_box_path = "/World/collision_box"
collision_box_name = "collision_box"
# Collision box is centered between MIN_DISTANCE and MAX_DISTANCE, with translation relative to camera in the z
# direction being negative due to cameras in Isaac Sim having coordinates of -z out, +y up, and +x right.
collision_box_translation_from_camera = np.array(
[0, 0, (config_data["MIN_DISTANCE"] + config_data["MAX_DISTANCE"]) / 2.0]
)
# Collision box has no rotation with respect to the camera.
collision_box_rotation_from_camera = np.array([0, 0, 0])
collision_box_orientation_from_camera = euler_angles_to_quat(collision_box_rotation_from_camera, degrees=True)
# Get the desired pose of the collision box from a pose defined locally with respect to the camera.
camera_prim = world.stage.GetPrimAtPath(self.camera_path)
collision_box_center, collision_box_orientation = get_world_pose_from_relative(
camera_prim, collision_box_translation_from_camera, collision_box_orientation_from_camera
)
return CollisionBox(
collision_box_path,
collision_box_name,
position=collision_box_center,
orientation=collision_box_orientation,
width=collision_box_width,
height=collision_box_height,
depth=collision_box_depth,
)
def _setup_distractors(self, collision_box):
# List of distractor objects should not contain objects that are being used for training
train_objects = [object["part_name"] for object in OBJECTS_TO_GENERATE]
distractor_mesh_filenames = [
file_name for file_name in config_data["MESH_FILENAMES"] if file_name not in train_objects
]
usd_path_list = [
f"{self.ycb_asset_path}{usd_filename_prefix}.usd" for usd_filename_prefix in distractor_mesh_filenames
]
mesh_list = [f"_{usd_filename_prefix[1:]}" for usd_filename_prefix in distractor_mesh_filenames]
if self.num_mesh > 0:
# Distractors for the MESH dataset
mesh_shape_set = DynamicShapeSet(
"/World/mesh_shape_set",
"mesh_shape_set",
"mesh_shape",
"mesh_shape",
config_data["NUM_MESH_SHAPES"],
collision_box,
scale=np.array(config_data["SHAPE_SCALE"]),
mass=config_data["SHAPE_MASS"],
fraction_glass=config_data["MESH_FRACTION_GLASS"],
)
self.mesh_distractors.add(mesh_shape_set)
mesh_object_set = DynamicObjectSet(
"/World/mesh_object_set",
"mesh_object_set",
usd_path_list,
mesh_list,
"mesh_object",
"mesh_object",
config_data["NUM_MESH_OBJECTS"],
collision_box,
scale=np.array(config_data["OBJECT_SCALE"]),
mass=config_data["OBJECT_MASS"],
fraction_glass=config_data["MESH_FRACTION_GLASS"],
)
self.mesh_distractors.add(mesh_object_set)
# Set the current distractors to the mesh dataset type
self.current_distractors = self.mesh_distractors
if self.num_dome > 0:
# Distractors for the DOME dataset
dome_shape_set = DynamicShapeSet(
"/World/dome_shape_set",
"dome_shape_set",
"dome_shape",
"dome_shape",
config_data["NUM_DOME_SHAPES"],
collision_box,
scale=np.array(config_data["SHAPE_SCALE"]),
mass=config_data["SHAPE_MASS"],
fraction_glass=config_data["DOME_FRACTION_GLASS"],
)
self.dome_distractors.add(dome_shape_set)
dome_object_set = DynamicObjectSet(
"/World/dome_object_set",
"dome_object_set",
usd_path_list,
mesh_list,
"dome_object",
"dome_object",
config_data["NUM_DOME_OBJECTS"],
collision_box,
scale=np.array(config_data["OBJECT_SCALE"]),
mass=config_data["OBJECT_MASS"],
fraction_glass=config_data["DOME_FRACTION_GLASS"],
)
self.dome_distractors.add(dome_object_set)
def _setup_train_objects(self):
# Add the part to train the network on
train_part_idx = 0
for object in OBJECTS_TO_GENERATE:
for prim_idx in range(object["num"]):
part_name = object["part_name"]
ref_path = self.asset_path + part_name + ".usd"
prim_type = object["prim_type"]
if self.writer_helper == YCBVideoWriter and prim_type not in config_data["CLASS_NAME_TO_INDEX"]:
raise Exception(f"Train object {prim_type} is not in CLASS_NAME_TO_INDEX in config.yaml.")
path = "/World/" + prim_type + f"_{prim_idx}"
mesh_path = path + "/" + prim_type
name = f"train_part_{train_part_idx}"
self.train_part_mesh_path_to_prim_path_map[mesh_path] = path
train_part = DynamicObject(
usd_path=ref_path,
prim_path=path,
mesh_path=mesh_path,
name=name,
position=np.array([0.0, 0.0, 0.0]),
scale=config_data["OBJECT_SCALE"],
mass=1.0,
)
train_part.prim.GetAttribute("physics:rigidBodyEnabled").Set(True)
self.train_parts.append(train_part)
# Add semantic information
mesh_prim = world.stage.GetPrimAtPath(mesh_path)
add_update_semantics(mesh_prim, prim_type)
train_part_idx += 1
if prim_idx == 0 and self.writer_helper == YCBVideoWriter:
# Save the vertices of the part in '.xyz' format. This will be used in one of PoseCNN's loss functions
coord_prim = world.stage.GetPrimAtPath(path)
self.writer_helper.save_mesh_vertices(mesh_prim, coord_prim, prim_type, self._output_folder)
def _setup_randomizers(self):
"""Add domain randomization with Replicator Randomizers"""
# Create and randomize sphere lights
def randomize_sphere_lights():
lights = rep.create.light(
light_type="Sphere",
color=rep.distribution.uniform((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
intensity=rep.distribution.uniform(100000, 3000000),
position=rep.distribution.uniform((-250, -250, -250), (250, 250, 100)),
scale=rep.distribution.uniform(1, 20),
count=config_data["NUM_LIGHTS"],
)
return lights.node
# Randomize prim colors
def randomize_colors(prim_path_regex):
prims = rep.get.prims(path_pattern=prim_path_regex)
mats = rep.create.material_omnipbr(
metallic=rep.distribution.uniform(0.0, 1.0),
roughness=rep.distribution.uniform(0.0, 1.0),
diffuse=rep.distribution.uniform((0, 0, 0), (1, 1, 1)),
count=100,
)
with prims:
rep.randomizer.materials(mats)
return prims.node
rep.randomizer.register(randomize_sphere_lights, override=True)
rep.randomizer.register(randomize_colors, override=True)
with rep.trigger.on_frame():
rep.randomizer.randomize_sphere_lights()
rep.randomizer.randomize_colors("(?=.*shape)(?=.*nonglass).*")
def _setup_dome_randomizers(self):
"""Add domain randomization with Replicator Randomizers"""
# Create and randomize a dome light for the DOME dataset
def randomize_domelight(texture_paths):
lights = rep.create.light(
light_type="Dome",
rotation=rep.distribution.uniform((0, 0, 0), (360, 360, 360)),
texture=rep.distribution.choice(texture_paths),
)
return lights.node
rep.randomizer.register(randomize_domelight, override=True)
dome_texture_paths = [
self.dome_texture_path + dome_texture + ".hdr" for dome_texture in config_data["DOME_TEXTURES"]
]
with rep.trigger.on_frame(interval=self.dome_interval):
rep.randomizer.randomize_domelight(dome_texture_paths)
def randomize_movement_in_view(self, prim):
"""Randomly move and rotate prim such that it stays in view of camera.
Args:
prim (DynamicObject): prim to randomly move and rotate.
"""
if not self.test:
camera_prim = world.stage.GetPrimAtPath(self.camera_path)
rig_prim = world.stage.GetPrimAtPath(self.rig.prim_path)
translation, orientation = get_random_world_pose_in_view(
camera_prim,
config_data["MIN_DISTANCE"],
config_data["MAX_DISTANCE"],
self.fov_x,
self.fov_y,
config_data["FRACTION_TO_SCREEN_EDGE"],
rig_prim,
np.array(config_data["MIN_ROTATION_RANGE"]),
np.array(config_data["MAX_ROTATION_RANGE"]),
)
else:
translation, orientation = np.array([0.0, 0.0, 1.0]), np.array([0.0, 0.0, 0.0, 1.0])
prim.set_world_pose(translation, orientation)
def __iter__(self):
return self
def __next__(self):
# First frame of DOME dataset
if self.cur_idx == self.num_mesh: # MESH datset generation complete, switch to DOME dataset
print(f"Starting DOME dataset generation of {self.num_dome} frames..")
# Hide the FlyingDistractors used for the MESH dataset
self.mesh_distractors.set_visible(False)
# Show the FlyingDistractors used for the DOME dataset
self.dome_distractors.set_visible(True)
# Switch the distractors to DOME
self.current_distractors = self.dome_distractors
# Randomize the dome backgrounds
self._setup_dome_randomizers()
# Run another preview to generate the replicator graphs for the DOME dataset without triggering any writing
rep.orchestrator.preview()
# Randomize the distractors by applying forces to them and changing their materials
self.current_distractors.apply_force_to_assets(config_data["FORCE_RANGE"])
self.current_distractors.randomize_asset_glass_color()
# Randomize the pose of the object(s) of interest in the camera view
for train_part in self.train_parts:
self.randomize_movement_in_view(train_part)
# Simulate the applied forces for a couple of frames
for _ in range(50):
world.step(render=False)
print(f"ID: {self.cur_idx}/{self.train_size - 1}")
rep.orchestrator.step(rt_subframes=4)
# Check that there was valid training data in the last frame (target object(s) visible to camera)
if self.writer.is_last_frame_valid():
self.cur_idx += 1
# Check if last frame has been reached
if self.cur_idx >= self.train_size:
print(f"Dataset of size {self.train_size} has been reached, generation loop will be stopped..")
print(f"Data outputted to: {self._output_folder}")
self.last_frame_reached = True
dataset = RandomScenario(
num_mesh=args.num_mesh,
num_dome=args.num_dome,
dome_interval=args.dome_interval,
output_folder=args.output_folder,
use_s3=args.use_s3,
bucket=args.bucket,
s3_region=args.s3_region,
endpoint=args.endpoint,
writer=args.writer.lower(),
test=args.test,
)
if dataset.result:
# Iterate through dataset and visualize the output
print("Loading materials. Will generate data soon...")
import datetime
start_time = datetime.datetime.now()
print("Start timestamp:", start_time.strftime("%m/%d/%Y, %H:%M:%S"))
if dataset.train_size > 0:
print(f"Starting dataset generation of {dataset.train_size} frames..")
if dataset.num_mesh > 0:
print(f"Starting MESH dataset generation of {dataset.num_mesh} frames..")
# Dataset generation loop
for _ in dataset:
if dataset.last_frame_reached:
print(f"Stopping generation loop at index {dataset.cur_idx}..")
break
if dataset.exiting:
break
else:
print(f"Dataset size is set to 0 (num_mesh={dataset.num_mesh} num_dope={dataset.num_dome}), nothing to write..")
print("End timestamp:", datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))
print("Total time taken:", str(datetime.datetime.now() - start_time).split(".")[0])
if args.test:
run_pose_generation_test(
writer=args.writer,
output_folder=dataset._output_folder,
test_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), "tests"),
)
# Close the app
kit.close()
| 23,434 | Python | 39.128425 | 181 | 0.618716 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from flying_distractors.collision_box import CollisionBox
from flying_distractors.dynamic_asset_set import DynamicAssetSet
from flying_distractors.dynamic_object import DynamicObject
from flying_distractors.dynamic_object_set import DynamicObjectSet
from flying_distractors.dynamic_shape_set import DynamicShapeSet
from flying_distractors.flying_distractors import FlyingDistractors
from utils import save_points_xyz
| 848 | Python | 52.062497 | 76 | 0.84434 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/dynamic_object_set.py | # Copyright (c) 2021-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 random
from typing import List, Optional
import numpy as np
from omni.isaac.core.materials.omni_glass import OmniGlass
from .collision_box import CollisionBox
from .dynamic_asset_set import DynamicAssetSet
from .dynamic_object import DynamicObject
class DynamicObjectSet(DynamicAssetSet):
"""Container class to hold and manage dynamic objects, providing an API to keep objects in motion within a collision
box, and to allow various properties of the assets to be randomized. Please note that this class assumes that
each referenced asset in usd_path_list has only a single mesh prim defining its geometry.
Args:
set_prim_path (str): prim path of the parent Prim to create, which contains all the objects in the object set
as its children.
set_name (str): name of the parent prim in the scene.
usd_path_list (List[str]): list of possible USD reference paths that the prims of each dynamic object in the
dynamic object set refer to.
mesh_list (List[str]): list of prim path base names for underlying mesh prims. Each base name in mesh_list
corresponds to the mesh prim of the referenced asset in usd_path_list.
asset_prim_path_base_prefix (str): prefix of what the objects are called in the stage (prim path base name).
asset_name_prefix (str): prefix of the objects' names in the scene.
num_assets (int): number of objects in the object set.
collision_box (CollisionBox): collision box in which to place objects, and allow objects to move within.
scale (Optional[np.ndarray], optional): local scale to be applied to each object's dimensions. Shape is (3, ).
Defaults to None, which means left unchanged.
mass (Optional[float], optional): mass of each object in kg. Defaults to None.
fraction_glass (int, optional): fraction of objects for which glass material should be applied.
"""
def __init__(
self,
set_prim_path: str,
set_name: str,
usd_path_list: List[str],
mesh_list: List[str],
asset_prim_path_base_prefix: str,
asset_name_prefix: str,
num_assets: int,
collision_box: CollisionBox,
scale: Optional[np.ndarray] = None,
mass: Optional[float] = None,
fraction_glass: float = 0.0,
):
self.usd_path_list = usd_path_list
self.mesh_list = mesh_list
self.glass_object_mesh_paths = []
self.nonglass_object_mesh_paths = []
if len(usd_path_list) != len(mesh_list):
raise Exception("usd_path_list and mesh_list must contain the same number of elements")
self.mesh_map = self._create_mesh_map(usd_path_list, mesh_list)
super().__init__(
set_prim_path,
set_name,
asset_prim_path_base_prefix,
asset_name_prefix,
num_assets,
collision_box,
scale,
mass,
fraction_glass,
)
self._create_random_dynamic_asset_set()
def _create_mesh_map(self, usd_path_list, mesh_list):
"""Gets a mapping from USD reference paths to the base name of the corresponding mesh prim in the referenced USD
file.
Args:
usd_path_list (List[str]): List of possible USD reference paths that the prims of each dynamic object in the
dynamic object set refer to.
mesh_list (List[str]): List of prim path base names for underlying mesh prims. Each base name in mesh_list
corresponds to the mesh prim of the referenced asset in usd_path_list.
Returns:
Dict: Mapping from USD reference paths to the base name of the corresponding mesh prim in the referenced USD
file.
"""
mesh_map = {}
for usd_path, mesh_name in zip(usd_path_list, mesh_list):
mesh_map[usd_path] = mesh_name
return mesh_map
def _create_random_dynamic_asset(self, glass=False):
"""Creates a random dynamic object and adds it to the scene. The reference path of the object is randomly chosen
from self.usd_path_list.
Args:
glass (bool, optional): flag to specify whether the created object should have a glass material applied.
Defaults to False.
"""
object_name = f"{self.asset_name_prefix}_{self.asset_count}"
if glass:
object_path = f"{self.set_prim_path}/{self.asset_prim_path_base_prefix}_{self.asset_count}"
else:
object_path = f"{self.set_prim_path}/{self.asset_prim_path_base_prefix}_nonglass_{self.asset_count}"
usd_path = random.choice(self.usd_path_list)
mesh_path = f"{object_path}/{self.mesh_map[usd_path]}"
position = self.collision_box.get_random_position()
dynamic_prim = DynamicObject(
usd_path=usd_path,
prim_path=object_path,
mesh_path=mesh_path,
name=object_name,
position=position,
scale=self.scale,
mass=self.mass,
)
self.asset_names.append(object_name)
if glass:
color = np.random.rand(3)
material = OmniGlass(
object_path + "_glass",
name=object_name + "_glass",
ior=1.25,
depth=0.001,
thin_walled=False,
color=color,
)
self.glass_mats.append(material)
dynamic_prim.apply_visual_material(material)
self.glass_asset_paths.append(object_path)
self.glass_assets.append(dynamic_prim)
self.glass_object_mesh_paths.append(mesh_path)
else:
self.nonglass_asset_paths.append(object_path)
self.nonglass_assets.append(dynamic_prim)
self.nonglass_object_mesh_paths.append(mesh_path)
self.world.scene.add(dynamic_prim)
self.asset_count += 1
| 6,626 | Python | 40.679245 | 120 | 0.616963 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/dynamic_shape_set.py | # Copyright (c) 2021-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 random
from typing import Optional
import numpy as np
from omni.isaac.core.materials.omni_glass import OmniGlass
from omni.isaac.core.objects import DynamicCapsule, DynamicCone, DynamicCuboid, DynamicCylinder, DynamicSphere
from .collision_box import CollisionBox
from .dynamic_asset_set import DynamicAssetSet
class DynamicShapeSet(DynamicAssetSet):
"""Container class to hold and manage dynamic shapes, providing an API to keep shapes in motion within a collision
box, and to allow various properties of the shapes to be randomized.
Args:
set_prim_path (str): prim path of the parent Prim to create, which contains all the shapes in the shape set
as its children.
set_name (str): name of the parent prim in the scene.
asset_prim_path_base_prefix (str): prefix of what the shapes are called in the stage (prim path base name).
asset_name_prefix (str): prefix of the shapes' names in the scene.
num_assets (int): number of shapes in the shape set.
collision_box (CollisionBox): collision box in which to place shapes, and allow shapes to move within.
scale (Optional[np.ndarray], optional): local scale to be applied to each shape's dimensions. Shape is (3, ).
Defaults to None, which means left unchanged.
mass (Optional[float], optional): mass of each shape in kg. Defaults to None.
fraction_glass (int, optional): fraction of shapes for which glass material should be applied.
"""
def __init__(
self,
set_prim_path: str,
set_name: str,
asset_prim_path_base_prefix: str,
asset_name_prefix: str,
num_assets: int,
collision_box: CollisionBox,
scale: Optional[np.ndarray] = None,
mass: Optional[float] = None,
fraction_glass: float = 0.0,
):
super().__init__(
set_prim_path,
set_name,
asset_prim_path_base_prefix,
asset_name_prefix,
num_assets,
collision_box,
scale,
mass,
fraction_glass,
)
self._create_random_dynamic_asset_set()
def _create_random_dynamic_asset(self, glass=False):
"""Creates a random dynamic shape (Cuboid, Sphere, Cylinder, Cone, or Capsule) and adds it to the scene.
Args:
glass (bool, optional): flag to specify whether the created shape should have a glass material applied.
Defaults to False.
"""
prim_type = [DynamicCapsule, DynamicCone, DynamicCuboid, DynamicCylinder, DynamicSphere]
shape_name = f"{self.asset_name_prefix}_{self.asset_count}"
if glass:
shape_path = f"{self.set_prim_path}/{self.asset_prim_path_base_prefix}_{self.asset_count}"
else:
shape_path = f"{self.set_prim_path}/{self.asset_prim_path_base_prefix}_nonglass_{self.asset_count}"
position = self.collision_box.get_random_position()
shape_prim = random.choice(prim_type)(
prim_path=shape_path, # The prim path of the cube in the USD stage
name=shape_name, # The unique name used to retrieve the object from the scene later on
position=position, # Using the current stage units which is meters by default.
scale=self.scale,
mass=self.mass,
)
self.asset_names.append(shape_name)
if glass:
color = np.random.rand(3)
material = OmniGlass(
shape_path + "_glass", name=shape_name + "_glass", ior=1.25, depth=0.001, thin_walled=False, color=color
)
self.glass_mats.append(material)
shape_prim.apply_visual_material(material)
self.glass_asset_paths.append(shape_path)
self.glass_assets.append(shape_prim)
else:
self.nonglass_asset_paths.append(shape_path)
self.nonglass_assets.append(shape_prim)
self.world.scene.add(shape_prim)
self.asset_count += 1
| 4,566 | Python | 40.899082 | 120 | 0.63929 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/collision_box.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import numpy as np
from omni.isaac.core import World
from omni.isaac.core.objects import FixedCuboid
from omni.isaac.core.prims.xform_prim import XFormPrim
from pxr import Usd, UsdGeom
class CollisionBox(XFormPrim):
"""Creates a fixed box with collisions enabled, and provides an API to determine world coordinates of a random
location in the interior of the collision box.
Args:
prim_path (str): top-level prim path (of the collision box) of the Prim to encapsulate or create.
name (str): shortname to be used as a key by Scene class. Note: needs to be unique if the object is added to the
Scene.
position (Optional[np.ndarray], optional): position in the world frame of the collision box. Shape is (3, ).
Defaults to None, which means left unchanged.
translation (Optional[np.ndarray], optional): translation in the local frame of the collision box (with respect
to its parent prim). Shape is (3, ). Defaults to None, which means
left unchanged.
orientation (Optional[np.ndarray], optional): quaternion orientation in the world/local frame of the collision
box (depends if translation or position is specified). Quaternion
is scalar-first (w, x, y, z). Shape is (4, ). Defaults to None,
which means left unchanged.
scale (Optional[np.ndarray], optional): local scale to be applied to the collision box's dimensions. Shape is
(3, ). Defaults to None, which means left unchanged.
width (float): width of the collision box interior in world units (if unrotated, corresponds to x direction).
Defaults to 1.0.
height (float): height of the collision box interior in world units (if unrotated, corresponds to y direction).
Defaults to 1.0.
depth (float): depth of the collision box interior in world units (if unrotated, corresponds to z direction).
Defaults to 1.0.
thickness (float, optional): thickness of the collision box walls in world units. Defaults to 0.2.
visible (bool, optional): set to false for an invisible prim in the stage while rendering. Defaults to False.
"""
def __init__(
self,
prim_path: str,
name: str,
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
width: float = 1.0,
height: float = 1.0,
depth: float = 1.0,
thickness: float = 0.2,
visible: bool = False,
):
self.world = World.instance()
XFormPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
)
self.width = width
self.height = height
self.depth = depth
self.thickness = thickness
self.visible = visible
self._create_collision_box()
def _create_face(self, suffix, translation, size):
"""Create a face/wall of the Collision Box, which has collisions enabled.
Args:
suffix (str): suffix used for the name of the face so it can be retrieved from the scene. The name of the
face has the form "{collision_box_name}_{suffix}"
translation (np.ndarray): translation of the center of the face (wall) from the center of the Collision
Box, in stage units. Shape is (3, ).
size (np.ndarray): dimensions of the face (wall) in the X, Y, and Z directions. Dimensions are in stage
units. Shape is (3, ).
"""
face_name = f"{self.name}_{suffix}"
face_path = f"{self.prim_path}/{face_name}"
face_cuboid = FixedCuboid(
prim_path=face_path, # The prim path of the cube in the USD stage
name=face_name, # The unique name used to retrieve the object from the scene later on
translation=translation, # Using the current stage units which is cms by default.
scale=size, # most arguments accept mainly numpy arrays.
size=1.0,
visible=self.visible,
)
self.world.scene.add(face_cuboid)
def _create_collision_box(self):
"""Create a Collision Box. The Collision Box consists of 6 faces/walls forming a static box-like volume. Each
wall of the Collision Box has collisions enabled.
"""
dx = self.width / 2.0 + self.thickness / 2.0
dy = self.height / 2.0 + self.thickness / 2.0
dz = self.depth / 2.0 + self.thickness / 2.0
floor_center = np.array([0, 0, -dz])
floor_dimensions = np.array([self.width, self.height, self.thickness])
self._create_face("floor", floor_center, floor_dimensions)
ceiling_center = np.array([0, 0, +dz])
ceiling_dimensions = np.array([self.width, self.height, self.thickness])
self._create_face("ceiling", ceiling_center, ceiling_dimensions)
left_wall_center = np.array([dx, 0, 0])
left_wall_dimensions = np.array([self.thickness, self.height, self.depth])
self._create_face("left_wall", left_wall_center, left_wall_dimensions)
right_wall_center = np.array([-dx, 0, 0])
right_wall_dimensions = np.array([self.thickness, self.height, self.depth])
self._create_face("right_wall", right_wall_center, right_wall_dimensions)
front_wall_center = np.array([0, dy, 0])
front_wall_dimensions = np.array([self.width, self.thickness, self.depth])
self._create_face("front_wall", front_wall_center, front_wall_dimensions)
back_wall_center = np.array([0, -dy, 0])
back_wall_dimensions = np.array([self.width, self.thickness, self.depth])
self._create_face("back_wall", back_wall_center, back_wall_dimensions)
def get_random_local_translation(self):
"""Get a random translation within the Collision Box in local coordinates. Translations are within the
volumetric region contained by the inner walls of the Collision Box. The local coordinate frame is considered
to be the frame of the prim at self.prim_path (center of the Collision Box).
Returns:
np.ndarray: random translation within the Collision Box in the local frame of the Collision Box. Shape is
(3, ).
"""
dim_fractions = np.random.rand(3)
tx = dim_fractions[0] * self.width - self.width / 2.0
ty = dim_fractions[1] * self.height - self.height / 2.0
tz = dim_fractions[2] * self.depth - self.depth / 2.0
translation = np.array([tx, ty, tz])
return translation
def get_random_position(self):
"""Get a random position within the Collision Box in world coordinates. Positions are within the volumetric
region contained by the inner walls of the Collision Box.
Returns:
np.ndarray: random position within the Collision Box in the world frame. Shape is (3, ).
"""
box_prim = self.world.stage.GetPrimAtPath(self.prim_path)
box_transform_matrix = UsdGeom.Xformable(box_prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default())
box_to_world = np.transpose(box_transform_matrix)
random_local_translation = self.get_random_local_translation()
random_local_translation_homogenous = np.pad(random_local_translation, ((0, 1)), constant_values=1.0)
position_homogenous = box_to_world @ random_local_translation_homogenous
position = position_homogenous[:-1]
return position
| 8,637 | Python | 46.988889 | 120 | 0.618733 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/__init__.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .collision_box import CollisionBox
from .dynamic_asset_set import DynamicAssetSet
from .dynamic_object import DynamicObject
from .dynamic_object_set import DynamicObjectSet
from .dynamic_shape_set import DynamicShapeSet
from .flying_distractors import FlyingDistractors
| 706 | Python | 46.13333 | 76 | 0.830028 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/flying_distractors.py | # Copyright (c) 2021-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 itertools
from omni.isaac.core import World
from .dynamic_object_set import DynamicObjectSet
from .dynamic_shape_set import DynamicShapeSet
class FlyingDistractors:
"""Container class to hold and manage both dynamic shape sets and dynamic object sets simultaneously. This class
provides an API to keep assets in each asset set in motion within their respective collision boxes, to show/hide
the assets of all the asset sets managed by this class, and to allow various properties of the assets of all the
asset sets managed by this class to be randomized.
"""
def __init__(self):
self.world = World.instance()
self.shape_sets = []
self.object_sets = []
def add(self, asset_set):
"""Add an asset set to be managed by this FlyingDistractors object.
Args:
asset_set (Union[DynamicShapeSet, DynamicObjectSet]): the asset set to add.
Raises:
Exception: if asset_set is neither a DynamicShapeSet nor a DynamicObjectSet.
"""
if isinstance(asset_set, DynamicShapeSet):
self.shape_sets.append(asset_set)
elif isinstance(asset_set, DynamicObjectSet):
self.object_sets.append(asset_set)
else:
raise Exception("The asset set provided is not of type DynamicShapeSet or DynamicObjectSet")
def set_visible(self, visible):
"""Sets the visibility of all assets contained in the managed asset sets.
Args:
visible (bool): flag to set the visibility of all assets contained in the managed asset sets.
"""
for asset_set in itertools.chain(self.shape_sets, self.object_sets):
for asset_name in asset_set.asset_names:
object_xform = self.world.scene.get_object(asset_name)
object_xform.set_visibility(visible=visible)
def reset_asset_positions(self):
"""Reset the positions of all assets contained in the managed asset sets to be within its corresponding
collision box.
"""
for asset_set in itertools.chain(self.shape_sets, self.object_sets):
asset_set.reset_position()
def apply_force_to_assets(self, force_limit):
"""Apply random forces to all assets contained in the managed asset sets.
Args:
force_limit (float): maximum force component to apply.
"""
for asset_set in itertools.chain(self.shape_sets, self.object_sets):
asset_set.apply_force_to_assets(force_limit)
def randomize_asset_glass_color(self):
"""Randomize color of assets in the managed asset sets with glass material applied."""
for asset_set in itertools.chain(self.shape_sets, self.object_sets):
asset_set.randomize_glass_color()
| 3,231 | Python | 38.901234 | 116 | 0.686784 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/dynamic_asset_set.py | # Copyright (c) 2021-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 itertools
import math
from abc import ABC, abstractmethod
from typing import Optional
import numpy as np
from omni.isaac.core import World
from .collision_box import CollisionBox
class DynamicAssetSet(ABC):
"""Container class to hold and manage dynamic assets, providing an API to keep assets in motion within a collision
box, and to allow various properties of the assets to be randomized.
Args:
set_prim_path (str): prim path of the parent Prim to create, which contains all the assets in the asset set as
its children.
set_name (str): name of the parent prim in the scene.
asset_prim_path_base_prefix (str): prefix of what the assets are called in the stage (prim path base name).
asset_name_prefix (str): prefix of the assets' names in the scene.
num_assets (int): number of assets in the asset set.
collision_box (CollisionBox): collision box in which to place assets, and allow assets to move within.
scale (Optional[np.ndarray], optional): local scale to be applied to each asset's dimensions. Shape is (3, ).
Defaults to None, which means left unchanged.
mass (Optional[float], optional): mass of each asset in kg. Defaults to None.
fraction_glass (int, optional): fraction of assets for which glass material should be applied.
"""
def __init__(
self,
set_prim_path: str,
set_name: str,
asset_prim_path_base_prefix: str,
asset_name_prefix: str,
num_assets: int,
collision_box: CollisionBox,
scale: Optional[np.ndarray] = None,
mass: Optional[float] = None,
fraction_glass: float = 0.0,
):
self.world = World.instance()
self.set_prim_path = set_prim_path
self.set_name = set_name
self.asset_prim_path_base_prefix = asset_prim_path_base_prefix
self.asset_name_prefix = asset_name_prefix
self.num_assets = num_assets
self.collision_box = collision_box
self.scale = scale
self.mass = mass
self.fraction_glass = fraction_glass
self.asset_count = 0
self.asset_names = []
self.glass_asset_paths = []
self.nonglass_asset_paths = []
self.glass_assets = []
self.nonglass_assets = []
self.glass_mats = []
def _create_random_dynamic_asset_set(self):
"""Create self.num_assets assets and add them to the dynamic asset set."""
self.world.stage.DefinePrim(self.set_prim_path, "Xform")
num_glass = math.floor(self.num_assets * self.fraction_glass)
for i in range(self.num_assets):
if i < num_glass:
self._create_random_dynamic_asset(glass=True)
else:
self._create_random_dynamic_asset()
@abstractmethod
def _create_random_dynamic_asset(self, glass=False):
pass
def apply_force_to_assets(self, force_limit):
"""Apply a force in a random direction to each asset in the dynamic asset set.
Args:
force_limit (float): maximum force component to apply.
"""
for path in itertools.chain(self.glass_asset_paths, self.nonglass_asset_paths):
# X, Y, and Z components of the force are constrained to be within [-force_limit, force_limit]
random_force = np.random.uniform(-force_limit, force_limit, 3).tolist()
handle = self.world.dc_interface.get_rigid_body(path)
self.world.dc_interface.apply_body_force(handle, random_force, (0, 0, 0), False)
def randomize_glass_color(self):
"""Randomize the color of the assets in the dynamic asset set with a glass material applied."""
for asset in itertools.chain(self.glass_assets):
glass_mat = asset.get_applied_visual_material()
glass_mat.set_color(np.random.rand(3))
def reset_position(self):
"""Reset the positions of assets in the dynamic asset set. The positions at which to place assets are randomly
chosen such that they are within the collision box.
"""
for asset in itertools.chain(self.glass_assets, self.nonglass_assets):
position = self.collision_box.get_random_position()
asset.set_world_pose(position)
| 4,798 | Python | 39.669491 | 118 | 0.651105 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/flying_distractors/dynamic_object.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import numpy as np
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.utils.prims import get_prim_at_path, is_prim_path_valid
from omni.isaac.core.utils.stage import add_reference_to_stage
from pxr import UsdGeom
class DynamicObject(RigidPrim, GeometryPrim):
"""Creates and adds a prim to stage from USD reference path, and wraps the prim with RigidPrim and GeometryPrim to
provide access to APIs for rigid body attributes, physics materials and collisions. Please note that this class
assumes the object has only a single mesh prim defining its geometry.
Args:
usd_path (str): USD reference path the Prim refers to.
prim_path (str): prim path of the Prim to encapsulate or create.
mesh_path (str): prim path of the underlying mesh Prim.
name (str, optional): shortname to be used as a key by Scene class. Note: needs to be unique if the object is
added to the Scene. Defaults to "dynamic_object".
position (Optional[np.ndarray], optional): position in the world frame of the prim. Shape is (3, ). Defaults to
None, which means left unchanged.
translation (Optional[np.ndarray], optional): translation in the local frame of the prim (with respect to its
parent prim). Shape is (3, ). Defaults to None, which means left
unchanged.
orientation (Optional[np.ndarray], optional): quaternion orientation in the world/local frame of the prim
(depends if translation or position is specified). Quaternion is
scalar-first (w, x, y, z). Shape is (4, ). Defaults to None, which
means left unchanged.
scale (Optional[np.ndarray], optional): local scale to be applied to the prim's dimensions. Shape is (3, ).
Defaults to None, which means left unchanged.
visible (bool, optional): set to false for an invisible prim in the stage while rendering. Defaults to True.
mass (Optional[float], optional): mass in kg. Defaults to None.
linear_velocity (Optional[np.ndarray], optional): linear velocity in the world frame. Defaults to None.
angular_velocity (Optional[np.ndarray], optional): angular velocity in the world frame. Defaults to None.
"""
def __init__(
self,
usd_path: str,
prim_path: str,
mesh_path: str,
name: str = "dynamic_object",
position: Optional[np.ndarray] = None,
translation: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
scale: Optional[np.ndarray] = None,
visible: bool = True,
mass: Optional[float] = None,
linear_velocity: Optional[np.ndarray] = None,
angular_velocity: Optional[np.ndarray] = None,
) -> None:
if is_prim_path_valid(mesh_path):
prim = get_prim_at_path(mesh_path)
if not prim.IsA(UsdGeom.Mesh):
raise Exception("The prim at path {} cannot be parsed as a Mesh object".format(mesh_path))
self.usd_path = usd_path
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
GeometryPrim.__init__(
self,
prim_path=mesh_path,
name=name,
translation=translation,
orientation=orientation,
visible=visible,
collision=True,
)
self.set_collision_approximation("convexHull")
RigidPrim.__init__(
self,
prim_path=prim_path,
name=name,
position=position,
translation=translation,
orientation=orientation,
scale=scale,
visible=visible,
mass=mass,
linear_velocity=linear_velocity,
angular_velocity=angular_velocity,
)
| 4,662 | Python | 47.072164 | 120 | 0.614972 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/config/dope_config.yaml | ---
# Default rendering parameters
CONFIG:
renderer: RayTracedLighting
headless: false
width: 512
height: 512
# Index of part in array of classes in PoseCNN training
CLASS_NAME_TO_INDEX:
003_cracker_box: 1
035_power_drill: 2
# prim_type is determined by the usd file.
# To determine, open the usd file in Isaac Sim and see the prim path. If you load it in /World, the path will be /World/<prim_type>
OBJECTS_TO_GENERATE:
- { part_name: 003_cracker_box, num: 1, prim_type: _03_cracker_box }
- { part_name: 035_power_drill, num: 1, prim_type: _35_power_drill }
# Maximum force component to apply to objects to keep them in motion
FORCE_RANGE: 30
# Camera Intrinsics
WIDTH: 512
HEIGHT: 512
F_X: 768.1605834960938
F_Y: 768.1605834960938
C_X: 256
C_Y: 256
# Default Camera Horizontal Aperture
HORIZONTAL_APERTURE: 20.955
# Number of sphere lights added to the scene
NUM_LIGHTS: 6
# Minimum and maximum distances of objects away from the camera (along the optical axis)
MIN_DISTANCE: 0.4
MAX_DISTANCE: 1.4
# Rotation of camera rig with respect to world frame, expressed as XYZ euler angles
CAMERA_RIG_ROTATION:
- 0
- 0
- 0
# Rotation of camera with respect to camera rig, expressed as XYZ euler angles. Please note that in this example, we
# define poses with respect to the camera rig instead of the camera prim. By using the rig's frame as a surrogate for
# the camera's frame, we effectively change the coordinate system of the camera. When
# CAMERA_RIG_ROTATION = np.array([0, 0, 0]) and CAMERA_ROTATION = np.array([0, 0, 0]), this corresponds to the default
# Isaac-Sim camera coordinate system of -z out the face of the camera, +x to the right, and +y up. When
# CAMERA_RIG_ROTATION = np.array([0, 0, 0]) and CAMERA_ROTATION = np.array([180, 0, 0]), this corresponds to
# the YCB Video Dataset camera coordinate system of +z out the face of the camera, +x to the right, and +y down.
CAMERA_ROTATION:
- 180
- 0
- 0
# Minimum and maximum XYZ euler angles for the part being trained on to be rotated, with respect to the camera rig
MIN_ROTATION_RANGE:
- -180
- -90
- -180
# Minimum and maximum XYZ euler angles for the part being trained on to be rotated, with respect to the camera rig
MAX_ROTATION_RANGE:
- 180
- 90
- 180
# How close the center of the part being trained on is allowed to be to the edge of the screen
FRACTION_TO_SCREEN_EDGE: 0.9
# MESH and DOME datasets
SHAPE_SCALE:
- 0.05
- 0.05
- 0.05
SHAPE_MASS: 1
OBJECT_SCALE:
- 1
- 1
- 1
OBJECT_MASS: 1
# MESH dataset
NUM_MESH_SHAPES: 500
NUM_MESH_OBJECTS: 200
MESH_FRACTION_GLASS: 0.15
MESH_FILENAMES:
- 002_master_chef_can
- 004_sugar_box
- 005_tomato_soup_can
- 006_mustard_bottle
- 007_tuna_fish_can
- 008_pudding_box
- 009_gelatin_box
- 010_potted_meat_can
- 011_banana
- 019_pitcher_base
- 021_bleach_cleanser
- 024_bowl
- 025_mug
- 035_power_drill
- 036_wood_block
- 037_scissors
- 040_large_marker
- 051_large_clamp
- 052_extra_large_clamp
- 061_foam_brick
# DOME dataset
NUM_DOME_SHAPES: 30
NUM_DOME_OBJECTS: 20
DOME_FRACTION_GLASS: 0.2
DOME_TEXTURES:
- Clear/evening_road_01_4k
- Clear/kloppenheim_02_4k
- Clear/mealie_road_4k
- Clear/noon_grass_4k
- Clear/qwantani_4k
- Clear/signal_hill_sunrise_4k
- Clear/sunflowers_4k
- Clear/syferfontein_18d_clear_4k
- Clear/venice_sunset_4k
- Clear/white_cliff_top_4k
- Cloudy/abandoned_parking_4k
- Cloudy/champagne_castle_1_4k
- Cloudy/evening_road_01_4k
- Cloudy/kloofendal_48d_partly_cloudy_4k
- Cloudy/lakeside_4k
- Cloudy/sunflowers_4k
- Cloudy/table_mountain_1_4k
- Evening/evening_road_01_4k
- Indoor/adams_place_bridge_4k
- Indoor/autoshop_01_4k
- Indoor/bathroom_4k
- Indoor/carpentry_shop_01_4k
- Indoor/en_suite_4k
- Indoor/entrance_hall_4k
- Indoor/hospital_room_4k
- Indoor/hotel_room_4k
- Indoor/lebombo_4k
- Indoor/old_bus_depot_4k
- Indoor/small_empty_house_4k
- Indoor/studio_small_04_4k
- Indoor/surgery_4k
- Indoor/vulture_hide_4k
- Indoor/wooden_lounge_4k
- Night/kloppenheim_02_4k
- Night/moonlit_golf_4k
- Storm/approaching_storm_4k
| 3,989 | YAML | 25.25 | 131 | 0.740035 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/tests/test_utils.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import json
import os
import shutil
import numpy as np
import scipy.io as sio
def run_pose_generation_test(writer, output_folder, test_folder):
if writer.lower() == "dope":
run_dope_test(test_folder, output_folder)
elif writer.lower() == "ycbvideo":
run_ycbvideo_tests(test_folder, output_folder)
else:
raise Exception(f"No tests exist for the selected writer: {writer}")
# Cleans up output directory so tests are not reading output files from previous run
def clean_output_dir(output_folder):
if os.path.isdir(output_folder):
shutil.rmtree(output_folder, ignore_errors=True)
# Checks if distance between points is within threshold
def within_threshold(p1, p2, threshold=20):
return np.linalg.norm(np.array(p1) - np.array(p2)) < threshold
def run_dope_test(test_folder, output_folder):
groundtruth_path = os.path.join(test_folder, "dope/000000_groundtruth.json")
# Look at output for 2nd frame because 1st frame does not get generated properly sometimes
output_path = os.path.join(output_folder, "000001.json")
with open(groundtruth_path) as gt_f:
gt_data = json.load(gt_f)
with open(output_path) as op_f:
op_data = json.load(op_f)
gt_objects, op_objects = gt_data["objects"], op_data["objects"]
# Does not work with multiple objects. There should be only one object in testing mode.
if not (len(gt_objects) == 1 and len(op_objects) == 1):
raise Exception(
f"Mismatch in .json files between number of objects. gt_objects: {len(gt_objects)}, op_objects: {len(op_objects)}"
)
for gt_obj, op_obj in zip(gt_objects, op_objects):
if not within_threshold(gt_obj["location"], op_obj["location"], 10):
raise Exception(
f"Distance between groundtruth location and output location exceeds threshold. (location) {gt_pt} and {op_pt}"
)
for gt_pt, op_pt in zip(gt_obj["projected_cuboid"], op_obj["projected_cuboid"]):
if not within_threshold(gt_pt, op_pt, 20.0):
raise Exception(
f"Distance between groundtruth points and output points exceeds threshold. (projected_cuboid) {gt_pt} and {op_pt}"
)
print("Tests pass for DOPE Writer.")
def run_ycbvideo_tests(test_folder, output_folder, threshold=10):
groundtruth_bbox_path = os.path.join(test_folder, "ycbvideo/000000-box_groundtruth.txt")
groundtruth_meta_path = os.path.join(test_folder, "ycbvideo/000000-meta_groundtruth.mat")
# Look at output for 2nd frame because 1st frame does not get generated properly sometimes
output_bbox_path = os.path.join(output_folder, "data/YCB_Video/data/0000", "000001-box.txt")
output_meta_path = os.path.join(output_folder, "data/YCB_Video/data/0000", "000001-meta.mat")
# Compare BBox
gt_bb = open(groundtruth_bbox_path, "r")
op_bb = open(output_bbox_path, "r")
for l1, l2 in zip(gt_bb, op_bb):
for gt_point, bb_point in zip(l1.strip().split()[1:5], l2.strip().split()[1:5]):
if not within_threshold([int(gt_point)], [int(bb_point)], 10):
raise Exception(f"Mismatch between files {groundtruth_bbox_path} and {output_bbox_path}")
gt_bb.close()
op_bb.close()
# Compare Meta File
gt_meta = sio.loadmat(groundtruth_meta_path)
op_meta = sio.loadmat(output_meta_path)
keys_to_compare = ["poses", "intrinsic_matrix", "center"]
print(f"gt_meta:\n{gt_meta}")
print(f"op_meta:\n{op_meta}")
for key in keys_to_compare:
gt = gt_meta[key].flatten()
op = op_meta[key].flatten()
if not len(gt) == len(op):
raise Exception(f"Mismatch between length of pose in {groundtruth_meta_path} and {output_meta_path}")
for i in range(len(gt)):
if abs(gt[i] - op[i]) > threshold:
raise Exception(
f"Mismatch between {key} values in groundtruth and output at index {i}. Groundtruth: {gt[i]} Output: {op[i]}"
)
print(f"{key} matches between groundtruth and output.")
print("Tests pass for YCBVideo Writer.")
| 4,599 | Python | 38.316239 | 134 | 0.661666 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/tests/ycbvideo/test_ycb_config.yaml | # DO NOT MODIFY OR TESTS WILL FAIL
---
CONFIG:
renderer: RayTracedLighting
headless: false
width: 1280
height: 720
CLASS_NAME_TO_INDEX:
_03_cracker_box: 1
OBJECTS_TO_GENERATE:
- { part_name: 003_cracker_box, num: 1, prim_type: _03_cracker_box }
FORCE_RANGE: 30
WIDTH: 1280
HEIGHT: 720
F_X: 665.80768
F_Y: 665.80754
C_X: 637.642
C_Y: 367.56
HORIZONTAL_APERTURE: 20.955
NUM_LIGHTS: 6
MIN_DISTANCE: 1.0
MAX_DISTANCE: 1.0
CAMERA_RIG_ROTATION:
- 0
- 0
- 0
CAMERA_ROTATION:
- 180
- 0
- 0
MIN_ROTATION_RANGE:
- 100
- 100
- 100
MAX_ROTATION_RANGE:
- 100
- 100
- 100
FRACTION_TO_SCREEN_EDGE: 0.0
SHAPE_SCALE:
- 0.05
- 0.05
- 0.05
SHAPE_MASS: 1
OBJECT_SCALE:
- 1
- 1
- 1
OBJECT_MASS: 1
NUM_MESH_SHAPES: 0
NUM_MESH_OBJECTS: 0
MESH_FRACTION_GLASS: 0.15
NUM_DOME_SHAPES: 0
NUM_DOME_OBJECTS: 0
DOME_FRACTION_GLASS: 0.2
DOME_TEXTURES: []
MESH_FILENAMES: []
| 853 | YAML | 13.724138 | 68 | 0.691676 |
2820207922/isaac_ws/standalone_examples/replicator/offline_pose_generation/tests/dope/test_dope_config.yaml | # DO NOT MODIFY OR TESTS WILL FAIL
---
CONFIG:
renderer: RayTracedLighting
headless: false
width: 512
height: 512
CLASS_NAME_TO_INDEX:
_03_cracker_box: 1
OBJECTS_TO_GENERATE:
- { part_name: 003_cracker_box, num: 1, prim_type: _03_cracker_box }
FORCE_RANGE: 30
WIDTH: 512
HEIGHT: 512
F_X: 768.1605834960938
F_Y: 768.1605834960938
C_X: 256
C_Y: 256
HORIZONTAL_APERTURE: 20.955
NUM_LIGHTS: 6
MIN_DISTANCE: 1.0
MAX_DISTANCE: 1.0
CAMERA_RIG_ROTATION:
- 0
- 0
- 0
CAMERA_ROTATION:
- 180
- 0
- 0
MIN_ROTATION_RANGE:
- 100
- 100
- 100
MAX_ROTATION_RANGE:
- 100
- 100
- 100
FRACTION_TO_SCREEN_EDGE: 0.0
SHAPE_SCALE:
- 0.05
- 0.05
- 0.05
SHAPE_MASS: 1
OBJECT_SCALE:
- 1
- 1
- 1
OBJECT_MASS: 1
NUM_MESH_SHAPES: 0
NUM_MESH_OBJECTS: 0
MESH_FRACTION_GLASS: 0.15
NUM_DOME_SHAPES: 0
NUM_DOME_OBJECTS: 0
DOME_FRACTION_GLASS: 0.2
DOME_TEXTURES: []
MESH_FILENAMES: []
| 860 | YAML | 13.844827 | 68 | 0.696512 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.gym/cartpole_train.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# import stable baselines
import carb
try:
from stable_baselines3 import PPO
except Exception as e:
carb.log_error(e)
carb.log_error(
"please install stable-baselines3 in the current python environment or run the following to install into the builtin python environment ./python.sh -m pip install stable-baselines3 "
)
exit()
try:
import tensorboard
except Exception as e:
carb.log_error(e)
carb.log_error(
"please install tensorboard in the current python environment or run the following to install into the builtin python environment ./python.sh -m pip install tensorboard"
)
exit()
# create isaac environment
from omni.isaac.gym.vec_env import VecEnvBase
env = VecEnvBase(headless=True)
# create task and register task
from cartpole_task import CartpoleTask
task = CartpoleTask(name="Cartpole")
env.set_task(task, backend="torch")
# create agent from stable baselines
model = PPO(
"MlpPolicy",
env,
n_steps=1000,
batch_size=1000,
n_epochs=20,
learning_rate=0.001,
gamma=0.99,
device="cuda:0",
ent_coef=0.0,
vf_coef=0.5,
max_grad_norm=1.0,
verbose=1,
tensorboard_log="./cartpole_tensorboard",
)
model.learn(total_timesteps=100000)
model.save("ppo_cartpole")
env.close()
| 1,721 | Python | 26.774193 | 190 | 0.732714 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.gym/cartpole_play.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# import stable baselines
import carb
try:
from stable_baselines3 import PPO
except Exception as e:
carb.log_error(e)
carb.log_error(
"please install stable-baselines3 in the current python environment or run the following to install into the builtin python environment ./python.sh -m pip install stable-baselines3 "
)
exit()
# create isaac environment
from omni.isaac.gym.vec_env import VecEnvBase
env = VecEnvBase(headless=False)
# create task and register task
from cartpole_task import CartpoleTask
task = CartpoleTask(name="Cartpole")
env.set_task(task, backend="torch")
# Run inference on the trained policy
model = PPO.load("ppo_cartpole")
env._world.reset()
obs, _ = env.reset()
while env._simulation_app.is_running():
action, _states = model.predict(obs)
obs, rewards, terminated, truncated, info = env.step(action)
env.close()
| 1,312 | Python | 30.261904 | 190 | 0.759909 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.gym/cartpole_task.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import math
import numpy as np
import omni.kit
import torch
from gymnasium import spaces
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.tasks.base_task import BaseTask
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import create_prim
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.utils.viewports import set_camera_view
class CartpoleTask(BaseTask):
def __init__(self, name, offset=None) -> None:
# task-specific parameters
self._cartpole_position = [0.0, 0.0, 2.0]
self._reset_dist = 3.0
self._max_push_effort = 400.0
# values used for defining RL buffers
self._num_observations = 4
self._num_actions = 1
self._device = "cpu"
self.num_envs = 1
# a few class buffers to store RL-related states
self.obs = torch.zeros((self.num_envs, self._num_observations))
self.resets = torch.zeros((self.num_envs, 1))
# set the action and observation space for RL
self.action_space = spaces.Box(
np.ones(self._num_actions, dtype=np.float32) * -1.0, np.ones(self._num_actions, dtype=np.float32) * 1.0
)
self.observation_space = spaces.Box(
np.ones(self._num_observations, dtype=np.float32) * -np.Inf,
np.ones(self._num_observations, dtype=np.float32) * np.Inf,
)
# trigger __init__ of parent class
BaseTask.__init__(self, name=name, offset=offset)
def set_up_scene(self, scene) -> None:
# retrieve file path for the Cartpole USD file
assets_root_path = get_assets_root_path()
usd_path = assets_root_path + "/Isaac/Robots/Cartpole/cartpole.usd"
# add the Cartpole USD to our stage
create_prim(prim_path="/World/Cartpole", prim_type="Xform", position=self._cartpole_position)
add_reference_to_stage(usd_path, "/World/Cartpole")
# Get stage handle
stage = omni.usd.get_context().get_stage()
if not stage:
print("Stage could not be used.")
else:
for prim in stage.Traverse():
prim_path = prim.GetPath()
prim_type = prim.GetTypeName()
print(f"prim_path: {prim_path}, prim_type: {prim_type}")
# create an ArticulationView wrapper for our cartpole - this can be extended towards accessing multiple cartpoles
self._cartpoles = ArticulationView(prim_paths_expr="/World/Cartpole*", name="cartpole_view")
# add Cartpole ArticulationView and ground plane to the Scene
scene.add(self._cartpoles)
scene.add_default_ground_plane()
# set default camera viewport position and target
self.set_initial_camera_params()
def set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]):
set_camera_view(eye=camera_position, target=camera_target, camera_prim_path="/OmniverseKit_Persp")
def post_reset(self):
self._cart_dof_idx = self._cartpoles.get_dof_index("cartJoint")
self._pole_dof_idx = self._cartpoles.get_dof_index("poleJoint")
# randomize all envs
indices = torch.arange(self._cartpoles.count, dtype=torch.int64, device=self._device)
self.reset(indices)
def reset(self, env_ids=None):
if env_ids is None:
env_ids = torch.arange(self.num_envs, device=self._device)
num_resets = len(env_ids)
# randomize DOF positions
dof_pos = torch.zeros((num_resets, self._cartpoles.num_dof), device=self._device)
dof_pos[:, self._cart_dof_idx] = 1.0 * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
dof_pos[:, self._pole_dof_idx] = 0.125 * math.pi * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
# randomize DOF velocities
dof_vel = torch.zeros((num_resets, self._cartpoles.num_dof), device=self._device)
dof_vel[:, self._cart_dof_idx] = 0.5 * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
dof_vel[:, self._pole_dof_idx] = 0.25 * math.pi * (1.0 - 2.0 * torch.rand(num_resets, device=self._device))
# apply resets
indices = env_ids.to(dtype=torch.int32)
self._cartpoles.set_joint_positions(dof_pos, indices=indices)
self._cartpoles.set_joint_velocities(dof_vel, indices=indices)
# bookkeeping
self.resets[env_ids] = 0
def pre_physics_step(self, actions) -> None:
reset_env_ids = self.resets.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset(reset_env_ids)
actions = torch.tensor(actions)
forces = torch.zeros((self._cartpoles.count, self._cartpoles.num_dof), dtype=torch.float32, device=self._device)
forces[:, self._cart_dof_idx] = self._max_push_effort * actions[0]
indices = torch.arange(self._cartpoles.count, dtype=torch.int32, device=self._device)
self._cartpoles.set_joint_efforts(forces, indices=indices)
def get_observations(self):
dof_pos = self._cartpoles.get_joint_positions()
dof_vel = self._cartpoles.get_joint_velocities()
# collect pole and cart joint positions and velocities for observation
cart_pos = dof_pos[:, self._cart_dof_idx]
cart_vel = dof_vel[:, self._cart_dof_idx]
pole_pos = dof_pos[:, self._pole_dof_idx]
pole_vel = dof_vel[:, self._pole_dof_idx]
self.obs[:, 0] = cart_pos
self.obs[:, 1] = cart_vel
self.obs[:, 2] = pole_pos
self.obs[:, 3] = pole_vel
return self.obs
def calculate_metrics(self) -> None:
cart_pos = self.obs[:, 0]
cart_vel = self.obs[:, 1]
pole_angle = self.obs[:, 2]
pole_vel = self.obs[:, 3]
# compute reward based on angle of pole and cart velocity
reward = 1.0 - pole_angle * pole_angle - 0.01 * torch.abs(cart_vel) - 0.005 * torch.abs(pole_vel)
# apply a penalty if cart is too far from center
reward = torch.where(torch.abs(cart_pos) > self._reset_dist, torch.ones_like(reward) * -2.0, reward)
# apply a penalty if pole is too far from upright
reward = torch.where(torch.abs(pole_angle) > np.pi / 2, torch.ones_like(reward) * -2.0, reward)
return reward.item()
def is_done(self) -> None:
cart_pos = self.obs[:, 0]
pole_pos = self.obs[:, 2]
# reset the robot if cart has reached reset_dist or pole is too far from upright
resets = torch.where(torch.abs(cart_pos) > self._reset_dist, 1, 0)
resets = torch.where(torch.abs(pole_pos) > math.pi / 2, 1, resets)
self.resets = resets
return resets.item()
| 7,209 | Python | 41.662722 | 121 | 0.636288 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.dofbot/pick_place.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import numpy as np
from omni.isaac.core import World
from omni.isaac.dofbot.controllers.pick_place_controller import PickPlaceController
from omni.isaac.dofbot.tasks import PickPlace
my_world = World(stage_units_in_meters=1.0)
my_task = PickPlace()
my_world.add_task(my_task)
my_world.reset()
task_params = my_task.get_params()
dofbot_name = task_params["robot_name"]["value"]
my_dofbot = my_world.scene.get_object(dofbot_name)
my_controller = PickPlaceController(
name="pick_place_controller", gripper=my_dofbot.gripper, robot_articulation=my_dofbot
)
articulation_controller = my_dofbot.get_articulation_controller()
i = 0
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
my_controller.reset()
observations = my_world.get_observations()
actions = my_controller.forward(
picking_position=observations[task_params["cube_name"]["value"]]["position"],
placing_position=observations[task_params["cube_name"]["value"]]["target_position"],
current_joint_positions=observations[dofbot_name]["joint_positions"],
end_effector_offset=np.array([0, -0.06, 0]),
)
if my_controller.is_done():
print("done picking and placing")
articulation_controller.apply_action(actions)
simulation_app.close()
| 1,954 | Python | 38.897958 | 96 | 0.72262 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.dofbot/follow_target_with_rmpflow.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.core import World
from omni.isaac.dofbot.controllers.rmpflow_controller import RMPFlowController
from omni.isaac.dofbot.tasks import FollowTarget
my_world = World(stage_units_in_meters=1.0)
my_task = FollowTarget(name="follow_target_task")
my_world.add_task(my_task)
my_world.reset()
task_params = my_world.get_task("follow_target_task").get_params()
dofbot_name = task_params["robot_name"]["value"]
target_name = task_params["target_name"]["value"]
my_dofbot = my_world.scene.get_object(dofbot_name)
my_controller = RMPFlowController(name="target_follower_controller", robot_articulation=my_dofbot)
articulation_controller = my_dofbot.get_articulation_controller()
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
my_controller.reset()
observations = my_world.get_observations()
actions = my_controller.forward(
target_end_effector_position=observations[target_name]["position"],
target_end_effector_orientation=observations[target_name]["orientation"],
)
articulation_controller.apply_action(actions)
simulation_app.close()
| 1,764 | Python | 42.048779 | 98 | 0.747732 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.dofbot/follow_target_with_ik.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import carb
import numpy as np
from omni.isaac.core import World
from omni.isaac.dofbot import KinematicsSolver
from omni.isaac.dofbot.controllers.rmpflow_controller import RMPFlowController
from omni.isaac.dofbot.tasks import FollowTarget
my_world = World(stage_units_in_meters=1.0)
my_task = FollowTarget(name="follow_target_task")
my_world.add_task(my_task)
my_world.reset()
task_params = my_world.get_task("follow_target_task").get_params()
dofbot_name = task_params["robot_name"]["value"]
target_name = task_params["target_name"]["value"]
my_dofbot = my_world.scene.get_object(dofbot_name)
my_controller = KinematicsSolver(my_dofbot)
articulation_controller = my_dofbot.get_articulation_controller()
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
observations = my_world.get_observations()
# IK does not work well on dofbot with orientation targets
actions, succ = my_controller.compute_inverse_kinematics(target_position=observations[target_name]["position"])
# actions,succ = my_controller.compute_inverse_kinematics(target_position=observations[target_name]["position"],
# target_orientation=observations[target_name]["orientation"], orientation_tolerance = np.pi/2)
if succ:
articulation_controller.apply_action(actions)
else:
carb.log_warn("IK did not converge to a solution. No action is being taken.")
simulation_app.close()
| 2,079 | Python | 43.255318 | 120 | 0.746513 |
2820207922/isaac_ws/standalone_examples/api/omni.kit.asset_converter/asset_usd_converter.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import argparse
import asyncio
import os
import omni
from omni.isaac.kit import SimulationApp
async def convert(in_file, out_file, load_materials=False):
# This import causes conflicts when global
import omni.kit.asset_converter
def progress_callback(progress, total_steps):
pass
converter_context = omni.kit.asset_converter.AssetConverterContext()
# setup converter and flags
converter_context.ignore_materials = not load_materials
# converter_context.ignore_animation = False
# converter_context.ignore_cameras = True
# converter_context.single_mesh = True
# converter_context.smooth_normals = True
# converter_context.preview_surface = False
# converter_context.support_point_instancer = False
# converter_context.embed_mdl_in_usd = False
# converter_context.use_meter_as_world_unit = True
# converter_context.create_world_as_default_root_prim = False
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(in_file, out_file, progress_callback, converter_context)
success = True
while True:
success = await task.wait_until_finished()
if not success:
await asyncio.sleep(0.1)
else:
break
return success
def asset_convert(args):
supported_file_formats = ["stl", "obj", "fbx"]
for folder in args.folders:
local_asset_output = folder + "_converted"
result = omni.client.create_folder(f"{local_asset_output}")
for folder in args.folders:
print(f"\nConverting folder {folder}...")
(result, models) = omni.client.list(folder)
for i, entry in enumerate(models):
if i >= args.max_models:
print(f"max models ({args.max_models}) reached, exiting conversion")
break
model = str(entry.relative_path)
model_name = os.path.splitext(model)[0]
model_format = (os.path.splitext(model)[1])[1:]
# Supported input file formats
if model_format in supported_file_formats:
input_model_path = folder + "/" + model
converted_model_path = folder + "_converted/" + model_name + "_" + model_format + ".usd"
if not os.path.exists(converted_model_path):
status = asyncio.get_event_loop().run_until_complete(
convert(input_model_path, converted_model_path, True)
)
if not status:
print(f"ERROR Status is {status}")
print(f"---Added {converted_model_path}")
if __name__ == "__main__":
kit = SimulationApp()
from omni.isaac.core.utils.extensions import enable_extension
enable_extension("omni.kit.asset_converter")
parser = argparse.ArgumentParser("Convert OBJ/STL assets to USD")
parser.add_argument(
"--folders", type=str, nargs="+", default=None, help="List of folders to convert (space seperated)."
)
parser.add_argument(
"--max-models", type=int, default=50, help="If specified, convert up to `max-models` per folder."
)
parser.add_argument(
"--load-materials", action="store_true", help="If specified, materials will be loaded from meshes"
)
args, unknown_args = parser.parse_known_args()
if args.folders is not None:
# Ensure Omniverse Kit is launched via SimulationApp before asset_convert() is called
asset_convert(args)
else:
print(f"No folders specified via --folders argument, exiting")
# cleanup
kit.close()
| 4,049 | Python | 36.850467 | 108 | 0.652013 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.cloner/clone_ants.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import sys
import carb
import numpy as np
from omni.isaac.cloner import GridCloner
from omni.isaac.core import World
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
my_world = World(stage_units_in_meters=1.0)
my_world.scene.add_default_ground_plane()
# create initial robot
asset_path = assets_root_path + "/Isaac/Robots/Ant/ant.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/Ants/Ant_0")
# create GridCloner instance
cloner = GridCloner(spacing=2)
# generate paths for clones
target_paths = cloner.generate_paths("/World/Ants/Ant", 4)
# clone
position_offsets = np.array([[0, 0, 1]] * 4)
cloner.clone(
source_prim_path="/World/Ants/Ant_0",
prim_paths=target_paths,
position_offsets=position_offsets,
replicate_physics=True,
base_env_path="/World/Ants",
)
# create ArticulationView
ants = ArticulationView(prim_paths_expr="/World/Ants/.*/torso", name="ants_view")
my_world.scene.add(ants)
my_world.reset()
for i in range(1000):
print(ants.get_world_poses())
my_world.step()
simulation_app.close()
| 1,909 | Python | 29.806451 | 81 | 0.756417 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.kit/load_stage.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import argparse
import sys
import carb
import omni
from omni.isaac.kit import SimulationApp
# This sample loads a usd stage and starts simulation
CONFIG = {"width": 1280, "height": 720, "sync_loads": True, "headless": False, "renderer": "RayTracedLighting"}
# Set up command line arguments
parser = argparse.ArgumentParser("Usd Load sample")
parser.add_argument(
"--usd_path", type=str, help="Path to usd file, should be relative to your default assets folder", required=True
)
parser.add_argument("--headless", default=False, action="store_true", help="Run stage headless")
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
# Start the omniverse application
CONFIG["headless"] = args.headless
kit = SimulationApp(launch_config=CONFIG)
# Locate Isaac Sim assets folder to load sample
from omni.isaac.core.utils.nucleus import get_assets_root_path, is_file
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
kit.close()
sys.exit()
usd_path = assets_root_path + args.usd_path
# make sure the file exists before we try to open it
try:
result = is_file(usd_path)
except:
result = False
if result:
omni.usd.get_context().open_stage(usd_path)
else:
carb.log_error(
f"the usd path {usd_path} could not be opened, please make sure that {args.usd_path} is a valid usd file in {assets_root_path}"
)
kit.close()
sys.exit()
# Wait two frames so that stage starts loading
kit.update()
kit.update()
print("Loading stage...")
from omni.isaac.core.utils.stage import is_stage_loading
while is_stage_loading():
kit.update()
print("Loading Complete")
omni.timeline.get_timeline_interface().play()
# Run in test mode, exit after a fixed number of steps
if args.test is True:
for i in range(10):
# Run in realtime mode, we don't specify the step size
kit.update()
else:
while kit.is_running():
# Run in realtime mode, we don't specify the step size
kit.update()
omni.timeline.get_timeline_interface().stop()
kit.close()
| 2,599 | Python | 31.5 | 135 | 0.727972 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.kit/hello_world.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni
from omni.isaac.kit import SimulationApp
# The most basic usage for creating a simulation app
kit = SimulationApp()
for i in range(100):
kit.update()
omni.kit.app.get_app().print_and_log("Hello World!")
kit.close() # Cleanup application
| 690 | Python | 30.40909 | 76 | 0.781159 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.kit/change_resolution.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import random
from omni.isaac.kit import SimulationApp
# Simple example showing how to change resolution
kit = SimulationApp({"headless": True})
kit.update()
for i in range(100):
width = random.randint(128, 1980)
height = random.randint(128, 1980)
kit.set_setting("/app/renderer/resolution/width", width)
kit.set_setting("/app/renderer/resolution/height", height)
kit.update()
print(f"resolution set to: {width}, {height}")
# cleanup
kit.close()
| 905 | Python | 32.555554 | 76 | 0.758011 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/add_cubes.py | # Copyright (c) 2021-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 numpy as np
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid, VisualCuboid
my_world = World(stage_units_in_meters=1.0)
cube_1 = my_world.scene.add(
VisualCuboid(
prim_path="/new_cube_1",
name="visual_cube",
position=np.array([0, 0, 0.5]),
size=0.3,
color=np.array([255, 255, 255]),
)
)
cube_2 = my_world.scene.add(
DynamicCuboid(
prim_path="/new_cube_2",
name="cube_1",
position=np.array([0, 0, 1.0]),
scale=np.array([0.6, 0.5, 0.2]),
size=1.0,
color=np.array([255, 0, 0]),
)
)
cube_3 = my_world.scene.add(
DynamicCuboid(
prim_path="/new_cube_3",
name="cube_2",
position=np.array([0, 0, 3.0]),
scale=np.array([0.1, 0.1, 0.1]),
size=1.0,
color=np.array([0, 0, 255]),
linear_velocity=np.array([0, 0, 0.4]),
)
)
my_world.scene.add_default_ground_plane()
for i in range(5):
my_world.reset()
for i in range(500):
my_world.step(render=True)
print(cube_2.get_angular_velocity())
print(cube_2.get_world_pose())
simulation_app.close()
| 1,702 | Python | 26.031746 | 76 | 0.63631 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/cloth.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import sys
import carb
import numpy as np
import torch
from omni.isaac.core import World
from omni.isaac.core.materials.particle_material import ParticleMaterial
from omni.isaac.core.prims.soft.cloth_prim import ClothPrim
from omni.isaac.core.prims.soft.cloth_prim_view import ClothPrimView
from omni.isaac.core.prims.soft.particle_system import ParticleSystem
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.physx.scripts import deformableUtils, physicsUtils
from pxr import Gf, UsdGeom
# The example shows how to create and manipulate environments with particle cloth through the ClothPrimView
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
class ParticleClothExample:
def __init__(self):
self._array_container = torch.Tensor
self.my_world = World(stage_units_in_meters=1.0, backend="torch", device="cuda")
self.stage = simulation_app.context.get_stage()
self.num_envs = 10
self.dimx = 5
self.dimy = 5
self.my_world.scene.add_default_ground_plane()
self.initial_positions = None
self.makeEnvs()
def makeEnvs(self):
for i in range(self.num_envs):
env_path = "/World/Env" + str(i)
env = UsdGeom.Xform.Define(self.stage, env_path)
# set up the geometry
cloth_path = env.GetPrim().GetPath().AppendChild("cloth")
plane_mesh = UsdGeom.Mesh.Define(self.stage, cloth_path)
tri_points, tri_indices = deformableUtils.create_triangle_mesh_square(dimx=5, dimy=5, scale=1.0)
if self.initial_positions is None:
self.initial_positions = torch.zeros((self.num_envs, len(tri_points), 3))
plane_mesh.GetPointsAttr().Set(tri_points)
plane_mesh.GetFaceVertexIndicesAttr().Set(tri_indices)
plane_mesh.GetFaceVertexCountsAttr().Set([3] * (len(tri_indices) // 3))
init_loc = Gf.Vec3f(i * 2, 0.0, 2.0)
physicsUtils.setup_transform_as_scale_orient_translate(plane_mesh)
physicsUtils.set_or_add_translate_op(plane_mesh, init_loc)
physicsUtils.set_or_add_orient_op(plane_mesh, Gf.Rotation(Gf.Vec3d([1, 0, 0]), 15 * i).GetQuat())
self.initial_positions[i] = torch.tensor(init_loc) + torch.tensor(plane_mesh.GetPointsAttr().Get())
particle_system_path = env.GetPrim().GetPath().AppendChild("particleSystem")
particle_material_path = env.GetPrim().GetPath().AppendChild("particleMaterial")
self.particle_material = ParticleMaterial(
prim_path=particle_material_path, drag=0.1, lift=0.3, friction=0.6
)
radius = 0.5 * (0.6 / 5.0)
restOffset = radius
contactOffset = restOffset * 1.5
self.particle_system = ParticleSystem(
prim_path=particle_system_path,
simulation_owner=self.my_world.get_physics_context().prim_path,
rest_offset=restOffset,
contact_offset=contactOffset,
solid_rest_offset=restOffset,
fluid_rest_offset=restOffset,
particle_contact_offset=contactOffset,
)
# note that no particle material is applied to the particle system at this point.
# this can be done manually via self.particle_system.apply_particle_material(self.particle_material)
# or to pass the material to the clothPrim which binds it internally to the particle system
self.cloth = ClothPrim(
name="clothPrim" + str(i),
prim_path=str(cloth_path),
particle_system=self.particle_system,
particle_material=self.particle_material,
)
self.my_world.scene.add(self.cloth)
# create a view to deal with all the cloths
self.clothView = ClothPrimView(prim_paths_expr="/World/Env*/cloth", name="clothView1")
self.my_world.scene.add(self.clothView)
self.my_world.reset(soft=False)
def play(self):
while simulation_app.is_running():
if self.my_world.is_playing():
# deal with sim re-initialization after restarting sim
if self.my_world.current_time_step_index == 0:
# initialize simulation views
self.my_world.reset(soft=False)
self.my_world.step(render=True)
if self.my_world.current_time_step_index % 50 == 1:
for i in range(self.num_envs):
print(
"cloth {} average height = {:.2f}".format(
i, self.clothView.get_world_positions()[i, :, 2].mean()
)
)
# reset some random environments
if self.my_world.current_time_step_index % 200 == 1:
indices = torch.tensor(
np.random.choice(range(self.num_envs), self.num_envs // 2, replace=False), dtype=torch.long
)
new_positions = self.initial_positions[indices] + torch.tensor([0, 0, 5])
self.clothView.set_world_positions(new_positions, indices)
updated_positions = self.clothView.get_world_positions()
for i in indices:
print("reset index {} average height = {:.2f}".format(i, updated_positions[i, :, 2].mean()))
simulation_app.close()
ParticleClothExample().play()
| 6,331 | Python | 45.558823 | 112 | 0.632128 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/add_frankas.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import sys
import carb
import numpy as np
from omni.isaac.core import World
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units
from omni.isaac.core.utils.types import ArticulationAction
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
my_world = World(stage_units_in_meters=1.0)
my_world.scene.add_default_ground_plane()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/Franka_1")
add_reference_to_stage(usd_path=asset_path, prim_path="/World/Franka_2")
articulated_system_1 = my_world.scene.add(Robot(prim_path="/World/Franka_1", name="my_franka_1"))
articulated_system_2 = my_world.scene.add(Robot(prim_path="/World/Franka_2", name="my_franka_2"))
for i in range(5):
print("resetting...")
my_world.reset()
articulated_system_1.set_world_pose(position=np.array([0.0, 2.0, 0.0]) / get_stage_units())
articulated_system_2.set_world_pose(position=np.array([0.0, -2.0, 0.0]) / get_stage_units())
articulated_system_1.set_joint_positions(np.array([1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5]))
for j in range(500):
my_world.step(render=True)
if j == 100:
articulated_system_2.get_articulation_controller().apply_action(
ArticulationAction(joint_positions=np.array([1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5]))
)
if j == 400:
print("Franka 1's joint positions are: ", articulated_system_1.get_joint_positions())
print("Franka 2's joint positions are: ", articulated_system_2.get_joint_positions())
if args.test is True:
break
simulation_app.close()
| 2,637 | Python | 41.548386 | 107 | 0.711794 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/simulation_callbacks.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": True})
from omni.isaac.core import SimulationContext
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
assets_root_path = get_assets_root_path()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
simulation_context = SimulationContext()
add_reference_to_stage(asset_path, "/Franka")
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
art = Articulation("/Franka")
art.initialize()
dof_ptr = art.get_dof_index("panda_joint2")
simulation_context.play()
def step_callback_1(step_size):
art.set_joint_positions([-1.5], [dof_ptr])
return
def step_callback_2(step_size):
print(
"Current joint 2 position @ step "
+ str(simulation_context.current_time_step_index)
+ " : "
+ str(art.get_joint_positions([dof_ptr])[0])
)
print("TIME: ", simulation_context.current_time)
return
def render_callback(event):
print("Render Frame")
simulation_context.add_physics_callback("physics_callback_1", step_callback_1)
simulation_context.add_physics_callback("physics_callback_2", step_callback_2)
simulation_context.add_render_callback("render_callback", render_callback)
# Simulate 60 timesteps
for i in range(60):
print("step", i)
simulation_context.step(render=False)
# Render one frame
simulation_context.render()
simulation_context.stop()
simulation_app.close()
| 2,052 | Python | 30.10606 | 78 | 0.752437 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/data_logging.py | # Copyright (c) 2021-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 sys
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import carb
from omni.isaac.core import World
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
my_world = World(stage_units_in_meters=1.0)
my_world.scene.add_default_ground_plane()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/Franka_1")
articulated_system_1 = my_world.scene.add(Robot(prim_path="/World/Franka_1", name="my_franka_1"))
my_world.reset()
data_logger = my_world.get_data_logger()
def frame_logging_func(tasks, scene):
return {
"joint_positions": scene.get_object("my_franka_1").get_joint_positions().tolist(),
"applied_joint_positions": scene.get_object("my_franka_1").get_applied_action().joint_positions.tolist(),
}
data_logger.add_data_frame_logging_func(frame_logging_func)
data_logger.start()
for j in range(100):
my_world.step(render=True)
data_logger.save(log_path="./isaac_sim_data.json")
data_logger.reset()
data_logger.load(log_path="./isaac_sim_data.json")
print(data_logger.get_data_frame(data_frame_index=2))
simulation_app.close()
| 1,922 | Python | 32.736842 | 113 | 0.752341 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/deformable.py | from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import sys
import carb
import numpy as np
import omni.isaac.core.utils.deformable_mesh_utils as deformableMeshUtils
import torch
from omni.isaac.core import World
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.isaac.core.utils.nucleus import get_assets_root_path
from omni.physx.scripts import deformableUtils, physicsUtils
from pxr import Gf, UsdGeom, UsdLux
# The example shows how to create and manipulate environments with deformable deformable through the DeformablePrimView
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
class DeformableExample:
def __init__(self):
self._array_container = torch.Tensor
self.my_world = World(stage_units_in_meters=1.0, backend="torch", device="cuda")
self.stage = simulation_app.context.get_stage()
self.num_envs = 10
self.dimx = 5
self.dimy = 5
self.my_world.scene.add_default_ground_plane()
self.initial_positions = None
self.makeEnvs()
def makeEnvs(self):
for i in range(self.num_envs):
init_loc = Gf.Vec3f(i * 2 - self.num_envs, 0.0, 0.0)
env_scope = UsdGeom.Scope.Define(self.stage, "/World/Envs")
env_path = "/World/Envs/Env" + str(i)
env = UsdGeom.Xform.Define(self.stage, env_path)
physicsUtils.set_or_add_translate_op(UsdGeom.Xformable(env), init_loc)
mesh_path = env.GetPrim().GetPath().AppendChild("deformable")
skin_mesh = UsdGeom.Mesh.Define(self.stage, mesh_path)
tri_points, tri_indices = deformableMeshUtils.createTriangleMeshCube(8)
skin_mesh.GetPointsAttr().Set(tri_points)
skin_mesh.GetFaceVertexIndicesAttr().Set(tri_indices)
skin_mesh.GetFaceVertexCountsAttr().Set([3] * (len(tri_indices) // 3))
physicsUtils.setup_transform_as_scale_orient_translate(skin_mesh)
physicsUtils.set_or_add_translate_op(skin_mesh, (0.0, 0.0, 2.0))
physicsUtils.set_or_add_orient_op(skin_mesh, Gf.Rotation(Gf.Vec3d([1, 0, 0]), 15 * i).GetQuat())
deformable_material_path = env.GetPrim().GetPath().AppendChild("deformableMaterial")
self.deformable_material = DeformableMaterial(
prim_path=deformable_material_path,
dynamic_friction=0.5,
youngs_modulus=5e4,
poissons_ratio=0.4,
damping_scale=0.1,
elasticity_damping=0.1,
)
self.deformable = DeformablePrim(
name="deformablePrim" + str(i),
prim_path=str(mesh_path),
deformable_material=self.deformable_material,
vertex_velocity_damping=0.0,
sleep_damping=1.0,
sleep_threshold=0.05,
settling_threshold=0.1,
self_collision=True,
self_collision_filter_distance=0.05,
solver_position_iteration_count=20,
kinematic_enabled=False,
simulation_hexahedral_resolution=2,
collision_simplification=True,
)
self.my_world.scene.add(self.deformable)
# create a view to deal with all the deformables
self.deformableView = DeformablePrimView(prim_paths_expr="/World/Envs/Env*/deformable", name="deformableView1")
self.my_world.scene.add(self.deformableView)
self.my_world.reset(soft=False)
# mesh data is available only after cooking
# rest_points are represented with respect to the env positions, but simulation_mesh_nodal_positions can be either global or local positions
# However, because we don't currently consider subspace root path with World/SimulationContext initialization, the environment xforms are not identified
# below and the following call will be positions w.r.t to a global frame.
self.initial_positions = self.deformableView.get_simulation_mesh_nodal_positions().cpu()
self.initial_velocities = self.deformableView.get_simulation_mesh_nodal_velocities().cpu()
# print(self.initial_positions)
# self.initial_positions = self.deformableView.get_simulation_mesh_rest_points().cpu()
# for i in range(self.num_envs):
# self.initial_positions[i] += torch.tensor([i * 2, 0.0, 2.0])
# print(self.initial_positions[i])
def play(self):
while simulation_app.is_running():
if self.my_world.is_playing():
# deal with sim re-initialization after restarting sim
if self.my_world.current_time_step_index == 1:
# initialize simulation views
self.my_world.reset(soft=False)
self.my_world.step(render=True)
if self.my_world.current_time_step_index == 200:
for i in range(self.num_envs):
print(
"deformable {} average height = {:.2f}".format(
i, self.deformableView.get_simulation_mesh_nodal_positions()[i, :, 2].mean()
)
)
print(
"deformable {} average vertical speed = {:.2f}".format(
i, self.deformableView.get_simulation_mesh_nodal_velocities()[i, :, 2].mean()
)
)
# reset some random environments
if self.my_world.current_time_step_index % 500 == 1:
indices = torch.tensor(
np.random.choice(range(self.num_envs), self.num_envs // 2, replace=False), dtype=torch.long
)
new_positions = self.initial_positions[indices] + torch.tensor([0, 0, 5])
new_velocities = self.initial_velocities[indices] + torch.tensor([0, 0, 3])
self.deformableView.set_simulation_mesh_nodal_positions(new_positions, indices)
self.deformableView.set_simulation_mesh_nodal_velocities(new_velocities, indices)
updated_positions = self.deformableView.get_simulation_mesh_nodal_positions()
updated_velocities = self.deformableView.get_simulation_mesh_nodal_velocities()
for i in indices:
print("reset index {} average height = {:.2f}".format(i, updated_positions[i, :, 2].mean()))
print(
"reset index {} average vertical speed = {:.2f}".format(i, updated_velocities[i, :, 2].mean())
)
simulation_app.close()
DeformableExample().play()
| 7,196 | Python | 47.959183 | 160 | 0.617982 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/visual_materials.py | # Copyright (c) 2021-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 numpy as np
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import random
import sys
import carb
from omni.isaac.core import World
from omni.isaac.core.materials.omni_glass import OmniGlass
from omni.isaac.core.materials.omni_pbr import OmniPBR
from omni.isaac.core.objects import VisualCuboid
from omni.isaac.core.utils.nucleus import get_assets_root_path
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
asset_path = assets_root_path + "/Isaac/Materials/Textures/Synthetic/bubbles_2.png"
my_world = World(stage_units_in_meters=1.0)
textured_material = OmniPBR(
prim_path="/World/visual_cube_material",
name="omni_pbr",
color=np.array([1, 0, 0]),
texture_path=asset_path,
texture_scale=[1.0, 1.0],
texture_translate=[0.5, 0],
)
glass = OmniGlass(
prim_path=f"/World/visual_cube_material_2",
ior=1.25,
depth=0.001,
thin_walled=False,
color=np.array([random.random(), random.random(), random.random()]),
)
cube_1 = my_world.scene.add(
VisualCuboid(
prim_path="/new_cube_1",
name="visual_cube",
position=np.array([0, 0, 0.5]),
size=1.0,
color=np.array([255, 255, 255]),
visual_material=textured_material,
)
)
cube_2 = my_world.scene.add(
VisualCuboid(
prim_path="/new_cube_2",
name="visual_cube_2",
position=np.array([2, 0.39, 0.5]),
size=1.0,
color=np.array([255, 255, 255]),
visual_material=glass,
)
)
visual_material = cube_2.get_applied_visual_material()
visual_material.set_color(np.array([1.0, 0.5, 0.0]))
my_world.scene.add_default_ground_plane()
my_world.reset()
for i in range(10000):
my_world.step(render=True)
if args.test is True:
break
simulation_app.close()
| 2,549 | Python | 27.333333 | 90 | 0.695175 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/time_stepping.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": True})
from omni.isaac.core import SimulationContext
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
assets_root_path = get_assets_root_path()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
simulation_context = SimulationContext(stage_units_in_meters=1.0)
add_reference_to_stage(asset_path, "/Franka")
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
def step_callback(step_size):
print("simulate with step: ", step_size)
return
def render_callback(event):
print("update app with step: ", event.payload["dt"])
simulation_context.add_physics_callback("physics_callback", step_callback)
simulation_context.add_render_callback("render_callback", render_callback)
simulation_context.stop()
simulation_context.play()
print("step physics once with a step size of 1/60 second, these are the default settings")
simulation_context.step(render=False)
print("step physics & rendering once with a step size of 1/60 second, these are the default settings")
simulation_context.step(render=True)
print("step physics & rendering once with a step size of 1/60 second")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=1.0 / 60.0)
simulation_context.step(render=True)
print("step physics 10 steps at a 1/600s per step and rendering at 1.0/60s")
simulation_context.set_simulation_dt(physics_dt=1.0 / 600.0, rendering_dt=1.0 / 60.0)
simulation_context.step(render=True)
print("step physics once at 600Hz without rendering")
simulation_context.set_simulation_dt(physics_dt=1.0 / 600.0, rendering_dt=1.0 / 60.0)
simulation_context.step(render=False)
print("step physics 10 steps at a 1/600s per step and rendering at 1.0/60s")
simulation_context.set_simulation_dt(physics_dt=1.0 / 600.0, rendering_dt=1.0 / 60.0)
for step in range(10):
simulation_context.step(render=False)
simulation_context.render()
print("render a frame, moving editor timeline forward by 1.0/60s, physics does not simulate")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=1.0 / 60.0)
simulation_context.render()
print("render a frame, moving editor timeline forward by 1.0/60s, physics does not simulate")
simulation_context.set_simulation_dt(physics_dt=0.0, rendering_dt=1.0 / 60)
simulation_context.step(render=True)
print("step physics once 1/60s per step and rendering 10 times at 1.0/600s")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=1.0 / 600.0)
for step in range(10):
simulation_context.step(render=True)
print("step physics once 1/60s per step and rendering once at 1.0/600s by explicitly calling step and render")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=1.0 / 600.0)
simulation_context.step(render=False)
simulation_context.render()
print("step physics once 1/60s per step, rendering a frame does not move editor timeline forward")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=0.0)
simulation_context.step(render=False)
simulation_context.render()
print("step physics once 1/60s per step, rendering a frame does not move editor timeline forward")
simulation_context.set_simulation_dt(physics_dt=1.0 / 60.0, rendering_dt=0.0)
simulation_context.step(render=True)
print("render a new frame with simulation stopped, editor timeline does not move forward")
simulation_context.stop()
simulation_context.render()
print("cleanup and exit")
simulation_context.stop()
simulation_app.close()
| 4,101 | Python | 40.434343 | 110 | 0.774201 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/control_robot.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.core import SimulationContext
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
assets_root_path = get_assets_root_path()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
simulation_context = SimulationContext()
add_reference_to_stage(asset_path, "/Franka")
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
art = Articulation("/Franka")
art.initialize()
dof_ptr = art.get_dof_index("panda_joint2")
simulation_context.play()
# NOTE: before interacting with dc directly you need to step physics for one step at least
# simulation_context.step(render=True) which happens inside .play()
for i in range(1000):
art.set_joint_positions([-1.5], [dof_ptr])
simulation_context.step(render=True)
simulation_context.stop()
simulation_app.close()
| 1,500 | Python | 36.524999 | 90 | 0.786667 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/rigid_contact_view.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import numpy as np
import torch
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.prims.geometry_prim import GeometryPrim
from omni.isaac.core.prims.geometry_prim_view import GeometryPrimView
from omni.isaac.core.prims.rigid_prim_view import RigidPrimView
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
class RigidViewExample:
def __init__(self):
self._array_container = torch.Tensor
self.my_world = World(stage_units_in_meters=1.0, backend="torch")
self.stage = simulation_app.context.get_stage()
def makeEnv(self):
self.cube_height = 1.0
self.top_cube_height = self.cube_height + 3.0
self.cube_dx = 5.0
self.cube_y = 2.0
self.top_cube_y = self.cube_y + 0.0
self.my_world._physics_context.set_gravity(-10)
self.my_world.scene.add_default_ground_plane()
for i in range(3):
DynamicCuboid(
prim_path=f"/World/Box_{i+1}", name=f"box_{i}", size=1.0, color=np.array([0.5, 0, 0]), mass=1.0
)
DynamicCuboid(
prim_path=f"/World/TopBox_{i+1}",
name=f"top_box_{i}",
size=1.0,
color=np.array([0.0, 0.0, 0.5]),
mass=1.0,
)
# add top box as filters to the view to receive contacts between the bottom boxes and top boxes
self._box_view = RigidPrimView(
prim_paths_expr="/World/Box_*",
name="box_view",
positions=self._array_container(
[
[0, self.cube_y, self.cube_height],
[-self.cube_dx, self.cube_y, self.cube_height],
[self.cube_dx, self.cube_y, self.cube_height],
]
),
contact_filter_prim_paths_expr=["/World/TopBox_*"],
)
# a view just to manipulate the top boxes
self._top_box_view = RigidPrimView(
prim_paths_expr="/World/TopBox_*",
name="top_box_view",
positions=self._array_container(
[
[0.0, self.top_cube_y, self.top_cube_height],
[-self.cube_dx, self.top_cube_y, self.top_cube_height],
[self.cube_dx, self.top_cube_y, self.top_cube_height],
]
),
track_contact_forces=True,
)
# can get contact forces with non-rigid body prims such as geometry prims either via the single prim class GeometryPrim, or the view class GeometryPrimView
self._geom_prim = GeometryPrim(
prim_path="/World/defaultGroundPlane",
name="groundPlane",
collision=True,
track_contact_forces=True,
prepare_contact_sensor=True,
contact_filter_prim_paths_expr=["/World/Box_1", "/World/Box_2"],
)
self._geom_view = GeometryPrimView(
prim_paths_expr="/World/defaultGroundPlane*",
name="groundPlaneView",
collisions=self._array_container([True]),
track_contact_forces=True,
prepare_contact_sensors=True,
contact_filter_prim_paths_expr=["/World/Box_1", "/World/Box_2", "/World/Box_3"],
)
self.my_world.scene.add(self._box_view)
self.my_world.scene.add(self._top_box_view)
self.my_world.scene.add(self._geom_prim)
self.my_world.scene.add(self._geom_view)
self.my_world.reset(soft=False)
def play(self):
self.makeEnv()
while simulation_app.is_running():
if self.my_world.is_playing():
# deal with sim re-initialization after restarting sim
if self.my_world.current_time_step_index == 0:
# initialize simulation views
self.my_world.reset(soft=False)
self.my_world.step(render=True)
if self.my_world.current_time_step_index % 100 == 1:
states = self._box_view.get_current_dynamic_state()
top_states = self._top_box_view.get_current_dynamic_state()
net_forces = self._box_view.get_net_contact_forces(None, dt=1 / 60)
forces_matrix = self._box_view.get_contact_force_matrix(None, dt=1 / 60)
top_net_forces = self._top_box_view.get_net_contact_forces(None, dt=1 / 60)
print("==================================================================")
print("Bottom box net forces: \n", net_forces)
print("Top box net forces: \n", top_net_forces)
print("Bottom box forces from top ones: \n", forces_matrix)
print("Bottom box positions: \n", states.positions)
print("Top box positions: \n", top_states.positions)
print("Bottom box velocities: \n", states.linear_velocities)
print("Top box velocities: \n", top_states.linear_velocities)
print("ground net force from GeometryPrimView : \n", self._geom_view.get_net_contact_forces(dt=1 / 60))
print(
"ground force matrix from GeometryPrimView: \n", self._geom_view.get_contact_force_matrix(dt=1 / 60)
)
print("ground net force from GeometryPrim : \n", self._geom_prim.get_net_contact_forces(dt=1 / 60))
print("ground force matrix from GeometryPrim: \n", self._geom_prim.get_contact_force_matrix(dt=1 / 60))
simulation_app.close()
RigidViewExample().play()
| 6,241 | Python | 42.347222 | 163 | 0.585002 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.core/simulate_robot.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
from omni.isaac.core import SimulationContext
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import create_prim
from omni.isaac.core.utils.stage import add_reference_to_stage, is_stage_loading
assets_root_path = get_assets_root_path()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
simulation_context = SimulationContext()
add_reference_to_stage(asset_path, "/Franka")
create_prim("/DistantLight", "DistantLight")
# wait for things to load
simulation_app.update()
while is_stage_loading():
simulation_app.update()
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
simulation_context.play()
for i in range(1000):
simulation_context.step(render=True)
simulation_context.stop()
simulation_app.close()
| 1,366 | Python | 34.973683 | 80 | 0.791362 |
2820207922/isaac_ws/standalone_examples/api/omni.replicator.isaac/randomization_demo.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import carb
import numpy as np
from omni.isaac.cloner import GridCloner
from omni.isaac.core import World
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.prims.rigid_prim_view import RigidPrimView
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import define_prim, get_prim_at_path
from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage
# create the world
world = World(stage_units_in_meters=1.0, physics_prim_path="/physicsScene", backend="numpy")
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder, closing app..")
simulation_app.close()
usd_path = assets_root_path + "/Isaac/Environments/Grid/default_environment.usd"
add_reference_to_stage(usd_path=usd_path, prim_path="/World/defaultGroundPlane")
# set up grid cloner
cloner = GridCloner(spacing=1.5)
cloner.define_base_env("/World/envs")
define_prim("/World/envs/env_0")
# set up the first environment
DynamicSphere(prim_path="/World/envs/env_0/object", radius=0.1, position=np.array([0.75, 0.0, 0.2]))
add_reference_to_stage(
usd_path=assets_root_path + "/Isaac/Robots/Franka/franka.usd", prim_path="/World/envs/env_0/franka"
)
# clone environments
num_envs = 4
prim_paths = cloner.generate_paths("/World/envs/env", num_envs)
env_pos = cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=prim_paths)
# creates the views and set up world
object_view = RigidPrimView(prim_paths_expr="/World/envs/*/object", name="object_view")
franka_view = ArticulationView(prim_paths_expr="/World/envs/*/franka", name="franka_view")
world.scene.add(object_view)
world.scene.add(franka_view)
world.reset()
num_dof = franka_view.num_dof
import omni.replicator.core as rep
# set up randomization with omni.replicator.isaac, imported as dr
import omni.replicator.isaac as dr
dr.physics_view.register_simulation_context(world)
dr.physics_view.register_rigid_prim_view(object_view)
dr.physics_view.register_articulation_view(franka_view)
with dr.trigger.on_rl_frame(num_envs=num_envs):
with dr.gate.on_interval(interval=20):
dr.physics_view.randomize_simulation_context(
operation="scaling", gravity=rep.distribution.uniform((1, 1, 0.0), (1, 1, 2.0))
)
with dr.gate.on_interval(interval=50):
dr.physics_view.randomize_rigid_prim_view(
view_name=object_view.name, operation="direct", force=rep.distribution.uniform((0, 0, 2.5), (0, 0, 5.0))
)
with dr.gate.on_interval(interval=10):
dr.physics_view.randomize_articulation_view(
view_name=franka_view.name,
operation="direct",
joint_velocities=rep.distribution.uniform(tuple([-2] * num_dof), tuple([2] * num_dof)),
)
with dr.gate.on_env_reset():
dr.physics_view.randomize_rigid_prim_view(
view_name=object_view.name,
operation="additive",
position=rep.distribution.normal((0.0, 0.0, 0.0), (0.2, 0.2, 0.0)),
velocity=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
)
dr.physics_view.randomize_articulation_view(
view_name=franka_view.name,
operation="additive",
joint_positions=rep.distribution.uniform(tuple([-0.5] * num_dof), tuple([0.5] * num_dof)),
position=rep.distribution.normal((0.0, 0.0, 0.0), (0.2, 0.2, 0.0)),
)
frame_idx = 0
while simulation_app.is_running():
if world.is_playing():
reset_inds = list()
if frame_idx % 200 == 0:
# triggers reset every 200 steps
reset_inds = np.arange(num_envs)
dr.physics_view.step_randomization(reset_inds)
world.step(render=True)
frame_idx += 1
simulation_app.close()
| 4,393 | Python | 38.945454 | 116 | 0.700433 |
2820207922/isaac_ws/standalone_examples/api/omni.kit.app/app_framework.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.kit.app
from omni.isaac.kit import AppFramework
argv = [
"--empty",
"--ext-folder",
f'{os.path.abspath(os.environ["ISAAC_PATH"])}/exts',
"--no-window",
"--/app/asyncRendering=False",
"--/app/fastShutdown=True",
"--enable",
"omni.usd",
"--enable",
"omni.kit.uiapp",
]
# startup
app = AppFramework("test_app", argv)
import omni.usd
stage_task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
while not stage_task.done():
app.update()
print("exiting")
app.close()
| 997 | Python | 23.949999 | 76 | 0.711133 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.dynamic_control/franka_articulation.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import sys
import carb
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": True})
# This sample loads an articulation and prints its information
import omni
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.dynamic_control import _dynamic_control
stage = simulation_app.context.get_stage()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
omni.usd.get_context().open_stage(asset_path)
# start simulation
omni.timeline.get_timeline_interface().play()
# perform timestep
simulation_app.update()
dc = _dynamic_control.acquire_dynamic_control_interface()
# Get handle to articulation
art = dc.get_articulation("/panda")
if art == _dynamic_control.INVALID_HANDLE:
print("*** '%s' is not an articulation" % "/panda")
else:
# Print information about articulation
root = dc.get_articulation_root_body(art)
print(str("Got articulation handle %d \n" % art) + str("--- Hierarchy\n"))
body_states = dc.get_articulation_body_states(art, _dynamic_control.STATE_ALL)
print(str("--- Body states:\n") + str(body_states) + "\n")
dof_states = dc.get_articulation_dof_states(art, _dynamic_control.STATE_ALL)
print(str("--- DOF states:\n") + str(dof_states) + "\n")
dof_props = dc.get_articulation_dof_properties(art)
print(str("--- DOF properties:\n") + str(dof_props) + "\n")
# Simulate robot coming to a rest configuration
for i in range(100):
simulation_app.update()
# Simulate robot for a fixed number of frames and specify a joint position target
for i in range(100):
dof_ptr = dc.find_articulation_dof(art, "panda_joint2")
# This should be called each frame of simulation if state on the articulation is being changed.
dc.wake_up_articulation(art)
# Set joint position target
dc.set_dof_position_target(dof_ptr, -1.5)
simulation_app.update()
simulation_app.close()
| 2,529 | Python | 35.142857 | 99 | 0.732305 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.shapenet/usd_convertor.py | # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""Convert ShapeNetCore V2 to USD without materials.
By only converting the ShapeNet geometry, we can more quickly load assets into scenes for the purpose of creating
large datasets or for online training of Deep Learning models.
"""
import argparse
import os
import carb
from omni.isaac.kit import SimulationApp
if "SHAPENET_LOCAL_DIR" not in os.environ:
carb.log_error("SHAPENET_LOCAL_DIR not defined:")
carb.log_error(
"Please specify the SHAPENET_LOCAL_DIR environment variable to the location of your local shapenet database, exiting"
)
exit()
kit = SimulationApp()
from omni.isaac.core.utils.extensions import enable_extension
enable_extension("omni.isaac.shapenet")
from omni.isaac.shapenet import utils
parser = argparse.ArgumentParser("Convert ShapeNet assets to USD")
parser.add_argument(
"--categories", type=str, nargs="+", default=None, help="List of ShapeNet categories to convert (space seperated)."
)
parser.add_argument(
"--max_models", type=int, default=50, help="If specified, convert up to `max_models` per category, default is 50"
)
parser.add_argument(
"--load_materials", action="store_true", help="If specified, materials will be loaded from shapenet meshes"
)
args, unknown_args = parser.parse_known_args()
# Ensure Omniverse Kit is launched via SimulationApp before shapenet_convert() is called
utils.shapenet_convert(args.categories, args.max_models, args.load_materials)
# cleanup
kit.close()
| 1,900 | Python | 34.203703 | 125 | 0.769474 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.manipulators/franka_pick_up.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import sys
import carb
import numpy as np
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.franka.controllers.pick_place_controller import PickPlaceController
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import ParallelGripper
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
my_world = World(stage_units_in_meters=1.0)
my_world.scene.add_default_ground_plane()
asset_path = assets_root_path + "/Isaac/Robots/Franka/franka_alt_fingers.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/Franka")
gripper = ParallelGripper(
end_effector_prim_path="/World/Franka/panda_rightfinger",
joint_prim_names=["panda_finger_joint1", "panda_finger_joint2"],
joint_opened_positions=np.array([0.05, 0.05]),
joint_closed_positions=np.array([0.0, 0.0]),
action_deltas=np.array([0.05, 0.05]),
)
my_franka = my_world.scene.add(
SingleManipulator(
prim_path="/World/Franka", name="my_franka", end_effector_prim_name="panda_rightfinger", gripper=gripper
)
)
cube = my_world.scene.add(
DynamicCuboid(
name="cube",
position=np.array([0.3, 0.3, 0.3]),
prim_path="/World/Cube",
scale=np.array([0.0515, 0.0515, 0.0515]),
size=1.0,
color=np.array([0, 0, 1]),
)
)
my_world.scene.add_default_ground_plane()
my_franka.gripper.set_default_state(my_franka.gripper.joint_opened_positions)
my_world.reset()
my_controller = PickPlaceController(
name="pick_place_controller", gripper=my_franka.gripper, robot_articulation=my_franka
)
articulation_controller = my_franka.get_articulation_controller()
i = 0
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
my_controller.reset()
observations = my_world.get_observations()
actions = my_controller.forward(
picking_position=cube.get_local_pose()[0],
placing_position=np.array([-0.3, -0.3, 0.0515 / 2.0]),
current_joint_positions=my_franka.get_joint_positions(),
end_effector_offset=np.array([0, 0.005, 0]),
)
if my_controller.is_done():
print("done picking and placing")
articulation_controller.apply_action(actions)
if args.test is True:
break
simulation_app.close()
| 3,410 | Python | 34.53125 | 112 | 0.708798 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.manipulators/ur10_pick_up.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
import sys
import carb
import numpy as np
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import SurfaceGripper
from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController
parser = argparse.ArgumentParser()
parser.add_argument("--test", default=False, action="store_true", help="Run in test mode")
args, unknown = parser.parse_known_args()
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
my_world = World(stage_units_in_meters=1.0)
my_world.scene.add_default_ground_plane()
asset_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd"
add_reference_to_stage(usd_path=asset_path, prim_path="/World/UR10")
gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd"
add_reference_to_stage(usd_path=gripper_usd, prim_path="/World/UR10/ee_link")
gripper = SurfaceGripper(end_effector_prim_path="/World/UR10/ee_link", translate=0.1611, direction="x")
ur10 = my_world.scene.add(
SingleManipulator(prim_path="/World/UR10", name="my_ur10", end_effector_prim_name="ee_link", gripper=gripper)
)
ur10.set_joints_default_state(positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0]))
cube = my_world.scene.add(
DynamicCuboid(
name="cube",
position=np.array([0.3, 0.3, 0.3]),
prim_path="/World/Cube",
scale=np.array([0.0515, 0.0515, 0.0515]),
size=1.0,
color=np.array([0, 0, 1]),
)
)
my_world.scene.add_default_ground_plane()
ur10.gripper.set_default_state(opened=True)
my_world.reset()
my_controller = PickPlaceController(name="pick_place_controller", gripper=ur10.gripper, robot_articulation=ur10)
articulation_controller = ur10.get_articulation_controller()
i = 0
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
my_controller.reset()
observations = my_world.get_observations()
actions = my_controller.forward(
picking_position=cube.get_local_pose()[0],
placing_position=np.array([0.7, 0.7, 0.0515 / 2.0]),
current_joint_positions=ur10.get_joint_positions(),
end_effector_offset=np.array([0, 0, 0.02]),
)
if my_controller.is_done():
print("done picking and placing")
articulation_controller.apply_action(actions)
if args.test is True:
break
simulation_app.close()
| 3,376 | Python | 37.375 | 113 | 0.712085 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.manipulators/rmpflow_supported_robots/supported_robot_follow_target_example.py | # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({"headless": False})
import argparse
from pprint import pprint
import numpy as np
from omni.isaac.core import World
from omni.isaac.core.objects import cuboid
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import create_prim
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.motion_generation.articulation_motion_policy import ArticulationMotionPolicy
from omni.isaac.motion_generation.interface_config_loader import (
get_supported_robot_policy_pairs,
load_supported_motion_policy_config,
)
from omni.isaac.motion_generation.lula import RmpFlow
parser = argparse.ArgumentParser()
parser.add_argument(
"-v",
"--verbose",
action="store_true",
default=True,
help="Print useful runtime information such as the list of supported robots",
)
parser.add_argument(
"--robot-name",
type=str,
default="Cobotta_Pro_900",
help="Key to use to access RMPflow config files for a specific robot.",
)
parser.add_argument(
"--usd-path",
type=str,
default="/Isaac/Robots/Denso/cobotta_pro_900.usd",
help="Path to supported robot on Nucleus Server",
)
parser.add_argument("--add-orientation-target", action="store_true", default=False, help="Add orientation target")
args, unknown = parser.parse_known_args()
robot_name = args.robot_name
usd_path = get_assets_root_path() + args.usd_path
prim_path = "/my_robot"
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
light_prim = create_prim("/DistantLight", "DistantLight")
light_prim.GetAttribute("inputs:intensity").Set(5000)
my_world = World(stage_units_in_meters=1.0)
robot = my_world.scene.add(Robot(prim_path=prim_path, name=robot_name))
if args.verbose:
print("Names of supported robots with provided RMPflow config")
print("\t", list(get_supported_robot_policy_pairs().keys()))
print()
# The load_supported_motion_policy_config() function is currently the simplest way to load supported robots.
# In the future, Isaac Sim will provide a centralized registry of robots with Lula robot description files
# and RMP configuration files stored alongside the robot USD.
rmp_config = load_supported_motion_policy_config(robot_name, "RMPflow")
if args.verbose:
print(
f"Successfully referenced RMPflow config for {robot_name}. Using the following parameters to initialize RmpFlow class:"
)
pprint(rmp_config)
print()
# Initialize an RmpFlow object
rmpflow = RmpFlow(**rmp_config)
physics_dt = 1 / 60.0
articulation_rmpflow = ArticulationMotionPolicy(robot, rmpflow, physics_dt)
articulation_controller = robot.get_articulation_controller()
# Make a target to follow
target_cube = cuboid.VisualCuboid(
"/World/target", position=np.array([0.5, 0, 0.5]), color=np.array([1.0, 0, 0]), size=0.1
)
# Make an obstacle to avoid
obstacle = cuboid.VisualCuboid(
"/World/obstacle", position=np.array([0.8, 0, 0.5]), color=np.array([0, 1.0, 0]), size=0.1
)
rmpflow.add_obstacle(obstacle)
my_world.reset()
while simulation_app.is_running():
my_world.step(render=True)
if my_world.is_playing():
if my_world.current_time_step_index == 0:
my_world.reset()
# Set rmpflow target to be the current position of the target cube.
if args.add_orientation_target:
target_orientation = target_cube.get_world_pose()[1]
else:
target_orientation = None
rmpflow.set_end_effector_target(
target_position=target_cube.get_world_pose()[0], target_orientation=target_orientation
)
# Query the current obstacle position
rmpflow.update_world()
actions = articulation_rmpflow.get_next_articulation_action()
articulation_controller.apply_action(actions)
simulation_app.close()
| 4,364 | Python | 33.642857 | 128 | 0.730981 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.manipulators/rmpflow_supported_robots/README.md | This standalone example provides a generic script for running a follow-target example on any supported robot that uses RMPflow to reach a target while avoiding obstacles. The purpose of this script is to show only how to use RMPflow, and for the sake of simplicity, it does not use the task/controller paradigm that is typical in other Isaac Sim examples.
The ./supported_robot_follow_target_example.py script takes in runtime with the path to the robot USD asset (which is assumed to be stored on the Nucleus Server) and the name of the robot. By running the script with the default command line arguments, the list of supported robot names will be printed in the terminal.
###### Command Line Arguments
The supported command-line arguments are as follows:
-v,--verbose: If True, prints out useful runtime information such as the list of supported robot names that map to RMPflow config files. Defaults to 'True'
--robot-name: Name of robot that maps to the stored RMPflow config. Defaults to "Cobotta_Pro_900"
--usd-path: Path to robot USD asset on the Nucleus Server. Defaults to "/Isaac/Robots/Denso/cobotta_pro_900.usd". The typical location of a specific robot is under
"/Isaac/Robots/{manufacturer_name}/{robot_name}/{robot_name}.usd"
--add-orientation-target: Add the orientation of the target cube to the RMPflow target. Defaults to False.
###### Choosing Correct Robot Name Argument
With the default arguments, the above script will run using the Cobotta Pro 900 robot and will produce the following output:
Names of supported robots with provided RMPflow config
['Franka', 'UR3', 'UR3e', 'UR5', 'UR5e', 'UR10', 'UR10e', 'UR16e', 'Rizon4', 'DofBot', 'Cobotta_Pro_900', 'Cobotta_Pro_1300', 'RS007L', 'RS007N', 'RS013N', 'RS025N', 'RS080N', 'FestoCobot']
Successfully referenced RMPflow config for Cobotta_Pro_900. Using the following parameters to initialize RmpFlow class:
{
'end_effector_frame_name': 'gripper_center',
'ignore_robot_state_updates': False,
'maximum_substep_size': 0.00334,
'rmpflow_config_path': '/path/to/omni_isaac_sim/_build/linux-x86_64/release/exts/omni.isaac.motion_generation/motion_policy_configs/./Denso/cobotta_pro_900/rmpflow/cobotta_rmpflow_common.yaml',
'robot_description_path': '/path/to/omni_isaac_sim/_build/linux-x86_64/release/exts/omni.isaac.motion_generation/motion_policy_configs/./Denso/cobotta_pro_900/rmpflow/robot_descriptor.yaml',
'urdf_path': '/path/to/omni_isaac_sim/_build/linux-x86_64/release/exts/omni.isaac.motion_generation/motion_policy_configs/./Denso/cobotta_pro_900/rmpflow/../cobotta_pro_900_gripper_frame.urdf'
}
The names of supported robots are suitable for the `--robot-name` argument, and each must correctly correspond to the robot USD path. In a future release, configuration data for supported robots will be centralized such that only a single argument will be required. The specific method of accessing supported robot RMPflow configs provided here will then be deprecated.
The remaining output shows the RMPflow configuration information that is found under the name "Cobotta_Pro_900". This configuration is used to initialize the `RmpFlow` class.
###### Examples of loading other robots
Multiple valid combinations of command line arguments are shown for different supported robots:
python.sh supported_robot_follow_target_example.py --robot-name RS080N --usd-path "/Isaac/Robots/Kawasaki/RS080N/rs080n_onrobot_rg2.usd"
python.sh supported_robot_follow_target_example.py --robot-name UR16e --usd-path "/Isaac/Robots/UniversalRobots/ur16e/ur16e.usd"
python.sh supported_robot_follow_target_example.py --robot-name FestoCobot --usd-path "/Isaac/Robots/Festo/FestoCobot/festo_cobot.usd"
| 3,811 | Markdown | 72.307691 | 371 | 0.755445 |
2820207922/isaac_ws/standalone_examples/api/omni.isaac.manipulators/cobotta_900/ik_solver.py | # Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from typing import Optional
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.extensions import get_extension_path_from_name
from omni.isaac.motion_generation.articulation_kinematics_solver import ArticulationKinematicsSolver
from omni.isaac.motion_generation.lula.kinematics import LulaKinematicsSolver
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
urdf_extension_path = get_extension_path_from_name("omni.isaac.urdf")
self._kinematics = LulaKinematicsSolver(
robot_description_path=os.path.join(os.path.dirname(__file__), "../rmpflow/robot_descriptor.yaml"),
urdf_path=os.path.join(urdf_extension_path, "data/urdf/robots/cobotta_pro_900/cobotta_pro_900.urdf"),
)
if end_effector_frame_name is None:
end_effector_frame_name = "onrobot_rg6_base_link"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,547 | Python | 50.599998 | 114 | 0.76212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.