file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/gui.py
import rclpy from rclpy.node import Node from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from utils import create_joint_state_message_array, create_publisher_array, save_yaml, insert_dict, get_parameter_values from ros2param.api import call_list_parameters, call_get_parameters, get_value from ros2node.api import get_absolute_node_name from rclpy.parameter import PARAMETER_SEPARATOR_STRING import os import yaml from ros2cli.node.strategy import NodeStrategy from ros2cli.node.direct import DirectNode from ros2node.api import get_node_names class GUI(Node): def __init__(self): super().__init__('gui') self.msg = Pose() # Define callback timer timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.gui_callback) joint_names = ['x_translation', 'y_translation', 'z_translation', 'x_rotation', 'y_rotation', 'z_rotation'] #publisher_array= create_publisher_array(self, number_of_shuttles, topic_prefix="configuration/shuttle", topic_name='/initialPosition', msg_type=Pose) #self.msg_array = create_joint_state_message_array(joint_names, number_of_shuttles) # try: # for idx, publisher in enumerate(publisher_array): # self.msg.position.x = param[idx][0] # self.msg.position.y = param[idx][1] # self.msg.position.z = param[idx][2] # publisher.publish(self.msg) # except: # pass #self.save_yaml() def gui_callback(self): try: pass #self.get_logger().info(str(self.get_parameter('shuttle1_position').get_parameter_value().double_array_value)) except: pass def save_yaml(self): node_names = get_node_names(node=self, include_hidden_nodes=False) yaml_output = {} for node in node_names: print(node.full_name) response = call_list_parameters(node=self, node_name=node.full_name) response = sorted(response) parameter_values = self.get_parameter_values(self, node.full_name, response) # yaml_output = {node.name: {'ros__parameters': {}}} yaml_output[node.name] = {'ros__parameters': {}} for param_name, pval in zip(response, parameter_values): self.insert_dict( yaml_output[node.name]['ros__parameters'], param_name, pval) with open(os.path.join("", "tester3" + '.yaml'), 'w') as yaml_file: yaml.dump(yaml_output, yaml_file, default_flow_style=False) def insert_dict(self, dictionary, key, value): split = key.split(".", 1) if len(split) > 1: if not split[0] in dictionary: dictionary[split[0]] = {} self.insert_dict(dictionary[split[0]], split[1], value) else: dictionary[key] = value @staticmethod def get_parameter_values(node, node_name, params): response = call_get_parameters( node=node, node_name=node_name, parameter_names=params) # requested parameter not set if not response.values: return '# Parameter not set' # extract type specific value return [get_value(parameter_value=i) for i in response.values] def main(args=None): """Initializes the gui node and spins it until it is destroyed.""" rclpy.init(args=args) gui_node = GUI() rclpy.spin(gui_node) gui_node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
3,629
Python
32.302752
158
0.613117
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/shuttle.py
import rclpy from rclpy.node import Node from utils import create_joint_state_message_array, create_publisher_array, destroy_publisher_array, load_yaml_file, save_yaml, create_action_server_array from utils import ShuttleMode import time from sensor_msgs.msg import JointState import random import numpy as np from rcl_interfaces.srv import GetParameters from rcl_interfaces.msg import ParameterDescriptor, ParameterValue, Parameter from rclpy.parameter import ParameterType from robot_actions.action import Shu from rclpy.action import ActionClient, ActionServer from rclpy.executors import MultiThreadedExecutor def generate_random_goals(num_shuttles): desired_positions = np.random.rand(num_shuttles, 2) desired_positions[:, 0] = (desired_positions[:, 0] * 0.84) +0.06 desired_positions[:, 1] = (desired_positions[:, 1] * 0.6)+0.06 # Check if any of the desired positions are within a manhatten distance of 2 of each other invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 0.2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) while invalid: desired_positions = np.random.rand(num_shuttles, 2) desired_positions[:, 0] = (desired_positions[:, 0] * 0.84) +0.06 desired_positions[:, 1] = (desired_positions[:, 1] * 0.6)+0.06 invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 0.2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) return desired_positions class Shuttle(Node): def __init__(self): super().__init__('shuttle') # Define publishers and messages shuttle_config = load_yaml_file(self.get_name()) print(shuttle_config) for key, value in shuttle_config.items(): if "position" in key: self.declare_parameter(key) param_value = rclpy.Parameter( key, rclpy.Parameter.Type.DOUBLE_ARRAY, value, ) self.set_parameters([param_value]) self.declare_parameter('sim_shuttle') sim_shuttle = self.get_parameter('sim_shuttle').get_parameter_value().bool_value # Define the number of shuttles that is from start self.num_shu = 0 self.client = self.create_client(GetParameters, '/global_parameter_server/get_parameters') self.shuttle_positions = np.zeros((100, 2)) self.shuttle_subscriber_array = [] if not sim_shuttle: self.num_shu = 0 else: joint_names = ['x_translation', 'y_translation', 'z_translation', 'x_rotation', 'y_rotation', 'z_rotation'] self.publisher_array = create_publisher_array(self, self.num_shu, topic_prefix=self.get_name(), topic_name='/joint_command', msg_type=JointState) self.msg_array = create_joint_state_message_array(joint_names, self.num_shu) for idx in range(self.num_shu): self.shuttle_subscriber_array.append(self.create_subscription(JointState, '/' + self.get_name() + f'{idx:02}' + '/joint_states', self.shuttle_joint_state_callback, 10)) self.action_server_array = create_action_server_array(self, Shu, topic_prefix=self.get_name(), callback_type=self.action_shuttle_callback, n_robots=self.num_shu) # Define callback timer timer_period = 1 # seconds timer_period_states = 0.1 self.timer = self.create_timer(timer_period, self.shuttle_callback) self.timer_states = self.create_timer(timer_period_states, self.update_states) self.mode = ShuttleMode() def update_states(self): # Request parameter from the /gui node request = GetParameters.Request() request.names = ['num_of_shuttles'] future = self.client.call_async(request=request) future.add_done_callback(self.callback_global_param) def shuttle_callback(self): # # try: # # self.get_logger().info(f'Shuttle positions {self.shuttle_positions}') # # except: # # pass # Update the amout of topics that there need to be if self.num_shu> len(self.publisher_array) or self.num_shu < len(self.publisher_array): destroy_publisher_array(self, self.publisher_array) self.publisher_array = create_publisher_array(self, self.num_shu, topic_prefix=self.get_name(), topic_name='/joint_command', msg_type=JointState) #self.action_server_array = create_action_server_array(self, Shu, topic_prefix=self.get_name(), callback_type=self.action_shuttle_callback, n_robots=self.num_shu) self.get_logger().info("Old shuttels destroyed") self.shuttle_subscriber_array = [] for action_server in self.action_server_array: action_server.destroy() self.action_server_array = [] for idx in range(self.num_shu): self.action_server_array.append(ActionServer(self, Shu, self.get_name() + f'{idx:02}', self.action_shuttle_callback)) for shuttle in self.shuttle_subscriber_array: shuttle.destroy() self.shuttle_subscriber_array = [] for idx in range(self.num_shu): self.shuttle_subscriber_array.append(self.create_subscription(JointState, '/' + self.get_name() + f'{idx:02}' + '/joint_states', self.shuttle_joint_state_callback, 10)) desired_positions = generate_random_goals(self.num_shu) # for idx, publisher in enumerate(self.publisher_array): # #pos = [0.06 + random.random()*0.84, 0.06 + random.random()*0.60, 0.0, 0.0, 0.0, 0.0] # pos = [desired_positions[idx, 0], desired_positions[idx, 1], 0.0, 0.0, 0.0, 0.0] # vel = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # msg = self.mode.move(pos, vel) # publisher.publish(msg) def action_shuttle_callback(self, goal_handle): self.get_logger().info("Goal request" + str(goal_handle.request.goal)) goal = goal_handle.request.goal shuttle_id = goal_handle.request.id target_position = goal target_position = np.array(target_position) # Loop until condition is met # self.get_logger().info("Shuttle " + str(shuttle_id) + " is moving to " + str(target_position)) #self.get_logger().info(f'{self.shuttle_positions[shuttle_id]}') # self.get_logger().info(f'{np.linalg.norm(target_position[0:2] - self.shuttle_positions[shuttle_id])}') self.get_logger().info(f'action shuttle id {shuttle_id}, target position {target_position}') while np.linalg.norm((target_position[0:2] - self.shuttle_positions[shuttle_id])) > 0.05: self.get_logger().info(f'distance {np.linalg.norm((target_position[0:2] - self.shuttle_positions[shuttle_id]))}') #self.get_logger().info(f'current position {self.shuttle_positions[shuttle_id]}') #self.get_logger().info(f'target position {target_position[0:2]}') pos = [target_position[0], target_position[1], 0.0, 0.0, 0.0, 0.0] vel = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] msg = self.mode.move(pos, vel) self.publisher_array[shuttle_id].publish(msg) time.sleep(0.1) self.get_logger().info("goal reached sleeping") time.sleep(5) self.get_logger().info("goal reached") result = Shu.Result() result.goalresult = "Success" result.id = shuttle_id return result def callback_global_param(self, future): try: result = future.result() except Exception as e: self.get_logger().warn("Service call failed inside shuttle %r" % (e,)) else: self.param = result.values[0] self.num_shu = self.param.integer_value #self.get_logger().info("Number of shuttle is: %s" % (self.num_shu,)) def shuttle_joint_state_callback(self, msg): #self.get_logger().info('I heard: "%s"' % msg) idx = int(msg.name[0]) # self.get_logger().info(f'shuttle joint state idx {idx}') x, y = msg.position[0], msg.position[1] position = np.array([x, y]) self.shuttle_positions[idx] = position def main(args=None): """Initializes the Shuttle node and spins it until it is destroyed.""" rclpy.init(args=args) shuttle_node = Shuttle() # rclpy.spin(shuttle_node) # #print("NU") # #save_yaml(shuttle_node) # shuttle_node.destroy_node() # rclpy.shutdown() executor = MultiThreadedExecutor() executor.add_node(shuttle_node) try: executor.spin() finally: # Shutdown and remove node executor.shutdown() shuttle_node.destroy() rclpy.shutdown() if __name__ == '__main__': main()
9,005
Python
41.28169
184
0.615658
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/__init__.py
# __init__.py
13
Python
12.999987
13
0.461538
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/task_planner.py
import rclpy from rclpy.node import Node import numpy as np from math import pi from robot_actions.action import Man from robot_actions.action import Shu from utils import create_action_client_array from utils import KR4R600, KR3R540, ValueIDManager, TaskPlannerUtils, Station, Shuttle from sensor_msgs.msg import JointState from rclpy.action import ActionClient from rcl_interfaces.srv import GetParameters class TaskPlanner(Node): def __init__(self): super().__init__('task_planner') # Define publishers and messages number_of_kuka540 = 2 number_of_kuka600 = 2 self.number_of_shuttles = 5 * ["Shuttle"] self.number_of_shuttles = 0 self.number_of_manipulators = 0 self.number_of_segments = 0 self.robot_position = [] self.segment_position = [] self.old_number_of_segments = 0 self.old_number_of_manipulators = 0 self.old_number_of_shuttles = 0 name540 = number_of_kuka540 * [KR3R540()._name] name600 = number_of_kuka600 * [KR4R600()._name] self.name_of_manipulators = np.concatenate((name600, name540)) self.shuttle_joint_state_subscribers = [] goal = [0, -pi/2, pi/2, 0, 0, 0] # for idx, name in enumerate(self.name_of_manipulators): # self.ManiActionClient = create_action_client_array(self, # Man, # topic_prefix=name, # n_robots=1) # for idx, name in enumerate(self.number_of_shuttles): # self.ShuActionClient = create_action_client_array(self, # Shu, # topic_prefix=name, # n_robots=1 # ) self.action_clients_manipulator = [] self.action_clients_shuttle = [] self.client = self.create_client(GetParameters, '/global_parameter_server/get_parameters') timer_period = 0.1 # seconds self.timer = self.create_timer(timer_period, self.main_callback) print("Task planner initialized") self.value_id_manager_shuttle = ValueIDManager() self.value_id_manager_manipulator = ValueIDManager() self.value_id_manager_segment = ValueIDManager() print("Task planner initialized") self.task_planner = TaskPlannerUtils() self.shuttles_id_to_storage_station = [] self.shuttles_waiting_for_storage = [] def main_callback(self): self.update_parameters_from_server() #self.print_parameters() #self.get_logger().info(f'task_planner {self.number_of_manipulators}') self.update_states() def update_parameters_from_server(self): request = GetParameters.Request() request.names = ['num_of_manipulators', 'robot_position', 'num_of_tables', 'table_position', 'num_of_shuttles'] future = self.client.call_async(request=request) future.add_done_callback(self.update_parameters_from_server_callback) #1. Run task planner self.task_planner.main() #2. Get active tasks active_tasks = self.task_planner.get_active_tasks() if active_tasks: for idx, active_task in enumerate(active_tasks): self.get_logger().info(f'active task idx{idx}: {active_task.get_assigned_shuttle_id()}') #3. Move the shuttles to the assigned stations and wait for 3 seconds per add command if active_tasks: for idx, active_task in enumerate(active_tasks): if not active_task.get_in_progress(): shuttle_id = active_task.get_assigned_shuttle_id() station = active_task.get_assigned_station() station_position = station.get_position() # call action client goal = [station_position[0], station_position[1], 0.0, 0.0, 0.0, 0.0] self.send_goal_for_shuttles(goal, shuttle_id) active_task.set_in_progress(True) self.get_logger().info(f'active task idx {idx}: {active_task.get_assigned_shuttle_id()}') #4. Move the shuttles to a random segment that is not a station and set shuttle to free if self.shuttles_id_to_storage_station: for shuttle_id in self.shuttles_id_to_storage_station: goal = [0.1, 0.1, 0.0, 0.0, 0.0, 0.0] self.send_goal_for_shuttles(goal, shuttle_id) self.shuttles_id_to_storage_station.pop(0) self.shuttles_waiting_for_storage.append(shuttle_id) def update_states(self): # self.get_logger().info(f'old number of manipulators {self.old_number_of_manipulators}') # self.get_logger().info(f'number of manipulators {self.number_of_manipulators}') #removed_array_index_shuttle, removed_ids_shuttle = self.value_id_manager_shuttle.sync_array(self.number_of_shuttles) removed_array_index_manipulator, removed_ids_manipulator = self.value_id_manager_manipulator.sync_array(self.robot_position) removed_array_index_segment, removed_ids_segment = self.value_id_manager_segment.sync_array(self.segment_position) #self.get_logger().info(f'segment position {self.segment_position}') if self.number_of_manipulators < self.old_number_of_manipulators: removed_array_index_manipulator.sort(reverse=True) for array_idx, idx in zip(removed_array_index_manipulator, removed_ids_manipulator): self.action_clients_manipulator[array_idx].destroy() self.action_clients_manipulator.pop(array_idx) ## Remove station from task planner class #station = self.find_closet_segment_to_manipulator(self.robot_position[array_idx]) station_to_remove = self.task_planner.stations.get_station_by_index(array_idx) self.task_planner.stations.remove_station(station_to_remove) #self.get_logger().info(f'stations {self.task_planner.stations.get_stations()}') self.old_number_of_manipulators = self.number_of_manipulators if self.number_of_manipulators > self.old_number_of_manipulators: if len(list(self.value_id_manager_manipulator.id_to_value.keys())) == 0: manipulator_id = 0 else: manipulator_id = list(self.value_id_manager_manipulator.id_to_value.keys())[-1] self.action_clients_manipulator.append(ActionClient(self,Man, KR4R600()._name + str(f'{manipulator_id:02}'))) ## Add station to task planner class station_position = self.find_closet_segment_to_manipulator(self.robot_position[manipulator_id]) station = Station() station.set_position(self.convert_to_xy(station_position)*0.24) # print(station) # print(self.task_planner.stations) self.task_planner.stations.add_station(station) # self.get_logger().info(f'stations {station}') # self.get_logger().info(f'stations {self.task_planner.stations}') # self.get_logger().info(f'stations {self.task_planner.stations.get_stations()}') self.old_number_of_manipulators = self.number_of_manipulators if self.number_of_shuttles < self.old_number_of_shuttles: shuttles = self.task_planner.shuttles.get_shuttles() shuttles_to_remove = shuttles[self.number_of_shuttles:] for shuttle in shuttles_to_remove: self.task_planner.shuttles.remove_shuttle(shuttle) self.shuttle_joint_state_subscribers[self.number_of_shuttles-1].destroy() self.shuttle_joint_state_subscribers.pop(self.number_of_shuttles-1) self.action_clients_shuttle[self.number_of_shuttles-1].destroy() self.action_clients_shuttle.pop(self.number_of_shuttles-1) self.old_number_of_shuttles = self.number_of_shuttles elif self.number_of_shuttles > self.old_number_of_shuttles: shuttle = Shuttle() diff = self.number_of_shuttles - self.old_number_of_shuttles for i in range(diff): self.shuttle_joint_state_subscribers.append(self.create_subscription(JointState, f'/shuttle{(self.number_of_shuttles-1+i):02}/joint_states', self.shuttle_joint_state_callback, 10)) self.task_planner.shuttles.add_shuttle(shuttle) self.action_clients_shuttle.append(ActionClient(self,Shu, f'/shuttle/shuttle{(self.number_of_shuttles-1+i):02}')) # self.shuttle_joint_state_subscribers.append(self.create_subscription(JointState, f'/shuttle{(self.number_of_shuttles-1):02}/joint_states', self.shuttle_joint_state_callback, 10)) # self.task_planner.shuttles.add_shuttle(shuttle) # self.get_logger().info(f'shuttles {self.task_planner.shuttles.get_shuttles()}') self.old_number_of_shuttles = self.number_of_shuttles def update_parameters_from_server_callback(self, future): try: result = future.result() #self.number_of_manipulators = result.values[0].integer_value self.robot_position = result.values[1].double_array_value # self.number_of_segments = result.values[2].integer_value self.segment_position = result.values[3].double_array_value self.number_of_shuttles = result.values[4].integer_value self.number_of_manipulators = len(self.robot_position) self.number_of_segments = len(self.segment_position) except Exception as e: self.get_logger().warn("Service call failed inside shuttle %r" % (e,)) def print_parameters(self): print(f'number of shuttles {self.number_of_shuttles}') print(f'number of manipulators {self.number_of_manipulators}') print(f'number of segments {self.number_of_segments}') print(f'positions of segments {self.segment_position}') print(f'positions of manipulators {self.robot_position}') def manipulator_send_goal(self, goal): # Function that send the goal for multiple manipulators goal_msg = Man.Goal() goal_msg.goal = goal for idx, Client in enumerate(self.ManiActionClient): self.ManiActionClient[idx].wait_for_server() future = self.ManiActionClient[idx].send_goal_async(goal_msg, feedback_callback=self.feedback_callback) future.add_done_callback(self.goal_response_callback) def shuttle_send_goal(self, goal): # Function that send the goal for multiple shuttles goal_msg = Shu.Goal() goal_msg.goal = goal for idx, Client in enumerate(self.ShuActionClient): self.ShuActionClient[idx].wait_for_server() future = self.ShuActionClient[idx].send_goal_async(goal_msg, feedback_callback=self.feedback_callback) future.add_done_callback(self.goal_response_callback) def goal_response_callback(self, future): goal_handle = future.result() if not goal_handle.accepted: self.get_logger().info('Goal rejected :(') return self.get_logger().info('Goal accepted :)') self._get_result_future = goal_handle.get_result_async() self._get_result_future.add_done_callback(self.get_result_callback) def get_result_callback(self, future): result = future.result().result self.get_logger().info('Result: {0}'.format(result.goalresult)) rclpy.shutdown() def feedback_callback(self, feedback_msg): feedback = feedback_msg.feedback self.get_logger().info('Received feedback: {0}'.format(feedback.goalfeedback)) def shuttle_joint_state_callback(self, msg: JointState): try: #self.get_logger().info(f'shuttle joint state {msg}') #self.get_logger().info(f'shuttle joint state {msg.name}') idx = int(msg.name[0]) # self.get_logger().info(f'shuttle joint state idx {idx}') x, y = msg.position[0], msg.position[1] position = np.array([x, y]) #self.get_logger().info(f'all shuttles {self.task_planner.shuttles.get_shuttles()}') self.task_planner.shuttles.get_shuttle_by_index(idx).set_position(position) # self.get_logger().info(f'shuttle joint state {msg}') except: pass def find_closet_segment_to_manipulator(self, position): segment_positions = self.segment_position min_distance = np.inf position = self.convert_to_xy(position) closest_segment = None for segment_position in segment_positions: segment_position_converted = self.convert_to_xy(segment_position) self.get_logger().info(f'position {position}') self.get_logger().info(f'segment_position {segment_position_converted}') distance = np.linalg.norm(position - segment_position_converted) if distance < min_distance: min_distance = distance closest_segment = segment_position return closest_segment def convert_to_xy(self, position): position = str(position) x, y = [float(xy) for xy in position.split('.')] return np.array([x, y]) def send_goal_for_shuttles(self, goal, id): # Function that send the goal for multiple shuttles self.get_logger().info(f'inside send goal for shuttles {id}') goal_msg = Shu.Goal() goal_msg.id = id goal_msg.goal = goal self.get_logger().info(f'debug #1') self.action_clients_shuttle[id].wait_for_server() self.get_logger().info(f'debug #2') future = self.action_clients_shuttle[id].send_goal_async(goal_msg, feedback_callback=self.feedback_callback) self.get_logger().info(f'debug #3') future.add_done_callback(self.shuttle_goal_response_callback) self.get_logger().info(f'debug #4') self.get_logger().info(f'end of send goal for shuttles {id}') def shuttle_feedback_callback(self, feedback_msg): pass # feedback = feedback_msg.feedback # self.get_logger().info('Received feedback: {0}'.format(feedback.goalfeedback)) def shuttle_goal_response_callback(self, future): goal_handle = future.result() if not goal_handle.accepted: self.get_logger().info('Goal rejected :(') return self.get_logger().info('Goal accepted for shuttle') result_future = goal_handle.get_result_async() result_future.add_done_callback(self.shuttle_get_result_callback) def shuttle_get_result_callback(self, future): result = future.result().result self.get_logger().info('Result: {0}'.format(result.id)) #status = 'Goal succeeded!' if result.succes else 'Goal failed!' # 1. active_tasks = self.task_planner.get_active_tasks() if active_tasks: for idx, active_task in enumerate(active_tasks): shuttle_id = active_task.get_assigned_shuttle_id() if result.id == shuttle_id: active_tasks.pop(idx) self.shuttles_id_to_storage_station.append(shuttle_id) self.get_logger().info(f'active task idx {idx}: {active_task.get_in_progress()}') self.task_planner.free_station(active_task.get_assigned_station()) self.get_logger().info(f'active task idx {idx}: {active_task.get_in_progress()}') if self.shuttles_waiting_for_storage: for idx, shuttle_id in enumerate(self.shuttles_waiting_for_storage): if result.id == shuttle_id: self.shuttles_waiting_for_storage.pop(idx) self.task_planner.free_shuttle(self.task_planner.shuttles.get_shuttle_by_index(shuttle_id)) self.get_logger().info(f'shuttle {shuttle_id} is free') def main(args=None): """Initializes the Manipulator node and spins it until it is destroyed.""" rclpy.init(args=args) task_node = TaskPlanner() # goal = [0.0, -pi/2, pi/2, 0.0, 0.0, 0.0] # task_node.Man_send_goal(goal) rclpy.spin(task_node) if __name__ == '__main__': main()
16,787
Python
45.120879
196
0.612855
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/spawn_manager.py
import rclpy from rclpy.node import Node from rcl_interfaces.srv import GetParameters from tutorial_interfaces.srv import PoseSrv from utils import ValueIDManager, ClientAsync from geometry_msgs.msg import Pose class SpawnManager(Node): def __init__(self): super().__init__('spawn_manager') # Define publishers and print("Spawn manager initialized") # Define callback timer timer_period = 0.5 self.timer = self.create_timer(timer_period, self.spawn_manager_callback) self.number_of_segments = 0 self.segment_positions = [] self.client = self.create_client(GetParameters, '/global_parameter_server/get_parameters') self.request = GetParameters.Request() self.request.names = ['num_of_tables', 'table_position'] self.states = {key: 0 for key in self.request.names} self.service_client = ClientAsync() self.value_id_manager = ValueIDManager() self.old_number_of_segments = 0 def spawn_manager_callback(self): future = self.client.call_async(request=self.request) future.add_done_callback(self.callback_global_param) removed_array_index, removed_ids = self.value_id_manager.sync_array(self.segment_positions) # if new_states['num_of_shuttles'] != self.states['num_of_shuttles']: # if new_states['num_of_shuttles'] > self.states['num_of_shuttles']: # for i in range(new_states['num_of_shuttles'] - self.states['num_of_shuttles']): # self.spawn_shuttle() # else: # for i in range(self.states['num_of_shuttles'] - new_states['num_of_shuttles']): # self.remove_shuttle() # if new_states['num_of_manipulators'] != self.states['num_of_manipulators']: # if new_states['num_of_manipulators'] > self.states['num_of_manipulators']: # for i in range(new_states['num_of_manipulators'] - self.states['num_of_manipulators']): # self.spawn_manipulator() if self.number_of_segments < self.old_number_of_segments: removed_array_index.sort(reverse=True) for array_idx, idx in zip(removed_array_index, removed_ids): self.service_client.remove_segment(idx) elif self.number_of_segments > self.old_number_of_segments: if len(list(self.value_id_manager.value_to_id.keys())) == 0: segment_id = 0 else: segment_id = list(self.value_id_manager.id_to_value.keys())[-1] segment_position = self.value_id_manager.id_to_value[segment_id] segment_pose = self.transform_to_pose(segment_position) self.service_client.spawn_segment(segment_id, segment_pose) self.old_number_of_segments = self.number_of_segments # self.spawn_shuttle() # self.spawn_manipulator() # self.spawn_segments() # try: # #print(f'Number of shuttles: {self.result.values[0].integer_value}') # print(f'number of shuttles {self.result.values[0].integer_value}') # print(f'number of manipulators {self.result.values[1].integer_value}') # print(f'number of segments {self.result.values[2].integer_value}') # print(f'positions of segments {self.result.values[3].double_array_value}') # print(f'positions of manipulators {self.result.values[4].double_array_value}') # except Exception as e: # print(e) def spawn_shuttle(self): pass def spawn_manipulator(self, robot_type, robot_id, pose): pass def spawn_segments(self): pass def remove_shuttle(self): pass def remove_manipulator(self, robot_type, robot_id): pass def remove_segments(self): pass def callback_global_param(self, future): try: result = future.result() self.number_of_segments = result.values[0].integer_value self.segment_positions = result.values[1].double_array_value self.number_of_segments = len(self.segment_positions) except Exception as e: self.get_logger().warn("Service call failed inside shuttle %r" % (e,)) def transform_to_pose(self, pos): pos = str(pos) x, y = pos.split('.') pose = Pose() pose.position.x = -float(y)*0.24-0.2 pose.position.y = float(x)*0.24+0.2 pose.position.z = float(0.9) pose.orientation.x = float(0) pose.orientation.y = float(0) pose.orientation.z = float(0) pose.orientation.w = float(1) return pose # def remove_extras(self, arr): # for value in list(self.value_to_id.keys()): # create a copy of keys to avoid runtime error # if value not in arr: # self.remove_by_value(value) def main(args=None): """Initializes the Shuttle node and spins it until it is destroyed.""" rclpy.init(args=args) node = SpawnManager() rclpy.spin(node) #print("NU") #save_yaml(shuttle_node) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
5,312
Python
33.953947
105
0.597139
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/manipulator.py
import rclpy from rclpy.node import Node from rclpy.action.server import ActionServer from robot_actions.action import Man from sensor_msgs.msg import JointState import numpy as np import time from rcl_interfaces.srv import GetParameters from spatialmath import SE3 import roboticstoolbox as rtb import time from utils import ValueIDManager from typing import List from utils import (create_joint_state_message_array, create_publisher_array, load_yaml_file, create_action_server_array, destroy_publisher_array) from utils import KR4R600, KR3R540, ClientAsync from geometry_msgs.msg import Pose class Manipulator(Node): def __init__(self): super().__init__('manipulator') # Define publishers and messages manipulator_config = load_yaml_file(self.get_name()) print(manipulator_config) for key, value in manipulator_config.items(): if "position" in key: self.declare_parameter(key) param_value = rclpy.Parameter( key, rclpy.Parameter.Type.DOUBLE_ARRAY, value, ) self.set_parameters([param_value]) self.client = self.create_client(GetParameters, '/global_parameter_server/get_parameters') # Request parameter from the /gui node self.number_of_manipulators = 0 self.manipulator_positions = [] self.value_id_manager = ValueIDManager() self.kuka540 = KR3R540() self.kuka600 = KR4R600() name600 = self.number_of_manipulators * [self.kuka600._name] self.name_of_manipulators = name600 self.publisher_array = [] self.msg = [] self.action_server: List[ActionServer] = [] self.manipulators = {'name': 'manipulator', 'position': [0, 0, 0] } self.joint_names = ['joint0', 'joint1', 'joint2', 'joint3', 'joint4', 'joint5'] self.publisher_array = create_publisher_array(self, self.number_of_manipulators, topic_prefix=self.kuka600._name, topic_name='/joint_command', msg_type=JointState) self.msg = create_joint_state_message_array(self.joint_names, self.number_of_manipulators) self.action_server = create_action_server_array(self, Man, topic_prefix=self.kuka600._name, callback_type=self.action_mani_callback, n_robots=self.number_of_manipulators) # Define callback timer timer_period = 0.1 # seconds self.new_goal = True self.pos = [] self.vel = [] self.timer = self.create_timer(timer_period, self.mani_callback) self.service_client = ClientAsync() def mani_callback(self): request = GetParameters.Request() request.names = ['num_of_manipulators', 'robot_position'] future = self.client.call_async(request=request) future.add_done_callback(self.callback_global_param) removed_array_index, removed_ids = self.value_id_manager.sync_array(self.manipulator_positions) if self.number_of_manipulators != len(self.publisher_array): print(f'Number of manipulators: {self.number_of_manipulators}') print(f'Number of publishers: {len(self.publisher_array)}') print(f'Remove ids: {removed_array_index}') if self.number_of_manipulators < len(self.publisher_array): self.get_logger().error("Number of manipulators is:" + str(self.number_of_manipulators)) removed_array_index.sort(reverse=True) self.get_logger().error("Remove ids is:" + str(removed_array_index)) for array_idx, idx in zip(removed_array_index, removed_ids): self.destroy_publisher(self.publisher_array[array_idx]) self.action_server[array_idx].destroy() self.service_client.remove_robot(self.kuka600._name, idx) self.publisher_array.pop(array_idx) self.msg.pop(array_idx) self.action_server.pop(array_idx) if self.number_of_manipulators > len(self.publisher_array): # Add new manipulator' print(self.value_id_manager.id_to_value) if len(list(self.value_id_manager.id_to_value.keys())) == 0: manipulator_id = 0 else: print(f'ID to value: {self.value_id_manager.id_to_value.keys()}') manipulator_id = list(self.value_id_manager.id_to_value.keys())[-1] manipulator_position = self.value_id_manager.id_to_value[manipulator_id] pose = self.transform_to_pose(manipulator_position) self.publisher_array.append(self.create_publisher(JointState, self.kuka600._name + str(manipulator_id) + '/joint_command', 10)) self.action_server.append(ActionServer(self, Man, self.kuka600._name + str(manipulator_id), self.action_mani_callback)) self.msg.append(JointState()) # pose = Pose() # import random # ros2 service call /segment/add tutorial_interfaces/srv/PoseSrv "{name: 'segment_00', pose: {position: {x: 1.0, y: 2.0, z: 3.0}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}}" # pose.position.x = float(random.random()) # pose.position.y = float(random.random()) # pose.position.z = float(random.random()) # pose.orientation.x = float(0) # pose.orientation.y = float(0) # pose.orientation.z = float(0) # pose.orientation.w = float(1) print(self.kuka600._name + f'{manipulator_id:02}') self.service_client.spawn_robot(self.kuka600._name, manipulator_id, pose) #destroy_publisher_array(self, self.publisher_array) # self.msg = [] # self.action_server = [] # self.publisher_array = create_publisher_array(self, # self.number_of_manipulators, # topic_prefix=self.kuka600._name, # topic_name='/joint_command', # msg_type=JointState) # self.msg = create_joint_state_message_array(self.joint_names, # self.number_of_manipulators) # self.action_server = create_action_server_array(self, # Man, # topic_prefix=self.kuka600._name, # callback_type=self.action_mani_callback, # n_robots=self.number_of_manipulators) self.new_goal = False if self.new_goal: for idx, publisher in enumerate(self.publisher_array): #print(len(self.pos)) pose = SE3.Trans(0.5, 0.3, 0.1) * SE3.OA([0, 1, 0], [0, 0, -1]) sol = self.kuka600.ik_lm_chan(pose) self.qt = rtb.jtraj(self.kuka600.home, self.kuka600.qz, 100) #print(str(idx)+" mellemrum "+str(publisher)) self.pos.append(self.qt.q.tolist()) self.vel.append(self.qt.qd.tolist()) if len(self.pos) > 7 and len(self.vel) > 7 and self.new_goal: for idy, pos in enumerate(self.pos[0]): for idx, publisher in enumerate(self.publisher_array): #print("SELF:POS: " + str(self.pos)) time.sleep(0.01) # Need to be removed self.msg[idx].position = self.pos[idx][idy] self.msg[idx].velocity = self.vel[idx][idy] #print("INDI POS: " + str(self.pos[idy][idx])) publisher.publish(self.msg[idx]) self.new_goal = False print("New goal is: " + str(self.new_goal)) def action_mani_callback(self, goal_handle): f_msg = Man.Feedback() f_msg.goalfeedback = "Running" self.get_logger().info("Goal request" + str(goal_handle.request.goal)) self.get_logger().info('Feedback: {0}'.format(f_msg.goalfeedback)) goal_handle.publish_feedback(f_msg) time.sleep(1) goal_handle.succeed() result = Man.Result() result.goalresult = " Done running" return result def callback_global_param(self, future): try: result = future.result() self.number_of_manipulators = result.values[0].integer_value self.manipulator_positions = result.values[1].double_array_value self.number_of_manipulators = len(self.manipulator_positions) except Exception as e: self.get_logger().warn("Service call failed inside manipulator %r" % (e,)) def transform_to_pose(self, pos): pos = str(pos) x, y = pos.split('.') pose = Pose() pose.position.x = float(x)*0.18+0.12 pose.position.y = float(y)*0.18+0.12 pose.position.z = float(0.9) pose.orientation.x = float(0) pose.orientation.y = float(0) pose.orientation.z = float(0) pose.orientation.w = float(1) return pose def main(args=None): """Initializes the Manipulator node and spins it until it is destroyed.""" rclpy.init(args=args) manipulator_node = Manipulator() rclpy.spin(manipulator_node) manipulator_node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
10,439
Python
41.439024
190
0.530032
abmoRobotics/MAPs/ros2_ws/src/orchestrator/orchestrator/pyside_gui.py
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import rclpy from rclpy.node import Node from threading import Thread from rclpy.executors import MultiThreadedExecutor from rcl_interfaces.srv import GetParameters from rcl_interfaces.srv import SetParameters from rcl_interfaces.msg import ParameterDescriptor, ParameterValue, Parameter from rclpy.parameter import ParameterType class Color(QWidget): def __init__(self, color): super(Color, self).__init__() self.setAutoFillBackground(True) palette = self.palette() palette.setColor(QPalette.Window, QColor(color)) self.setPalette(palette) class Pos(QWidget): shuttle = pyqtSignal(int) robot = pyqtSignal(int) default_robot = pyqtSignal(int) default_shuttle = pyqtSignal(int) robot_position = [] table_position = [] def __init__(self, x, y, *args, **kwargs): super(Pos, self).__init__(*args, **kwargs) self.setFixedSize(QSize(20, 20)) self.x = x self.y = y self.draw_robot_img = False self.draw_shuttle_img = False self.draw_default_robot = False self.draw_default_shuttle = False def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) r = event.rect() p.drawRect(r) # Draw robot if self.draw_robot_img and not self.draw_shuttle_img: #p.begin() #Node("gui").get_logger().info("Position robot: " + str(self.x)) p.fillRect(r,QColor(Qt.gray)) self.robot_position.append(float('%d.%d' % (self.x, self.y))) print("Robot position: " + str(self.robot_position)) # Parameter('robot_position',Parameter.Type.INTEGER_ARRAY,self.robot_position) self.draw_default_shuttle = False self.draw_default_robot = False self.draw_shuttle_img = False #self.update() #p.end() # Draw shuttle if self.draw_shuttle_img and not self.draw_robot_img: #p.begin() p.fillRect(r,QColor(Qt.black)) self.table_position.append(float('%d.%d' % (self.x, self.y))) print("Position table: " + str(self.table_position)) #Parameter('table_position',Parameter.Type.INTEGER_ARRAY,self.table_position) self.draw_default_robot = False self.draw_default_shuttle = False self.draw_robot_img = False #self.update() # Reset robot or shuttle if self.draw_default_robot: #p.begin() p.eraseRect(r) self.robot_position.remove(float('%d.%d' % (self.x, self.y))) print("Robot position: " + str(self.robot_position)) p.drawRect(r) self.draw_robot_img = False #p.end() if self.draw_default_shuttle: #p.begin() p.eraseRect(r) self.table_position.remove(float('%d.%d' % (self.x, self.y))) print("Position table: " + str(self.table_position)) p.drawRect(r) self.draw_shuttle_img = False def mouseReleaseEvent(self, e): if (e.button() == Qt.RightButton) and self.draw_robot_img: self.draw_robot_img = False self.draw_default_robot = True self.default_robot.emit(1) self.update() elif (e.button() == Qt.LeftButton) and self.draw_shuttle_img: self.draw_shuttle_img = False self.draw_default_shuttle = True self.default_shuttle.emit(1) self.update() elif (e.button() == Qt.RightButton): self.draw_robot_img = True self.draw_default_robot = False self.robot.emit(1) self.update() elif (e.button() == Qt.LeftButton): self.draw_shuttle_img = True self.draw_default_shuttle = False self.shuttle.emit(1) self.update() class Input(QLineEdit): def __init__(self, placeholder): super(Input, self).__init__() self.lenght = 10 self.width = 10 self.setPlaceholderText(placeholder) self.setValidator(QIntValidator(0,1000,self)) self.textChanged.connect(MainWindow.input) class Grid(QGridLayout): def __init__(self, input_width, input_lenght): super(Grid, self).__init__() self.setSpacing(0) self.width = input_width self.lenght = input_lenght rclpy.init() self.gui = Node("gui") self.num_robot = 0 self.num_tabels = 0 self.client = self.gui.create_client(GetParameters, '/global_parameter_server/get_parameters') request = GetParameters.Request() # self.cli = self.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') # while not self.cli.wait_for_service(timeout_sec=1.0): # self.gui.get_logger().warn('111service not available, waiting again...') #self.req = SetParameters.Request() #input = MainWindow() #self.send_request() request.names = ['num_of_shuttles'] # while not self.client.wait_for_service(timeout_sec=3): # self.gui.get_logger().warn('222service not available, waiting again...') future = self.client.call_async(request=request) future.add_done_callback(self.callback_global_param) self.result = future.result() # self.num_robot = self.gui.get_parameter('num_of_manipulators').get_parameter_value().integer_value # self.num_tabels = self.gui.get_parameter('num_of_tabels').get_parameter_value().integer_value #self.num_shuttels = self.gui.get_parameter('num_of_shuttles').get_parameter_value().integer_value # self.robot_position = [] # self.table_position = [] # self.gui.declare_parameter('robot_position', self.robot_position) # self.gui.declare_parameter('table_position', self.table_position) self.setSizeConstraint(QLayout.SetFixedSize) self.shuttle = False self.but = None self.create_grid(input_width, input_lenght) def callback_global_param(self, future): try: result = future.result() except Exception as e: self.gui.get_logger().warn("service call failed %r" % (e,)) else: self.param = result.values[0].integer_value self.gui.get_logger().error("Got global param: %s" % (self.param,)) # def send_request(self, value: int, name: str): # new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=value) # self.req.parameters = [Parameter(name='num_of_shuttles', value=new_param_value)] # self.future = self.cli.call_async(self.req) def update_grid(self, input_width, input_lenght): # Delete the old grid, and create a new for x in range(0, self.width): for y in range(0, self.lenght): w = Pos(x, y) self.itemAtPosition(y, x).widget().deleteLater() self.width = input_width self.lenght = input_lenght self.create_grid(input_width, input_lenght) def create_grid(self, input_width, input_lenght): #Create the map grid for x in range(0,self.width): for y in range(0, self.lenght): self.w = Pos(x, y) self.w.robot.connect(self.draw_robot) self.w.shuttle.connect(self.draw_shuttle) self.w.default_robot.connect(self.draw_default_robot_img) self.w.default_shuttle.connect(self.draw_default_shuttle_img) self.addWidget(self.w,y,x) def draw_robot(self): self.num_robot += 1 # Initial setup for parameters cli = self.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') req = SetParameters.Request() # Parameters for number of manipulators new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=int(self.num_robot)) req.parameters = [Parameter(name='num_of_manipulators', value=new_param_value)] self.future = cli.call_async(req) # Parameters for manipulator position robot_pos_param = ParameterValue(type=ParameterType.PARAMETER_DOUBLE_ARRAY, double_array_value=self.w.robot_position) req.parameters = [Parameter(name='robot_position', value=robot_pos_param)] self.future = cli.call_async(req) self.gui.get_logger().warn("Robot positions: " + str(self.w.robot_position)) print("Number of robot:", self.num_robot) self.draw_robot_img = True def draw_shuttle(self): self.num_tabels += 1 # Initial setup for parameters cli = self.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') req = SetParameters.Request() # Parameters for number of tabels new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=int(self.num_tabels)) req.parameters = [Parameter(name='num_of_tabels', value=new_param_value)] self.future = cli.call_async(req) # Parameters for table position table_pos_param = ParameterValue(type=ParameterType.PARAMETER_DOUBLE_ARRAY, double_array_value=self.w.table_position) req.parameters = [Parameter(name='table_position', value=table_pos_param)] self.future = cli.call_async(req) self.gui.get_logger().warn("Table positions: " + str(self.w.table_position)) print("Number of tables:", self.num_tabels) self.draw_shuttle_img = True def draw_default_robot_img(self): self.num_robot -= 1 # Initial setup for parameters cli = self.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') req = SetParameters.Request() # Parameters for number of manipulators new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=int(self.num_robot)) req.parameters = [Parameter(name='num_of_manipulators', value=new_param_value)] self.future = cli.call_async(req) # Parameters for manipulator position robot_pos_param = ParameterValue(type=ParameterType.PARAMETER_DOUBLE_ARRAY, double_array_value=self.w.robot_position) req.parameters = [Parameter(name='robot_position', value=robot_pos_param)] self.future = cli.call_async(req) self.gui.get_logger().warn("Robot positions: " + str(self.w.robot_position)) print("Number of robot:", self.num_robot) self.draw_default_robot = True def draw_default_shuttle_img(self): self.num_tabels -= 1 # Initial setup for parameters cli = self.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') req = SetParameters.Request() # Parameters for number of tabels new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=int(self.num_tabels)) req.parameters = [Parameter(name='num_of_tabels', value=new_param_value)] self.future = cli.call_async(req) # Parameters for table position table_pos_param = ParameterValue(type=ParameterType.PARAMETER_DOUBLE_ARRAY, double_array_value=self.w.table_position) req.parameters = [Parameter(name='table_position', value=table_pos_param)] self.future = cli.call_async(req) self.gui.get_logger().warn("Table positions: " + str(self.w.table_position)) print("Number of tables:", self.num_tabels) self.draw_default_shuttle = True class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Interface for shuttles and robots") # Setting the line edit up for self.line_w = QLineEdit() self.line_w.setPlaceholderText("Width") self.line_w.setValidator(QIntValidator(0,99,self)) self.line_w.textChanged.connect(self.input) self.line_l = QLineEdit() self.line_l.setPlaceholderText("Lenght") self.line_l.setValidator(QIntValidator(0,99,self)) self.line_l.textChanged.connect(self.input) self.num_shu = QLineEdit() self.num_shu.setPlaceholderText("Number of shuttels") self.num_shu.setValidator(QIntValidator(0,80,self)) self.num_shu.textChanged.connect(self.num_shuttle) lenght = 3 width = 3 layout1 = QHBoxLayout() self.width2 = 0 self.lenght2 = 0 but_create = QPushButton("Create grid") but_stop = QPushButton("Stop") robot = QPushButton("Robot") shuttle = QPushButton("Shuttle") layout1.addWidget(robot) layout1.addWidget(shuttle) layout1.addWidget(but_create) layout1.addWidget(but_stop) layout1.addWidget(self.num_shu, stretch=0.2) layout1.addWidget(self.line_w, stretch=0.2) layout1.addWidget(self.line_l, stretch=0.2) self.grid = Grid(width, lenght) layout1.addLayout(self.grid) but_create.clicked.connect(self.update1) layout1.setContentsMargins(0,0,0,0) layout1.setSpacing(10) widget = QWidget() widget.frameSize() widget.setLayout(layout1) self.setCentralWidget(widget) def update1(self): # Update the grid self.grid.update_grid(int(self.line_w.text()), int(self.line_l.text())) def num_shuttle(self): # Update the number of shuttels # Send the number of shuttles to param server self.cli = self.grid.gui.create_client(SetParameters, '/global_parameter_server/set_parameters') self.req = SetParameters.Request() new_param_value = ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=int(self.num_shu.text())) self.req.parameters = [Parameter(name='num_of_shuttles', value=new_param_value)] self.future = self.cli.call_async(self.req) def input(self): # Take the input from the line edit and return it return self.width2, self.lenght2, def main(args=None): app = QApplication(sys.argv) window = MainWindow() executor = MultiThreadedExecutor() executor.add_node(window.grid.gui) thread = Thread(target=executor.spin) thread.start() try: window.show() sys.exit(app.exec()) finally: window.grid.gui.get_logger().info("Shutting down ROS2 Node . . .") # window.grid.gui.destroy_node() # executor.shutdown() if __name__ == '__main__': main()
15,700
Python
35.599068
109
0.588153
abmoRobotics/MAPs/ros2_ws/src/orchestrator/config/config.yaml
shuttle: ros__parameters: num_of_shuttles: 5 shuttle1_position: [0.0,0.0,0.0] shuttle2_position: [0.0,3.0,0.0] shuttle3_position: [1.0,0.0,0.0] shuttle4_position: [1.0,0.0,0.0] shuttle5_position: [1.0,0.0,0.0] manipulator: ros__parameters: num_of_manipulators: 1 manipulator1_position: [0.0,0.0,0.0] gui: ros__parameters: num_of_shuttles: 5 num_of_tabels: 0 num_of_manipulators: 0 robot_position: [0.0 ,0.0] table_position: [0.0 ,0.0]
495
YAML
21.545454
40
0.618182
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/manipulator_utils.py
import roboticstoolbox as rtb from roboticstoolbox import DHRobot, RevoluteDH import numpy as np from PIL import Image class KR3R540(DHRobot): """ Class that models a KR 3 R540 manipulator :param symbolic: use symbolic constants :type symbolic: bool ``KR3R540()`` is an object which models a KUKA KR 3 R540 robot and describes its kinematic standard DH conventions. Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - home, vertical 'READY' configuration """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym pi = sym.pi() else: from math import pi deg = pi / 180 super().__init__( [ RevoluteDH(a=-0.020, alpha=-pi/2, d= 0.345, offset= pi/2, qlim=[-170 * deg, 170 * deg]), RevoluteDH(a= 0.260, qlim=[-170 * deg, 50 * deg]), RevoluteDH(a= 0.020, alpha= pi/2, offset=-pi/2, qlim=[-110 * deg, 155 * deg]), RevoluteDH( alpha=-pi/2, d=-0.260, qlim=[-175 * deg, 175 * deg]), RevoluteDH( alpha= pi/2, qlim=[-120 * deg, 120 * deg]), RevoluteDH( d=-0.075, qlim=[-350 * deg, 350 * deg]) ], name = "KR_3_R540_", manufacturer = "KUKA", keywords=("dynamics", "symbolic", "mesh"), symbolic=symbolic ) self.home = np.array([0, -pi/2, pi/2, 0, 0, 0]) self.qz = np.zeros(6) self.addconfiguration("home", self.home) self.addconfiguration("zero", self.qz) class KR4R600(DHRobot): """ Class that models a KR 4 R600 manipulator :param symbolic: use symbolic constants :type symbolic: bool ``KR4R600()`` is an object which models a KUKA KR 4 R600 robot and describes its kinematic standard DH conventions. Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - home, vertical 'READY' configuration """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym pi = sym.pi() else: from math import pi deg = pi / 180 super().__init__( [ RevoluteDH( alpha=-pi/2, d= 0.330, offset= pi/2, qlim=[-170 * deg, 170 * deg]), RevoluteDH(a=0.290, qlim=[-195 * deg, 40 * deg]), RevoluteDH(a=0.020, alpha= pi/2, offset=-pi/2, qlim=[-115 * deg, 150 * deg]), RevoluteDH( alpha=-pi/2, d=-0.310, qlim=[-185 * deg, 180 * deg]), RevoluteDH( alpha= pi/2, qlim=[-120 * deg, 120 * deg]), RevoluteDH( d=-0.075, qlim=[-350 * deg, 350 * deg]) ], name = "KR4R600_", manufacturer = "KUKA", keywords=("dynamics", "symbolic", "mesh"), symbolic=symbolic ) self.home = np.array([0, -pi/2, pi/2, 0, 0, 0]) self.qz = np.zeros(6) self.addconfiguration("home", self.home) self.addconfiguration("zero", self.qz)
3,620
Python
37.521276
108
0.481215
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/test_manipulator.py
import roboticstoolbox as rtb from manipulator_utils import KR4R600, KR3R540 robot = KR4R600() Te = robot.fkine(robot.qz) # forward kinematics print(Te) from spatialmath import SE3 Tep = SE3.Trans(0, 0, 0) * SE3.OA([0, 1, 0], [0, 0, 1]) print(Tep) sol = robot.ik_lm_chan(Tep) # solve IK print(sol) q_pickup = sol[0] print(robot.fkine(q_pickup)) qt = rtb.jtraj(robot.qz, robot.home, 50) robot.plot(qt.q, backend='pyplot')
436
Python
19.809523
55
0.683486
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/__init__.py
# __init__.py from .utils import * from .shuttle_utils import ShuttleMode from .manipulator_utils import KR3R540 from .manipulator_utils import KR4R600 from .task_planner_utils import *
185
Python
29.999995
38
0.789189
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/shuttle_utils.py
import math from sensor_msgs.msg import JointState class ShuttleMode(): """ Holds a number of different task that the ACOPOS 6D can do. : move Move the shuttel to different positions (X,Y) : rotate Rotate the shuttle in a specific RPM (Joint Z) : shake Lift and sink the shuttle in Z to make i shake : tumble Tumble the shuttle around the Z joint, moving the X and Y joint. """ def __init__(self): self.msg = JointState() def move(self, position: float, velocity: float): """ Move the shuttel to different positions (X,Y,Z) """ self.msg.position = position self.msg.velocity = velocity return self.msg def rotate(self, RPM: int, time: float): """ Rotate the shuttle in a specific RPM (Joint Z) """ self.msg.position = [0,0,0,0,0,1] self.msg.velocity = [0,0,0,0,0,(RPM/60)*360] return self.msg def shake(self, RPM: int): """ Lift and sink the shuttle in Z to make i shake """ self.msg.position = [0, 0, 1, 0, 0, 0] self.msg.velocity = [0, 0, 2, 0, 0, 0] return self.msg def tumbler(self): return self.msg def dispensing(self): return self.msg
1,359
Python
19.60606
80
0.543046
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/utils.py
#!/usr/bin/env python3 # utils.py from rclpy.node import Node from rclpy.action import ActionServer from rclpy.action import ActionClient import yaml import numpy as np import os from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from ament_index_python.packages import get_package_share_directory import os from ros2param.api import call_list_parameters, call_get_parameters, get_value from ros2node.api import get_absolute_node_name from rclpy.parameter import PARAMETER_SEPARATOR_STRING from ros2node.api import get_node_names def create_publisher_array(node: Node, n_robots: int, topic_prefix: str, topic_name: str, msg_type: type): """ Create a list of ROS publishers for a given number of robots. :param node: The ROS Node object that will be used to create the publishers. :type node: Node :param n_robots: The number of publishers to create. :type n_robots: int :returns: A list of ROS publishers created by the given node for each robot, with the topic name and index based on the robot number. :rtype: List[Publisher] """ publishers = [] for i in range(n_robots): node.get_logger().info('created topic: ' + topic_prefix + str(i) + topic_name) node.get_logger().info('n_robots: ' + str(n_robots)) publishers.append(node.create_publisher(msg_type, topic_prefix+str(i)+topic_name, 10)) return publishers def destroy_publisher_array(node: Node, publishers: int): """s Create a list of ROS publishers for a given number of robots. :param node: The ROS Node object that will be used to create the publishers. :type node: Node :param n_robots: The number of publishers to create. :type n_robots: int :returns: A list of ROS publishers created by the given node for each robot, with the topic name and index based on the robot number. :rtype: List[Publisher] """ for i in range(len(publishers)): node.get_logger().info('Destroy all topics') node.destroy_publisher(publishers[i]) return publishers def create_joint_state_message_array(joint_names: str, n_msgs: int) -> JointState: """ Creates an array of JointState messages with the given number of messages and joint names. Args: joint_names (str): A string representing the names of the joints in the messages. n_msgs (int): The number of JointState messages to create. Returns: List[JointState]: An array of JointState messages, each with the same joint names. """ msgs = [] msg = JointState() for i in range(n_msgs): zero_array = [0.0] * len(joint_names) msg.name = joint_names msg.position = zero_array msg.velocity = zero_array msg.effort = zero_array msgs.append(msg) return msgs def load_yaml_file(node_name: str) -> dict: config_path = os.path.join( get_package_share_directory('orchestrator'), 'config', 'config.yaml') with open(config_path, 'r') as f: config = yaml.full_load(f) config = config[node_name]["ros__parameters"] return config def yaml_position_generate(node: Node, number_of_robots: int): positions = {} with open('src/orchestrator/config/initial_position.yaml', 'w') as yaml_file: for i in range(number_of_robots): positions['shuttle'+str(i+1)+'_position'] = [] node.get_logger().info(str(positions)) node_n = {str(node.get_name()): {'ros__parameters': positions}} yaml_out = yaml.dump(node_n, yaml_file, sort_keys=False) node.get_logger().info(str(yaml_out)) def insert_dict(dictionary, key, value): split = key.split(".", 1) if len(split) > 1: if not split[0] in dictionary: dictionary[split[0]] = {} insert_dict(dictionary[split[0]], split[1], value) else: dictionary[key] = value def get_parameter_values(node, node_name, params): response = call_get_parameters( node=node, node_name=node_name, parameter_names=params) # requested parameter not set if not response.values: return '# Parameter not set' # extract type specific value return [get_value(parameter_value=i) for i in response.values] #TODO FIX def save_yaml(self): node_names = get_node_names(node=self, include_hidden_nodes=False) yaml_output = {} for node in node_names: print(node.full_name) print("jeg sidder fast2") response = call_list_parameters(node=self, node_name=node.full_name) print("jeg sidder fast3") response = sorted(response) print("jeg sidder fast4") parameter_values = get_parameter_values(self, node.full_name, response) print("jeg sidder fast5") #yaml_output = {node.name: {'ros__parameters': {}}} yaml_output[node.name] = {'ros__parameters': {}} for param_name, pval in zip(response, parameter_values): print("jeg sidder fast") insert_dict( yaml_output[node.name]['ros__parameters'], param_name, pval) print(yaml_output) print("NU2") print(yaml_output) with open(os.path.join("", "tester3" + '.yaml'), 'w') as yaml_file: yaml.dump(yaml_output, yaml_file, default_flow_style=False) def create_action_server_array(node: Node, action_type: type, topic_prefix: str, callback_type: type, n_robots: int): """ Create a list of ROS action servers for a given number of robots. :param node: The ROS Node object that will be used to create the action. :type node: Node :param action_type: The type of action that is asigned for the robot :type action_type: type :param n_robots: The number of servers to create. :type n_robots: int :returns: A list of ROS publishers created by the given node for each robot, with the topic name and index based on the robot number. :rtype: List[Publisher] """ action_servers = [] for i in range(n_robots): node.get_logger().info('created action server: ' + topic_prefix + str(i)) node.get_logger().info('n_robots: ' + str(topic_prefix)) action_servers.append(ActionServer(node, action_type, topic_prefix + str(f'{i:02}'), callback_type)) return action_servers def create_action_client_array(node: Node, action_type: type, topic_prefix: str, callback, n_robots: int): """ Create a list of ROS action clients for a given number of robots. :param node: The ROS Node object that will be used to create the action client. :type node: Node :param action_type: The type of action that is asigned for the robot :type action_type: type :param n_robots: The number of clients to create. :type n_robots: int :returns: A list of ROS action clients created by the given node for each robot, with the topic prefic and index based on the robot number. :rtype: List[Action Clients] """ action_clients = [] for i in range(n_robots): node.get_logger().info('created action: ' + topic_prefix + str(i)) node.get_logger().info('n_robots: ' + str(topic_prefix)) action_clients.append(ActionClient(node, action_type, topic_prefix + str(f'{i:02}', callback))) return action_clients import heapq class ValueIDManager: """ A class that manages a set of values and their corresponding IDs. The IDs are integers that are assigned to values in the order they are added. The class also keeps track of IDs that have been removed, and reuses them when new values are added. args: None methods: remove_by_value(value): Removes a value from the database. remove_by_id(id_): Removes a value from the database. add_value(value): Adds a value to the database. get_id(value): Returns the ID of a value. get_value(id_): Returns the value of an ID. sync_array(arr): Adds all values in an array to the database, and removes all values that are not in the array. """ def __init__(self): self.id_to_value = {} self.value_to_id = {} self.available_ids = [] self.next_id = 0 def remove_by_value(self, value): if value in self.value_to_id: del_id = self.value_to_id[value] heapq.heappush(self.available_ids, del_id) array_index = list(self.id_to_value.keys()).index(del_id) value_removed = self.id_to_value[del_id] del self.value_to_id[value] del self.id_to_value[del_id] print(f"Value: {value} removed.") return array_index, del_id else: print(f"No such value: {value} in the database.") def remove_by_id(self, id_): if id_ in self.id_to_value: del_value = self.id_to_value[id_] heapq.heappush(self.available_ids, id_) del self.id_to_value[id_] del self.value_to_id[del_value] print(f"ID: {id_} removed.") else: print(f"No such ID: {id_} in the database.") def add_value(self, value): if value in self.value_to_id: print(f"Value: {value} already exists.") else: if self.available_ids: new_id = heapq.heappop(self.available_ids) else: new_id = self.next_id self.next_id += 1 self.id_to_value[new_id] = value self.value_to_id[value] = new_id print(f"Value: {value} added with ID: {new_id}.") def get_id(self, value): return self.value_to_id.get(value, "No such value in the database.") def get_value(self, id_): return self.id_to_value.get(id_, "No such ID in the database.") def sync_array(self, arr): removed_array_index = [] removed_ids = [] for value in arr: if value not in self.value_to_id: self.add_value(value) for value in list(self.value_to_id.keys()): # create a copy of keys to avoid runtime error if value not in arr: array_index_removed, id_removed = self.remove_by_value(value) if id_removed is not None: removed_ids.append(id_removed) removed_array_index.append(array_index_removed) return removed_array_index, removed_ids from tutorial_interfaces.srv import PoseSrv class ClientAsync(Node): def __init__(self): super().__init__('client_async') self.client_add_manipulator = self.create_client(PoseSrv, '/manipulator/add') self.client_add_shuttle = self.create_client(PoseSrv, '/shuttle/add') self.client_add_segment = self.create_client(PoseSrv, '/segment/add') self.client_remove_manipulator = self.create_client(PoseSrv, '/manipulator/remove') self.client_remove_shuttle = self.create_client(PoseSrv, '/shuttle/remove') self.client_remove_segment = self.create_client(PoseSrv, '/segment/remove') #self.service_clients = [self.client_add_manipulator, self.client_add_shuttle, self.client_add_segment, self.client_remove_manipulator, self.client_remove_shuttle, self.client_remove_segment] self.service_clients = [self.client_add_manipulator, self.client_remove_manipulator] for service_clients in self.service_clients: while not service_clients.wait_for_service(timeout_sec=1.0): print(f'{service_clients.srv_name} service not available, waiting again...') def spawn_robot(self, robot_type, robot_id, pose): request = PoseSrv.Request() print(robot_id) print(type(robot_id)) request.name = f'{robot_type}{robot_id:02}' print(request.name) request.pose = pose future = self.client_add_manipulator.call_async(request) #rclpy.spin_until_future_complete(self, future) #return future.result() #future.add_done_callback(self.callback_spawn_robot) def remove_robot(self, robot_type, robot_id): print("Debug #4") request = PoseSrv.Request() request.name = f'{robot_type}{robot_id:02}' future = self.client_remove_manipulator.call_async(request) #rclpy.spin_until_future_complete(self, future) #return future.result() #future.add_done_callback(self.callback_remove_robot) def spawn_shuttle(self, shuttle_id, pose): request = PoseSrv.Request() request.name = f'shuttle_{shuttle_id}' request.pose = pose future = self.client_add_shuttle.call_async(request) #rclpy.spin_until_future_complete(self, future) #return future.result() #future.add_done_callback(self.callback_spawn_shuttle) def remove_shuttle(self, shuttle_id): request = PoseSrv.Request() request.name = f'shuttle_{shuttle_id}' future = self.client_remove_shuttle.call_async(request) #rclpy.spin_until_future_complete(self, future) #return future.result() #future.add_done_callback(self.callback_remove_shuttle) def spawn_segment(self, segment_id, pose): request = PoseSrv.Request() request.name = f'segment_{segment_id:02}' request.pose = pose future = self.client_add_segment.call_async(request) #rclpy.spin_until_future_complete(self, future) #return future.result() #future.add_done_callback(self.callback_spawn_segment) def remove_segment(self, segment_id): request = PoseSrv.Request() request.name = f'segment_{segment_id:02}' future = self.client_remove_segment.call_async(request) #return future.result() #future.add_done_callback(self.callback_remove_segment)
13,853
Python
37.060439
199
0.637551
abmoRobotics/MAPs/ros2_ws/src/orchestrator/utils/task_planner_utils.py
# import rclpy # from rclpy.node import Node import time import heapq from typing import List import numpy as np import copy class Station(): """Class for a single station""" def __init__(self) -> None: self.available = True def get_position(self): return self.position def set_position(self, position: np.ndarray): if position.size != 2: raise ValueError(f"position should be a 2D vector, but got {position.size}D vector, {position}") self.position = position def get_availibility(self): return self.available def set_availibility(self, available: bool): self.available = available class Shuttle(): """Class for a single shuttle""" def __init__(self) -> None: self.available = True self.position = np.array([0,0]) self.index = None def get_position(self): return self.position def set_position(self, position: np.ndarray): if position.size != 2: raise ValueError(f"position should be a 2D vector, but got {position.size}D vector, {position}") self.position = position def get_availibility(self): return self.available def set_availibility(self, available: bool): self.available = available def get_index(self): return self.index def set_index(self, index: int): self.index = index class Task(): """Class for a single task""" def __init__(self, task) -> None: self.creation_time = time.time() self.task = task self.assigned_shuttle_id = None self.in_progress = False self.assigned_station = None def get_creation_time(self): return self.creation_time def get_task(self): return self.task def set_assigned_shuttle_id(self, shuttle_id: int): self.assigned_shuttle_id = shuttle_id def get_assigned_shuttle_id(self): return self.assigned_shuttle_id def set_in_progress(self, status: bool): self.in_progress = status def get_in_progress(self): return self.in_progress def set_assigned_station(self, station: Station): self.assigned_station = station def get_assigned_station(self): return self.assigned_station class StationManager(): """Class for keeping track of the stations""" def __init__(self) -> None: self.stations = [] def add_station(self, station: Station): self.stations.append(station) def remove_station(self, station: Station): self.stations.remove(station) def get_station_by_index(self, station_id: int) -> Station: return self.stations[station_id] def get_stations(self): return self.stations def set_status(self, station: Station, status: bool): station.set_availibility(status) class TaskManager(): """Class for keeping track of the tasks""" def __init__(self) -> None: self.tasks = [] def add_task(self, task: Task): assert isinstance(task, Task), "task is not of type Task" self.tasks.append(task) def remove_task(self, task: Task): self.tasks.remove(task) def get_tasks(self): return self.tasks class ShuttleManager(): """Class for keeping track of the shuttles""" def __init__(self) -> None: self.shuttles: List[Shuttle] = [] def add_shuttle(self, shuttle: Shuttle): index = len(self.shuttles) self.shuttles.append(shuttle) self.shuttles[index].set_index(index) def remove_shuttle(self, shuttle: Shuttle): self.shuttles.remove(shuttle) def get_shuttles(self): return self.shuttles def get_shuttle_by_index(self, shuttle_id: int) -> Shuttle: return self.shuttles[shuttle_id] def get_available_shuttles(self): pass def set_status(self, shuttle: Shuttle, status: bool): shuttle.set_availibility(status) class TaskPlannerUtils(): """ Node for planning and orchestrating tasks for the manipulators and shuttles""" def __init__(self) -> None: self.stations = StationManager() self.tasks = TaskManager() self.shuttles = ShuttleManager() self.active_tasks: List[Task] = [] self.heuristic_spatial_weight = 0.5 self.heuristic_temporal_weight = 0.5 tasks = create_fake_tasks() for task in tasks: self.tasks.add_task(Task(task)) def main(self): # 1. Assign the next task to the available shuttle and manipulator self.next_task() # 2. Check if task is done # 3. Check if sub-task is done def timer_callback(self): self.main() def priority_scores(self, task: Task) -> float: """Function to calculate the priority score of a task""" # 1. Get the requirements of the task # 2. Get the available stations and shuttles that can fulfill the requirements stations = self.get_available_stations() shuttles = self.get_available_shuttles() # 3. Calculate the priority score for each station and shuttle and store them in a heapq priority_scores_heap = [] for station in stations: for shuttle in shuttles: score = self.heuristic(task, station, shuttle) # Use heapq to store the scores heapq.heappush(priority_scores_heap, (score, station, shuttle, shuttle.get_index())) # 4. Return the lowest priority score score, station, shuttle, shuttle_idx = heapq.heappop(priority_scores_heap) return score, station, shuttle, shuttle_idx def heuristic(self, task: Task, station: Station, shuttle: Shuttle, materialShuttle: Shuttle = None) -> float: """Function to calculate the heuristic of a task""" spatial_priority_score = 0 temporal_priority_score = 0 ws = self.heuristic_spatial_weight wt = self.heuristic_temporal_weight if materialShuttle is not None: station_position = station.get_position() spatial_priority_score = (station_position - shuttle.get_position()) + (station_position - materialShuttle.get_position()) else: spatial_priority_score = station.get_position() - shuttle.get_position() # 2. Calculate temporal priority score creation_time = task.get_creation_time() temporal_priority_score = time.time() - creation_time spatial_priority_score = np.linalg.norm(spatial_priority_score) score = ws * spatial_priority_score + wt * temporal_priority_score return score def next_task(self): """Function to assign find the next task to be executed""" # 1. Check if there are any tasks tasks = self.get_tasks() if not tasks: return None # 2. Check if there are any stations available stations = self.get_available_stations() if not stations: return None # 3. Check if there are any shuttles available shuttles = self.get_available_shuttles() if not shuttles: return None # 4. Check if there are any manipulators available -> Not required for now # 5. Calculate the priority score of the tasks min_score = float('inf') min_station = None min_shuttle = None min_task = None idx_shuttle_min_task = None for task in tasks: score, station, shuttle, shuttle_idx = self.priority_scores(task) if score < min_score: min_score = score min_station = station min_shuttle = shuttle min_task = task idx_shuttle_min_task = shuttle_idx # 5.1 set the assigned shuttle to the task min_task.set_assigned_shuttle_id(idx_shuttle_min_task) min_task.set_assigned_station(min_station) # 6. Assign the task with the lowest priority score to the available shuttle and manipulator # task = # 6.1. Update the station list self.stations.set_status(min_station, False) # 6.2. Update the shuttle list self.shuttles.set_status(min_shuttle, False) # 6.3 # 6.3. Update the manipulator list # 7. Update the task list self.active_tasks.append(min_task) self.tasks.remove_task(min_task) print(self.active_tasks) def assign_task(self, task: Task): """Function to assign a task to a shuttle and manipulator""" def get_tasks(self) -> List[Task]: """Function to get the tasks from the task manager""" if self.tasks.get_tasks(): return self.tasks.get_tasks() else: return None def get_active_tasks(self): """Function to get the active tasks from the task manager""" if self.active_tasks: return self.active_tasks else: return None def get_available_stations(self): """Function to get the stations from the station manager""" if self.stations.get_stations(): stations = [] for station in self.stations.get_stations(): if station.get_availibility(): stations.append(station) return stations else: return None def get_available_shuttles(self): """Function to get the shuttles from the shuttle manager""" if self.shuttles.get_shuttles(): shuttles = [] for shuttle in self.shuttles.get_shuttles(): if shuttle.get_availibility(): shuttles.append(shuttle) return shuttles else: None def free_station(self, station: Station): """Function to free a station""" self.stations.set_status(station, True) def free_shuttle(self, shuttle: Shuttle): """Function to free a shuttle""" self.shuttles.set_status(shuttle, True) import random def create_fake_tasks(): """Function to create fake tasks""" fake1_actions = [{"name": 'add', "material": {'value': '4-bromoaniline', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'dichloromethane', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'sodium hydroxide', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'stir', "content": {'duration': {'value': 15, 'unit': 'seconds'}}}, {"name": 'store', "content": {'sample_name': {'value': 15, 'unit': 'seconds'}}}] fake2_actions = [{"name": 'add', "material": {'value': '4-bromoaniline', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'dichloromethane', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'sodium hydroxide', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'stir', "content": {'duration': {'value': 15, 'unit': 'seconds'}}}, {"name": 'store', "content": {'sample_name': {'value': 15, 'unit': 'seconds'}}}] fake3_actions = [{"name": 'add', "material": {'value': '4-bromoaniline', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'dichloromethane', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'sodium hydroxide', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'stir', "content": {'duration': {'value': 15, 'unit': 'seconds'}}}, {"name": 'store', "content": {'sample_name': {'value': 15, 'unit': 'seconds'}}}] fake4_actions = [{"name": 'add', "material": {'value': '4-bromoaniline', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'dichloromethane', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'sodium hydroxide', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'stir', "content": {'duration': {'value': 15, 'unit': 'seconds'}}}, {"name": 'store', "content": {'sample_name': {'value': 15, 'unit': 'seconds'}}}] fake5_actions = [{"name": 'add', "material": {'value': '4-bromoaniline', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'dichloromethane', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'add', "material": {'value': 'sodium hydroxide', "quantity": {'value': 15, 'unit': 'ml'}},}, {"name": 'stir', "content": {'duration': {'value': 15, 'unit': 'seconds'}}}, {"name": 'store', "content": {'sample_name': {'value': 15, 'unit': 'seconds'}}}] fake_tasks = [fake1_actions, fake2_actions, fake3_actions, fake4_actions, fake5_actions] tasks = [task for task in fake_tasks for _ in range(20)] random.shuffle(tasks) return tasks if __name__ == '__main__': tasks = create_fake_tasks() task_planner = TaskPlannerUtils() for task in tasks: task_planner.tasks.add_task(Task(task)) Station1 = Station() Station2 = Station() Station3 = Station() Station1.set_position(np.array([0,0])) Station2.set_position(np.array([1,0])) Station3.set_position(np.array([2,0])) task_planner.stations.add_station(Station1) task_planner.stations.add_station(Station2) task_planner.stations.add_station(Station3) Shuttle1 = Shuttle() Shuttle2 = Shuttle() Shuttle3 = Shuttle() Shuttle1.set_position(np.array([2,2])) Shuttle2.set_position(np.array([3,3])) Shuttle3.set_position(np.array([4,4])) task_planner.shuttles.add_shuttle(Shuttle1) task_planner.shuttles.add_shuttle(Shuttle2) task_planner.shuttles.add_shuttle(Shuttle3) #task_planner.main() for i in range(4): task_planner.main() active_tasks = task_planner.get_active_tasks() for active_task in active_tasks: #print(f'Active task: {active_task.get_task()}') print(f'Assigned shuttle id: {active_task.get_assigned_shuttle_id()}') print(f'Active task: {active_task.get_task()}') #print(f'Get available shuttles: {task_planner.get_available_shuttles()}') #print(f'Get available stations: {task_planner.get_available_stations()}') # 1. Start executing the task
15,863
Python
33.189655
134
0.543025
abmoRobotics/MAPs/ros2_ws/src/acopos_bringup/launch/acopos.launch.py
import os from launch import LaunchDescription from launch_ros.actions import Node from ament_index_python.packages import get_package_share_directory def generate_launch_description(): ld = LaunchDescription() global_parameters = os.path.join( get_package_share_directory('acopos_bringup'), 'config', 'global_params.yaml' ) global_param_node = Node( package='acopos_bringup', executable='global_parameter_server', name='global_parameter_server', parameters=[global_parameters] ) ld.add_action(global_param_node) return ld
606
Python
30.947367
67
0.686469
abmoRobotics/MAPs/ros2_ws/src/acopos_bringup/src/global_parameter_server_node.cpp
#include "rclcpp/rclcpp.hpp" int main(int argc, char **argv) { rclcpp::init(argc, argv); rclcpp::NodeOptions options; options.allow_undeclared_parameters(true); options.automatically_declare_parameters_from_overrides(true); auto node = std::make_shared<rclcpp::Node>("global_parameter_server", options); rclcpp::spin(node); rclcpp::shutdown(); return 0; }
387
C++
31.333331
83
0.697674
abmoRobotics/MAPs/ros2_ws/src/acopos_bringup/config/global_params.yaml
gui: ros__parameters: num_of_shuttles: 8 num_of_manipulators: 0 num_of_tabels: 0 robot_position: [0.0] table_position: [0.0]
146
YAML
19.999997
26
0.616438
abmoRobotics/MAPs/omniverse/README.md
## Where entry usd is placed
28
Markdown
27.999972
28
0.75
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/asynctest.py
import asyncio import rclpy from rclpy.node import Node from std_msgs.msg import String async def tester(pub): msg = String() msg.data = "Hello World" for i in range(10): print(i) pub.publish(msg) await asyncio.sleep(1.0) print("ok") pub.unregister() pub = None node = rclpy.create_node("inline_publisher") publisher = node.create_publisher(String, "topicer", 10) asyncio.ensure_future(tester(publisher)) ### Version 2 import asyncio import rclpy from rclpy.node import Node from std_msgs.msg import String async def tester(pub): msg = String() msg.data = "Hello World" while rclpy.ok(): pub.publish(msg) await asyncio.sleep(0.00000001) print("ok") pub.unregister() pub = None node = rclpy.create_node("inline_publisher") publisher = node.create_publisher(String, "topicer", 10) asyncio.ensure_future(tester(publisher)) ### Service import rclpy from std_srvs.srv import SetBool import asyncio async def toggle_led(request, response): global led_state led_state = request.data response.success = True response.message = "LED toggled" return response async def service_test(): global led_state node = rclpy.create_node("service_test") srv = node.create_service(SetBool, "/toggle_led", toggle_led) for i in range(10): print(i) rclpy.spin_once(node) await asyncio.sleep(0.5) node.destroy_node() asyncio.ensure_future(service_test())
1,505
Python
18.063291
65
0.669103
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/README.md
# This is an extensions for a digital twin of a chemical synthesis in Isaac Sim.
82
Markdown
26.666658
80
0.768293
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/extension.py
import omni.ext import carb.events import pxr.Usd as Usd import pxr.Sdf as Sdf import omni.kit.app import time import rclpy from .ros2.manager import RosManager import omni.ui as ui import omni.kit.commands import omni.usd from sensor_msgs.msg import JointState # import pxr.Usd # import pxr.Sdf # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[abmoRobotics.maps] some_public_function waas called wcith x: ", x) return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class AbmoroboticsMapsExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def initialize(self): self.dummy_node = rclpy.create_node("dummy") def on_startup(self, ext_id): self.ros_started = False print("[abmoRobotics.maps] abmoRobotics mas startup") self.update_stream = omni.kit.app.get_app().get_update_event_stream() self.sub = self.update_stream.create_subscription_to_pop(self.on_event, name="abmoRobotics.maps") self.last_time = time.perf_counter() self.stage: Usd.Stage = omni.usd.get_context().get_stage() self.ros_manager = RosManager() self._count = 1 self._window = ui.Window("MAPs ", width=300, height=100) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_reset(): self.stage: Usd.Stage = omni.usd.get_context().get_stage() for i in range(50): sdf_path = Sdf.Path(f"/World/tableScaled/joints/shuttle_120x120_{i:02}") prim: Usd.Prim = self.stage.GetPrimAtPath(sdf_path) if prim.IsValid(): try: self.stage.RemovePrim(prim.GetPath()) self.ros_manager.reset_manager() self.ros_started = False except Exception as e: print(f"Error deleting prim: {e}") label.text = "Not runnng" def on_click(): self._count += 1 # label.text = f"count: {self._count}" self.start_ros() label.text = "Status: Running" # on_reset() with ui.HStack(): ui.Button("Start", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def start_ros(self): try: print("starting ros") self.ros_manager.check_for_new_shuttle_topics() self.ros_started = True except Exception as e: print(f"Error starting ROS: {e}") def on_shutdown(self): print("[abmoRobotics.maps] abmoRobotics maaps shutdown") def on_event(self, e: carb.events.IEvent): # if not self.ros_started: # self.start_ros() dt = time.perf_counter() - self.last_time self.last_time = time.perf_counter() fps = 1.0 / dt # print(f) if self.ros_started: if self.ros_manager.shuttles[0] is not None: self.ros_manager.calculate_and_apply_control_input() for joint_state_subscriber in self.ros_manager.joint_state_subscribers: rclpy.spin_once(joint_state_subscriber, timeout_sec=0.00000000000000001) for initial_pose_subscriber in self.ros_manager.initial_pose_subscribers: rclpy.spin_once(initial_pose_subscriber, timeout_sec=0.00000000000000001) velocities, positions, target_positions = self.ros_manager._get_current_shuttle_states() for idx, joint_state_publisher in enumerate(self.ros_manager.joint_state_publisher): joint_state = JointState() joint_state.name.append(f"{idx}") for i in range(3): joint_state.position.append(float(positions[idx][i])) joint_state.velocity.append(float(velocities[idx][i])) joint_state_publisher.publish_joint_state(joint_state)
4,569
Python
39.442478
119
0.589407
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/__init__.py
from .extension import *
24
Python
23.999976
24
0.791667
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/ros2/subscribers.py
from rclpy.node import Node from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from ..package.planar_motor import PlanarMotor class JointStateSubscriber(Node): def __init__(self, topic, prim_path: PlanarMotor): super().__init__("joint_state_subscriber") self.subscription = self.create_subscription(JointState, topic, self.listener_callback, 10) self.subscription # prevent unused variable warning self.prim_path = prim_path self.position = 0 def listener_callback(self, msg: JointState): if not self.position == msg.position: self.prim_path.set_joint_target(msg.position) self.position = msg.position class InitialPoseSubscriber(Node): def __init__(self, topic, prim_path: PlanarMotor): super().__init__("initial_state_subscriber") self.subscription = self.create_subscription(Pose, topic, self.listener_callback, 10) self.subscription # prevent unused variable warning self.prim_path = prim_path def listener_callback(self, msg: Pose): self.prim_path.set_initial_transform(msg.position.x * 100, msg.position.y * 100, msg.position.z * 100)
1,200
Python
39.033332
110
0.69
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/ros2/__init__.py
from .subscribers import *
27
Python
12.999994
26
0.777778
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/ros2/manager.py
import rclpy import pxr.Usd as Usd import pxr.Sdf as Sdf from .subscribers import JointStateSubscriber, InitialPoseSubscriber from .publishers import JointStatePublisher from ..package.planar_motor import PlanarMotor import omni.usd import omni.kit.commands from typing import List import numpy as np class RosManager: def __init__(self) -> None: self.joint_state_subscribers: List[JointStateSubscriber] = [] self.initial_pose_subscribers: List[InitialPoseSubscriber] = [] self.joint_state_publisher: List[JointStatePublisher] = [] self.shuttles: List[PlanarMotor] = [] self.shuttle_prefix = "/World/tableScaled/joints/shuttle_120x120_" # Format _ + f'{idx:02}' self.stage = omni.usd.get_context().get_stage() self.initialize_ros() print("ROS initialized") def initialize_ros(self): if not rclpy.utilities.ok(): rclpy.init() self.dummy_node = rclpy.create_node("dummy_node") def reset_manager(self): self.joint_state_subscribers = [] self.initial_pose_subscribers = [] self.joint_state_publisher = [] self.shuttles = [] def add_subscriber(self, topic, prim_path): self.joint_state_subscribers.append(JointStateSubscriber(topic, prim_path)) self.initial_pose_subscribers.append(InitialPoseSubscriber(topic, prim_path)) def add_publisher(self, topic): self.joint_state_publisher.append(JointStatePublisher(topic)) def add_shuttle_prim(self, shuttle): self.shuttles.append(shuttle) def check_for_new_shuttle_topics(self): shuttle_topics = [ x[0] for x in self.dummy_node.get_topic_names_and_types() if ("shuttle" in x[0] and x[0].endswith("joint_command")) ] for idx, topic in enumerate(shuttle_topics): sdf_path = Sdf.Path(f"{self.shuttle_prefix}{idx:02}") prim: Usd.Prim = self.stage.GetPrimAtPath(sdf_path) if bool(self.dummy_node.get_publishers_info_by_topic(topic)): if not prim.IsValid(): planar_motor = PlanarMotor(self.shuttle_prefix, idx) planar_motor.spawn() self.add_shuttle_prim(planar_motor) self.add_subscriber(topic, planar_motor) self.add_publisher(f"shuttle{idx:02}/joint_states") else: if prim.IsValid(): omni.kit.commands.execute("DeletePrims", paths=[Sdf.Path(f"{self.shuttle_prefix}{idx:02}")], destructive=False) def _apply_control_input(self, control_inputs): for shuttle, control_input in zip(self.shuttles, control_inputs): control_input = [-control_input[0], -control_input[1], 0.0, 0.0, 0.0, 0.0] shuttle.set_target_velocity(control_input) def _get_current_shuttle_states(self): velocities = np.zeros((len(self.shuttles), 3)) positions = np.zeros((len(self.shuttles), 3)) target_positions = np.zeros((len(self.shuttles), 6)) for idx, shuttle in enumerate(self.shuttles): velocities[idx] = shuttle.get_joint_velocity() positions[idx] = shuttle.get_joint_position() target_positions[idx] = shuttle.get_joint_target() return velocities, positions, target_positions def calculate_and_apply_control_input(self): velocities, positions, target_positions = self._get_current_shuttle_states() potentials = np.zeros((len(self.shuttles), 2)) if self.check_for_collisions(positions): print("Collision detected") try: self.potential_field, control_signal = self.shuttles[0].apply_force_field_controller( positions, velocities, target_positions, potentials ) self._apply_control_input(control_signal) except Exception as e: print(f"Err: {e}") return potentials def check_for_collisions(self, positions): distances = self.calculate_distances(positions) return self.check_threshold(distances, 0.121) def calculate_distances(self, points): points = np.array(points) diff = points[:, np.newaxis, :] - points[np.newaxis, :, :] distances = np.max(np.abs(diff), axis=-1) return distances def check_threshold(self, distances, threshold): np.fill_diagonal(distances, np.inf) # Set diagonal elements to infinity to ignore self-distances return np.any(distances < threshold)
4,536
Python
39.873874
131
0.637346
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/ros2/publishers.py
from rclpy.node import Node from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from ..package.planar_motor import PlanarMotor class JointStatePublisher(Node): def __init__(self, topic): super().__init__("shuttle_joint_state_publisher") self.publisher = self.create_publisher(JointState, topic, 10) def publish_joint_state(self, msg: JointState): self.publisher.publish(msg)
432
Python
29.928569
69
0.722222
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/base.py
import omni.kit.commands from pxr import Gf, Sdf class Manipulator: def __init__(self, manipulator_root: str, manipulator_index: int) -> None: self.manipulator_root = f"{manipulator_root}{manipulator_index:02}" self.manipulator_index = manipulator_index self.simulator = OmniverseInterface() def set_joint_target(set_target_position: list): raise NotImplementedError("Method not implemeted") def set_joint_target_relative(self, target_positions: list): raise NotImplementedError("Method not implemented") def set_target_velocity(self, target_velocities: list): raise NotImplementedError("Method not implemented") def spawn(self): raise NotImplementedError("Method not implemented") def despawn(self): raise NotImplementedError("Method not implemented") def set_initial_transform(self, x, y, z): raise NotImplementedError("Method not implemented") class SixAxisRobotInterace(): def __init__(self, manipulator_root: str, manipulator_index: int) -> None: self.manipulator_root = f"{manipulator_root}_{manipulator_index:02}" self.manipulator_index = manipulator_index self.omni_interface = OmniverseInterface() def change_node_namespace(self, namespace: str): raise NotImplementedError("Method not implemented") def change_topic(self, topic: str): raise NotImplementedError("Method not implemented") def spawn(self): raise NotImplementedError("Method not implemented") def _set_initial_transform(self, x, y, z): raise NotImplementedError("Method not implemented") class OmniverseInterface: def __init__(self) -> None: self.stage = omni.usd.get_context().get_stage() def _change_property(self, prim_path: str, attribute_name: str, value: float): prim = self.stage.GetPrimAtPath(prim_path) prim.GetAttribute(attribute_name).Set(value) def _get_property(self, prim_path: str, attribute: str): prim = self.stage.GetPrimAtPath(prim_path) prim_property = prim.GetAttribute(attribute) return prim_property.Get() def _create_payload(self, prim_path: str, asset_path: str): omni.kit.commands.execute('CreatePayload', usd_context=omni.usd.get_context(), path_to=Sdf.Path(prim_path), asset_path=asset_path, instanceable=False) def _transform_prim(self, prim_path: str, x: float, y: float, z: float): print(Gf.Matrix4d(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0)) omni.kit.commands.execute('TransformPrim', path=Sdf.Path(prim_path), new_transform_matrix=Gf.Matrix4d(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0))
3,227
Python
38.851851
86
0.575147
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/planar_motor/controller.py
import numpy as np class Controller: """PD controller for a single joint""" def __init__(self, p_gain: np.ndarray, d_gain: np.ndarray, max_veloicty: np.ndarray): self.p_gain = p_gain self.d_gain = d_gain self.max_veloicty = max_veloicty # self.omni_interface = OmniverseInterface() def get_control_signal(self, current_position: np.ndarray, target_position: np.ndarray, current_velocity: np.ndarray): error = target_position - current_position error_dot = error - current_velocity control_signal = self.p_gain * error + self.d_gain * error_dot # control_signal = np.clip(control_signal, -self.max_veloicty, self.max_veloicty) return control_signal class ForceFieldController: """Calculate Force Fields required to avoid collisions""" def __init__(self, dt: float, timesteps: int, p_gain: float, d_gain: float, max_velocity: float): self.dt = dt self.timesteps = timesteps self.base_controller = Controller(p_gain, d_gain, max_velocity) def predict_trajectory( self, current_position: np.ndarray, current_velocity: np.ndarray, target_position: np.ndarray, potential_field: np.ndarray = None ): """Predict the trajectory of the robot based on the current position and velocity""" potential_field = np.zeros((current_position.shape[0], 2)) number_of_shuttles = current_position.shape[0] if potential_field is None: potential_field = np.zeros((number_of_shuttles, 2)) has_valid_trajectory = False # print(f'current_position: {current_position}') control_signal = np.zeros((number_of_shuttles, 2)) current_position = current_position current_velocity = current_velocity while not has_valid_trajectory: for i in range(self.timesteps): for j in range(number_of_shuttles): current_position[j][0:2], current_velocity[j][0:2] = self.new_states( current_position[j], current_velocity[j], target_position[j], potential_field[j] ) if i == 0: # Print shapes control_signal[j, 0:2] = current_velocity[j, 0:2] # Check if there is a collision, and if so, calculate the force field collision, potentials = self.potential_field_checker(current_position, current_velocity, target_position, potential_field) potential_field += potentials if collision: break if not collision: has_valid_trajectory = True return control_signal, potential_field def new_states( self, current_position: np.ndarray, current_velocity: np.ndarray, target_position: np.ndarray, potential_field: np.ndarray = np.array([0.0, 0.0]), ): control_signal = self.base_controller.get_control_signal(current_position[0:2], target_position[0:2], current_velocity[0:2]) # print(f'control_signal 1: {control_signal}') control_signal += potential_field # print(f'control_signal 2: {control_signal}') norm_of_control_signal = np.linalg.norm(control_signal) control_signal = (control_signal + potential_field) * norm_of_control_signal / np.linalg.norm(control_signal + potential_field) # current_velocity[0:2] + control_signal * self.dt next_velocity = control_signal next_position = current_position[0:2] + next_velocity * self.dt return next_position, next_velocity def potential_field_checker( self, current_position: np.ndarray, current_velocity: np.ndarray, target_position: np.ndarray, potential_field: np.ndarray ): """Check if the potential field is valid""" # Paramters repulsive_gain = 0.003 epsilon = 1e-5 # Variables repulsive_force = np.zeros((current_position.shape[0], 2)) collision = False for i in range(current_position.shape[0]): for j in range(current_position.shape[0]): if i != j: distance = np.linalg.norm(current_position[i, 0:2] - current_position[j, 0:2], np.inf) if distance < 0.12: # print(f'Collision between {i} and {j}') collision = True # Calculate the repulsive force magnitude = repulsive_gain / (distance + epsilon) # np.clip(magnitude, -0.25, 0.25) # magnitude = np.clip(magnitude, 0, 2) # magnitude = repulsive_gain * (1 - distance) #/ distance direction = (current_position[i, 0:2] - current_position[j, 0:2]) / distance # Print shapes repulsive_force[i] += magnitude * direction if not collision: return False, repulsive_force else: return True, repulsive_force
5,117
Python
43.894736
138
0.591558
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/planar_motor/__init__.py
from .planar_motor import * from .controller import *
53
Python
25.999987
27
0.773585
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/planar_motor/planar_motor.py
from ..base import Manipulator from .controller import Controller, ForceFieldController import numpy as np import time class PlanarMotor(Manipulator): def __init__(self, manipulator_root: str, manipulator_index: int) -> None: super().__init__(manipulator_root, manipulator_index) self.manipulator_type = "planar_motor" self.manipulator_joint = self.manipulator_root + "/D6Joint" self.joint_names = ["transX", "transY", "transZ", "rotX", "rotY", "rotZ"] self.joint_target_position_attributes = ["drive:%s:physics:targetPosition" % joint_name for joint_name in self.joint_names] self.joint_target_velocity_attributes = ["drive:%s:physics:targetVelocity" % joint_name for joint_name in self.joint_names] self.position_for_controller = np.zeros(3) self.time_stamp_for_controller = time.time() self.velocity = np.zeros(3) self.joint_targets = np.zeros(6) self.previous_control_signal = np.zeros((5, 2)) def set_joint_target(self, target_positions: list): self.joint_targets = np.array(target_positions) if not (len(target_positions) == len(self.joint_target_position_attributes)): raise AssertionError("Invalid number of joints") for attribute, target_position in zip(self.joint_target_position_attributes, target_positions): self.simulator._change_property(prim_path=self.manipulator_joint, attribute_name=attribute, value=target_position) def set_joint_target_relative(self, target_positions: list): if not (len(target_positions) == len(self.joint_target_position_attributes)): raise AssertionError("Invalid number of joints") for attribute, target_position in zip(self.joint_target_position_attributes, target_positions): target_position += self.simulator._get_property(prim_path=self.manipulator_joint, attribute=attribute) self.simulator._change_property(prim_path=self.manipulator_joint, attribute_name=attribute, value=target_position) def set_target_velocity(self, target_velocities: list): if not (len(target_velocities) == len(self.joint_target_velocity_attributes)): raise AssertionError("Invalid number of joints") for attribute, target_velocity in zip(self.joint_target_velocity_attributes, target_velocities): self.simulator._change_property(prim_path=self.manipulator_joint, attribute_name=attribute, value=target_velocity) def spawn(self): prim_path = self.manipulator_root asset_path = "./assets/robots/shuttle_120x120.usd" self.simulator._create_payload(prim_path=prim_path, asset_path=asset_path) x = 0 y = 0 if self.manipulator_index == 0: x = 6.0 y = 6.0 elif self.manipulator_index == 1: x = 6.0 y = 90.0 elif self.manipulator_index == 2: x = 90.0 y = 6.0 elif self.manipulator_index == 3: x = 90.0 y = 90.0 self.set_initial_transform(x=x, y=y, z=1.0) # self.set_initial_transform(x=20 * self.manipulator_index + 6.0, y=6.0, z=1.0) def despawn(self): pass def set_initial_transform(self, x, y, z): print(str(x) + " " + str(y) + " " + str(z)) prim_path = f"{self.manipulator_root}/shuttle" print("prim path" + prim_path) self.simulator._transform_prim(prim_path=prim_path, x=x, y=y, z=z) self.set_joint_target([x * 0.01, y * 0.01, z * 0.01, 0.0, 0.0, 0.0]) def get_joint_position(self): position = np.array( self.simulator._get_property(prim_path=self.manipulator_root + "/shuttle", attribute="xformOp:translate") * 0.01 ) return position def get_joint_velocity(self): if time.time() - self.time_stamp_for_controller > 0.01: current_position = self.get_joint_position()[0:3] self.velocity = (current_position - self.position_for_controller) / (time.time() - self.time_stamp_for_controller) self.position_for_controller = current_position self.time_stamp_for_controller = time.time() return self.velocity def get_joint_target(self): return self.joint_targets def apply_control_input(self): controller = Controller(p_gain=1, d_gain=0.1, max_veloicty=0.5) current_position = self.get_joint_position() current_velocity = self.get_joint_velocity() control_signal = -controller.get_control_signal( current_position=current_position[0:2], target_position=self.joint_targets[0:2], current_velocity=current_velocity[0:2], ) self.set_target_velocity([control_signal[0], control_signal[1], 0.0, 0.0, 0.0, 0.0]) def apply_force_field_controller(self, current_positions, current_velocities, target_positions, potential_fields): max_velocity = 1 controller = ForceFieldController(dt=0.015, timesteps=15, p_gain=2.5, d_gain=0.5, max_velocity=max_velocity) # timesteps = 15 # current_position = self.get_joint_position() # current_velocity = self.get_joint_velocity() control_signal, repulsive_field = controller.predict_trajectory( current_position=current_positions[:, 0:2], target_position=target_positions[:, 0:2], current_velocity=current_velocities[:, 0:2], potential_field=potential_fields, ) for idx, (o, p) in enumerate(zip(control_signal, self.previous_control_signal)): angle = np.arccos(np.dot(o, p) / (np.linalg.norm(o) * np.linalg.norm(p) + 0.0001)) if angle > np.pi / 18 or angle < -np.pi / 18: control_signal[idx] = (o + p) / 2 for idx, (o, p) in enumerate(zip(control_signal, self.previous_control_signal)): # Scale amplitude of control_signal to 90% or 110% of previous control_signal if np.linalg.norm(p) > 1.05: if np.linalg.norm(o) > 1.05 * np.linalg.norm(p): factor = np.linalg.norm(o) / np.linalg.norm(p) control_signal[idx] = o / factor * 1.05 if np.linalg.norm(o) < 0.95 * np.linalg.norm(p): factor = np.linalg.norm(o) / np.linalg.norm(p) control_signal[idx] = o / factor * 0.95 self.previous_control_signal = control_signal idx = self.manipulator_index control_signal = np.clip(control_signal, -max_velocity, max_velocity) return (repulsive_field, control_signal) # class ForceFieldManager: # def __init__(self, shuttles: List[PlanarMotor]) -> None: # self.shuttles = shuttles # self.potential_fields = np.zeros((len(self.shuttles), 2)) # def calculate_force_field(self): # for idx, shuttle in enumerate(self.shuttles): # current_position = shuttle.get_joint_position() # current_velocity = shuttle.get_joint_velocity() # target_position = shuttle.get_joint_target() # controller = ForceFieldController(dt=0.01, timesteps=100, p_gain=5, d_gain=0.4, max_veloicty=2) # #self.potential_fields[idx] = self.calculate_repulsive_field(current_position, current_velocity, target_position) # #return self.potential_fields
7,380
Python
47.880794
134
0.631301
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/six_axis/__init__.py
from .six_axis import *
24
Python
11.499994
23
0.708333
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/package/six_axis/six_axis.py
from ..base import SixAxisRobotInterace class SixAxis(SixAxisRobotInterace): def __init__(self, manipulator_root: str, manipulator_index: int) -> None: super().__init__(manipulator_root, manipulator_index) self.manipulator_joint = self.manipulator_root + "/ActionGraph" def change_node_namespace(self, namespace: str): prim_path = self.manipulator_root + "/ActionGraph" attribute_name = "inputs:nodeNamespace" self.omni_interface._change_property(prim_path=prim_path, attribute_name=attribute_name, value=namespace) def change_topic(self, topic: str): prim_path = self.manipulator_root + "/ActionGraph" attribute_name = "inputs:topicName" self.omni_interface._change_property(prim_path=prim_path, attribute_name=attribute_name, value=topic) def spawn(self, asset_name: str = "KR3R540"): prim_path = self.manipulator_root asset_path = f"./assets/robots/{asset_name}.usd" self.omni_interface._create_payload(prim_path=prim_path, asset_path=asset_path) self._set_initial_transform(x=20 * self.manipulator_index + 6.0, y=6.0, z=1.0) def _set_initial_transform(self, x, y, z): print(str(x) + " " + str(y) + " " + str(z)) prim_path = f"{self.manipulator_root}/shuttle" print("prim path" + prim_path) self.omni_interface._transform_prim(prim_path=prim_path, x=x, y=y, z=z)
1,420
Python
46.366665
113
0.66338
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/abmoRobotics/maps/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import abmoRobotics.maps # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = abmoRobotics.maps.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,670
Python
34.553191
142
0.682635
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "abmoRobotics maps" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import abmoRobotics.maps". [[python.module]] name = "abmoRobotics.maps" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,577
TOML
31.874999
118
0.746354
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/docs/README.md
# Python Extension Example [abmoRobotics.maps] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
176
Markdown
34.399993
126
0.789773
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps/docs/index.rst
abmoRobotics.maps ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"abmoRobotics.maps" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
335
reStructuredText
14.999999
43
0.620896
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/custom_msgs.py
import rclpy from typing import List, Any import time import json import asyncio import threading import omni import carb import omni.kit from pxr import Usd, Gf, PhysxSchema from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.core.utils.stage import get_stage_units from rclpy.context import Context from rclpy.node import Node from rclpy.duration import Duration from rclpy.action import ActionServer, CancelResponse, GoalResponse from rclpy.parameter import Parameter from std_msgs.msg import Bool from geometry_msgs.msg import Pose import omni.kit.commands import pxr.Sdf as Sdf import pxr.Usd as Usd def acquire_maps_msgs_interface() -> Any: """TESTER FUNCTION.""" global PoseSrv # import tutorial_interfaces # .tutorial_interfaces from tutorial_interfaces.srv import PoseSrv as pose_srv PoseSrv = pose_srv try: rclpy.init() except: # noqa E722 print("ROS2 Already Initialized") bridge = ROS2Interface(PoseSrv) executer = rclpy.executors.MultiThreadedExecutor() executer.add_node(bridge) threading.Thread(target=executer.spin).start() return bridge class ROS2Interface(Node): def __init__(self, msg_type): self._components = [] super().__init__("tester_node") self.srv = self.create_service(msg_type, "manipulator/add", self.spawn_robot) self.srv = self.create_service(msg_type, "manipulator/remove", self.remove_robot) self.srv = self.create_service(msg_type, "segment/add", self.spawn_segement) self.srv = self.create_service(msg_type, "segment/remove", self.remove_segment) # omni objects and interfaces self._usd_context = omni.usd.get_context() self._stage = self._usd_context.get_stage() self._timeline = omni.timeline.get_timeline_interface() self._physx_interface = omni.physx.acquire_physx_interface() self._dci = _dynamic_control.acquire_dynamic_control_interface() # events self._update_event = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_event) self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event) self._stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop(self._on_stage_event) self._physx_event = self._physx_interface.subscribe_physics_step_events(self._on_physics_event) self._stage # variables self._manipulator_prim_path = "/World/tableScaled/Manipulators/" self._manipulator_asset_path = "./assets/robots/" self._manipulators_to_spawn = [] self._manipulators_to_delete = [] self._manipulators = [] self._segments_prim_path = "/World/tableScaled/Segments/" self._segments_asset_path = "./assets/usd/segment.usd" self._segments_to_spawn = [] self._segments_to_delete = [] self._segments = [] def spawn_robot(self, request, response): """SERVICE CALLBACK.""" print(request) # response = True # create_payload(context=self._usd_context, prim_path=self._manipulator_prim_path, asset_path=self._manipulator_asset_path) self._manipulators_to_spawn.append({"name": request.name, "pose": request.pose}) rate = self.create_rate(10) # 10hz while self._manipulators_to_spawn: rate.sleep() response.success = True # response.data = True return response def remove_robot(self, request, response): """SERVICE CALLBACK.""" self._manipulators_to_delete.append({"name": request.name, "pose": request.pose}) rate = self.create_rate(10) # 10hz print(self._manipulators_to_delete) while self._manipulators_to_delete: rate.sleep() response.success = True return response def spawn_segement(self, request, response): """Function to spawn a segment.""" self._segments_to_spawn.append({"name": request.name, "pose": request.pose}) rate = self.create_rate(10) # 10hz while self._segments_to_spawn: rate.sleep() response.success = True return response def remove_segment(self, request, response): """Function to remove a segment.""" self._segments_to_delete.append({"name": request.name, "pose": request.pose}) rate = self.create_rate(10) while self._segments_to_delete: rate.sleep() response.success = True return response def _on_update_event(self, e: carb.events.IEvent): # pass if self._manipulators_to_spawn: for manipulator in self._manipulators_to_spawn: prim_path = self._manipulator_prim_path + manipulator["name"] asset_path = self._manipulator_asset_path + manipulator["name"][:-3] + ".usd" create_payload(context=self._usd_context, prim_path=prim_path, asset_path=asset_path) position = manipulator["pose"].position orientation = manipulator["pose"].orientation pos = Gf.Vec3d(position.x, position.y, position.z) quat = Gf.Quatd(orientation.w, orientation.x, orientation.y, orientation.z) if manipulator["name"][:-3] == "KR4R600": # rotate 90 degrees about x axis quat = quat * Gf.Quatd(0.707, 0.707, 0, 0) scale = 0.001 matrix = convert_position_orientation_to_matrix(pos, quat, scale) transform_prim(prim_path, matrix) elif manipulator["name"][:-3] == "KR3R540": matrix = convert_position_orientation_to_matrix(pos, quat, scale=1.0) transform_prim(prim_path, matrix) usd_prim = omni.usd.get_context().get_stage().GetPrimAtPath(prim_path + "/ActionGraph/ros2_subscribe_joint_state") print(usd_prim) print(usd_prim.GetAttribute("inputs:nodeNamespace").Get()) attribute = usd_prim.GetAttribute("inputs:nodeNamespace") attribute.Set(manipulator["name"]) # f'/{manipulator["name"]}') # except Exception as e: # print(e) self._manipulators_to_spawn.remove(manipulator) if self._manipulators_to_delete: for manipulator in self._manipulators_to_delete: prim_path = self._manipulator_prim_path + manipulator["name"] self._stage.RemovePrim(prim_path) # delete_payload(context=self._usd_context, prim_path=self._manipulator_prim_path) self._manipulators_to_delete.remove(manipulator) print("deleted") if self._segments_to_spawn: for segment in self._segments_to_spawn: prim_path = self._segments_prim_path + segment["name"] asset_path = self._segments_asset_path create_payload(context=self._usd_context, prim_path=prim_path, asset_path=asset_path) position = segment["pose"].position orientation = segment["pose"].orientation pos = Gf.Vec3d(position.x, position.y, position.z) quat = Gf.Quatd(orientation.w, orientation.x, orientation.y, orientation.z) matrix = convert_position_orientation_to_matrix(pos, quat, scale=1.0) transform_prim(prim_path, matrix) self._segments_to_spawn.remove(segment) if self._segments_to_delete: for segment in self._segments_to_delete: prim_path = self._segments_prim_path + segment["name"] self._stage.RemovePrim(prim_path) self._segments_to_delete.remove(segment) print("deleted") # # print("ok") def _on_timeline_event(self, e: carb.events.IEvent): pass def _on_stage_event(self, e: carb.events.IEvent): pass def _on_physics_event(self, e: carb.events.IEvent): pass def _stop_components(self) -> None: """Stop all components.""" for component in self._components: component.stop() def shutdown(self) -> None: """Shutdown the ROS2Interface inteface.""" self._update_event = None self._timeline_event = None self._stage_event = None self._stop_components() self.destroy_node() rclpy.shutdown() def destroy_maps_msgs_interface(ROS2Interface: ROS2Interface) -> None: """ Release the Ros2Bridge interface. :param bridge: The Ros2Bridge interface :type bridge: Ros2Bridge """ ROS2Interface.shutdown() def create_payload(context: omni.usd._usd.UsdContext, prim_path: str, asset_path: str): """Create a payload.""" omni.kit.commands.execute("CreatePayload", usd_context=context, path_to=Sdf.Path(prim_path), asset_path=asset_path, instanceable=False) print("Created Payload") def delete_prims(context: omni.usd._usd.UsdContext, prim_path: str): """Delete prims.""" omni.kit.commands.execute("DeletePrims", paths=[Sdf.Path(prim_path)], destructive=False) def transform_prim(prim_path: str, matrix: Gf.Matrix3d): """Transform a prim.""" omni.kit.commands.execute( "TransformPrim", path=Sdf.Path(prim_path), new_transform_matrix=matrix, ) def convert_position_orientation_to_matrix(position: Gf.Vec3d, orientation: Gf.Quatd, scale: float) -> Gf.Matrix4d: """Convert position and orientation to a matrix.""" # Create a translation matrix from the position translation_matrix = Gf.Matrix4d().SetTranslate(position) # Create a rotation matrix from the orientation rotation_matrix = Gf.Matrix4d().SetRotate(orientation) # Create a scale matrix to scale the object scale_matrix = Gf.Matrix4d().SetScale(Gf.Vec3d(scale, scale, scale)) # Combine the translation, rotation, and scale matrices transformation_matrix = scale_matrix * rotation_matrix * translation_matrix return transformation_matrix
10,209
Python
36.675277
139
0.631795
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/scripts/extension.py
import omni.ext import os import sys import carb import rclpy # import srv.srv._pose_srv as pose_srv # from .srv_test import srv try: from .. import _custom_msgs except Exception as e: # noqa E722 print(">>>> [DEVELOPMENT] imort custom_msgs") from .. import custom_msgs as _custom_msgs # from .. import custom_msgs as _custom_msgs class Extension(omni.ext.IExt): def on_startup(self, ext_id): self.bridge = None self._extension_path = None ext_manager = omni.kit.app.get_app().get_extension_manager() if ext_manager.is_extension_enabled("omni.isacc.ros_bridge"): carb.log("ROS2 Bridge external extension cannot be enabled if ROS Bridge is enabled") ext_manager.disable_extension("abmoRobotics.maps_msgs") return self._extension_path = ext_manager.get_extension_path(ext_id) sys.path.append(os.path.join(self._extension_path, "abmoRobotics", "maps_msgs", "packages")) if os.environ.get("LD_LIBRARY_PATH"): os.environ["LD_LIBRARY_PATH"] = os.environ.get("LD_LIBRARY_PATH") + ":{}/bin".format(self._extension_path) else: os.environ["LD_LIBRARY_PATH"] = "{}/bin".format(self._extension_path) self.bridge = _custom_msgs.acquire_maps_msgs_interface() def on_shutdown(self): print("o2ka21") if self._extension_path is not None: sys.path.remove(os.path.join(self._extension_path, "abmoRobotics", "maps_msgs", "packages")) self._extension_path = None if self.bridge is not None: try: _custom_msgs.destroy_maps_msgs_interface(self.bridge) self.bridge = None except Exception as e: print("EXCEPTION SHUTDOWN") print(e)
1,807
Python
33.76923
118
0.621472
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/packages/tutorial_interfaces/srv/_pose_srv_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from tutorial_interfaces:srv/PoseSrv.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "tutorial_interfaces/srv/detail/pose_srv__struct.h" #include "tutorial_interfaces/srv/detail/pose_srv__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_IMPORT bool geometry_msgs__msg__pose__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * geometry_msgs__msg__pose__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool tutorial_interfaces__srv__pose_srv__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[50]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("tutorial_interfaces.srv._pose_srv.PoseSrv_Request", full_classname_dest, 49) == 0); } tutorial_interfaces__srv__PoseSrv_Request * ros_message = _ros_message; { // name PyObject * field = PyObject_GetAttrString(_pymsg, "name"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->name, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // pose PyObject * field = PyObject_GetAttrString(_pymsg, "pose"); if (!field) { return false; } if (!geometry_msgs__msg__pose__convert_from_py(field, &ros_message->pose)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * tutorial_interfaces__srv__pose_srv__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PoseSrv_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("tutorial_interfaces.srv._pose_srv"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PoseSrv_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } tutorial_interfaces__srv__PoseSrv_Request * ros_message = (tutorial_interfaces__srv__PoseSrv_Request *)raw_ros_message; { // name PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->name.data, strlen(ros_message->name.data), "replace"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "name", field); Py_DECREF(field); if (rc) { return NULL; } } } { // pose PyObject * field = NULL; field = geometry_msgs__msg__pose__convert_to_py(&ros_message->pose); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "pose", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "tutorial_interfaces/srv/detail/pose_srv__struct.h" // already included above // #include "tutorial_interfaces/srv/detail/pose_srv__functions.h" ROSIDL_GENERATOR_C_EXPORT bool tutorial_interfaces__srv__pose_srv__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[51]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("tutorial_interfaces.srv._pose_srv.PoseSrv_Response", full_classname_dest, 50) == 0); } tutorial_interfaces__srv__PoseSrv_Response * ros_message = _ros_message; { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * tutorial_interfaces__srv__pose_srv__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PoseSrv_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("tutorial_interfaces.srv._pose_srv"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PoseSrv_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } tutorial_interfaces__srv__PoseSrv_Response * ros_message = (tutorial_interfaces__srv__PoseSrv_Response *)raw_ros_message; { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
7,577
C
30.840336
123
0.640623
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/packages/tutorial_interfaces/srv/__init__.py
from tutorial_interfaces.srv._pose_srv import PoseSrv
54
Python
26.499987
53
0.833333
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/abmoRobotics/maps_msgs/packages/tutorial_interfaces/srv/_pose_srv.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from tutorial_interfaces:srv/PoseSrv.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_PoseSrv_Request(type): """Metaclass of message 'PoseSrv_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('tutorial_interfaces') except ImportError: import logging import traceback logger = logging.getLogger( 'tutorial_interfaces.srv.PoseSrv_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__pose_srv__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__pose_srv__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__pose_srv__request cls._TYPE_SUPPORT = module.type_support_msg__srv__pose_srv__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__pose_srv__request from geometry_msgs.msg import Pose if Pose.__class__._TYPE_SUPPORT is None: Pose.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PoseSrv_Request(metaclass=Metaclass_PoseSrv_Request): """Message class 'PoseSrv_Request'.""" __slots__ = [ '_name', '_pose', ] _fields_and_field_types = { 'name': 'string', 'pose': 'geometry_msgs/Pose', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'Pose'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.name = kwargs.get('name', str()) from geometry_msgs.msg import Pose self.pose = kwargs.get('pose', Pose()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.name != other.name: return False if self.pose != other.pose: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def name(self): """Message field 'name'.""" return self._name @name.setter def name(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'name' field must be of type 'str'" self._name = value @property def pose(self): """Message field 'pose'.""" return self._pose @pose.setter def pose(self, value): if __debug__: from geometry_msgs.msg import Pose assert \ isinstance(value, Pose), \ "The 'pose' field must be a sub message of type 'Pose'" self._pose = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PoseSrv_Response(type): """Metaclass of message 'PoseSrv_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('tutorial_interfaces') except ImportError: import logging import traceback logger = logging.getLogger( 'tutorial_interfaces.srv.PoseSrv_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__pose_srv__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__pose_srv__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__pose_srv__response cls._TYPE_SUPPORT = module.type_support_msg__srv__pose_srv__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__pose_srv__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PoseSrv_Response(metaclass=Metaclass_PoseSrv_Response): """Message class 'PoseSrv_Response'.""" __slots__ = [ '_success', ] _fields_and_field_types = { 'success': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.success = kwargs.get('success', bool()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.success != other.success: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value class Metaclass_PoseSrv(type): """Metaclass of service 'PoseSrv'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('tutorial_interfaces') except ImportError: import logging import traceback logger = logging.getLogger( 'tutorial_interfaces.srv.PoseSrv') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__pose_srv from tutorial_interfaces.srv import _pose_srv if _pose_srv.Metaclass_PoseSrv_Request._TYPE_SUPPORT is None: _pose_srv.Metaclass_PoseSrv_Request.__import_type_support__() if _pose_srv.Metaclass_PoseSrv_Response._TYPE_SUPPORT is None: _pose_srv.Metaclass_PoseSrv_Response.__import_type_support__() class PoseSrv(metaclass=Metaclass_PoseSrv): from tutorial_interfaces.srv._pose_srv import PoseSrv_Request as Request from tutorial_interfaces.srv._pose_srv import PoseSrv_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
10,684
Python
34.148026
134
0.567765
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "abmoRobotics maps custom messages" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import abmoRobotics.maps". [[python.module]] name = "abmoRobotics.maps_msgs" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ] [[native.library]] path = "bin/libtutorial_interfaces__python.so" [[native.library]] path = "bin/libtutorial_interfaces__rosidl_generator_c.so" [[native.library]] path = "bin/libtutorial_interfaces__rosidl_typesupport_c.so" [[native.library]] path = "bin/libtutorial_interfaces__rosidl_typesupport_connext_c.so" [[native.library]] path = "bin/libtutorial_interfaces__rosidl_typesupport_fastrtps_c.so" [[native.library]] path = "bin/libtutorial_interfaces__rosidl_typesupport_introspection_c.so" # [[native.library]] # # path = "bin/libadd_on_msgs__python.so" # path = "srv/tutorial_interfaces_s__rosidl_typesupport_c.cpython-37m-x86_64-linux-gnu.so" # # [[native.library]] # # path = "bin/libadd_on_msgs__rosidl_generator_c.so" # # [[native.library]] # # path = "bin/libadd_on_msgs__rosidl_typesupport_c.so" # [[native.library]] # path = "srv/tutorial_interfaces_s__rosidl_typesupport_introspection_c.cpython-37m-x86_64-linux-gnu.so" # [[native.library]] # # path = "bin/libadd_on_msgs__rosidl_typesupport_fastrtps_c.so" # path = "srv/tutorial_interfaces_s__rosidl_typesupport_fastrtps_c.cpython-37m-x86_64-linux-gnu.so" # [[native.library]] # # path = "bin/libadd_on_msgs__rosidl_typesupport_introspection_c.so" # #path = "srv/tutorial_interfaces_s__rosidl_typesupport_introspection_c.cpython-37m-x86_64-linux-gnu.so"
2,919
TOML
36.922077
118
0.741692
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/docs/README.md
# Python Extension Example [abmoRobotics.maps_msgs] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
181
Markdown
35.399993
126
0.790055
abmoRobotics/MAPs/omniverse/extensions/material-acceleration-platform/exts/abmoRobotics.maps_msgs/docs/index.rst
abmoRobotics.maps ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"abmoRobotics.maps_msgs" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
340
reStructuredText
15.238095
43
0.623529
abmoRobotics/MAPs/omniverse/scripts/testpublisherworking.py
import asyncio import rclpy from rclpy.node import Node from std_msgs.msg import String class MinimalSubscriber(Node): def __init__(self): super().__init__('minimal_subscriber') self.subscription = self.create_subscription( String, '/chatter', self.listener_callback, 10) self.subscription # prevent unused variable warning def listener_callback(self, msg): self.get_logger().info('I heard: "%s"' % msg.data) async def my_task(): rclpy.init() minimal_subscriber = MinimalSubscriber() for x in range(100): rclpy.spin_once(minimal_subscriber, timeout_sec=0.001) await asyncio.sleep(0.1) print("hej") asyncio.ensure_future(my_task()) print("hej2") rclpy.shutdown()
767
Python
21.588235
60
0.650587
abmoRobotics/MAPs/omniverse/scripts/shuttle.py
# This script is executed the first time the script node computes, or the next time it computes after this script # is modified or the 'Reset' button is pressed. # The following callback functions may be defined in this script: # setup(db): Called immediately after this script is executed # compute(db): Called every time the node computes (should always be defined) # cleanup(db): Called when the node is deleted or the reset button is pressed (if setup(db) was called before) # Defining setup(db) and cleanup(db) is optional, but if compute(db) is not defined then this script node will run # in legacy mode, where the entire script is executed on every compute and the callback functions above are ignored. # Available variables: # db: og.Database The node interface, attributes are db.inputs.data, db.outputs.data. # Use db.log_error, db.log_warning to report problems. # Note that this is available outside of the callbacks only to support legacy mode. # og: The OmniGraph module # Import statements, function/class definitions, and global variables may be placed outside of the callbacks. # Variables may also be added to the db.internal_state state object. # Example code snippet: import omni.kit.commands from pxr import Sdf, Usd import omni.usd from abmoRobotics.maps.package.planar_motor import PlanarMotor #from abmoRobotics.maps.package.six_axis import SixAxis from abmoRobotics.maps.ros2 import JointStateSubscriber, InitialPoseSubscriber import asyncio import rclpy from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from rclpy.node import Node import numpy as np import copy from typing import List import random from omni.isaac.debug_draw import _debug_draw def generate_random_goals(num_shuttles): desired_positions = np.random.rand(num_shuttles, 2) desired_positions[:, 0] = desired_positions[:, 0] * 0.96 desired_positions[:, 1] = desired_positions[:, 1] * 0.72 # Check if any of the desired positions are within a manhatten distance of 2 of each other invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 0.2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) while invalid: desired_positions = np.random.rand(num_shuttles, 2) desired_positions[:, 0] = desired_positions[:, 0] * 0.96 desired_positions[:, 1] = desired_positions[:, 1] * 0.72 invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 0.2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) return desired_positions def setup(db): db.stage = omni.usd.get_context().get_stage() shuttle_prefix = "shuttle_120x120" remove_shuttle_paths = [x.GetPrimPath() for x in db.stage.Traverse() if (x.GetTypeName() == "Xform" and shuttle_prefix in str(x.GetPrimPath()))] print(remove_shuttle_paths) omni.kit.commands.execute('DeletePrims', paths=remove_shuttle_paths, destructive=True) if not rclpy.utilities.ok(): rclpy.init() db.dummy_node = rclpy.create_node('dummy') db.shuttles = [] db.joint_state_subscriber = [] db.initial_pose_subscriber = [] db.potentials = np.zeros((4,2)) db.target_positions = np.zeros((4,6)) goals = generate_random_goals(4) goals[:4,0:2] = [[0.9,0.6],[0.8,0.1],[0.1,0.6],[0.12,0.18]] db.target_positions[:, 0:2] = goals db.draw = _debug_draw.acquire_debug_draw_interface() N = 10000 point_list_1 = [(0, 0, 0)] point_list_2 = [(1, 1, 1)] colors = [(0, 0, 255, 1)] sizes = [3] db.draw.draw_lines(point_list_1, point_list_2, colors, sizes) #draw.clear_lines() debug = False def compute(db): shuttle_topics = [x[0] for x in db.dummy_node.get_topic_names_and_types() if ("shuttle" in x[0] and x[0].endswith("joint_command") and "JointState" in x[1][0])] velocities = np.zeros((len(db.shuttles), 3)) positions = np.zeros((len(db.shuttles), 3)) target_positions = np.zeros((len(db.shuttles), 6)) #print(db.target_positions) db.draw.clear_lines() for idx, shuttle in enumerate(db.shuttles): try: velocities[idx] = shuttle.get_joint_velocity() positions[idx] = shuttle.get_joint_position() target_positions[idx] = shuttle.get_joint_target() #print(db.target_positions[idx].shape) # print(f'db.target_positions.shape: {db.target_positions.shape}') # print(f'shuttle.get_joint_target.shape: {shuttle.get_joint_target().shape}') #print(f'target_positions: {target_positions}') except Exception as e: print(e) pass control_signal = np.zeros((len(db.shuttles), 2)) db.potentials = db.potentials * 0.9 a = 0 for idx, shuttle in enumerate(db.shuttles): pass #shuttle.apply_control_input()current_points try: db.potentials, control_signal = db.shuttles[0].apply_force_field_controller(copy.deepcopy(positions), copy.deepcopy(velocities) , copy.deepcopy(target_positions), db.potentials) except Exception as e: print(e) #pass for idx, shuttle in enumerate(db.shuttles): #shuttle_input = [control_signal[idx, 0], control_signal[idx, 1],0,0,0,0] shuttle.set_target_velocity([control_signal[idx, 0], control_signal[idx, 1],0,0,0,0]) ## Spawn new shuttles, and create subscribers for them if they are not already spawned. for idx, topic in enumerate(shuttle_topics): #print(idx) sdf_path = Sdf.Path(f"/World/tableScaled/joints/shuttle_120x120_{idx:02}") #print(sdf_path) prim: Usd.Prim = db.stage.GetPrimAtPath(sdf_path) if bool(db.dummy_node.get_publishers_info_by_topic(topic)): if not prim.IsValid(): planar_motor = PlanarMotor("/World/tableScaled/joints/shuttle_120x120", idx) planar_motor.spawn() joint_state_subscriber = JointStateSubscriber(topic, planar_motor) initial_pose_subscriber = InitialPoseSubscriber(f"configuration/shuttle{idx}/initialPosition", planar_motor) db.shuttles.append(planar_motor) db.joint_state_subscriber.append(joint_state_subscriber) db.initial_pose_subscriber.append(initial_pose_subscriber) else: if prim.IsValid(): omni.kit.commands.execute('DeletePrims', paths=[Sdf.Path(f"/World/tableScaled/joints/shuttle_120x120_{idx:02}")], destructive=False) for joint_state_subscriber in db.joint_state_subscriber: rclpy.spin_once(joint_state_subscriber, timeout_sec=0.00000000000000001) for initial_pose_subscriber in db.initial_pose_subscriber: rclpy.spin_once(initial_pose_subscriber, timeout_sec=0.00000000000000001) try: targets_points = [(target_positions[i, 0]-1.2845, target_positions[i, 1]+0.3251, .99) for i in range(4)] current_points = [(positions[i, 0]-1.2845, positions[i, 1]+0.3251, 0.99) for i in range(4)] colors = [(0, 255, 0, 1) for i in range(4)] sizes = [3 for i in range(4)] db.draw.draw_lines(targets_points, current_points, colors, sizes) except Exception as e: print(e) pass if debug: try: control_signal_points = [(positions[i, 0]-1.2845+control_signal[i, 0], positions[i, 1]+0.3251+control_signal[i, 1], 0.99) for i in range(4)] # #control_signal_points = [(db.target_positions[i, 0]-1.2845, db.target_positions[i, 1]+0.3251, 1) for i in range(5)] current_points = [(positions[i, 0]-1.2845, positions[i, 1]+0.3251, .99) for i in range(4)] colors = [(0, 0, 255, 1) for i in range(4)] sizes = [10 for i in range(4)] db.draw.draw_lines(control_signal_points, current_points, colors, sizes) except Exception as e: # print(f'positions shape: {positions.shape}') # print(f'control_signal shape: {control_signal.shape}') #print(e) pass if debug: try: control_signal_points = [(positions[i, 0]-1.2845+db.potentials[i, 0], positions[i, 1]+0.3251+db.potentials[i, 1], 0.99) for i in range(4)] # #control_signal_points = [(db.target_positions[i, 0]-1.2845, db.target_positions[i, 1]+0.3251, 1) for i in range(4)] current_points = [(positions[i, 0]-1.2845, positions[i, 1]+0.3251, .99) for i in range(4)] colors = [(255, 0, 0, 1) for i in range(4)] sizes = [4 for i in range(4)] db.draw.draw_lines(control_signal_points, current_points, colors, sizes) except Exception as e: # print(f'positions shape: {positions.shape}') # print(f'control_signal shape: {control_signal.shape}') #print(e) pass def cleanup(db): print("SHUTTING DOWN") rclpy.shutdown() #ros2 topic pub --once /joint_states sensor_msgs/msg/JointState "{name: ['<your-name>', '<your-second-name>'], position: [0.0, 0.4], velocity: [1.0, 1.2], effort: [0.0, 0.4]}" #ros2 topic pub -r 10 /shuttle/shuttle5/joint_command sensor_msgs/msg/JointState "{name: ['x','y','z','xrot','yrot','zrot'], position: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], velocity: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], effort: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}"
9,607
Python
47.04
253
0.633288
abmoRobotics/MAPs/omniverse/scripts/setup.py
"""Installation script for the 'omni.maps' python package.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from setuptools import find_packages, setup # Minimum dependencies required prior to installation INSTALL_REQUIRES = [] # Installation operation setup( name="mapper", author="Anton Bjørndahl Mortensen", version="1.0.0", description="Environment for materials acceleration platforms", keywords=["robotics", "materials acceleration platforms"], include_package_data=True, install_requires=INSTALL_REQUIRES, packages=find_packages(where=['omni']),#where="./package"), classifiers=[ "Natural Language :: English", "Programming Language :: Python :: 3.7, 3.8", ], zip_safe=False, )
813
Python
27.068965
67
0.699877
abmoRobotics/MAPs/omniverse/scripts/testsubscriberworking.py
import asyncio import rclpy from rclpy.node import Node from std_msgs.msg import String class MinimalSubscriber(Node): def __init__(self): super().__init__('minimal_subscriber') self.subscription = self.create_subscription( String, '/chatter', self.listener_callback, 10) self.subscription # prevent unused variable warning def listener_callback(self, msg): self.get_logger().info('I heard: "%s"' % msg.data) async def my_task(): rclpy.init() minimal_subscriber = MinimalSubscriber() while rclpy.ok(): rclpy.spin_once(minimal_subscriber, timeout_sec=0.001) print("hej") asyncio.ensure_future(my_task()) print("hej2") rclpy.shutdown()
750
Python
21.757575
66
0.637333
abmoRobotics/MAPs/omniverse/scripts/README.md
## Where scripts are placed
27
Markdown
26.999973
27
0.777778
abmoRobotics/MAPs/omniverse/assets/usd/README.md
## Where usd files are placed
29
Markdown
28.999971
29
0.758621
abmoRobotics/MAPs/omniverse/assets/materials/README.md
## Where material files are placed
34
Markdown
33.999966
34
0.794118
abmoRobotics/MAPs/omniverse/assets/robots/README.md
## Where usd files containing robots are placed
47
Markdown
46.999953
47
0.808511
abmoRobotics/MAPs/docker/README.md
# Where docker container is placed
35
Markdown
16.999992
34
0.8
abmoRobotics/MAPs/shuttle_simulator/simulator_continous_multi_agent.py
import pygame import logging from controllers.controllers import ShuttlePredictor # ForceFieldController, AttractivePotentialField, RepulsivePotentialField from worlds import GridWorld, DrawPlanarMotor from simulation import MultiShuttleSimulator import numpy as np import copy # Set logging level from the following: DEBUG, INFO, WARNING, ERROR, CRITICAL logging.basicConfig(level=logging.WARNING) # Define debug decorator def log_decorator(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) logging.info(f"{func.__name__} returned {result}") return result return wrapper def generate_random_goals(num_shuttles): desired_positions = np.random.rand(num_shuttles, 2)*6 # Check if any of the desired positions are within a manhatten distance of 2 of each other invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) while invalid: desired_positions = np.random.rand(num_shuttles, 2)*6 invalid = np.sum(np.abs(desired_positions[:, None, :] - desired_positions[None, :, :]), axis=-1) < 2 np.fill_diagonal(invalid, False) invalid = np.any(invalid) return desired_positions # Initialize pygame pygame.init() # Define constants GRID_SIZE = (6, 8) CELL_SIZE = 150 SCREEN_SIZE = (GRID_SIZE[0] * CELL_SIZE, GRID_SIZE[1] * CELL_SIZE) WHITE = (255, 255, 255) BLACK = (0, 0, 0) SPEED = 1 / 60 def main(): screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption("Continuous Multi-Shuttle Simulator") clock = pygame.time.Clock() # import time # time.sleep(1) # controller_gain = 1.1 relative_time = 0 #position = np.array([[1.0, 1.0], [6.0, 1.1], [1.0, 6.0], [6.0, 6.0]]) # On a line # 6 shuttles position = np.array([[0.0, 1.0], [0.0, 2.5], [0.0, 4.0], [0.0, 5.5], [0.0, 7.0], [6.0, 1.0], [6.0, 2.5], [6.0, 4.0], [6.0, 5.5], [6.0, 7.0]]) simulator = MultiShuttleSimulator(10, grid_size=GRID_SIZE, initial_positions=position) # attrative_potential_field = AttractivePotentialField(2, 0.01, 1) # repulsive_potential_field = RepulsivePotentialField(3, 0.01, 1) # simulator.get_shuttles()[0].set_controller(ForceFieldController(attrative_potential_field, repulsive_potential_field, 2)) # simulator.get_shuttles()[1].set_controller(ForceFieldController(attrative_potential_field, repulsive_potential_field, 2)) # simulator.get_shuttles()[2].set_controller(ForceFieldController(attrative_potential_field, repulsive_potential_field, 2)) world = GridWorld(grid_size=CELL_SIZE, screen_size=SCREEN_SIZE, cell_size=CELL_SIZE) drawShuttle = DrawPlanarMotor(world=world, size=CELL_SIZE) # Set desired positions for testing #desired_positions = np.array([[6.0, 6.0], [1., 6.0], [6.0, 1.0], [1.0, 1.0]]) # , [6.1, 1.0], [1.1, 1.0]]) desired_positions = generate_random_goals(10) # desired_positions = [[2.0, 2.0], [2.0, 5.0], [0.0, 7.0]] # Set desired positions for testing for desired_position, shuttle in zip(desired_positions, simulator.shuttles): shuttle.set_desired_position(desired_position) potentials = np.zeros((len(simulator.shuttles), 2)) prev_output = np.zeros((len(simulator.shuttles), 2)) while True: # for shuttle in simulator.get_shuttles(): # shuttle.controller.set_other_shuttles_positions(simulator.get_other_shuttle_positions(shuttle.get_idx())) # simulator.get_shuttles()[0].controller.set_other_shuttles_positions(simulator.get_other_shuttle_positions(0)) # simulator.get_shuttles()[1].controller.set_other_shuttles_positions(simulator.get_other_shuttle_positions(1)) # simulator.get_shuttles()[2].controller.set_other_shuttles_positions(simulator.get_other_shuttle_positions(2)) dt = clock.tick(120) / 1000 # Convert milliseconds to seconds relative_time += dt # Update relative time print(f'dt: {dt}') world.update_display() # Update the display predictor = ShuttlePredictor(copy.deepcopy(simulator.get_shuttles()), dt, 20) # print(f'Potential: {potentials}') potentials = potentials * 0.9 output, potentials = predictor.predict(potentials) # Calculate angle between output and prev_output and check if difference is 10 degrees for idx, (o, p) in enumerate(zip(output, prev_output)): angle = np.arccos(np.dot(o, p) / (np.linalg.norm(o) * np.linalg.norm(p))) if angle > np.pi / 18 or angle < -np.pi / 18: output[idx] = (o + p) / 2 for idx, (o, p) in enumerate(zip(output, prev_output)): # Scale amplitude of output to 90% or 110% of previous output if np.linalg.norm(p) > 1.1: if np.linalg.norm(o) > 1.1 * np.linalg.norm(p): factor = np.linalg.norm(o) / np.linalg.norm(p) output[idx] = o / factor * 1.1 if np.linalg.norm(o) < 0.9 * np.linalg.norm(p): factor = np.linalg.norm(o) / np.linalg.norm(p) output[idx] = o / factor * 0.9 prev_output = output # Handle events for idx, shuttle in enumerate(simulator.get_shuttles()): drawShuttle.draw(screen, shuttle) drawShuttle.draw_arrow_to_goal(screen, shuttle) drawShuttle.draw_potential_vector(screen, shuttle, 10, output[idx]) # shuttle.update(dt) pygame.display.flip() # draw potential vector for shuttle, output in zip(simulator.get_shuttles(), output): shuttle.update(dt=dt, control_signal=output) # for idx, potential in enumerate(potentials): # print(f'Shuttle {idx} - potential: {potential}') # Check for collisions simulator.collision_detection() # Flip the display print(f'Current time: {relative_time:.2f} seconds') if __name__ == "__main__": main()
6,065
Python
41.71831
145
0.642374
abmoRobotics/MAPs/shuttle_simulator/worlds.py
from abc import ABC, abstractmethod from manipulators.manipulators import PlanarMotor import pygame import numpy as np import math class World(ABC): def __init__(self): self.black = (0, 0, 0) self.white = (255, 255, 255) self.red = (255, 0, 0) self.green = (0, 255, 0) self.blue = (0, 0, 255) self.yellow = (255, 255, 0) @abstractmethod def initialize(self): pass @abstractmethod def update_display(self, dt): pass class GridWorld(World): def __init__(self, grid_size: tuple, screen_size: tuple, cell_size: int) -> None: super().__init__() self.grid_size = grid_size self.screen_size = screen_size self.cell_size = cell_size self.initialize() def initialize(self): self.screen = pygame.display.set_mode(self.screen_size) pygame.display.set_caption("Grid World") def update_display(self): self.screen.fill(self.white) self._draw_grid() # pygame.display.flip() def _draw_grid(self): for x in range(0, self.screen_size[0], self.cell_size): pygame.draw.line(self.screen, self.black, (x, 0), (x, self.screen_size[1])) for y in range(0, self.screen_size[1], self.cell_size): pygame.draw.line(self.screen, self.black, (0, y), (self.screen_size[0], y)) class DrawPlanarMotor(): def __init__(self, world: World, size: int): self.world = world self.size = size def draw(self, screen: pygame.display, shuttle: PlanarMotor): x, y = shuttle.get_position() idx = shuttle.get_idx() pygame.draw.rect(screen, self.world.black, (x * self.size, y * self.size, self.size, self.size)) # Print idx on top of the shuttle font = pygame.font.SysFont('Arial', 30) text = font.render(str(idx), True, self.world.red) # Center the text in the cell text_rect = text.get_rect(center=(x * self.size + self.size / 2, y * self.size + self.size / 2)) screen.blit(text, text_rect) def draw_arrow_to_goal(self, screen: pygame.display, shuttle: PlanarMotor, arrow_size: int = 10): pygame.draw.line(screen, self.world.red, shuttle.get_position() * self.size + self.size / 2, shuttle.desired_position * self.size + self.size / 2, 2) pos1 = shuttle.get_position() dx = shuttle.desired_position[0] - shuttle.get_position()[0] dy = shuttle.desired_position[1] - shuttle.get_position()[1] angle = math.atan2(dy, dx) def draw_potential_vector(self, screen: pygame.display, shuttle: PlanarMotor, arrow_size: int = 10, potential: np.ndarray = None): if potential is None: potential = shuttle # Draw line from current position to potential vector pygame.draw.line(screen, self.world.green, shuttle.get_position() * self.size + self.size / 2, (shuttle.get_position() + potential) * self.size + self.size / 2, 2) # # Draw arrow head # arrow_tip_x = (shuttle.desired_position[0] - arrow_size * np.cos(angle)) # arrow_tip_y = (shuttle.desired_position[1] - arrow_size * np.sin(angle)) # arrow_point1 = (arrow_tip_x + arrow_size * math.sin(angle), arrow_tip_y - arrow_size * math.cos(angle)) # arrow_point2 = (arrow_tip_x - arrow_size * math.sin(angle), arrow_tip_y + arrow_size * math.cos(angle)) # pygame.draw.line(screen, self.world.red, shuttle.desired_position * self.size, arrow_point1, 2) # pygame.draw.line(screen, self.world.red, shuttle.desired_position * self.size, arrow_point2, 2)
3,619
Python
39.674157
171
0.618956
abmoRobotics/MAPs/shuttle_simulator/simulation.py
from manipulators.manipulators import PlanarMotor import numpy as np import copy class MultiShuttleSimulator: def __init__(self, num_shuttles, grid_size, initial_positions=None): self.shuttles = [PlanarMotor(position=initial_positions[i], idx=i, grid_size=grid_size) for i in range(num_shuttles)] self.initial_positions = [copy.deepcopy(shuttle.get_position()) for shuttle in self.shuttles] self.current_shuttle = 0 def switch_shuttle(self, index): if 0 <= index < len(self.shuttles): self.current_shuttle = index def move_current_shuttle(self, direction): self.shuttles[self.current_shuttle].move(direction) def get_shuttles(self): return self.shuttles def _get_other_shuttles(self, index): return [shuttle for shuttle in self.shuttles if shuttle.get_idx() != index] def get_other_shuttle_positions(self, index): return [shuttle.get_position() for shuttle in self._get_other_shuttles(index)] def collision_detection(self): for i in range(len(self.shuttles)): for j in range(i + 1, len(self.shuttles)): # If circles overlap, return True if (self.shuttles[i].get_position()[0] - self.shuttles[j].get_position()[0]) ** 2 + (self.shuttles[i].get_position()[1] - self.shuttles[j].get_position()[1]) ** 2 < 1: # Reset both shuttles to their initial positions self.shuttles[i].set_position(copy.deepcopy(self.initial_positions[i])) print(self.initial_positions) self.shuttles[j].set_position(copy.deepcopy(self.initial_positions[j])) print(f'collision detected between {i} and {j}') return False
1,763
Python
43.099999
183
0.640953
abmoRobotics/MAPs/shuttle_simulator/controllers/base.py
from abc import ABC, abstractmethod class Controller(ABC): """Abstract class for controllers.""" @abstractmethod def set_initial_position(self, position): pass @abstractmethod def set_initial_velocity(self, velocity): pass @abstractmethod def update(self, position, velocity, desired_position): pass @abstractmethod def get_control_signal(self, error): pass class PotentialField(ABC): """Abstract class for potential fields.""" @abstractmethod def calculate_force(self, position, velocity, desired_position): pass class Predictor(ABC): """Abstract class for predictors.""" @abstractmethod def predict(self, time: float): """Predicts the state of the system at a given time.""" pass
807
Python
21.444444
68
0.657993
abmoRobotics/MAPs/shuttle_simulator/controllers/controllers.py
from typing import List import numpy as np from .base import Controller, PotentialField, Predictor from manipulators.base import Manipulator, ManipulatorState import logging from typing import Tuple import copy class PDController(Controller): """PD Controller.""" def __init__(self, p_gain: float, d_gain: float, max_velocity: float): """ Constructor Args: p_gain: Proportional gain d_gain: Derivative gain max_velocity: Maximum velocity """ self.p_gain = p_gain self.d_gain = d_gain self.max_velocity = max_velocity def set_initial_position(self, position): self.position = position self.desired_position = position def set_initial_velocity(self, velocity): self.velocity = velocity def update(self, position, velocity, desired_position): self.position = position self.velocity = velocity self.desired_position = desired_position def get_control_signal(self, error): # Compute error position_error = np.array([desired_position - current_position for desired_position, current_position in zip(self.desired_position, self.position)]) velocity_error = np.array([desired_velocity - current_velocity for desired_velocity, current_velocity in zip(position_error, self.velocity)]) # Compute control signal control_signal = np.array([self.p_gain * position_error + self.d_gain * velocity_error for position_error, velocity_error in zip(position_error, velocity_error)]) # Clip control signal control_signal = np.array([max(min(control_signal, self.max_velocity), -self.max_velocity) for control_signal in control_signal]) return control_signal class AttractivePotentialField(PotentialField): def __init__(self, p_gain: float, d_gain: float, max_force: float): """ Constructor Args: p_gain: Proportional gain d_gain: Derivative gain """ self.p_gain = p_gain self.d_gain = d_gain def calculate_force(self, position, velocity, desired_position): position_error = desired_position - position velocity_error = -velocity return self.p_gain * position_error + self.d_gain * velocity_error class RepulsivePotentialField(PotentialField): """Repulsive potential field.""" def __init__(self, p_gain: float, d_gain: float, max_force: float): """ Constructor Args: p_gain: Proportional gain d_gain: Derivative gain """ self.p_gain = p_gain self.d_gain = d_gain self.repulsive_range = 2 self.repulsive_gain = self.p_gain def calculate_force(self, position, other_shuttles_positions): repulsive_force = np.zeros_like(position) for other_position in other_shuttles_positions: other_position = np.array(other_position) distance_vector = position - other_position distance = np.linalg.norm(distance_vector) if distance < self.repulsive_range: force_magnitude = self.repulsive_gain / (distance**2 + 0.00001) force_direction = distance_vector / distance repulsive_force += force_magnitude * force_direction return repulsive_force class ForceFieldController(Controller): def __init__(self, attractive_field, repulsive_field, max_force): self.attractive_field = attractive_field self.repulsive_field = repulsive_field self.max_force = max_force def set_initial_position(self, position): self.position = np.array(position) self.desired_position = np.array(position) def set_initial_velocity(self, velocity): self.velocity = np.array(velocity) def update(self, position, velocity, desired_position): self.position = np.array(position) self.velocity = np.array(velocity) self.desired_position = np.array(desired_position) def get_control_signal(self, error): attractive_force = self.attractive_field.calculate_force(self.position, self.velocity, self.desired_position) repulsive_force = self.repulsive_field.calculate_force(self.position, self.get_other_shuttles_positions()) control_signal = attractive_force + repulsive_force control_signal_magnitude = np.linalg.norm(control_signal) if control_signal_magnitude > self.max_force: control_signal = (control_signal / control_signal_magnitude) * self.max_force return control_signal def set_other_shuttles_positions(self, other_shuttles_positions): self.other_shuttles_positions = other_shuttles_positions def get_other_shuttles_positions(self): return self.other_shuttles_positions class ShuttlePredictor(Predictor): """ Class for predicting future states of shuttles, and add potential to the states if they are in collision with other shuttles. Args: shuttles: List of shuttles dt: Time step timesteps: Number of time steps to predict Attributes: predicted_states: List of predicted states predicted_times: List of predicted times shuttles: List of shuttles states: List of current states """ def __init__(self, shuttles: List[Manipulator], dt: float, timesteps: int): """ShuttlePredictor constructor""" # self.predicted_times = [dt * i for i in range(timesteps)] # Initialize predicted times self.dt = dt self.time_range = timesteps self.shuttles = shuttles self.states: List[ManipulatorState] = [shuttle.get_state() for shuttle in shuttles] def predict(self, potentials: np.ndarray = None) -> np.ndarray: """ Predict future states of shuttles, and add potential to the states if they are in collision with other shuttles.""" # Initialize variables is_finished = False if potentials is None: potentials = np.zeros((len(self.shuttles), 2)) first_control_signal = np.zeros((len(self.shuttles), 2)) counter = 0 # Predict future states until no collisions detected while not is_finished: # Get attributes of the class time_range = copy.deepcopy(self.time_range) states = copy.deepcopy(self.states) collision = False # Predict future states for i in range(time_range): for idx, shuttle in enumerate(self.shuttles): current_state = states[idx] # Get current state of the shuttle new_state = shuttle.get_next_state(dt=self.dt, current_state=current_state, additional_force=potentials[idx]) # Get next state of the shuttle states[idx] = new_state # Update the current state of the shuttle if i == 0: direction_vector = shuttle.get_desired_position() - new_state.get_position() velocity_magnitude = np.linalg.norm(new_state.get_velocity()) * 0.25 velocity_command = new_state.get_velocity()# + direction_vector * velocity_magnitude first_control_signal[idx] = velocity_command # Check if there is a collision, and calculate potential field. collision, potential = self.potentialFieldChecker(self.shuttles, states) potentials += potential # If collision detected, then stop predicting, and add potential to the states, and try again with different potential field if collision: # import time # print(f'Collision detected at time {i} for shuttle {shuttle.get_idx()}') # time.sleep(2) # logging.info(f'Collision detected at time {i} for shuttle {shuttle.get_idx()}') break # If no collisions detected for all the shuttles at the end of the time range, then the prediction is finished if not collision: is_finished = True counter += 1 #print(counter) print(f'Potentials: {potentials[0]}') # print(f) return first_control_signal, potentials def potentialFieldChecker(self, shuttles, states: List[ManipulatorState]) -> Tuple[bool, np.ndarray]: """ Check if there is a collision between shuttles, and calculate the potential field. Args: shuttles: List of shuttles states: List of states of the shuttles Returns: collision: Boolean indicating if there is a collision between shuttles potential: Repulsive potential field """ repulsive_gain = 1 repulsive_force = np.zeros((len(shuttles), 2), dtype=float) collision = False # Check if there is a collision between shuttles for i in range(len(shuttles)): for j in range(len(shuttles)): if i != j: # Calculate the distance between the shuttles, using the infinite norm, and check if it is less than 2 pos1 = states[i].get_position() pos2 = states[j].get_position() L_inifnite_norm = np.linalg.norm(states[i].get_position() - states[j].get_position(), np.inf) if L_inifnite_norm < 1: collision = True # If there is a collision, then calculate the repulsive force force_magnitude = repulsive_gain / (L_inifnite_norm**2 + 0.00001) #force_magnitude = np.clip(force_magnitude, -2, 2) force_direction = (states[i].get_position() - states[j].get_position()) / L_inifnite_norm repulsive_force[i] += force_magnitude * force_direction # If there is no collision, then return False, and 0 as the potential if not collision: return False, repulsive_force else: return True, repulsive_force if __name__ == '__main__': pass
10,289
Python
40.829268
170
0.618622
abmoRobotics/MAPs/shuttle_simulator/manipulators/manipulators.py
from controllers.base import Controller from controllers.controllers import PDController from .base import Manipulator, ManipulatorState import numpy as np class PlanarMotor(Manipulator): def __init__(self, position, idx, grid_size): self._idx = idx self.grid_size = grid_size # self.position = position self._velocity = np.array([0.0, 0.0]) self._shuttle_state = PlanarMotorState(position=position, velocity=self._velocity) self.controller = PDController(p_gain=0.5, d_gain=0.01, max_velocity=1) self.controller.set_initial_position(position) self.controller.set_initial_velocity(self.get_velocity()) def get_idx(self): return self._idx def update(self, dt: float, control_signal: np.ndarray = None): # Get control signal if control_signal is not None: self.set_velocity(control_signal) else: self.set_velocity(self.controller.get_control_signal(1)) # Get current state current_position = self._shuttle_state.get_position() current_velocity = self._shuttle_state.get_velocity() # Update state self._shuttle_state.set_position(current_position + current_velocity * dt) # New state new_position = self._shuttle_state.get_position() new_velocity = self._shuttle_state.get_velocity() # Update controller self.controller.update(new_position, new_velocity, self.desired_position) def set_velocity(self, velocity): self._shuttle_state.set_velocity(velocity) def set_desired_position(self, desired_position): self.desired_position = desired_position def get_desired_position(self): return self.desired_position def get_state(self): return self._shuttle_state def set_state(self, state): self._shuttle_state = state def set_controller(self, controller: Controller): self.controller = controller self.controller.set_initial_position(self.get_position()) self.controller.set_initial_velocity(self.get_velocity()) def get_position(self): return self._shuttle_state.get_position() def get_velocity(self): return self._shuttle_state.get_velocity() def set_position(self, position): self._shuttle_state.set_position(position) def get_next_state(self, dt: float, current_state: ManipulatorState, additional_force: np.ndarray = np.array([0.0, 0.0])): """Get the next state of the planar motor given the current state and a time step.""" # Get control signal self.controller.update(current_state.get_position(), current_state.get_velocity(), self.desired_position) self.controller.get_control_signal(1) # print(f'Control signal: {self.controller.get_control_signal(1)}') # print(f'Additional force: {additional_force}') # Update velocity3 norm = np.linalg.norm(self.controller.get_control_signal(1)) force = (self.controller.get_control_signal(dt) + additional_force) * norm / np.linalg.norm(self.controller.get_control_signal(dt) + additional_force) # print(norm) # print(force) # print(f'norm') current_state.set_velocity(force) # Update position current_state.set_position(current_state.get_position() + current_state.get_velocity() * dt) return current_state class PlanarMotorState(ManipulatorState): """Class for storing the state of a planar motor.""" def __init__(self, position: np.ndarray, velocity: np.ndarray): self._position = position self._velocity = velocity def set_position(self, position): """Set the position of the planar motor.""" self._position = position def set_velocity(self, velocity): """Set the velocity of the planar motor.""" self._velocity = velocity def get_position(self): """Get the position of the planar motor.""" return self._position def get_velocity(self): """Get the velocity of the planar motor.""" return self._velocity
4,144
Python
35.681416
159
0.65806
abmoRobotics/MAPs/shuttle_simulator/manipulators/base.py
from abc import ABC, abstractmethod from controllers.controllers import Controller import numpy as np from typing import List class ManipulatorState(ABC): """Abstract class for storing the state of a manipulator""" @abstractmethod def set_position(self, position): pass @abstractmethod def set_velocity(self, velocity): pass @abstractmethod def get_position(self): pass @abstractmethod def get_velocity(self): pass # @abstractmethod # def get_state(self): # pass # @abstractmethod # def set_state(self, state): # pass class Manipulator(ABC): """Abstract class for manipulators.""" @abstractmethod def get_idx(self): pass @abstractmethod def update(self, dt): pass @abstractmethod def set_velocity(self, velocity): pass @abstractmethod def set_desired_position(self, desired_position): pass @abstractmethod def set_controller(self, controller: Controller): pass @abstractmethod def get_state(self): pass @abstractmethod def set_state(self, state: ManipulatorState): pass @abstractmethod def get_next_state(self, dt: float, current_state: ManipulatorState, additional_force: np.ndarray): pass # @abstractmethod # def simulate_next_step(self, state, dt): # pass class ManipulatorTemporalStates(ABC): """Abstract class for storing the temporal states of a manipulator""" @property def __init__(self, manipulators: List[Manipulator], horizon) -> None: number_of_manipulators = len(manipulators) self._temporal_states = np.array([number_of_manipulators, horizon], dtype=ManipulatorState)
1,780
Python
20.719512
103
0.652247
mateamilloshi/kit-exts-project1/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "company.hello.world1" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable company.hello.world ``` # App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Sharing Your Extensions This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
2,044
Markdown
37.584905
258
0.757339
mateamilloshi/kit-exts-project1/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
mateamilloshi/kit-exts-project1/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
mateamilloshi/kit-exts-project1/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
mateamilloshi/kit-exts-project1/exts/company.hello.world1/company/hello/world1/extension.py
import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[company.hello.world1] some_public_function was called with x: ", x) return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class CompanyHelloWorld1Extension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[company.hello.world1] company hello world1 startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[company.hello.world1] company hello world1 shutdown")
1,589
Python
35.136363
119
0.609188
mateamilloshi/kit-exts-project1/exts/company.hello.world1/company/hello/world1/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
mateamilloshi/kit-exts-project1/exts/company.hello.world1/company/hello/world1/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
mateamilloshi/kit-exts-project1/exts/company.hello.world1/company/hello/world1/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import company.hello.world1 # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = company.hello.world1.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,676
Python
34.68085
142
0.682578
mateamilloshi/kit-exts-project1/exts/company.hello.world1/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "company hello world1" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import company.hello.world1". [[python.module]] name = "company.hello.world1" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,586
TOML
32.062499
118
0.745902
mateamilloshi/kit-exts-project1/exts/company.hello.world1/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
mateamilloshi/kit-exts-project1/exts/company.hello.world1/docs/README.md
# Python Extension Example [company.hello.world1] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
179
Markdown
34.999993
126
0.787709
mateamilloshi/kit-exts-project1/exts/company.hello.world1/docs/index.rst
company.hello.world1 ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"company.hello.world1" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
341
reStructuredText
15.285714
43
0.621701
kimsooyoung/legged_robotics/log.md
unitree_quadruped > quadruped_example.py > quadruped_example_extension.py > QuadrupedExampleExtension class > quadruped_example.py from omni.isaac.quadruped.robots import Unitree omni.isaac.quadruped > omni\isaac\quadruped > robots > Unitree 이제 여기서부터 분석 시작 ========================================== Unitree - Constructor A1State: base_frame(FrameState)/joint_pos/joint_vel FrameState - name - pos - quat - lin_vel - ang_vel - pose A1Measurement: state/foot_forces/base_lin_acc/base_ang_vel A1Command: desired_joint_torque ContactSensor * 4 - omni.isaac.sensor [] foot_filter? self._foot_filters = [deque(), deque(), deque(), deque()] IMUSensor - omni.isaac.sensor A1QPController set_state - self.set_world_pose - self.set_linear_velocity - self.set_angular_velocity - self.set_joint_positions - self.set_joint_velocities - self.set_joint_efforts update_contact_sensor_data - self.foot_force update_imu_sensor_data - self.base_lin - self.ang_vel update - update robot sensor variables, state variables in A1Measurement advance - compute desired torque and set articulation effort to robot joints - self._command.desired_joint_torque = self._qp_controller.advance(...) > self._qp_controller.advance를 봐야 한다. > self._qp_controller = A1QPController() > from omni.isaac.quadruped.controllers import A1QPController 사용되는 함수 _qp_controller.reset _qp_controller.setup _qp_controller.set_target_command _qp_controller.advance ========================================== controllers\qp_controller.py - A1QPController Constructor self._ctrl_params = A1CtrlParams() - _kp_foot - _kd_foot - _km_foot - _kp_linear - _kd_linear - _kp_angular - _kd_angular - _torque_gravity self._ctrl_states = A1CtrlStates() - 뭐가 엄청 많다. self._desired_states = A1DesiredStates() - _root_pos_d : desired body position - _root_lin_vel_d : desired body velocity - _euler_d : desired body orientation - _root_ang_vel_d : desired body angular velocity self._root_control = A1RobotControl() > a1_robot_control.py self._sys_model = A1SysModel() - kinematics # toggle standing/moving mode def ctrl_state_reset - _ctrl_params._kp_linear : foot force position - _ctrl_params._kd_linear : foot force velocity - _ctrl_params._kp_angular : foot force orientation - _ctrl_params._kd_angular : foot force orientation - _ctrl_params._kp_foot : swing foot position - _ctrl_params._kd_foot : swing foot velocity - _ctrl_params._km_foot : swing foot force amplitude - _ctrl_params._robot_mass : mass of the robot - _ctrl_params._foot_force_low : low threshold of foot contact force - _ctrl_states._counter - _ctrl_states._gait_counter - _ctrl_states._exp_time def update Fill measurement into _ctrl_states - self._ctrl_states._euler - self._ctrl_states._rot_mat - self._ctrl_states._root_ang_vel - self._ctrl_states._rot_mat_z - self._ctrl_states._joint_vel - self._ctrl_states._joint_pos - self._ctrl_states._foot_pos_rel > kinematics - self._ctrl_states._j_foot > jacobian - self._ctrl_states._foot_pos_abs - self._ctrl_states._foot_forces def set_target_command Set target base velocity command from joystick def advance Perform torque command generation. ============================== generate_ctrl > _compute_grf > _get_qp_params
3,259
Markdown
24.076923
71
0.711568
kimsooyoung/legged_robotics/README.md
# legged_robotics python examples for legged robots
52
Markdown
16.666661
33
0.826923
kimsooyoung/legged_robotics/unitree_quadruped/quadruped_example.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni from omni.isaac.examples.base_sample import BaseSample from omni.isaac.quadruped.robots import Unitree import omni.appwindow # Contains handle to keyboard import numpy as np import carb class QuadrupedExample(BaseSample): def __init__(self) -> None: super().__init__() self._world_settings["stage_units_in_meters"] = 1.0 self._world_settings["physics_dt"] = 1.0 / 400.0 self._world_settings["rendering_dt"] = 20.0 / 400.0 self._enter_toggled = 0 self._base_command = [0.0, 0.0, 0.0, 0] self._event_flag = False # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.5, 0.0, 0.0], "UP": [1.5, 0.0, 0.0], # back command "NUMPAD_2": [-1.5, 0.0, 0.0], "DOWN": [-1.5, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.0, 0.0], "RIGHT": [0.0, -1.0, 0.0], # right command "NUMPAD_4": [0.0, 1.0, 0.0], "LEFT": [0.0, 1.0, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } return def setup_scene(self) -> None: world = self.get_world() self._world.scene.add_default_ground_plane( z_position=0, name="default_ground_plane", prim_path="/World/defaultGroundPlane", static_friction=0.2, dynamic_friction=0.2, restitution=0.01, ) self._a1 = world.scene.add(Unitree(prim_path="/World/A1", name="A1", position=np.array([0, 0, 0.400]))) return async def setup_post_load(self) -> None: self._world = self.get_world() self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("sending_actions", callback_fn=self.on_physics_step) await self._world.play_async() return async def setup_pre_reset(self) -> None: self._event_flag = False return async def setup_post_reset(self) -> None: await self._world.play_async() self._a1.check_dc_interface() self._a1.set_state(self._a1._default_a1_state) return def on_physics_step(self, step_size) -> None: if self._event_flag: self._a1._qp_controller.switch_mode() self._event_flag = False self._a1.advance(step_size, self._base_command) def _sub_keyboard_event(self, event, *args, **kwargs) -> bool: """Subscriber callback to when kit is updated.""" # reset event self._event_flag = False # when a key is pressedor released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER" and self._enter_toggled is False: self._enter_toggled = True if self._base_command[3] == 0: self._base_command[3] = 1 else: self._base_command[3] = 0 self._event_flag = True elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER": self._enter_toggled = False # since no error, we are fine :) return True
4,774
Python
39.466101
111
0.574152
kimsooyoung/legged_robotics/unitree_quadruped/__init__.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # NOTE: Import here your extension examples to be propagated to ISAAC SIM Extensions startup from omni.isaac.examples.unitree_quadruped.quadruped_example import QuadrupedExample from omni.isaac.examples.unitree_quadruped.quadruped_example_extension import QuadrupedExampleExtension
717
Python
50.285711
103
0.828452
kimsooyoung/legged_robotics/unitree_quadruped/quadruped_example_extension.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os from omni.isaac.examples.base_sample import BaseSampleExtension from omni.isaac.examples.unitree_quadruped import QuadrupedExample class QuadrupedExampleExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) overview = "This Example shows how to simulate an Unitree A1 quadruped in Isaac Sim." overview += "\n\tKeybord Input:" overview += "\n\t\tup arrow / numpad 8: Move Forward" overview += "\n\t\tdown arrow/ numpad 2: Move Reverse" overview += "\n\t\tleft arrow/ numpad 4: Move Left" overview += "\n\t\tright arrow / numpad 6: Move Right" overview += "\n\t\tN / numpad 7: Spin Counterclockwise" overview += "\n\t\tM / numpad 9: Spin Clockwise" overview += "\n\nPress the 'Open in IDE' button to view the source code." super().start_extension( menu_name="", submenu_name="", name="Quadruped", title="Unitree A1 Quadruped Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_quadruped.html", overview=overview, file_path=os.path.abspath(__file__), sample=QuadrupedExample(), ) return
1,718
Python
41.974999
113
0.671711
kimsooyoung/legged_robotics/cpp_qp_quadruped/parameters.hpp
/* Rigid body state space model parameters */ #define SSM_GRAVITY -9.81 /* MPC parameters */ #define MPC_STATE_ERROR_WEIGHT {10.0, 10.0, 10.0, 50.0, 50.0, 100.0, 0.0, 0.0, 0.5, 3.0, 3.0, 3.0} #define MPC_INPUT_WEIGHT 1e-6
222
C++
21.299998
98
0.653153
kimsooyoung/legged_robotics/cpp_qp_quadruped/rigid_body_mpc.cpp
#include <rigid_body_mpc.hpp> RigidBodyMPC::RigidBodyMPC() { double weight[] = MPC_STATE_ERROR_WEIGHT; for (int i = 0; i < 12; i++) { state_weight(i) = weight[i]; } state_weight(12) = 0.0; qpSolver.settings()->setVerbosity(false); } RigidBodyMPC::~RigidBodyMPC() { } void RigidBodyMPC::setup(int predictionHorizon, double dt, double mass, double mu, double max_force, double ixx, double iyy, double izz) { this->dt = dt; this->horizonLen = predictionHorizon; this->mass = mass; this->mu = mu; this->max_f = max_force; this->I.setZero(); this->I(0, 0) = ixx; this->I(1, 1) = iyy; this->I(2, 2) = izz; X_ref.resize(13 * horizonLen, NoChange); C_qp.resize(20 * horizonLen, 12 * horizonLen); L_qp.resize(13 * horizonLen, 13 * horizonLen); K_qp.resize(12 * horizonLen, 12 * horizonLen); A_qp.resize(13 * horizonLen, NoChange); B_qp.resize(13 * horizonLen, 12 * horizonLen); g_qp.resize(12 * horizonLen, NoChange); H_qp.resize(12 * horizonLen, 12 * horizonLen); c_l.resize(20 * horizonLen, NoChange); c_u.resize(20 * horizonLen, NoChange); stateTrajectory.resize(12 * horizonLen, NoChange); c_l.setZero(); friction << 1.0 / mu, 0.0, 1.0, -1.0 / mu, 0.0, 1.0, 0.0, 1.0 / mu, 1.f, 0.0, -1.0 / mu, 1.0, 0.0, 0.0, 1.0; for (int i = 0; i < horizonLen * 4; i++) { C_qp.block(5 * i, 3 * i, 5, 3) = friction; } C_qp_spare = C_qp.sparseView(); L_qp.setZero(); L_qp.diagonal() = state_weight.replicate(horizonLen, 1); K_qp.setIdentity(); K_qp *= MPC_INPUT_WEIGHT; } void RigidBodyMPC::buildContinuousSSM() { A_con.setZero(); B_con.setZero(); A_con.block(3, 9, 3, 3) = Matrix<double, 3, 3>::Identity(); A_con(11, 12) = 1.0; A_con.block(0, 6, 3, 3) = R_z.transpose(); Matrix<double, 3, 3> I_world_inv = I_world.inverse(); for (int i = 0; i < 4; i++) { Matrix<double, 3, 3> cross_m; double *foot = &feet_pos[i * 3]; cross_m << 0.0, -foot[2], foot[1], foot[2], 0.0, -foot[0], -foot[1], foot[0], 0.0; B_con.block(6, i * 3, 3, 3) = I_world_inv * cross_m; B_con(9, i * 3 + 0) = 1.0 / mass; B_con(10, i * 3 + 1) = 1.0 / mass; B_con(11, i * 3 + 2) = 1.0 / mass; } } void RigidBodyMPC::convertToDiscreteSSM() { AB_con.setZero(); AB_con.block(0, 0, 13, 13) = A_con; AB_con.block(0, 13, 13, 12) = B_con; AB_con *= dt; exp_AB_con = AB_con.exp(); A_des = exp_AB_con.block(0, 0, 13, 13); B_des = exp_AB_con.block(0, 13, 13, 12); } void RigidBodyMPC::convertToQPForm() { //TODO: Optimize this function using DP for (int row = 0; row < horizonLen; row++) { A_qp.block(13 * row, 0, 13, 13) = A_des.pow(row + 1); for (int col = 0; col < horizonLen; col++) { if (row >= col) { B_qp.block(13 * row, 12 * col, 13, 12) = A_des.pow(row - col) * B_des; } } } H_qp = 2.0 * (B_qp.transpose() * L_qp * B_qp + K_qp); g_qp = 2.0 * B_qp.transpose() * L_qp * (A_qp * current_X - X_ref); H_qp_spare = H_qp.sparseView(); int k = 0; for (int i = 0; i < horizonLen; i++) { for (int j = 0; j < 4; j++) { c_u(5 * k + 0) = numeric_limits<double>::infinity(); c_u(5 * k + 1) = numeric_limits<double>::infinity(); c_u(5 * k + 2) = numeric_limits<double>::infinity(); c_u(5 * k + 3) = numeric_limits<double>::infinity(); c_u(5 * k + 4) = max_f * (double)gait[i * 4 + j]; k++; } } } void RigidBodyMPC::run(double *current_state, double *ref_state, bool *gait, double *feet_pos) { this->feet_pos = feet_pos; this->gait = gait; for (int i = 0; i < 12; i++) { current_X(i) = current_state[i]; } current_X(12) = (double)SSM_GRAVITY; for (int i = 0; i < horizonLen; i++) { for (int j = 0; j < 12; j++) { X_ref(i * 13 + j) = ref_state[i * 12 + j]; } X_ref(i * 13 + 12) = (double)SSM_GRAVITY; } double yaw = current_state[2]; double c_yaw = cos(yaw); double s_yaw = sin(yaw); R_z << c_yaw, -s_yaw, 0.0, s_yaw, c_yaw, 0.0, 0.0, 0.0, 1.0; I_world = R_z * I * R_z.transpose(); buildContinuousSSM(); convertToDiscreteSSM(); convertToQPForm(); qpSolver.data()->setNumberOfVariables(12 * horizonLen); qpSolver.data()->setNumberOfConstraints(20 * horizonLen); qpSolver.data()->setLinearConstraintsMatrix(C_qp_spare); qpSolver.data()->setHessianMatrix(H_qp_spare); qpSolver.data()->setGradient(g_qp); qpSolver.data()->setLowerBound(c_l); qpSolver.data()->setUpperBound(c_u); qpSolver.initSolver(); qpSolver.solve(); U = qpSolver.getSolution(); U_body = U; input = U.data(); for (int i = 0; i < 4; i++) { Matrix<double, 3, 1> body_f; Matrix<double, 3, 1> world_f; body_f(0) = input[i * 3 + 0]; body_f(1) = input[i * 3 + 1]; body_f(2) = input[i * 3 + 2]; world_f = -R_z.transpose() * body_f; input[i * 3 + 0] = world_f(0); input[i * 3 + 1] = world_f(1); input[i * 3 + 2] = world_f(2); } qpSolver.data()->clearLinearConstraintsMatrix(); qpSolver.data()->clearHessianMatrix(); qpSolver.clearSolver(); } void RigidBodyMPC::getResults(double *&input_forces_world, double *&input_forces_body) { input_forces_world = this->input; input_forces_body = this->U_body.data(); } void RigidBodyMPC::getPredictedTrajectory(double *&inputTrajectory, double *&stateTrajectory) { inputTrajectory = this->input; auto X = A_qp * current_X + B_qp * U; for (int i = 0; i < horizonLen; i++) { for (int j = 0; j < 12; j++) { this->stateTrajectory(i * 12 + j) = X(i * 13 + j); } } stateTrajectory = this->stateTrajectory.data(); }
6,090
C++
24.485356
136
0.526437
kimsooyoung/legged_robotics/cpp_qp_quadruped/rigid_body_mpc.hpp
#include <Eigen/Dense> #include <Eigen/Sparse> #include <unsupported/Eigen/MatrixFunctions> #include <ros/ros.h> #include <iostream> #include <parameters.hpp> #include <OsqpEigen/OsqpEigen.h> using Eigen::Dynamic; using Eigen::NoChange; using namespace Eigen; using namespace std; /* xhat = Ac * x[k] + Bc * u[k] x[k+1] = Ad * x[k] + Bd * u[k] x = [ roll, pitch, yaw, x, y, z, roll_vel, pitch_vel, yaw_vel, x_vel, y_vel, z_vel, g ] u = [ force1_x, force1_y, force1_z, force2_x, force2_y, force2_z, force3_x, force3_y, force3_z, force4_x, force4_y, force4_z, ] */ class RigidBodyMPC { private: double mass = 0.0; double mu = 0.0; double max_f = 0.0; Matrix<double, 3, 3> I; double *feet_pos; bool *gait; Matrix<double, 13, 1> state_weight; Matrix<double, 3, 3> I_world; Matrix<double, 5, 3> friction; Matrix<double, 13, 13> A_con; Matrix<double, 13, 12> B_con; Matrix<double, Dynamic, 1> X_ref; Matrix<double, 13, 1> current_X; Matrix<double, 3, 3> R_z; Matrix<double, 25, 25> AB_con; Matrix<double, 25, 25> exp_AB_con; Matrix<double, 13, 13> A_des; Matrix<double, 13, 12> B_des; Matrix<double, Dynamic, 13> A_qp; Matrix<double, Dynamic, Dynamic> B_qp; Matrix<double, Dynamic, Dynamic> L_qp; Matrix<double, Dynamic, Dynamic> K_qp; Matrix<double, Dynamic, Dynamic> C_qp; Matrix<double, Dynamic, Dynamic> H_qp; Matrix<double, Dynamic, 1> g_qp; Matrix<double, Dynamic, 1> c_u; Matrix<double, Dynamic, 1> c_l; Matrix<double, Dynamic, 1> U; Matrix<double, 12, 1> U_body; Matrix<double, Dynamic, 1> stateTrajectory; double *input; SparseMatrix<double, Eigen::ColMajor> H_qp_spare; SparseMatrix<double, Eigen::ColMajor> C_qp_spare; OsqpEigen::Solver qpSolver; double dt = 0.0; int horizonLen = 0; void buildContinuousSSM(); void convertToDiscreteSSM(); void convertToQPForm(); int a = 0; public: RigidBodyMPC(); ~RigidBodyMPC(); void setup(int predictionHorizon, double dt, double mass, double mu, double max_force, double ixx, double iyy, double izz); void run(double *current_state, double *ref_state, bool *gait, double *feet_pos); void getResults(double *&input_forces, double *&input_forces_body); void getPredictedTrajectory(double *&inputTrajectory, double *&stateTrajectory); };
2,496
C++
18.356589
127
0.621394
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/go1_ros1_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ Introduction This is a demo for the go1 robot's ros integration. In this example, the robot's foot position and contact forces are being published to "/isaac_a1/output" topic, and these values can be plotted using plotjugler. """ from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.quadruped.robots import Unitree from omni.isaac.core.utils.extensions import enable_extension import omni.appwindow # Contains handle to keyboard import numpy as np import carb import omni.graph.core as og # enable ROS bridge extension enable_extension("omni.isaac.ros_bridge") simulation_app.update() # check if rosmaster node is running # this is to prevent this sample from waiting indefinetly if roscore is not running # can be removed in regular usage import rosgraph if not rosgraph.is_master_online(): carb.log_error("Please run roscore before executing this script") simulation_app.close() exit() from std_msgs.msg import Float32MultiArray import rospy class Go1_runner(object): def __init__(self, physics_dt, render_dt) -> None: """ [Summary] creates the simulation world with preset physics_dt and render_dt and creates a unitree go1 robot Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) self._go1 = self._world.scene.add( Unitree( prim_path="/World/Go1", name="Go1", position=np.array([0, 0, 0.40]), physics_dt=physics_dt, model="Go1" ) ) self._world.scene.add_default_ground_plane( z_position=0, name="default_ground_plane", prim_path="/World/defaultGroundPlane", static_friction=0.2, dynamic_friction=0.2, restitution=0.01, ) self._world.reset() self._enter_toggled = 0 self._base_command = [0.0, 0.0, 0.0, 0] self._event_flag = False # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.8, 0.0, 0.0], "UP": [1.8, 0.0, 0.0], # back command "NUMPAD_2": [-1.8, 0.0, 0.0], "DOWN": [-1.8, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.8, 0.0], "RIGHT": [0.0, -1.8, 0.0], # right command "NUMPAD_4": [0.0, 1.8, 0.0], "LEFT": [0.0, 1.8, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } # Creating an ondemand push graph with ROS Clock, everything in the ROS environment must synchronize with this clock try: keys = og.Controller.Keys (self._clock_graph, _, _, _) = og.Controller.edit( { "graph_path": "/ROS_Clock", "evaluator_name": "push", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishClock", "omni.isaac.ros_bridge.ROS1PublishClock"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "publishClock.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"), ], }, ) except Exception as e: print(e) simulation_app.close() exit() self._pub = rospy.Publisher("/isaac_a1/output", Float32MultiArray, queue_size=10) return def setup(self) -> None: """ [Summary] Set unitree robot's default stance, set up keyboard listener and add physics callback """ self._go1.set_state(self._go1._default_a1_state) self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("a1_advance", callback_fn=self.on_physics_step) def on_physics_step(self, step_size) -> None: """ [Summary] Physics call back, switch robot mode and call robot advance function to compute and apply joint torque """ if self._event_flag: self._go1._qp_controller.switch_mode() self._event_flag = False self._go1.advance(step_size, self._base_command) # Tick the ROS Clock og.Controller.evaluate_sync(self._clock_graph) self._pub.publish(Float32MultiArray(data=self.get_footforce_data())) def get_footforce_data(self) -> np.array: """ [Summary] get foot force and position data """ data = np.concatenate((self._go1.foot_force, self._go1._qp_controller._ctrl_states._foot_pos_abs[:, 2])) return data def run(self) -> None: """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) return def _sub_keyboard_event(self, event, *args, **kwargs) -> None: """ [Summary] Subscriber callback to when kit is updated. """ # reset event self._event_flag = False # when a key is pressedor released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER" and self._enter_toggled is False: self._enter_toggled = True if self._base_command[3] == 0: self._base_command[3] = 1 else: self._base_command[3] = 0 self._event_flag = True elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER": self._enter_toggled = False # since no error, we are fine :) return True def main() -> None: """ [Summary] Instantiate ros node and start a1 runner """ rospy.init_node("go1_standalone", anonymous=False, disable_signals=True, log_level=rospy.ERROR) rospy.set_param("use_sim_time", True) physics_downtime = 1 / 400.0 runner = Go1_runner(physics_dt=physics_downtime, render_dt=16 * physics_downtime) simulation_app.update() runner.setup() # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() rospy.signal_shutdown("go1 complete") simulation_app.close() if __name__ == "__main__": main()
8,482
Python
33.344129
124
0.578755
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/a1_vision_ros2_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.quadruped.robots import UnitreeVision from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import get_assets_root_path import omni.graph.core as og import omni.appwindow # Contains handle to keyboard import numpy as np import carb import argparse import json # enable ROS2 bridge extension ext_manager = omni.kit.app.get_app().get_extension_manager() ext_manager.set_extension_enabled_immediate("omni.isaac.ros2_bridge", True) class A1_runner(object): def __init__(self, physics_dt, render_dt, way_points=None) -> None: """ Summary Creates the simulation world with preset physics_dt and render_dt and creates a unitree a1 robot (with ROS2 cameras) inside the warehouse Also instantiate a ROS2 clock Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. way_points {List[List[float]]} -- x coordinate, y coordinate, heading (in rad) """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") prim = get_prim_at_path("/World/Warehouse") if not prim.IsValid(): prim = define_prim("/World/Warehouse", "Xform") asset_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd" prim.GetReferences().AddReference(asset_path) self._a1 = self._world.scene.add( UnitreeVision( prim_path="/World/A1", name="A1", position=np.array([0, 0, 0.40]), physics_dt=physics_dt, model="A1", way_points=way_points, is_ros2=True, ) ) # Publish camera images every 3 frames simulation_app.update() self._a1.setCameraExeutionStep(3) # Creating an ondemand push graph with ROS Clock, everything in the ROS environment must synchronize with this clock try: keys = og.Controller.Keys (self._clock_graph, _, _, _) = og.Controller.edit( { "graph_path": "/ROS_Clock", "evaluator_name": "push", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "publishClock.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"), ], }, ) except Exception as e: print(e) simulation_app.close() exit() self._world.reset() self._enter_toggled = 0 self._base_command = [0.0, 0.0, 0.0, 0] self._event_flag = False # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.8, 0.0, 0.0], "UP": [1.8, 0.0, 0.0], # back command "NUMPAD_2": [-1.8, 0.0, 0.0], "DOWN": [-1.8, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.8, 0.0], "RIGHT": [0.0, -1.8, 0.0], # right command "NUMPAD_4": [0.0, 1.8, 0.0], "LEFT": [0.0, 1.8, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } def setup(self, way_points=None): """ [Summary] Set unitree robot's default stance, set up keyboard listener and add physics callback """ self._a1.set_state(self._a1._default_a1_state) self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("a1_advance", callback_fn=self.on_physics_step) if way_points is None: self._path_follow = False else: self._path_follow = True def on_physics_step(self, step_size): """ [Summary] Physics call back, switch robot mode and call robot advance function to compute and apply joint torque """ if self._event_flag: self._a1._qp_controller.switch_mode() self._event_flag = False self._a1.advance(step_size, self._base_command, self._path_follow) og.Controller.evaluate_sync(self._clock_graph) def run(self): """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) return def _sub_keyboard_event(self, event, *args, **kwargs): """ [Summary] Keyboard subscriber callback to when kit is updated. """ # reset event self._event_flag = False # when a key is pressedor released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER" and self._enter_toggled is False: self._enter_toggled = True if self._base_command[3] == 0: self._base_command[3] = 1 else: self._base_command[3] = 0 self._event_flag = True elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER": self._enter_toggled = False # since no error, we are fine :) return True parser = argparse.ArgumentParser(description="a1 quadruped demo") parser.add_argument("-w", "--waypoint", type=str, metavar="", required=False, help="file path to the waypoints") args, unknown = parser.parse_known_args() def main(): """ [Summary] Instantiate ros node and start a1 runner """ physics_downtime = 1 / 400.0 if args.waypoint: waypoint_pose = [] try: print(str(args.waypoint)) file = open(str(args.waypoint)) waypoint_data = json.load(file) for waypoint in waypoint_data: waypoint_pose.append(np.array([waypoint["x"], waypoint["y"], waypoint["rad"]])) except FileNotFoundError: print("error file not found, ending") simulation_app.close() return runner = A1_runner(physics_dt=physics_downtime, render_dt=8 * physics_downtime, way_points=waypoint_pose) simulation_app.update() runner.setup(way_points=waypoint) else: runner = A1_runner(physics_dt=physics_downtime, render_dt=8 * physics_downtime, way_points=None) simulation_app.update() runner.setup(way_points=None) # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() simulation_app.close() if __name__ == "__main__": main()
9,001
Python
34.164062
145
0.575047
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/a1_direct_ros1_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """ Introduction We start a runner which publishes robot sensor data as ROS1 topics and listens to outside ROS1 topic "isaac_a1/joint_torque_cmd". The runner set robot joint torques directly using the external ROS1 topic "isaac_a1/joint_torque_cmd". The runner instantiate robot UnitreeDirect, which directly takes in joint torques and sends torques to lowlevel joint controllers This is a very simple example to demonstrate how to treat Isaac Sim as a simulation component with in the ROS1 ecosystem """ from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.quadruped.robots import UnitreeDirect from omni.isaac.quadruped.utils.a1_classes import A1Measurement from omni.isaac.core.utils.extensions import enable_extension from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import get_assets_root_path import omni.appwindow # Contains handle to keyboard import numpy as np import carb import omni.graph.core as og # enable ROS bridge extension enable_extension("omni.isaac.ros_bridge") simulation_app.update() # check if rosmaster node is running # this is to prevent this sample from waiting indefinetly if roscore is not running # can be removed in regular usage import rosgraph if not rosgraph.is_master_online(): carb.log_error("Please run roscore before executing this script") simulation_app.close() exit() # ros-python and ROS1 messages import geometry_msgs.msg as geometry_msgs import rospy import sensor_msgs.msg as sensor_msgs class A1_direct_runner(object): def __init__(self, physics_dt, render_dt) -> None: """ [Summary] creates the simulation world with preset physics_dt and render_dt and creates a unitree a1 robot inside the warehouse Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") prim = get_prim_at_path("/World/Warehouse") if not prim.IsValid(): prim = define_prim("/World/Warehouse", "Xform") asset_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd" prim.GetReferences().AddReference(asset_path) self._a1 = self._world.scene.add( UnitreeDirect( prim_path="/World/A1", name="A1", position=np.array([0, 0, 0.40]), physics_dt=physics_dt, model="A1" ) ) self._world.reset() # Creating an ondemand push graph with ROS Clock, everything in the ROS environment must synchronize with this clock try: keys = og.Controller.Keys (self._clock_graph, _, _, _) = og.Controller.edit( { "graph_path": "/ROS_Clock", "evaluator_name": "push", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishClock", "omni.isaac.ros_bridge.ROS1PublishClock"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "publishClock.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"), ], }, ) except Exception as e: print(e) simulation_app.close() exit() ## # ROS publishers ## # a) ground truth body pose self._pub_body_pose = rospy.Publisher("isaac_a1/gt_body_pose", geometry_msgs.PoseStamped, queue_size=21) self._msg_body_pose = geometry_msgs.PoseStamped() self._msg_body_pose.header.frame_id = "base_link" # b) joint angle and foot force self._pub_joint_state = rospy.Publisher("isaac_a1/joint_foot", sensor_msgs.JointState, queue_size=21) self._msg_joint_state = sensor_msgs.JointState() self._msg_joint_state.name = [ "FL0", "FL1", "FL2", "FR0", "FR1", "FR2", "RL0", "RL1", "RL2", "RR0", "RR1", "RR2", "FL_foot", "FR_foot", "RL_foot", "RR_foot", ] self._msg_joint_state.position = [0.0] * 16 self._msg_joint_state.velocity = [0.0] * 16 self._msg_joint_state.effort = [0.0] * 16 # c) IMU measurements self._pub_imu_debug = rospy.Publisher("isaac_a1/imu_data", sensor_msgs.Imu, queue_size=21) self._msg_imu_debug = sensor_msgs.Imu() self._msg_imu_debug.header.frame_id = "base_link" # d) ground truth body pose with a fake covariance self._pub_body_pose_with_cov = rospy.Publisher( "isaac_a1/gt_body_pose_with_cov", geometry_msgs.PoseWithCovarianceStamped, queue_size=21 ) self._msg_body_pose_with_cov = geometry_msgs.PoseWithCovarianceStamped() self._msg_body_pose_with_cov.header.frame_id = "base_link" ## # ROS subscribers ## self._sub_joint_cmd = rospy.Subscriber( "isaac_a1/joint_torque_cmd", sensor_msgs.JointState, self.joint_command_callback ) # buffer to store the robot command self._ros_command = np.zeros(12) def setup(self): """ [Summary] add physics callback """ self._app_window = omni.appwindow.get_default_app_window() self._world.add_physics_callback("robot_sim_step", callback_fn=self.robot_simulation_step) # start ROS publisher and subscribers def run(self): """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) return def publish_ros_data(self, measurement: A1Measurement): """ [Summary] Publish body pose, joint state, imu data """ # update all header timestamps ros_timestamp = rospy.get_rostime() self._msg_body_pose.header.stamp = ros_timestamp self._msg_joint_state.header.stamp = ros_timestamp self._msg_imu_debug.header.stamp = ros_timestamp self._msg_body_pose_with_cov.header.stamp = ros_timestamp # a) ground truth pose self._update_body_pose_msg(measurement) self._pub_body_pose.publish(self._msg_body_pose) # b) joint state and contact force self._update_msg_joint_state(measurement) self._pub_joint_state.publish(self._msg_joint_state) # c) IMU self._update_imu_msg(measurement) self._pub_imu_debug.publish(self._msg_imu_debug) # d) ground truth pose with covariance self._update_body_pose_with_cov_msg(measurement) self._pub_body_pose_with_cov.publish(self._msg_body_pose_with_cov) return """call backs""" def robot_simulation_step(self, step_size): """ [Summary] Call robot update and advance, and tick ros bridge """ self._a1.update() self._a1.advance() # Tick the ROS Clock og.Controller.evaluate_sync(self._clock_graph) # Publish ROS data self.publish_ros_data(self._a1._measurement) def joint_command_callback(self, data): """ [Summary] Joint command call back, set command torque for the joints """ for i in range(12): self._ros_command[i] = data.effort[i] self._a1.set_command_torque(self._ros_command) """ Utilities functions. """ def _update_body_pose_msg(self, measurement: A1Measurement): """ [Summary] Updates the body pose message. """ # base position self._msg_body_pose.pose.position.x = measurement.state.base_frame.pos[0] self._msg_body_pose.pose.position.y = measurement.state.base_frame.pos[1] self._msg_body_pose.pose.position.z = measurement.state.base_frame.pos[2] # base orientation self._msg_body_pose.pose.orientation.w = measurement.state.base_frame.quat[3] self._msg_body_pose.pose.orientation.x = measurement.state.base_frame.quat[0] self._msg_body_pose.pose.orientation.y = measurement.state.base_frame.quat[1] self._msg_body_pose.pose.orientation.z = measurement.state.base_frame.quat[2] def _update_msg_joint_state(self, measurement: A1Measurement): """ [Summary] Updates the joint state message. """ # joint position and velocity for i in range(12): self._msg_joint_state.position[i] = measurement.state.joint_pos[i] self._msg_joint_state.velocity[i] = measurement.state.joint_vel[i] # foot force for i in range(4): # notice this order is: FL, FR, RL, RR self._msg_joint_state.effort[12 + i] = measurement.foot_forces[i] def _update_imu_msg(self, measurement: A1Measurement): """ [Summary] Updates the IMU message. """ # accelerometer data self._msg_imu_debug.linear_acceleration.x = measurement.base_lin_acc[0] self._msg_imu_debug.linear_acceleration.y = measurement.base_lin_acc[1] self._msg_imu_debug.linear_acceleration.z = measurement.base_lin_acc[2] # gyroscope data self._msg_imu_debug.angular_velocity.x = measurement.base_ang_vel[0] self._msg_imu_debug.angular_velocity.y = measurement.base_ang_vel[1] self._msg_imu_debug.angular_velocity.z = measurement.base_ang_vel[2] def _update_body_pose_with_cov_msg(self, measurement: A1Measurement): """ [Summary] Updates the body pose with fake covariance message. """ # base position self._msg_body_pose_with_cov.pose.pose.position.x = measurement.state.base_frame.pos[0] self._msg_body_pose_with_cov.pose.pose.position.y = measurement.state.base_frame.pos[1] self._msg_body_pose_with_cov.pose.pose.position.z = measurement.state.base_frame.pos[2] # base orientation self._msg_body_pose_with_cov.pose.pose.orientation.w = measurement.state.base_frame.quat[3] self._msg_body_pose_with_cov.pose.pose.orientation.x = measurement.state.base_frame.quat[0] self._msg_body_pose_with_cov.pose.pose.orientation.y = measurement.state.base_frame.quat[1] self._msg_body_pose_with_cov.pose.pose.orientation.z = measurement.state.base_frame.quat[2] # Setting fake covariance for i in range(6): self._msg_body_pose_with_cov.pose.covariance[i * 6 + i] = 0.001 def main(): """ [Summary] The function launches the simulator, creates the robot, and run the simulation steps """ # first enable ros node, make sure using simulation time rospy.init_node("isaac_a1", anonymous=False, disable_signals=True, log_level=rospy.ERROR) rospy.set_param("use_sim_time", True) physics_downtime = 1 / 400.0 runner = A1_direct_runner(physics_dt=physics_downtime, render_dt=physics_downtime) simulation_app.update() runner.setup() # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() rospy.signal_shutdown("a1 direct complete") simulation_app.close() if __name__ == "__main__": main()
12,576
Python
35.140804
129
0.617287
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/anymal_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.quadruped.robots import Anymal from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import get_assets_root_path from pxr import Gf, UsdGeom import omni.appwindow # Contains handle to keyboard import numpy as np import carb class Anymal_runner(object): def __init__(self, physics_dt, render_dt) -> None: """ Summary creates the simulation world with preset physics_dt and render_dt and creates an anymal robot inside the warehouse Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") # spawn warehouse scene prim = get_prim_at_path("/World/GroundPlane") if not prim.IsValid(): prim = define_prim("/World/GroundPlane", "Xform") asset_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd" prim.GetReferences().AddReference(asset_path) self._anymal = self._world.scene.add( Anymal( prim_path="/World/Anymal", name="Anymal", usd_path=assets_root_path + "/Isaac/Robots/ANYbotics/anymal_c.usd", position=np.array([0, 0, 0.70]), ) ) self._world.reset() self._enter_toggled = 0 self._base_command = np.zeros(3) # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.0, 0.0, 0.0], "UP": [1.0, 0.0, 0.0], # back command "NUMPAD_2": [-1.0, 0.0, 0.0], "DOWN": [-1.0, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.0, 0.0], "RIGHT": [0.0, -1.0, 0.0], # right command "NUMPAD_4": [0.0, 1.0, 0.0], "LEFT": [0.0, 1.0, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } self.needs_reset = False def setup(self) -> None: """ [Summary] Set up keyboard listener and add physics callback """ self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("anymal_advance", callback_fn=self.on_physics_step) def on_physics_step(self, step_size) -> None: """ [Summary] Physics call back, switch robot mode and call robot advance function to compute and apply joint torque """ if self.needs_reset: self._world.reset(True) self.needs_reset = False self._anymal.advance(step_size, self._base_command) def run(self) -> None: """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) if not self._world.is_simulating(): self.needs_reset = True return def _sub_keyboard_event(self, event, *args, **kwargs) -> bool: """ [Summary] Keyboard subscriber callback to when kit is updated. """ # reset event self._event_flag = False # when a key is pressed for released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) return True def main(): """ [Summary] Parse arguments and instantiate the ANYmal runner """ physics_dt = 1 / 200.0 render_dt = 1 / 60.0 runner = Anymal_runner(physics_dt=physics_dt, render_dt=render_dt) simulation_app.update() runner.setup() # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() simulation_app.close() if __name__ == "__main__": main()
5,653
Python
32.258823
122
0.589775
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/a1_vision_ros1_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ Introduction: In this demo, the quadruped is publishing data from a pair of stereovision cameras and imu data for the VINS fusion visual interial odometry algorithm. Users can use the keyboard mapping to control the motion of the quadruped while the quadruped localize itself. """ from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.quadruped.robots import UnitreeVision from omni.isaac.core.utils.extensions import enable_extension from omni.isaac.core.utils.nucleus import get_assets_root_path import omni.appwindow # Contains handle to keyboard import numpy as np import carb import omni.graph.core as og # enable ROS bridge extension enable_extension("omni.isaac.ros_bridge") simulation_app.update() # check if rosmaster node is running # this is to prevent this sample from waiting indefinetly if roscore is not running # can be removed in regular usage import rosgraph if not rosgraph.is_master_online(): carb.log_error("Please run roscore before executing this script") simulation_app.close() exit() from std_msgs.msg import Float32MultiArray import sensor_msgs.msg as sensor_msgs import rospy class A1_stereo_vision(object): def __init__(self, physics_dt, render_dt) -> None: """ [Summary] creates the simulation world with preset physics_dt and render_dt and creates a unitree a1 robot (with ros cameras) inside a custom environment, set up ros publishers for the isaac_a1/imu_data and isaac_a1/foot_force topic Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) prim = get_prim_at_path("/World/Warehouse") if not prim.IsValid(): prim = define_prim("/World/Warehouse", "Xform") assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets server") asset_path = assets_root_path + "/Isaac/Samples/ROS/Scenario/visual_odometry_testing.usd" prim.GetReferences().AddReference(asset_path) self._a1 = self._world.scene.add( UnitreeVision( prim_path="/World/A1", name="A1", position=np.array([0, 0, 0.27]), physics_dt=physics_dt, model="A1" ) ) # Publish camera images every 3 frames simulation_app.update() self._a1.setCameraExeutionStep(3) self._world.reset() self._enter_toggled = 0 self._base_command = [0.0, 0.0, 0.0, 0] self._event_flag = False # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.8, 0.0, 0.0], "UP": [1.8, 0.0, 0.0], # back command "NUMPAD_2": [-1.8, 0.0, 0.0], "DOWN": [-1.8, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.8, 0.0], "RIGHT": [0.0, -1.8, 0.0], # right command "NUMPAD_4": [0.0, 1.8, 0.0], "LEFT": [0.0, 1.8, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } # Creating an ondemand push graph with ROS Clock, everything in the ROS environment must synchronize with this clock try: keys = og.Controller.Keys (self._clock_graph, _, _, _) = og.Controller.edit( { "graph_path": "/ROS_Clock", "evaluator_name": "push", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishClock", "omni.isaac.ros_bridge.ROS1PublishClock"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "publishClock.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"), ], }, ) except Exception as e: print(e) simulation_app.close() exit() self._footforce_pub = rospy.Publisher("isaac_a1/foot_force", Float32MultiArray, queue_size=10) self._imu_pub = rospy.Publisher("isaac_a1/imu_data", sensor_msgs.Imu, queue_size=21) self._step_count = 0 self._publish_interval = 2 self._foot_force = Float32MultiArray() self._imu_msg = sensor_msgs.Imu() self._imu_msg.header.frame_id = "base_link" def setup(self) -> None: """ [Summary] Set unitree robot's default stance, set up keyboard listener and add physics callback """ self._a1.set_state(self._a1._default_a1_state) self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("a1_advance", callback_fn=self.on_physics_step) def on_physics_step(self, step_size) -> None: """ [Summary] Physics call back, switch robot mode and call robot advance function to compute and apply joint torque """ if self._event_flag: self._a1._qp_controller.switch_mode() self._event_flag = False self._a1.advance(step_size, self._base_command) og.Controller.evaluate_sync(self._clock_graph) self._step_count += 1 if self._step_count % self._publish_interval == 0: ros_time = rospy.get_rostime() self.update_footforce_data() self._footforce_pub.publish(self._foot_force) self.update_imu_data() self._imu_msg.header.stamp = ros_time self._imu_pub.publish(self._imu_msg) self._step_count = 0 def update_footforce_data(self) -> None: """ [Summary] Update foot position and foot force data for ros publisher """ self._foot_force.data = np.concatenate( (self._a1.foot_force, self._a1._qp_controller._ctrl_states._foot_pos_abs[:, 2]) ) def update_imu_data(self) -> None: """ [Summary] Update imu data for ros publisher """ self._imu_msg.orientation.x = self._a1._state.base_frame.quat[0] self._imu_msg.orientation.y = self._a1._state.base_frame.quat[1] self._imu_msg.orientation.z = self._a1._state.base_frame.quat[2] self._imu_msg.orientation.w = self._a1._state.base_frame.quat[3] self._imu_msg.linear_acceleration.x = self._a1._measurement.base_lin_acc[0] self._imu_msg.linear_acceleration.y = self._a1._measurement.base_lin_acc[1] self._imu_msg.linear_acceleration.z = self._a1._measurement.base_lin_acc[2] self._imu_msg.angular_velocity.x = self._a1._measurement.base_ang_vel[0] self._imu_msg.angular_velocity.y = self._a1._measurement.base_ang_vel[1] self._imu_msg.angular_velocity.z = self._a1._measurement.base_ang_vel[2] def run(self) -> None: """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) return def _sub_keyboard_event(self, event, *args, **kwargs) -> bool: """ [Summary] Keyboard subscriber callback to when kit is updated. """ # reset event self._event_flag = False # when a key is pressedor released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER" and self._enter_toggled is False: self._enter_toggled = True if self._base_command[3] == 0: self._base_command[3] = 1 else: self._base_command[3] = 0 self._event_flag = True elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER": self._enter_toggled = False # since no error, we are fine :) return True def main() -> None: """ [Summary] Instantiate ros node and start a1 runner """ rospy.init_node("isaac_a1", anonymous=False, disable_signals=True, log_level=rospy.ERROR) rospy.set_param("use_sim_time", True) physics_downtime = 1 / 400.0 runner = A1_stereo_vision(physics_dt=physics_downtime, render_dt=8 * physics_downtime) simulation_app.update() runner.setup() # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() rospy.signal_shutdown("a1 vision complete") simulation_app.close() if __name__ == "__main__": main()
10,706
Python
35.667808
139
0.5949
kimsooyoung/legged_robotics/standalone_ex/omni.isaac.quadruped/a1_standalone.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.isaac.quadruped.robots import Unitree from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import get_assets_root_path from pxr import Gf, UsdGeom import omni.appwindow # Contains handle to keyboard import numpy as np import carb import argparse import json class A1_runner(object): def __init__(self, physics_dt, render_dt, way_points=None) -> None: """ Summary creates the simulation world with preset physics_dt and render_dt and creates a unitree a1 robot inside the warehouse Argument: physics_dt {float} -- Physics downtime of the scene. render_dt {float} -- Render downtime of the scene. way_points {List[List[float]]} -- x coordinate, y coordinate, heading (in rad) """ self._world = World(stage_units_in_meters=1.0, physics_dt=physics_dt, rendering_dt=render_dt) assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") # spawn warehouse scene prim = get_prim_at_path("/World/Warehouse") if not prim.IsValid(): prim = define_prim("/World/Warehouse", "Xform") asset_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd" prim.GetReferences().AddReference(asset_path) self._a1 = self._world.scene.add( Unitree( prim_path="/World/A1", name="A1", position=np.array([0, 0, 0.40]), physics_dt=physics_dt, model="A1", way_points=way_points, ) ) self._world.reset() self._enter_toggled = 0 self._base_command = [0.0, 0.0, 0.0, 0] self._event_flag = False # bindings for keyboard to command self._input_keyboard_mapping = { # forward command "NUMPAD_8": [1.8, 0.0, 0.0], "UP": [1.8, 0.0, 0.0], # back command "NUMPAD_2": [-1.8, 0.0, 0.0], "DOWN": [-1.8, 0.0, 0.0], # left command "NUMPAD_6": [0.0, -1.8, 0.0], "RIGHT": [0.0, -1.8, 0.0], # right command "NUMPAD_4": [0.0, 1.8, 0.0], "LEFT": [0.0, 1.8, 0.0], # yaw command (positive) "NUMPAD_7": [0.0, 0.0, 1.0], "N": [0.0, 0.0, 1.0], # yaw command (negative) "NUMPAD_9": [0.0, 0.0, -1.0], "M": [0.0, 0.0, -1.0], } def setup(self, way_points=None) -> None: """ [Summary] Set unitree robot's default stance, set up keyboard listener and add physics callback """ self._a1.set_state(self._a1._default_a1_state) self._appwindow = omni.appwindow.get_default_app_window() self._input = carb.input.acquire_input_interface() self._keyboard = self._appwindow.get_keyboard() self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) self._world.add_physics_callback("a1_advance", callback_fn=self.on_physics_step) if way_points is None: self._path_follow = False else: self._path_follow = True def on_physics_step(self, step_size) -> None: """ [Summary] Physics call back, switch robot mode and call robot advance function to compute and apply joint torque """ if self._event_flag: self._a1._qp_controller.switch_mode() self._event_flag = False self._a1.advance(step_size, self._base_command, self._path_follow) def run(self) -> None: """ [Summary] Step simulation based on rendering downtime """ # change to sim running while simulation_app.is_running(): self._world.step(render=True) return def _sub_keyboard_event(self, event, *args, **kwargs) -> bool: """ [Summary] Keyboard subscriber callback to when kit is updated. """ # reset event self._event_flag = False # when a key is pressed for released the command is adjusted w.r.t the key-mapping if event.type == carb.input.KeyboardEventType.KEY_PRESS: # on pressing, the command is incremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER" and self._enter_toggled is False: self._enter_toggled = True if self._base_command[3] == 0: self._base_command[3] = 1 else: self._base_command[3] = 0 self._event_flag = True elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: # on release, the command is decremented if event.input.name in self._input_keyboard_mapping: self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name]) self._event_flag = True # enter, toggle the last command if event.input.name == "ENTER": self._enter_toggled = False # since no error, we are fine :) return True parser = argparse.ArgumentParser(description="a1 quadruped demo") parser.add_argument("-w", "--waypoint", type=str, metavar="", required=False, help="file path to the waypoints") args, unknown = parser.parse_known_args() def main(): """ [Summary] Parse arguments and instantiate A1 runner """ physics_downtime = 1 / 400.0 if args.waypoint: waypoint_pose = [] try: print(str(args.waypoint)) file = open(str(args.waypoint)) waypoint_data = json.load(file) for waypoint in waypoint_data: waypoint_pose.append(np.array([waypoint["x"], waypoint["y"], waypoint["rad"]])) # print(str(waypoint_pose)) except FileNotFoundError: print("error file not found, ending") simulation_app.close() return runner = A1_runner(physics_dt=physics_downtime, render_dt=16 * physics_downtime, way_points=waypoint_pose) simulation_app.update() runner.setup(way_points=waypoint) else: runner = A1_runner(physics_dt=physics_downtime, render_dt=16 * physics_downtime, way_points=None) simulation_app.update() runner.setup(None) # an extra reset is needed to register runner._world.reset() runner._world.reset() runner.run() simulation_app.close() if __name__ == "__main__": main()
7,537
Python
33.577981
125
0.580735
kimsooyoung/legged_robotics/omni.isaac.quadruped/mpc_qp.py
import osqp import numpy as np import scipy as sp from scipy import sparse # Discrete time model of a quadcopter Ad = sparse.csc_matrix([ [1., 0., 0., 0., 0., 0., 0.1, 0., 0., 0., 0., 0. ], [0., 1., 0., 0., 0., 0., 0., 0.1, 0., 0., 0., 0. ], [0., 0., 1., 0., 0., 0., 0., 0., 0.1, 0., 0., 0. ], [0.0488, 0., 0., 1., 0., 0., 0.0016, 0., 0., 0.0992, 0., 0. ], [0., -0.0488, 0., 0., 1., 0., 0., -0.0016, 0., 0., 0.0992, 0. ], [0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.0992], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0. ], [0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0. ], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0. ], [0.9734, 0., 0., 0., 0., 0., 0.0488, 0., 0., 0.9846, 0., 0. ], [0., -0.9734, 0., 0., 0., 0., 0., -0.0488, 0., 0., 0.9846, 0. ], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.9846] ]) Bd = sparse.csc_matrix([ [0., -0.0726, 0., 0.0726], [-0.0726, 0., 0.0726, 0. ], [-0.0152, 0.0152, -0.0152, 0.0152], [-0., -0.0006, -0., 0.0006], [0.0006, 0., -0.0006, 0.0000], [0.0106, 0.0106, 0.0106, 0.0106], [0, -1.4512, 0., 1.4512], [-1.4512, 0., 1.4512, 0. ], [-0.3049, 0.3049, -0.3049, 0.3049], [-0., -0.0236, 0., 0.0236], [0.0236, 0., -0.0236, 0. ], [0.2107, 0.2107, 0.2107, 0.2107]]) [nx, nu] = Bd.shape # Constraints u0 = 10.5916 umin = np.array([9.6, 9.6, 9.6, 9.6]) - u0 umax = np.array([13., 13., 13., 13.]) - u0 xmin = np.array([-np.pi/6,-np.pi/6,-np.inf,-np.inf,-np.inf,-1., -np.inf,-np.inf,-np.inf,-np.inf,-np.inf,-np.inf]) xmax = np.array([ np.pi/6, np.pi/6, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf]) # Objective function Q = sparse.diags([0., 0., 10., 10., 10., 10., 0., 0., 0., 5., 5., 5.]) QN = Q R = 0.1*sparse.eye(4) # Initial and reference states x0 = np.zeros(12) xr = np.array([0.,0.,1.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) # Prediction horizon N = 10 # state 12 * 10 + control # Cast MPC problem to a QP: x = (x(0),x(1),...,x(N),u(0),...,u(N-1)) - quadratic objective P = sparse.block_diag([sparse.kron(sparse.eye(N), Q), QN, sparse.kron(sparse.eye(N), R)], format='csc') # (120, 120) # (12, 12) # (40, 40) print(sparse.kron(sparse.eye(N), Q).shape) print(QN.shape) print(sparse.kron(sparse.eye(N), R).shape) print(P.shape) # => (172, 172) # - linear objective q = np.hstack([np.kron(np.ones(N), -Q@xr), -QN@xr, np.zeros(N*nu)]) # - linear dynamics Ax = sparse.kron(sparse.eye(N+1),-sparse.eye(nx)) + sparse.kron(sparse.eye(N+1, k=-1), Ad) Bu = sparse.kron(sparse.vstack([sparse.csc_matrix((1, N)), sparse.eye(N)]), Bd) Aeq = sparse.hstack([Ax, Bu]) leq = np.hstack([-x0, np.zeros(N*nx)]) ueq = leq # - input and state constraints Aineq = sparse.eye((N+1)*nx + N*nu) lineq = np.hstack([np.kron(np.ones(N+1), xmin), np.kron(np.ones(N), umin)]) uineq = np.hstack([np.kron(np.ones(N+1), xmax), np.kron(np.ones(N), umax)]) # - OSQP constraints A = sparse.vstack([Aeq, Aineq], format='csc') l = np.hstack([leq, lineq]) u = np.hstack([ueq, uineq]) # Create an OSQP object prob = osqp.OSQP() # Setup workspace # prob.setup(P, q, A, l, u, warm_starting=True) prob.setup(P, q, A, l, u) # Simulate in closed loop nsim = 15 res = None # for i in range(nsim): # # Solve # res = prob.solve() # # Check solver status # if res.info.status != 'solved': # raise ValueError('OSQP did not solve the problem!') # # Apply first control input to the plant # ctrl = res.x[-N*nu:-(N-1)*nu] # x0 = Ad@x0 + Bd@ctrl # # Update initial state # l[:nx] = -x0 # u[:nx] = -x0 # prob.update(l=l, u=u) # print(res.__dir__()) # print(res.x.reshape(12, 12))
4,040
Python
34.13913
90
0.471782
kimsooyoung/legged_robotics/omni.isaac.quadruped/qp_basic.py
import osqp import numpy as np from scipy import sparse # Define problem data P = sparse.csc_matrix([[4, 1], [1, 2]]) q = np.array([1, 1]) A = sparse.csc_matrix([[1, 1], [1, 0], [0, 1]]) l = np.array([1, 0, 0]) u = np.array([1, 0.7, 0.7]) # Create an OSQP object prob = osqp.OSQP() # Setup workspace and change alpha parameter prob.setup(P, q, A, l, u, alpha=1.0) # Solve problem res = prob.solve() print(res.x)
416
Python
18.857142
47
0.625
kimsooyoung/legged_robotics/omni.isaac.quadruped/bezier_ex.py
import matplotlib.pyplot as plt import bezier import numpy as np # create curve passing points # (0.0, 0.0) (0.5, 1.0) (1.0, 0.0) nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 0.25, 0.5, 0.75, 1.0], [0.0, 2.0, -2.0, 2.0, 0.0], ]) nodes3 = np.asfortranarray([ [0.0, 0.25, 0.5, 0.75, 1.0], [0.0, 0.0, 1.0, 1.0, 1.0], ]) # second order bezier curve # order should be (# of points - 1) curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=4) cuirve3 = bezier.Curve(nodes3, degree=4) N = 100 t_span = np.linspace(0.0, 1.0, N) result1 = np.zeros((2, N)) result2 = np.zeros((2, N)) result3 = np.zeros((2, N)) for i, t in enumerate(t_span): result1[0, i] = curve1.evaluate(t)[0, 0] result1[1, i] = curve1.evaluate(t)[1, 0] result2[0, i] = curve2.evaluate(t)[0, 0] result2[1, i] = curve2.evaluate(t)[1, 0] result3[0, i] = cuirve3.evaluate(t)[0, 0] result3[1, i] = cuirve3.evaluate(t)[1, 0] plt.plot(result1[0, :], result1[1, :]) plt.plot(result2[0, :], result2[1, :]) plt.plot(result3[0, :], result3[1, :]) plt.show()
1,143
Python
23.869565
45
0.589676
kimsooyoung/legged_robotics/omni.isaac.quadruped/test.py
import osqp import numpy as np import scipy as sp from scipy import sparse N = 10 Q = sparse.diags([0., 0., 10., 10., 10., 10., 0., 0., 0., 5., 5., 5.]) QN = Q R = 0.1*sparse.eye(4) # (120, 120) # (12, 12) # (40, 40) P = sparse.block_diag([sparse.kron(sparse.eye(N), Q), QN, sparse.kron(sparse.eye(N), R)], format='csc') # (172, 172) print([sparse.kron(sparse.eye(N), Q), QN, sparse.kron(sparse.eye(N), R)]) modified_contacts = [True, True, True, True] F_min = 0 F_max = 250.0 mu = 0.2 linearMatrix = np.zeros([20, 12]) lowerBound = np.zeros(20) upperBound = np.zeros(20) for i in range(4): # extract F_zi linearMatrix[i, 2 + i * 3] = 1.0 # friction pyramid # 1. F_xi < uF_zi linearMatrix[4 + i * 4, i * 3] = 1.0 linearMatrix[4 + i * 4, 2 + i * 3] = -mu lowerBound[4 + i * 4] = -np.inf # 2. -F_xi > uF_zi linearMatrix[4 + i * 4 + 1, i * 3] = -1.0 linearMatrix[4 + i * 4 + 1, 2 + i * 3] = -mu lowerBound[4 + i * 4 + 1] = -np.inf # 3. F_yi < uF_zi linearMatrix[4 + i * 4 + 2, 1 + i * 3] = 1.0 linearMatrix[4 + i * 4 + 2, 2 + i * 3] = -mu lowerBound[4 + i * 4 + 2] = -np.inf # 4. -F_yi > uF_zi linearMatrix[4 + i * 4 + 3, 1 + i * 3] = -1.0 linearMatrix[4 + i * 4 + 3, 2 + i * 3] = -mu lowerBound[4 + i * 4 + 3] = -np.inf c_flag = 1.0 if modified_contacts[i] else 0.0 lowerBound[i] = c_flag * F_min upperBound[i] = c_flag * F_max print(f'linearMatrix: {linearMatrix}') print(f'lowerBound: {lowerBound}') print(f'upperBound: {upperBound}') """ linearMatrix: FL_x, FL_y, FL_z,FR_x,FR_y,FR_z,RL_x,RL_y,RL_z,RR_x,RR_y,RR_z [[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. ] [ 1. 0. -0.2 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [-1. 0. -0.2 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 1. -0.2 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. -1. -0.2 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 1. 0. -0.2 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. -1. 0. -0.2 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 1. -0.2 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. -1. -0.2 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 1. 0. -0.2 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. -1. 0. -0.2 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. 1. -0.2 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. -1. -0.2 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. -0.2] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. -1. 0. -0.2] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. -0.2] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. -1. -0.2]] lowerBound: [ 0. 0. 0. 0. -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf -inf] upperBound: [250. 250. 250. 250. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 0 <= FL_z <= 250 0 <= FR_z <= 250 0 <= RL_z <= 250 0 <= RR_z <= 250 -inf <= FL_x - 0.2*FL_z <= 0 -inf <= -FL_x - 0.2*FL_z <= 0 therefore -0.2*FL_z <= FL_x <= 0.2*FL_z -0.2*FL_z <= FL_y <= 0.2*FL_z -0.2*FR_z <= FR_x <= 0.2*FR_z -0.2*FR_z <= FR_y <= 0.2*FR_z -0.2*RL_z <= RL_x <= 0.2*RL_z -0.2*RL_z <= RL_y <= 0.2*RL_z -0.2*RR_z <= RR_x <= 0.2*RR_z -0.2*RR_z <= RR_y <= 0.2*RR_z """
3,507
Python
34.434343
82
0.400627
kimsooyoung/legged_robotics/omni.isaac.quadruped/PACKAGE-LICENSES/omni.isaac.quadruped-LICENSE.md
Copyright (c) 2020, 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.
412
Markdown
57.999992
74
0.839806
kimsooyoung/legged_robotics/omni.isaac.quadruped/config/extension.toml
display_name = "Isaac Quadruped Robot" [package] version = "1.3.0" category = "Simulation" title = "Isaac Quadruped Robot" description = "Simulation for unitree 12 dof quadrupeds" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "robot", "quadruped"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" [dependencies] "omni.isaac.core" = {} "omni.isaac.sensor" = {} "omni.isaac.core_nodes" = {} [[python.module]] name = "omni.isaac.quadruped" [[python.module]] name = "omni.isaac.quadruped.tests" public = false
531
TOML
20.279999
56
0.694915
kimsooyoung/legged_robotics/omni.isaac.quadruped/omni/isaac/quadruped/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. #
428
Python
46.666661
76
0.808411