file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
Toni-SM/skrl/docs/source/examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_skrl_train.py
import torch import torch.nn as nn # Import the skrl components to build the RL system from skrl.models.torch import Model, GaussianMixin, DeterministicMixin from skrl.memories.torch import RandomMemory from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils.omniverse_isaacgym_utils import get_env_instance from skrl.envs.torch import wrap_env from skrl.utils import set_seed # Seed for reproducibility seed = set_seed() # e.g. `set_seed(42)` for fixed seed # Define the models (stochastic and deterministic models) for the agent using helper mixin. # - Policy: takes as input the environment's observation/state and returns an action # - Value: takes the state as input and provides a value to guide the policy class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # instance VecEnvBase and setup task headless = True # set headless to False for rendering env = get_env_instance(headless=headless) from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig from reaching_franka_omniverse_isaacgym_env import ReachingFrankaTask, TASK_CFG TASK_CFG["seed"] = seed TASK_CFG["headless"] = headless TASK_CFG["task"]["env"]["numEnvs"] = 1024 TASK_CFG["task"]["env"]["controlSpace"] = "joint" # "joint" or "cartesian" sim_config = SimConfig(TASK_CFG) task = ReachingFrankaTask(name="ReachingFranka", sim_config=sim_config, env=env) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=True) # wrap the environment env = wrap_env(env, "omniverse-isaacgym") device = env.device # Instantiate a RandomMemory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # Instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ppo.html#spaces-and-models models_ppo = {} models_ppo["policy"] = Policy(env.observation_space, env.action_space, device) models_ppo["value"] = Value(env.observation_space, env.action_space, device) # Configure and instantiate the agent. # Only modify some of the default configuration, visit its documentation to see all the options # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ppo.html#configuration-and-hyperparameters cfg_ppo = PPO_DEFAULT_CONFIG.copy() cfg_ppo["rollouts"] = 16 cfg_ppo["learning_epochs"] = 8 cfg_ppo["mini_batches"] = 8 cfg_ppo["discount_factor"] = 0.99 cfg_ppo["lambda"] = 0.95 cfg_ppo["learning_rate"] = 5e-4 cfg_ppo["learning_rate_scheduler"] = KLAdaptiveRL cfg_ppo["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg_ppo["random_timesteps"] = 0 cfg_ppo["learning_starts"] = 0 cfg_ppo["grad_norm_clip"] = 1.0 cfg_ppo["ratio_clip"] = 0.2 cfg_ppo["value_clip"] = 0.2 cfg_ppo["clip_predicted_values"] = True cfg_ppo["entropy_loss_scale"] = 0.0 cfg_ppo["value_loss_scale"] = 2.0 cfg_ppo["kl_threshold"] = 0 cfg_ppo["state_preprocessor"] = RunningStandardScaler cfg_ppo["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg_ppo["value_preprocessor"] = RunningStandardScaler cfg_ppo["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints each 32 and 250 timesteps respectively cfg_ppo["experiment"]["write_interval"] = 32 cfg_ppo["experiment"]["checkpoint_interval"] = 250 agent = PPO(models=models_ppo, memory=memory, cfg=cfg_ppo, observation_space=env.observation_space, action_space=env.action_space, device=device) # Configure and instantiate the RL trainer cfg_trainer = {"timesteps": 5000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
5,539
Python
40.037037
102
0.67449
Toni-SM/skrl/docs/source/examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_env.py
import time import numpy as np import gymnasium as gym import libiiwa class ReachingIiwa(gym.Env): def __init__(self, control_space="joint"): self.control_space = control_space # joint or cartesian # spaces self.observation_space = gym.spaces.Box(low=-1000, high=1000, shape=(18,), dtype=np.float32) if self.control_space == "joint": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(7,), dtype=np.float32) elif self.control_space == "cartesian": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(3,), dtype=np.float32) else: raise ValueError("Invalid control space:", self.control_space) # init iiwa print("Connecting to robot...") self.robot = libiiwa.LibIiwa() self.robot.set_control_interface(libiiwa.ControlInterface.CONTROL_INTERFACE_SERVO) self.robot.set_desired_joint_velocity_rel(0.5) self.robot.set_desired_joint_acceleration_rel(0.5) self.robot.set_desired_joint_jerk_rel(0.5) self.robot.set_desired_cartesian_velocity(10) self.robot.set_desired_cartesian_acceleration(10) self.robot.set_desired_cartesian_jerk(10) print("Robot connected") self.motion = None self.motion_thread = None self.dt = 1 / 120.0 self.action_scale = 2.5 self.dof_vel_scale = 0.1 self.max_episode_length = 100 self.robot_dof_speed_scales = 1 self.target_pos = np.array([0.65, 0.2, 0.2]) self.robot_default_dof_pos = np.radians([0, 0, 0, -90, 0, 90, 0]) self.robot_dof_lower_limits = np.array([-2.9671, -2.0944, -2.9671, -2.0944, -2.9671, -2.0944, -3.0543]) self.robot_dof_upper_limits = np.array([ 2.9671, 2.0944, 2.9671, 2.0944, 2.9671, 2.0944, 3.0543]) self.progress_buf = 1 self.obs_buf = np.zeros((18,), dtype=np.float32) def _get_observation_reward_done(self): # get robot state robot_state = self.robot.get_state(refresh=True) # observation robot_dof_pos = robot_state["joint_position"] robot_dof_vel = robot_state["joint_velocity"] end_effector_pos = robot_state["cartesian_position"] dof_pos_scaled = 2.0 * (robot_dof_pos - self.robot_dof_lower_limits) / (self.robot_dof_upper_limits - self.robot_dof_lower_limits) - 1.0 dof_vel_scaled = robot_dof_vel * self.dof_vel_scale self.obs_buf[0] = self.progress_buf / float(self.max_episode_length) self.obs_buf[1:8] = dof_pos_scaled self.obs_buf[8:15] = dof_vel_scaled self.obs_buf[15:18] = self.target_pos # reward distance = np.linalg.norm(end_effector_pos - self.target_pos) reward = -distance # done done = self.progress_buf >= self.max_episode_length - 1 done = done or distance <= 0.075 print("Distance:", distance) if done: print("Target or Maximum episode length reached") time.sleep(1) return self.obs_buf, reward, done def reset(self): print("Reseting...") # go to 1) safe position, 2) random position self.robot.command_joint_position(self.robot_default_dof_pos) time.sleep(3) dof_pos = self.robot_default_dof_pos + 0.25 * (np.random.rand(7) - 0.5) self.robot.command_joint_position(dof_pos) time.sleep(1) # get target position from prompt while True: try: print("Enter target position (X, Y, Z) in meters") raw = input("or press [Enter] key for a random target position: ") if raw: self.target_pos = np.array([float(p) for p in raw.replace(' ', '').split(',')]) else: noise = (2 * np.random.rand(3) - 1) * np.array([0.1, 0.2, 0.2]) self.target_pos = np.array([0.6, 0.0, 0.4]) + noise print("Target position:", self.target_pos) break except ValueError: print("Invalid input. Try something like: 0.65, 0.0, 0.4") input("Press [Enter] to continue") self.progress_buf = 0 observation, reward, done = self._get_observation_reward_done() return observation, {} def step(self, action): self.progress_buf += 1 # get robot state robot_state = self.robot.get_state(refresh=True) # control space # joint if self.control_space == "joint": dof_pos = robot_state["joint_position"] + (self.robot_dof_speed_scales * self.dt * action * self.action_scale) self.robot.command_joint_position(dof_pos) # cartesian elif self.control_space == "cartesian": end_effector_pos = robot_state["cartesian_position"] + action / 100.0 self.robot.command_cartesian_pose(end_effector_pos) # the use of time.sleep is for simplicity. It does not guarantee control at a specific frequency time.sleep(1 / 30.0) observation, reward, terminated = self._get_observation_reward_done() return observation, reward, terminated, False, {} def render(self, *args, **kwargs): pass def close(self): pass
5,314
Python
35.404109
144
0.589198
Toni-SM/skrl/docs/source/examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros2_env.py
import time import numpy as np import gymnasium as gym import rclpy from rclpy.node import Node from rclpy.qos import QoSPresetProfiles import sensor_msgs.msg import geometry_msgs.msg import libiiwa_msgs.srv class ReachingIiwa(gym.Env): def __init__(self, control_space="joint"): self.control_space = control_space # joint or cartesian # spaces self.observation_space = gym.spaces.Box(low=-1000, high=1000, shape=(18,), dtype=np.float32) if self.control_space == "joint": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(7,), dtype=np.float32) elif self.control_space == "cartesian": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(3,), dtype=np.float32) else: raise ValueError("Invalid control space:", self.control_space) # initialize the ROS node rclpy.init() self.node = Node(self.__class__.__name__) import threading threading.Thread(target=self._spin).start() # create publishers self.pub_command_joint = self.node.create_publisher(sensor_msgs.msg.JointState, '/iiwa/command/joint', QoSPresetProfiles.SYSTEM_DEFAULT.value) self.pub_command_cartesian = self.node.create_publisher(geometry_msgs.msg.Pose, '/iiwa/command/cartesian', QoSPresetProfiles.SYSTEM_DEFAULT.value) # keep compatibility with libiiwa Python API self.robot_state = {"joint_position": np.zeros((7,)), "joint_velocity": np.zeros((7,)), "cartesian_position": np.zeros((3,))} # create subscribers self.node.create_subscription(msg_type=sensor_msgs.msg.JointState, topic='/iiwa/state/joint_states', callback=self._callback_joint_states, qos_profile=QoSPresetProfiles.SYSTEM_DEFAULT.value) self.node.create_subscription(msg_type=geometry_msgs.msg.Pose, topic='/iiwa/state/end_effector_pose', callback=self._callback_end_effector_pose, qos_profile=QoSPresetProfiles.SYSTEM_DEFAULT.value) # service clients client_control_interface = self.node.create_client(libiiwa_msgs.srv.SetString, '/iiwa/set_control_interface') client_control_interface.wait_for_service() request = libiiwa_msgs.srv.SetString.Request() request.data = "SERVO" # or "servo" client_control_interface.call(request) client_joint_velocity_rel = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_joint_velocity_rel') client_joint_acceleration_rel = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_joint_acceleration_rel') client_joint_jerk_rel = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_joint_jerk_rel') client_cartesian_velocity = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_cartesian_velocity') client_cartesian_acceleration = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_cartesian_acceleration') client_cartesian_jerk = self.node.create_client(libiiwa_msgs.srv.SetNumber, '/iiwa/set_desired_cartesian_jerk') client_joint_velocity_rel.wait_for_service() client_joint_acceleration_rel.wait_for_service() client_joint_jerk_rel.wait_for_service() client_cartesian_velocity.wait_for_service() client_cartesian_acceleration.wait_for_service() client_cartesian_jerk.wait_for_service() request = libiiwa_msgs.srv.SetNumber.Request() request.data = 0.5 client_joint_velocity_rel.call(request) client_joint_acceleration_rel.call(request) client_joint_jerk_rel.call(request) request.data = 10.0 client_cartesian_velocity.call(request) client_cartesian_acceleration.call(request) client_cartesian_jerk.call(request) print("Robot connected") self.motion = None self.motion_thread = None self.dt = 1 / 120.0 self.action_scale = 2.5 self.dof_vel_scale = 0.1 self.max_episode_length = 100 self.robot_dof_speed_scales = 1 self.target_pos = np.array([0.65, 0.2, 0.2]) self.robot_default_dof_pos = np.radians([0, 0, 0, -90, 0, 90, 0]) self.robot_dof_lower_limits = np.array([-2.9671, -2.0944, -2.9671, -2.0944, -2.9671, -2.0944, -3.0543]) self.robot_dof_upper_limits = np.array([ 2.9671, 2.0944, 2.9671, 2.0944, 2.9671, 2.0944, 3.0543]) self.progress_buf = 1 self.obs_buf = np.zeros((18,), dtype=np.float32) def _spin(self): rclpy.spin(self.node) def _callback_joint_states(self, msg): self.robot_state["joint_position"] = np.array(msg.position) self.robot_state["joint_velocity"] = np.array(msg.velocity) def _callback_end_effector_pose(self, msg): positon = msg.position self.robot_state["cartesian_position"] = np.array([positon.x, positon.y, positon.z]) def _get_observation_reward_done(self): # observation robot_dof_pos = self.robot_state["joint_position"] robot_dof_vel = self.robot_state["joint_velocity"] end_effector_pos = self.robot_state["cartesian_position"] dof_pos_scaled = 2.0 * (robot_dof_pos - self.robot_dof_lower_limits) / (self.robot_dof_upper_limits - self.robot_dof_lower_limits) - 1.0 dof_vel_scaled = robot_dof_vel * self.dof_vel_scale self.obs_buf[0] = self.progress_buf / float(self.max_episode_length) self.obs_buf[1:8] = dof_pos_scaled self.obs_buf[8:15] = dof_vel_scaled self.obs_buf[15:18] = self.target_pos # reward distance = np.linalg.norm(end_effector_pos - self.target_pos) reward = -distance # done done = self.progress_buf >= self.max_episode_length - 1 done = done or distance <= 0.075 print("Distance:", distance) if done: print("Target or Maximum episode length reached") time.sleep(1) return self.obs_buf, reward, done def reset(self): print("Reseting...") # go to 1) safe position, 2) random position msg = sensor_msgs.msg.JointState() msg.position = self.robot_default_dof_pos.tolist() self.pub_command_joint.publish(msg) time.sleep(3) msg.position = (self.robot_default_dof_pos + 0.25 * (np.random.rand(7) - 0.5)).tolist() self.pub_command_joint.publish(msg) time.sleep(1) # get target position from prompt while True: try: print("Enter target position (X, Y, Z) in meters") raw = input("or press [Enter] key for a random target position: ") if raw: self.target_pos = np.array([float(p) for p in raw.replace(' ', '').split(',')]) else: noise = (2 * np.random.rand(3) - 1) * np.array([0.1, 0.2, 0.2]) self.target_pos = np.array([0.6, 0.0, 0.4]) + noise print("Target position:", self.target_pos) break except ValueError: print("Invalid input. Try something like: 0.65, 0.0, 0.4") input("Press [Enter] to continue") self.progress_buf = 0 observation, reward, done = self._get_observation_reward_done() return observation, {} def step(self, action): self.progress_buf += 1 # control space # joint if self.control_space == "joint": joint_positions = self.robot_state["joint_position"] + (self.robot_dof_speed_scales * self.dt * action * self.action_scale) msg = sensor_msgs.msg.JointState() msg.position = joint_positions.tolist() self.pub_command_joint.publish(msg) # cartesian elif self.control_space == "cartesian": end_effector_pos = self.robot_state["cartesian_position"] + action / 100.0 msg = geometry_msgs.msg.Pose() msg.position.x = end_effector_pos[0] msg.position.y = end_effector_pos[1] msg.position.z = end_effector_pos[2] msg.orientation.x = np.nan msg.orientation.y = np.nan msg.orientation.z = np.nan msg.orientation.w = np.nan self.pub_command_cartesian.publish(msg) # the use of time.sleep is for simplicity. It does not guarantee control at a specific frequency time.sleep(1 / 30.0) observation, reward, terminated = self._get_observation_reward_done() return observation, reward, terminated, False, {} def render(self, *args, **kwargs): pass def close(self): # shutdown the node self.node.destroy_node() rclpy.shutdown()
9,047
Python
40.315068
154
0.607605
Toni-SM/skrl/docs/source/examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros_env.py
import time import numpy as np import gymnasium as gym import rospy import sensor_msgs.msg import geometry_msgs.msg import libiiwa_msgs.srv class ReachingIiwa(gym.Env): def __init__(self, control_space="joint"): self.control_space = control_space # joint or cartesian # spaces self.observation_space = gym.spaces.Box(low=-1000, high=1000, shape=(18,), dtype=np.float32) if self.control_space == "joint": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(7,), dtype=np.float32) elif self.control_space == "cartesian": self.action_space = gym.spaces.Box(low=-1, high=1, shape=(3,), dtype=np.float32) else: raise ValueError("Invalid control space:", self.control_space) # create publishers self.pub_command_joint = rospy.Publisher('/iiwa/command/joint', sensor_msgs.msg.JointState, queue_size=1) self.pub_command_cartesian = rospy.Publisher('/iiwa/command/cartesian', geometry_msgs.msg.Pose, queue_size=1) # keep compatibility with libiiwa Python API self.robot_state = {"joint_position": np.zeros((7,)), "joint_velocity": np.zeros((7,)), "cartesian_position": np.zeros((3,))} # create subscribers rospy.Subscriber('/iiwa/state/joint_states', sensor_msgs.msg.JointState, self._callback_joint_states) rospy.Subscriber('/iiwa/state/end_effector_pose', geometry_msgs.msg.Pose, self._callback_end_effector_pose) # create service clients rospy.wait_for_service('/iiwa/set_control_interface') proxy = rospy.ServiceProxy('/iiwa/set_control_interface', libiiwa_msgs.srv.SetString) proxy("SERVO") # or "servo" rospy.wait_for_service('/iiwa/set_desired_joint_velocity_rel') rospy.wait_for_service('/iiwa/set_desired_joint_acceleration_rel') rospy.wait_for_service('/iiwa/set_desired_joint_jerk_rel') proxy = rospy.ServiceProxy('/iiwa/set_desired_joint_velocity_rel', libiiwa_msgs.srv.SetNumber) proxy(0.5) proxy = rospy.ServiceProxy('/iiwa/set_desired_joint_acceleration_rel', libiiwa_msgs.srv.SetNumber) proxy(0.5) proxy = rospy.ServiceProxy('/iiwa/set_desired_joint_jerk_rel', libiiwa_msgs.srv.SetNumber) proxy(0.5) rospy.wait_for_service('/iiwa/set_desired_cartesian_velocity') rospy.wait_for_service('/iiwa/set_desired_cartesian_acceleration') rospy.wait_for_service('/iiwa/set_desired_cartesian_jerk') proxy = rospy.ServiceProxy('/iiwa/set_desired_cartesian_velocity', libiiwa_msgs.srv.SetNumber) proxy(10.0) proxy = rospy.ServiceProxy('/iiwa/set_desired_cartesian_acceleration', libiiwa_msgs.srv.SetNumber) proxy(10.0) proxy = rospy.ServiceProxy('/iiwa/set_desired_cartesian_jerk', libiiwa_msgs.srv.SetNumber) proxy(10.0) # initialize the ROS node rospy.init_node(self.__class__.__name__) print("Robot connected") self.motion = None self.motion_thread = None self.dt = 1 / 120.0 self.action_scale = 2.5 self.dof_vel_scale = 0.1 self.max_episode_length = 100 self.robot_dof_speed_scales = 1 self.target_pos = np.array([0.65, 0.2, 0.2]) self.robot_default_dof_pos = np.radians([0, 0, 0, -90, 0, 90, 0]) self.robot_dof_lower_limits = np.array([-2.9671, -2.0944, -2.9671, -2.0944, -2.9671, -2.0944, -3.0543]) self.robot_dof_upper_limits = np.array([ 2.9671, 2.0944, 2.9671, 2.0944, 2.9671, 2.0944, 3.0543]) self.progress_buf = 1 self.obs_buf = np.zeros((18,), dtype=np.float32) def _callback_joint_states(self, msg): self.robot_state["joint_position"] = np.array(msg.position) self.robot_state["joint_velocity"] = np.array(msg.velocity) def _callback_end_effector_pose(self, msg): positon = msg.position self.robot_state["cartesian_position"] = np.array([positon.x, positon.y, positon.z]) def _get_observation_reward_done(self): # observation robot_dof_pos = self.robot_state["joint_position"] robot_dof_vel = self.robot_state["joint_velocity"] end_effector_pos = self.robot_state["cartesian_position"] dof_pos_scaled = 2.0 * (robot_dof_pos - self.robot_dof_lower_limits) / (self.robot_dof_upper_limits - self.robot_dof_lower_limits) - 1.0 dof_vel_scaled = robot_dof_vel * self.dof_vel_scale self.obs_buf[0] = self.progress_buf / float(self.max_episode_length) self.obs_buf[1:8] = dof_pos_scaled self.obs_buf[8:15] = dof_vel_scaled self.obs_buf[15:18] = self.target_pos # reward distance = np.linalg.norm(end_effector_pos - self.target_pos) reward = -distance # done done = self.progress_buf >= self.max_episode_length - 1 done = done or distance <= 0.075 print("Distance:", distance) if done: print("Target or Maximum episode length reached") time.sleep(1) return self.obs_buf, reward, done def reset(self): print("Reseting...") # go to 1) safe position, 2) random position msg = sensor_msgs.msg.JointState() msg.position = self.robot_default_dof_pos.tolist() self.pub_command_joint.publish(msg) time.sleep(3) msg.position = (self.robot_default_dof_pos + 0.25 * (np.random.rand(7) - 0.5)).tolist() self.pub_command_joint.publish(msg) time.sleep(1) # get target position from prompt while True: try: print("Enter target position (X, Y, Z) in meters") raw = input("or press [Enter] key for a random target position: ") if raw: self.target_pos = np.array([float(p) for p in raw.replace(' ', '').split(',')]) else: noise = (2 * np.random.rand(3) - 1) * np.array([0.1, 0.2, 0.2]) self.target_pos = np.array([0.6, 0.0, 0.4]) + noise print("Target position:", self.target_pos) break except ValueError: print("Invalid input. Try something like: 0.65, 0.0, 0.4") input("Press [Enter] to continue") self.progress_buf = 0 observation, reward, done = self._get_observation_reward_done() return observation, {} def step(self, action): self.progress_buf += 1 # control space # joint if self.control_space == "joint": joint_positions = self.robot_state["joint_position"] + (self.robot_dof_speed_scales * self.dt * action * self.action_scale) msg = sensor_msgs.msg.JointState() msg.position = joint_positions.tolist() self.pub_command_joint.publish(msg) # cartesian elif self.control_space == "cartesian": end_effector_pos = self.robot_state["cartesian_position"] + action / 100.0 msg = geometry_msgs.msg.Pose() msg.position.x = end_effector_pos[0] msg.position.y = end_effector_pos[1] msg.position.z = end_effector_pos[2] msg.orientation.x = np.nan msg.orientation.y = np.nan msg.orientation.z = np.nan msg.orientation.w = np.nan self.pub_command_cartesian.publish(msg) # the use of time.sleep is for simplicity. It does not guarantee control at a specific frequency time.sleep(1 / 30.0) observation, reward, terminated = self._get_observation_reward_done() return observation, reward, terminated, False, {} def render(self, *args, **kwargs): pass def close(self): pass
7,831
Python
39.371134
144
0.605542
Toni-SM/skrl/docs/source/snippets/utils_postprocessing.py
# [start-memory_file_iterator-torch] from skrl.utils import postprocessing # assuming there is a directory called "memories" with Torch files in it memory_iterator = postprocessing.MemoryFileIterator("memories/*.pt") for filename, data in memory_iterator: filename # str: basename of the current file data # dict: keys are the names of the memory tensors in the file. # Tensor shapes are (memory size, number of envs, specific content size) # example of simple usage: # print the filenames of all memories and their tensor shapes print("\nfilename:", filename) print(" |-- states:", data['states'].shape) print(" |-- actions:", data['actions'].shape) print(" |-- rewards:", data['rewards'].shape) print(" |-- next_states:", data['next_states'].shape) print(" |-- dones:", data['dones'].shape) # [end-memory_file_iterator-torch] # [start-memory_file_iterator-numpy] from skrl.utils import postprocessing # assuming there is a directory called "memories" with NumPy files in it memory_iterator = postprocessing.MemoryFileIterator("memories/*.npz") for filename, data in memory_iterator: filename # str: basename of the current file data # dict: keys are the names of the memory arrays in the file. # Array shapes are (memory size, number of envs, specific content size) # example of simple usage: # print the filenames of all memories and their array shapes print("\nfilename:", filename) print(" |-- states:", data['states'].shape) print(" |-- actions:", data['actions'].shape) print(" |-- rewards:", data['rewards'].shape) print(" |-- next_states:", data['next_states'].shape) print(" |-- dones:", data['dones'].shape) # [end-memory_file_iterator-numpy] # [start-memory_file_iterator-csv] from skrl.utils import postprocessing # assuming there is a directory called "memories" with CSV files in it memory_iterator = postprocessing.MemoryFileIterator("memories/*.csv") for filename, data in memory_iterator: filename # str: basename of the current file data # dict: keys are the names of the memory list of lists extracted from the file. # List lengths are (memory size * number of envs) and # sublist lengths are (specific content size) # example of simple usage: # print the filenames of all memories and their list lengths print("\nfilename:", filename) print(" |-- states:", len(data['states'])) print(" |-- actions:", len(data['actions'])) print(" |-- rewards:", len(data['rewards'])) print(" |-- next_states:", len(data['next_states'])) print(" |-- dones:", len(data['dones'])) # [end-memory_file_iterator-csv] # [start-tensorboard_file_iterator-list] from skrl.utils import postprocessing # assuming there is a directory called "runs" with experiments and Tensorboard files in it tensorboard_iterator = postprocessing.TensorboardFileIterator("runs/*/events.out.tfevents.*", \ tags=["Reward / Total reward (mean)"]) for dirname, data in tensorboard_iterator: dirname # str: path of the directory (experiment name) containing the Tensorboard file data # dict: keys are the tags, values are lists of [step, value] pairs # example of simple usage: # print the directory name and the value length for the "Reward / Total reward (mean)" tag print("\ndirname:", dirname) for tag, values in data.items(): print(" |-- tag:", tag) print(" | |-- value length:", len(values)) # [end-tensorboard_file_iterator-list]
3,582
Python
40.66279
95
0.676159
Toni-SM/skrl/docs/source/snippets/shared_model.py
# [start-mlp-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin, DeterministicMixin # define the shared model class SharedModel(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction, role="policy") DeterministicMixin.__init__(self, clip_actions, role="value") # shared layers/network self.net = nn.Sequential(nn.Linear(self.num_observations, 32), nn.ELU(), nn.Linear(32, 32), nn.ELU()) # separated layers ("policy") self.mean_layer = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) # separated layer ("value") self.value_layer = nn.Linear(32, 1) # override the .act(...) method to disambiguate its call def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) # forward the input to compute model output according to the specified role def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # instantiate the shared model and pass the same instance to the other key models = {} models["policy"] = SharedModel(env.observation_space, env.action_space, env.device) models["value"] = models["policy"] # [end-mlp-torch]
1,974
Python
39.306122
116
0.624113
Toni-SM/skrl/docs/source/snippets/noises.py
# [start-base-class-torch] from typing import Union, Tuple import torch from skrl.resources.noises.torch import Noise class CustomNoise(Noise): def __init__(self, device: Union[str, torch.device] = "cuda:0") -> None: """ :param device: Device on which a torch tensor is or will be allocated (default: "cuda:0") :type device: str or torch.device, optional """ super().__init__(device) def sample(self, size: Union[Tuple[int], torch.Size]) -> torch.Tensor: """Sample noise :param size: Shape of the sampled tensor :type size: tuple or list of integers, or torch.Size :return: Sampled noise :rtype: torch.Tensor """ # ================================ # - sample noise # ================================ # [end-base-class-torch] # [start-base-class-jax] from typing import Optional, Union, Tuple import numpy as np import jaxlib import jax.numpy as jnp from skrl.resources.noises.torch import Noise class CustomNoise(Noise): def __init__(self, device: Optional[Union[str, jaxlib.xla_extension.Device]] = None) -> None: """Custom noise :param device: Device on which a jax array is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or jaxlib.xla_extension.Device, optional """ super().__init__(device) def sample(self, size: Tuple[int]) -> Union[np.ndarray, jnp.ndarray]: """Sample noise :param size: Shape of the sampled tensor :type size: tuple or list of integers :return: Sampled noise :rtype: np.ndarray or jnp.ndarray """ # ================================ # - sample noise # ================================ # [end-base-class-jax] # ============================================================================= # [torch-start-gaussian] from skrl.resources.noises.torch import GaussianNoise cfg = DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(mean=0, std=0.2, device="cuda:0") # [torch-end-gaussian] # [jax-start-gaussian] from skrl.resources.noises.jax import GaussianNoise cfg = DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(mean=0, std=0.2) # [jax-end-gaussian] # ============================================================================= # [torch-start-ornstein-uhlenbeck] from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise cfg = DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.2, base_scale=1.0, device="cuda:0") # [torch-end-ornstein-uhlenbeck] # [jax-start-ornstein-uhlenbeck] from skrl.resources.noises.jax import OrnsteinUhlenbeckNoise cfg = DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.2, base_scale=1.0) # [jax-end-ornstein-uhlenbeck]
2,976
Python
28.77
108
0.589718
Toni-SM/skrl/docs/source/snippets/gaussian_model.py
# [start-definition-torch] class GaussianModel(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) # [end-definition-torch] # [start-definition-jax] class GaussianModel(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) # [end-definition-jax] # ============================================================================= # [start-mlp-sequential-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin # define the model class MLP(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = MLP(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # [end-mlp-sequential-torch] # [start-mlp-functional-torch] import torch import torch.nn as nn import torch.nn.functional as F from skrl.models.torch import Model, GaussianMixin # define the model class MLP(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.fc1 = nn.Linear(self.num_observations, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): x = self.fc1(inputs["states"]) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) return torch.tanh(x), self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = MLP(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # [end-mlp-functional-torch] # [start-mlp-setup-jax] import jax.numpy as jnp import flax.linen as nn from skrl.models.jax import Model, GaussianMixin # define the model class MLP(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def setup(self): self.fc1 = nn.Dense(64) self.fc2 = nn.Dense(32) self.fc3 = nn.Dense(self.num_actions) self.log_std_parameter = self.param("log_std_parameter", lambda _: jnp.zeros(self.num_actions)) def __call__(self, inputs, role): x = self.fc1(inputs["states"]) x = nn.relu(x) x = self.fc2(x) x = nn.relu(x) x = self.fc3(x) return nn.tanh(x), self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = MLP(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # initialize model's state dict policy.init_state_dict("policy") # [end-mlp-setup-jax] # [start-mlp-compact-jax] import jax.numpy as jnp import flax.linen as nn from skrl.models.jax import Model, GaussianMixin # define the model class MLP(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.Dense(64)(inputs["states"]) x = nn.relu(x) x = nn.Dense(32)(x) x = nn.relu(x) x = nn.Dense(self.num_actions)(x) log_std_parameter = self.param("log_std_parameter", lambda _: jnp.zeros(self.num_actions)) return nn.tanh(x), log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = MLP(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # initialize model's state dict policy.init_state_dict("policy") # [end-mlp-compact-jax] # ============================================================================= # [start-cnn-sequential-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin # define the model class CNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Conv2d(3, 32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=1), nn.ReLU(), nn.Flatten(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 16), nn.Tanh(), nn.Linear(16, 64), nn.Tanh(), nn.Linear(64, 32), nn.Tanh(), nn.Linear(32, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # permute (samples, width * height * channels) -> (samples, channels, width, height) return self.net(inputs["states"].view(-1, *self.observation_space.shape).permute(0, 3, 1, 2)), self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = CNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # [end-cnn-sequential-torch] # [start-cnn-functional-torch] import torch import torch.nn as nn import torch.nn.functional as F from skrl.models.torch import Model, GaussianMixin # define the model class CNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.conv1 = nn.Conv2d(3, 32, kernel_size=8, stride=4) self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2) self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1) self.fc1 = nn.Linear(1024, 512) self.fc2 = nn.Linear(512, 16) self.fc3 = nn.Linear(16, 64) self.fc4 = nn.Linear(64, 32) self.fc5 = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # permute (samples, width * height * channels) -> (samples, channels, width, height) x = inputs["states"].view(-1, *self.observation_space.shape).permute(0, 3, 1, 2) x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = self.conv3(x) x = F.relu(x) x = torch.flatten(x, start_dim=1) x = self.fc1(x) x = F.relu(x) x = self.fc2(x) x = torch.tanh(x) x = self.fc3(x) x = torch.tanh(x) x = self.fc4(x) x = torch.tanh(x) x = self.fc5(x) return x, self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = CNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # [end-cnn-functional-torch] # [start-cnn-setup-jax] import jax.numpy as jnp import flax.linen as nn from skrl.models.jax import Model, GaussianMixin # define the model class CNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def setup(self): self.conv1 = nn.Conv(32, kernel_size=(8, 8), strides=(4, 4), padding="VALID") self.conv2 = nn.Conv(64, kernel_size=(4, 4), strides=(2, 2), padding="VALID") self.conv3 = nn.Conv(64, kernel_size=(3, 3), strides=(1, 1), padding="VALID") self.fc1 = nn.Dense(512) self.fc2 = nn.Dense(16) self.fc3 = nn.Dense(64) self.fc4 = nn.Dense(32) self.fc5 = nn.Dense(self.num_actions) self.log_std_parameter = self.param("log_std_parameter", lambda _: jnp.zeros(self.num_actions)) def __call__(self, inputs, role): x = inputs["states"].reshape((-1, *self.observation_space.shape)) x = self.conv1(x) x = nn.relu(x) x = self.conv2(x) x = nn.relu(x) x = self.conv3(x) x = nn.relu(x) x = x.reshape((x.shape[0], -1)) x = self.fc1(x) x = nn.relu(x) x = self.fc2(x) x = nn.tanh(x) x = self.fc3(x) x = nn.tanh(x) x = self.fc4(x) x = nn.tanh(x) x = self.fc5(x) return nn.tanh(x), self.log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = CNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # initialize model's state dict policy.init_state_dict("policy") # [end-cnn-setup-jax] # [start-cnn-compact-jax] import jax.numpy as jnp import flax.linen as nn from skrl.models.jax import Model, GaussianMixin # define the model class CNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = inputs["states"].reshape((-1, *self.observation_space.shape)) x = nn.Conv(32, kernel_size=(8, 8), strides=(4, 4), padding="VALID")(x) x = nn.relu(x) x = nn.Conv(64, kernel_size=(4, 4), strides=(2, 2), padding="VALID")(x) x = nn.relu(x) x = nn.Conv(64, kernel_size=(3, 3), strides=(1, 1), padding="VALID")(x) x = nn.relu(x) x = x.reshape((x.shape[0], -1)) x = nn.Dense(512)(x) x = nn.relu(x) x = nn.Dense(16)(x) x = nn.tanh(x) x = nn.Dense(64)(x) x = nn.tanh(x) x = nn.Dense(32)(x) x = nn.tanh(x) x = nn.Dense(self.num_actions)(x) log_std_parameter = self.param("log_std_parameter", lambda _: jnp.zeros(self.num_actions)) return nn.tanh(x), log_std_parameter, {} # instantiate the model (assumes there is a wrapped environment: env) policy = CNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum") # initialize model's state dict policy.init_state_dict("policy") # [end-cnn-compact-jax] # ============================================================================= # [start-rnn-sequential-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin # define the model class RNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), self.log_std_parameter, {"rnn": [hidden_states]} # instantiate the model (assumes there is a wrapped environment: env) policy = RNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-rnn-sequential-torch] # [start-rnn-functional-torch] import torch import torch.nn as nn import torch.nn.functional as F from skrl.models.torch import Model, GaussianMixin # define the model class RNN(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.fc1 = nn.Linear(self.hidden_size, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = self.fc1(rnn_output) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) return torch.tanh(x), self.log_std_parameter, {"rnn": [hidden_states]} # instantiate the model (assumes there is a wrapped environment: env) policy = RNN(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-rnn-functional-torch] # ============================================================================= # [start-gru-sequential-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin # define the model class GRU(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), self.log_std_parameter, {"rnn": [hidden_states]} # instantiate the model (assumes there is a wrapped environment: env) policy = GRU(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-gru-sequential-torch] # [start-gru-functional-torch] import torch import torch.nn as nn import torch.nn.functional as F from skrl.models.torch import Model, GaussianMixin # define the model class GRU(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.fc1 = nn.Linear(self.hidden_size, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = self.fc1(rnn_output) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) return torch.tanh(x), self.log_std_parameter, {"rnn": [hidden_states]} # instantiate the model (assumes there is a wrapped environment: env) policy = GRU(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-gru-functional-torch] # ============================================================================= # [start-lstm-sequential-torch] import torch import torch.nn as nn from skrl.models.torch import Model, GaussianMixin # define the model class LSTM(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), self.log_std_parameter, {"rnn": [rnn_states[0], rnn_states[1]]} # instantiate the model (assumes there is a wrapped environment: env) policy = LSTM(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-lstm-sequential-torch] # [start-lstm-functional-torch] import torch import torch.nn as nn import torch.nn.functional as F from skrl.models.torch import Model, GaussianMixin # define the model class LSTM(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=10): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.fc1 = nn.Linear(self.hidden_size, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs during rollout return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = self.fc1(rnn_output) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) return torch.tanh(x), self.log_std_parameter, {"rnn": [rnn_states[0], rnn_states[1]]} # instantiate the model (assumes there is a wrapped environment: env) policy = LSTM(observation_space=env.observation_space, action_space=env.action_space, device=env.device, clip_actions=True, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=env.num_envs, num_layers=1, hidden_size=64, sequence_length=10) # [end-lstm-functional-torch]
41,575
Python
41.038423
146
0.566133
Toni-SM/skrl/docs/source/snippets/model_mixin.py
# [start-model-torch] from typing import Optional, Union, Mapping, Sequence, Tuple, Any import gym, gymnasium import torch from skrl.models.torch import Model class CustomModel(Model): def __init__(self, observation_space: Union[int, Sequence[int], gym.Space, gymnasium.Space], action_space: Union[int, Sequence[int], gym.Space, gymnasium.Space], device: Optional[Union[str, torch.device]] = None) -> None: """Custom model :param observation_space: Observation/state space or shape. The ``num_observations`` property will contain the size of that space :type observation_space: int, sequence of int, gym.Space, gymnasium.Space :param action_space: Action space or shape. The ``num_actions`` property will contain the size of that space :type action_space: int, sequence of int, gym.Space, gymnasium.Space :param device: Device on which a torch tensor is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or torch.device, optional """ super().__init__(observation_space, action_space, device) # ===================================== # - define custom attributes and others # ===================================== flax.linen.Module.__post_init__(self) def act(self, inputs: Mapping[str, Union[torch.Tensor, Any]], role: str = "") -> Tuple[torch.Tensor, Union[torch.Tensor, None], Mapping[str, Union[torch.Tensor, Any]]]: """Act according to the specified behavior :param inputs: Model inputs. The most common keys are: - ``"states"``: state of the environment used to make the decision - ``"taken_actions"``: actions taken by the policy for the given states :type inputs: dict where the values are typically torch.Tensor :param role: Role play by the model (default: ``""``) :type role: str, optional :return: Model output. The first component is the action to be taken by the agent. The second component is the log of the probability density function for stochastic models or None for deterministic models. The third component is a dictionary containing extra output values :rtype: tuple of torch.Tensor, torch.Tensor or None, and dictionary """ # ============================== # - act in response to the state # ============================== # [end-model-torch] # [start-model-jax] from typing import Optional, Union, Mapping, Tuple, Any import gym, gymnasium import flax import jaxlib import jax.numpy as jnp from skrl.models.jax import Model class CustomModel(Model): def __init__(self, observation_space: Union[int, Sequence[int], gym.Space, gymnasium.Space], action_space: Union[int, Sequence[int], gym.Space, gymnasium.Space], device: Optional[Union[str, jaxlib.xla_extension.Device]] = None, parent: Optional[Any] = None, name: Optional[str] = None) -> None: """Custom model :param observation_space: Observation/state space or shape. The ``num_observations`` property will contain the size of that space :type observation_space: int, sequence of int, gym.Space, gymnasium.Space :param action_space: Action space or shape. The ``num_actions`` property will contain the size of that space :type action_space: int, sequence of int, gym.Space, gymnasium.Space :param device: Device on which a jax array is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or jaxlib.xla_extension.Device, optional :param parent: The parent Module of this Module (default: ``None``). It is a Flax reserved attribute :type parent: str, optional :param name: The name of this Module (default: ``None``). It is a Flax reserved attribute :type name: str, optional """ Model.__init__(self, observation_space, action_space, device, parent, name) # ===================================== # - define custom attributes and others # ===================================== flax.linen.Module.__post_init__(self) def act(self, inputs: Mapping[str, Union[jnp.ndarray, Any]], role: str = "", params: Optional[jnp.ndarray] = None) -> Tuple[jnp.ndarray, Union[jnp.ndarray, None], Mapping[str, Union[jnp.ndarray, Any]]]: """Act according to the specified behavior :param inputs: Model inputs. The most common keys are: - ``"states"``: state of the environment used to make the decision - ``"taken_actions"``: actions taken by the policy for the given states :type inputs: dict where the values are typically jnp.ndarray :param role: Role play by the model (default: ``""``) :type role: str, optional :param params: Parameters used to compute the output (default: ``None``). If ``None``, internal parameters will be used :type params: jnp.array :return: Model output. The first component is the action to be taken by the agent. The second component is the log of the probability density function. The third component is a dictionary containing the mean actions ``"mean_actions"`` and extra output values :rtype: tuple of jnp.ndarray, jnp.ndarray or None, and dictionary """ # ============================== # - act in response to the state # ============================== # [end-model-jax] # ============================================================================= # [start-mixin-torch] from typing import Union, Mapping, Tuple, Any import torch class CustomMixin: def __init__(self, role: str = "") -> None: """Custom mixin :param role: Role play by the model (default: ``""``) :type role: str, optional """ # ===================================== # - define custom attributes and others # ===================================== def act(self, inputs: Mapping[str, Union[torch.Tensor, Any]], role: str = "") -> Tuple[torch.Tensor, Union[torch.Tensor, None], Mapping[str, Union[torch.Tensor, Any]]]: """Act according to the specified behavior :param inputs: Model inputs. The most common keys are: - ``"states"``: state of the environment used to make the decision - ``"taken_actions"``: actions taken by the policy for the given states :type inputs: dict where the values are typically torch.Tensor :param role: Role play by the model (default: ``""``) :type role: str, optional :return: Model output. The first component is the action to be taken by the agent. The second component is the log of the probability density function for stochastic models or None for deterministic models. The third component is a dictionary containing extra output values :rtype: tuple of torch.Tensor, torch.Tensor or None, and dictionary """ # ============================== # - act in response to the state # ============================== # [end-mixin-torch] # [start-mixin-jax] from typing import Optional, Union, Mapping, Tuple, Any import flax import jax.numpy as jnp class CustomMixin: def __init__(self, role: str = "") -> None: """Custom mixin :param role: Role play by the model (default: ``""``) :type role: str, optional """ # ===================================== # - define custom attributes and others # ===================================== flax.linen.Module.__post_init__(self) def act(self, inputs: Mapping[str, Union[jnp.ndarray, Any]], role: str = "", params: Optional[jnp.ndarray] = None) -> Tuple[jnp.ndarray, Union[jnp.ndarray, None], Mapping[str, Union[jnp.ndarray, Any]]]: """Act according to the specified behavior :param inputs: Model inputs. The most common keys are: - ``"states"``: state of the environment used to make the decision - ``"taken_actions"``: actions taken by the policy for the given states :type inputs: dict where the values are typically jnp.ndarray :param role: Role play by the model (default: ``""``) :type role: str, optional :param params: Parameters used to compute the output (default: ``None``). If ``None``, internal parameters will be used :type params: jnp.array :return: Model output. The first component is the action to be taken by the agent. The second component is the log of the probability density function. The third component is a dictionary containing the mean actions ``"mean_actions"`` and extra output values :rtype: tuple of jnp.ndarray, jnp.ndarray or None, and dictionary """ # ============================== # - act in response to the state # ============================== # [end-mixin-jax]
9,778
Python
43.857798
137
0.562896
Toni-SM/skrl/docs/source/snippets/multi_agents_basic_usage.py
# [start-ippo-torch] # import the agent and its default configuration from skrl.multi_agents.torch.ippo import IPPO, IPPO_DEFAULT_CONFIG # instantiate the agent's models models = {} for agent_name in env.possible_agents: models[agent_name] = {} models[agent_name]["policy"] = ... models[agent_name]["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = IPPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memories <memories>) agent = IPPO(possible_agents=env.possible_agents, models=models, memory=memories, # only required during training cfg=cfg_agent, observation_spaces=env.observation_spaces, action_spaces=env.action_spaces, device=env.device) # [end-ippo-torch] # [start-ippo-jax] # import the agent and its default configuration from skrl.multi_agents.jax.ippo import IPPO, IPPO_DEFAULT_CONFIG # instantiate the agent's models models = {} for agent_name in env.possible_agents: models[agent_name] = {} models[agent_name]["policy"] = ... models[agent_name]["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = IPPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memories <memories>) agent = IPPO(possible_agents=env.possible_agents, models=models, memory=memories, # only required during training cfg=cfg_agent, observation_spaces=env.observation_spaces, action_spaces=env.action_spaces, device=env.device) # [end-ippo-jax] # [start-mappo-torch] # import the agent and its default configuration from skrl.multi_agents.torch.mappo import MAPPO, MAPPO_DEFAULT_CONFIG # instantiate the agent's models models = {} for agent_name in env.possible_agents: models[agent_name] = {} models[agent_name]["policy"] = ... models[agent_name]["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = MAPPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memories <memories>) agent = MAPPO(possible_agents=env.possible_agents, models=models, memory=memories, # only required during training cfg=cfg_agent, observation_spaces=env.observation_spaces, action_spaces=env.action_spaces, device=env.device, shared_observation_spaces=env.shared_observation_spaces) # [end-mappo-torch] # [start-mappo-jax] # import the agent and its default configuration from skrl.multi_agents.jax.mappo import MAPPO, MAPPO_DEFAULT_CONFIG # instantiate the agent's models models = {} for agent_name in env.possible_agents: models[agent_name] = {} models[agent_name]["policy"] = ... models[agent_name]["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = MAPPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memories <memories>) agent = MAPPO(possible_agents=env.possible_agents, models=models, memory=memories, # only required during training cfg=cfg_agent, observation_spaces=env.observation_spaces, action_spaces=env.action_spaces, device=env.device, shared_observation_spaces=env.shared_observation_spaces) # [end-mappo-jax]
3,674
Python
32.715596
70
0.66957
Toni-SM/skrl/docs/source/snippets/agents_basic_usage.py
# [torch-start-a2c] # import the agent and its default configuration from skrl.agents.torch.a2c import A2C, A2C_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = A2C_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = A2C(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-a2c] # [jax-start-a2c] # import the agent and its default configuration from skrl.agents.jax.a2c import A2C, A2C_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = A2C_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = A2C(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-a2c] # [torch-start-a2c-rnn] # import the agent and its default configuration from skrl.agents.torch.a2c import A2C_RNN as A2C, A2C_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = A2C_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = A2C(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-a2c-rnn] # ============================================================================= # [torch-start-amp] # import the agent and its default configuration from skrl.agents.torch.amp import AMP, AMP_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training models["discriminator"] = ... # only required during training # adjust some configuration if necessary cfg_agent = AMP_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) # (assuming defined memories for motion <motion_dataset> and <reply_buffer>) # (assuming defined methods to collect motion <collect_reference_motions> and <collect_observation>) agent = AMP(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device, amp_observation_space=env.amp_observation_space, motion_dataset=motion_dataset, reply_buffer=reply_buffer, collect_reference_motions=collect_reference_motions, collect_observation=collect_observation) # [torch-end-amp] # ============================================================================= # [torch-start-cem] # import the agent and its default configuration from skrl.agents.torch.cem import CEM, CEM_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... # adjust some configuration if necessary cfg_agent = CEM_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = CEM(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-cem] # [jax-start-cem] # import the agent and its default configuration from skrl.agents.jax.cem import CEM, CEM_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... # adjust some configuration if necessary cfg_agent = CEM_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = CEM(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-cem] # ============================================================================= # [torch-start-ddpg] # import the agent and its default configuration from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic"] = ... # only required during training models["target_critic"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DDPG_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DDPG(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-ddpg] # [jax-start-ddpg] # import the agent and its default configuration from skrl.agents.jax.ddpg import DDPG, DDPG_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic"] = ... # only required during training models["target_critic"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DDPG_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DDPG(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-ddpg] # [torch-start-ddpg-rnn] # import the agent and its default configuration from skrl.agents.torch.ddpg import DDPG_RNN as DDPG, DDPG_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic"] = ... # only required during training models["target_critic"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DDPG_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DDPG(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-ddpg-rnn] # ============================================================================= # [torch-start-ddqn] # import the agent and its default configuration from skrl.agents.torch.dqn import DDQN, DDQN_DEFAULT_CONFIG # instantiate the agent's models models = {} models["q_network"] = ... models["target_q_network"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DDQN_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DDQN(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-ddqn] # [jax-start-ddqn] # import the agent and its default configuration from skrl.agents.jax.dqn import DDQN, DDQN_DEFAULT_CONFIG # instantiate the agent's models models = {} models["q_network"] = ... models["target_q_network"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DDQN_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DDQN(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-ddqn] # ============================================================================= # [torch-start-dqn] # import the agent and its default configuration from skrl.agents.torch.dqn import DQN, DQN_DEFAULT_CONFIG # instantiate the agent's models models = {} models["q_network"] = ... models["target_q_network"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DQN_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DQN(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-dqn] # [jax-start-dqn] # import the agent and its default configuration from skrl.agents.jax.dqn import DQN, DQN_DEFAULT_CONFIG # instantiate the agent's models models = {} models["q_network"] = ... models["target_q_network"] = ... # only required during training # adjust some configuration if necessary cfg_agent = DQN_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = DQN(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-dqn] # ============================================================================= # [torch-start-ppo] # import the agent and its default configuration from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = PPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = PPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-ppo] # [jax-start-ppo] # import the agent and its default configuration from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = PPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = PPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-ppo] # [torch-start-ppo-rnn] # import the agent and its default configuration from skrl.agents.torch.ppo import PPO_RNN as PPO, PPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = PPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = PPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-ppo-rnn] # ============================================================================= # [torch-start-q-learning] # import the agent and its default configuration from skrl.agents.torch.q_learning import Q_LEARNING, Q_LEARNING_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... # adjust some configuration if necessary cfg_agent = Q_LEARNING_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env>) agent = Q_LEARNING(models=models, memory=None, cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-q-learning] # ============================================================================= # [torch-start-rpo-with-rpo] class Policy(GaussianMixin, Model): ... def compute(self, inputs, role): # compute the mean actions using the neural network mean_actions = self.net(inputs["states"]) # perturb the mean actions by adding a randomized uniform sample rpo_alpha = inputs["alpha"] perturbation = torch.zeros_like(mean_actions).uniform_(-rpo_alpha, rpo_alpha) mean_actions += perturbation return mean_actions, self.log_std_parameter, {} # [torch-end-rpo-with-rpo] # [jax-start-rpo-with-rpo] class Policy(GaussianMixin, Model): ... def __call__(self, inputs, role): # compute the mean actions using the neural network mean_actions = ... log_std = ... # perturb the mean actions by adding a randomized uniform sample rpo_alpha = inputs["alpha"] perturbation = jax.random.uniform(inputs["key"], mean_actions.shape, minval=-rpo_alpha, maxval=rpo_alpha) mean_actions += perturbation return mean_actions, log_std, {} # [jax-end-rpo-with-rpo] # [torch-start-rpo-without-rpo] class Policy(GaussianMixin, Model): ... def compute(self, inputs, role): # compute the mean actions using the neural network mean_actions = self.net(inputs["states"]) # perturb the mean actions by adding a randomized uniform sample rpo_alpha = 0.5 perturbation = torch.zeros_like(mean_actions).uniform_(-rpo_alpha, rpo_alpha) mean_actions += perturbation return mean_actions, self.log_std_parameter, {} # [torch-end-rpo-without-rpo] # [jax-start-rpo-without-rpo] class Policy(GaussianMixin, Model): ... def __call__(self, inputs, role): # compute the mean actions using the neural network mean_actions = ... log_std = ... # perturb the mean actions by adding a randomized uniform sample rpo_alpha = 0.5 perturbation = jax.random.uniform(inputs["key"], mean_actions.shape, minval=-rpo_alpha, maxval=rpo_alpha) mean_actions += perturbation return mean_actions, log_std, {} # [jax-end-rpo-without-rpo] # [torch-start-rpo] # import the agent and its default configuration from skrl.agents.torch.rpo import RPO, RPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = RPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = RPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-rpo] # [jax-start-rpo] # import the agent and its default configuration from skrl.agents.jax.rpo import RPO, RPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = RPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = RPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-rpo] # [torch-start-rpo-rnn] # import the agent and its default configuration from skrl.agents.torch.rpo import RPO_RNN as RPO, RPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = RPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = RPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-rpo-rnn] # ============================================================================= # [torch-start-sac] # import the agent and its default configuration from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = SAC_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = SAC(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-sac] # [jax-start-sac] # import the agent and its default configuration from skrl.agents.jax.sac import SAC, SAC_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = SAC_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = SAC(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-sac] # [torch-start-sac-rnn] # import the agent and its default configuration from skrl.agents.torch.sac import SAC_RNN as SAC, SAC_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = SAC_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = SAC(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-sac-rnn] # ============================================================================= # [torch-start-sarsa] # import the agent and its default configuration from skrl.agents.torch.sarsa import SARSA, SARSA_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... # adjust some configuration if necessary cfg_agent = SARSA_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env>) agent = SARSA(models=models, memory=None, cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-sarsa] # ============================================================================= # [torch-start-td3] # import the agent and its default configuration from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = TD3_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = TD3(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-td3] # [jax-start-td3] # import the agent and its default configuration from skrl.agents.jax.td3 import TD3, TD3_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = TD3_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = TD3(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [jax-end-td3] # [torch-start-td3-rnn] # import the agent and its default configuration from skrl.agents.torch.td3 import TD3_RNN as TD3, TD3_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["target_policy"] = ... # only required during training models["critic_1"] = ... # only required during training models["critic_2"] = ... # only required during training models["target_critic_1"] = ... # only required during training models["target_critic_2"] = ... # only required during training # adjust some configuration if necessary cfg_agent = TD3_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = TD3(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-td3-rnn] # ============================================================================= # [torch-start-trpo] # import the agent and its default configuration from skrl.agents.torch.trpo import TRPO, TRPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = TRPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = TRPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-trpo] # [torch-start-trpo-rnn] # import the agent and its default configuration from skrl.agents.torch.trpo import TRPO_RNN as TRPO, TRPO_DEFAULT_CONFIG # instantiate the agent's models models = {} models["policy"] = ... models["value"] = ... # only required during training # adjust some configuration if necessary cfg_agent = TRPO_DEFAULT_CONFIG.copy() cfg_agent["<KEY>"] = ... # instantiate the agent # (assuming a defined environment <env> and memory <memory>) agent = TRPO(models=models, memory=memory, # only required during training cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=env.device) # [torch-end-trpo-rnn]
25,726
Python
30.840346
113
0.645378
Toni-SM/skrl/docs/source/snippets/memories.py
# [start-base-class-torch] from typing import Union, Tuple, List import torch from skrl.memories.torch import Memory class CustomMemory(Memory): def __init__(self, memory_size: int, num_envs: int = 1, device: Union[str, torch.device] = "cuda:0") -> None: """Custom memory :param memory_size: Maximum number of elements in the first dimension of each internal storage :type memory_size: int :param num_envs: Number of parallel environments (default: 1) :type num_envs: int, optional :param device: Device on which a torch tensor is or will be allocated (default: "cuda:0") :type device: str or torch.device, optional """ super().__init__(memory_size, num_envs, device) def sample(self, names: Tuple[str], batch_size: int, mini_batches: int = 1) -> List[List[torch.Tensor]]: """Sample a batch from memory :param names: Tensors names from which to obtain the samples :type names: tuple or list of strings :param batch_size: Number of element to sample :type batch_size: int :param mini_batches: Number of mini-batches to sample (default: 1) :type mini_batches: int, optional :return: Sampled data from tensors sorted according to their position in the list of names. The sampled tensors will have the following shape: (batch size, data size) :rtype: list of torch.Tensor list """ # ================================ # - sample a batch from memory. # It is possible to generate only the sampling indexes and call self.sample_by_index(...) # ================================ # [end-base-class-torch] # [start-base-class-jax] from typing import Optional, Union, Tuple, List import jaxlib import jax.numpy as jnp from skrl.memories.jax import Memory class CustomMemory(Memory): def __init__(self, memory_size: int, num_envs: int = 1, device: Optional[jaxlib.xla_extension.Device] = None) -> None: """Custom memory :param memory_size: Maximum number of elements in the first dimension of each internal storage :type memory_size: int :param num_envs: Number of parallel environments (default: 1) :type num_envs: int, optional :param device: Device on which an array is or will be allocated (default: None) :type device: jaxlib.xla_extension.Device, optional """ super().__init__(memory_size, num_envs, device) def sample(self, names: Tuple[str], batch_size: int, mini_batches: int = 1) -> List[List[jnp.ndarray]]: """Sample a batch from memory :param names: Tensors names from which to obtain the samples :type names: tuple or list of strings :param batch_size: Number of element to sample :type batch_size: int :param mini_batches: Number of mini-batches to sample (default: 1) :type mini_batches: int, optional :return: Sampled data from tensors sorted according to their position in the list of names. The sampled tensors will have the following shape: (batch size, data size) :rtype: list of jnp.ndarray list """ # ================================ # - sample a batch from memory. # It is possible to generate only the sampling indexes and call self.sample_by_index(...) # ================================ # [end-base-class-jax] # ============================================================================= # [start-random-torch] # import the memory class from skrl.memories.torch import RandomMemory # instantiate the memory (assumes there is a wrapped environment: env) memory = RandomMemory(memory_size=1000, num_envs=env.num_envs, device=env.device) # [end-random-torch] # [start-random-jax] # import the memory class from skrl.memories.jax import RandomMemory # instantiate the memory (assumes there is a wrapped environment: env) memory = RandomMemory(memory_size=1000, num_envs=env.num_envs, device=env.device) # [end-random-jax]
4,112
Python
38.171428
113
0.625486
Toni-SM/skrl/docs/source/snippets/data.py
# [start-tensorboard-configuration] DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } # [end-tensorboard-configuration] # [start-wandb-configuration] DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } # [end-wandb-configuration] # [start-checkpoint-configuration] DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } # [end-checkpoint-configuration] # [start-checkpoint-load-agent-torch] from skrl.agents.torch.ppo import PPO # Instantiate the agent agent = PPO(models=models, # models dict memory=memory, # memory instance, or None if not required cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.) observation_space=env.observation_space, action_space=env.action_space, device=env.device) # Load the checkpoint agent.load("./runs/22-09-29_22-48-49-816281_DDPG/checkpoints/agent_1200.pt") # [end-checkpoint-load-agent-torch] # [start-checkpoint-load-agent-jax] from skrl.agents.jax.ppo import PPO # Instantiate the agent agent = PPO(models=models, # models dict memory=memory, # memory instance, or None if not required cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.) observation_space=env.observation_space, action_space=env.action_space, device=env.device) # Load the checkpoint agent.load("./runs/22-09-29_22-48-49-816281_DDPG/checkpoints/agent_1200.pickle") # [end-checkpoint-load-agent-jax] # [start-checkpoint-load-model-torch] from skrl.models.torch import Model, DeterministicMixin # Define the model class Policy(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # Instantiate the model policy = Policy(env.observation_space, env.action_space, env.device, clip_actions=True) # Load the checkpoint policy.load("./runs/22-09-29_22-48-49-816281_DDPG/checkpoints/2500_policy.pt") # [end-checkpoint-load-model-torch] # [start-checkpoint-load-model-jax] from skrl.models.jax import Model, DeterministicMixin # Define the model class Policy(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.Dense(32)(inputs["states"]) x = nn.relu(x) x = nn.Dense(32)(x) x = nn.relu(x) x = nn.Dense(self.num_actions)(x) return x, {} # Instantiate the model policy = Policy(env.observation_space, env.action_space, env.device, clip_actions=True) # Load the checkpoint policy.load("./runs/22-09-29_22-48-49-816281_DDPG/checkpoints/2500_policy.pickle") # [end-checkpoint-load-model-jax] # [start-checkpoint-load-huggingface-torch] from skrl.agents.torch.ppo import PPO from skrl.utils.huggingface import download_model_from_huggingface # Instantiate the agent agent = PPO(models=models, # models dict memory=memory, # memory instance, or None if not required cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.) observation_space=env.observation_space, action_space=env.action_space, device=env.device) # Load the checkpoint from Hugging Face Hub path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Cartpole-PPO", filename="agent.pt") agent.load(path) # [end-checkpoint-load-huggingface-torch] # [start-checkpoint-load-huggingface-jax] from skrl.agents.jax.ppo import PPO from skrl.utils.huggingface import download_model_from_huggingface # Instantiate the agent agent = PPO(models=models, # models dict memory=memory, # memory instance, or None if not required cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.) observation_space=env.observation_space, action_space=env.action_space, device=env.device) # Load the checkpoint from Hugging Face Hub path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Cartpole-PPO", filename="agent.pickle") agent.load(path) # [end-checkpoint-load-huggingface-jax] # [start-checkpoint-migrate-agent-torch] from skrl.agents.torch.ppo import PPO # Instantiate the agent agent = PPO(models=models, # models dict memory=memory, # memory instance, or None if not required cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.) observation_space=env.observation_space, action_space=env.action_space, device=env.device) # Migrate a rl_games checkpoint agent.migrate(path="./runs/Cartpole/nn/Cartpole.pth") # [end-checkpoint-migrate-agent-torch] # [start-checkpoint-migrate-model-torch] from skrl.models.torch import Model, DeterministicMixin # Define the model class Policy(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # Instantiate the model policy = Policy(env.observation_space, env.action_space, env.device, clip_actions=True) # Migrate a rl_games checkpoint (only the model) policy.migrate(path="./runs/Cartpole/nn/Cartpole.pth") # or migrate a stable-baselines3 checkpoint policy.migrate(path="./ddpg_pendulum.zip") # or migrate a checkpoint of any other library state_dict = torch.load("./external_model.pt") policy.migrate(state_dict=state_dict) # [end-checkpoint-migrate-model-torch] # [start-export-memory-torch] from skrl.memories.torch import RandomMemory # Instantiate a memory and enable its export memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device, export=True, export_format="pt", export_directory="./memories") # [end-export-memory-torch] # [start-export-memory-jax] from skrl.memories.jax import RandomMemory # Instantiate a memory and enable its export memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device, export=True, export_format="np", export_directory="./memories") # [end-export-memory-jax]
9,058
Python
35.091633
101
0.643851
Toni-SM/skrl/docs/source/snippets/isaacgym_utils.py
import math from isaacgym import gymapi from skrl.utils import isaacgym_utils # create a web viewer instance web_viewer = isaacgym_utils.WebViewer() # configure and create simulation sim_params = gymapi.SimParams() sim_params.up_axis = gymapi.UP_AXIS_Z sim_params.gravity = gymapi.Vec3(0.0, 0.0, -9.8) sim_params.physx.solver_type = 1 sim_params.physx.num_position_iterations = 4 sim_params.physx.num_velocity_iterations = 1 sim_params.physx.use_gpu = True sim_params.use_gpu_pipeline = True gym = gymapi.acquire_gym() sim = gym.create_sim(compute_device=0, graphics_device=0, type=gymapi.SIM_PHYSX, params=sim_params) # setup num_envs and env's grid num_envs = 1 spacing = 2.0 env_lower = gymapi.Vec3(-spacing, -spacing, 0.0) env_upper = gymapi.Vec3(spacing, 0.0, spacing) # add ground plane plane_params = gymapi.PlaneParams() plane_params.normal = gymapi.Vec3(0.0, 0.0, 1.0) gym.add_ground(sim, plane_params) envs = [] cameras = [] for i in range(num_envs): # create env env = gym.create_env(sim, env_lower, env_upper, int(math.sqrt(num_envs))) # add sphere pose = gymapi.Transform() pose.p, pose.r = gymapi.Vec3(0.0, 0.0, 1.0), gymapi.Quat(0.0, 0.0, 0.0, 1.0) gym.create_actor(env, gym.create_sphere(sim, 0.2, None), pose, "sphere", i, 0) # add camera cam_props = gymapi.CameraProperties() cam_props.width, cam_props.height = 300, 300 cam_handle = gym.create_camera_sensor(env, cam_props) gym.set_camera_location(cam_handle, env, gymapi.Vec3(1, 1, 1), gymapi.Vec3(0, 0, 0)) envs.append(env) cameras.append(cam_handle) # setup web viewer web_viewer.setup(gym, sim, envs, cameras) gym.prepare_sim(sim) for i in range(100000): gym.simulate(sim) # render the scene web_viewer.render(fetch_results=True, step_graphics=True, render_all_camera_sensors=True, wait_for_page_load=True)
1,927
Python
26.942029
99
0.677218
Toni-SM/skrl/docs/source/snippets/loaders.py
# [start-omniverse-isaac-gym-envs-parameters-torch] # import the environment loader from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(task_name="Cartpole") # [end-omniverse-isaac-gym-envs-parameters-torch] # [start-omniverse-isaac-gym-envs-parameters-jax] # import the environment loader from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(task_name="Cartpole") # [end-omniverse-isaac-gym-envs-parameters-jax] # [start-omniverse-isaac-gym-envs-cli-torch] # import the environment loader from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env() # [end-omniverse-isaac-gym-envs-cli-torch] # [start-omniverse-isaac-gym-envs-cli-jax] # import the environment loader from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env() # [end-omniverse-isaac-gym-envs-cli-jax] # [start-omniverse-isaac-gym-envs-multi-threaded-parameters-torch] import threading # import the environment loader from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) # ... # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run() # [end-omniverse-isaac-gym-envs-multi-threaded-parameters-torch] # [start-omniverse-isaac-gym-envs-multi-threaded-parameters-jax] import threading # import the environment loader from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) # ... # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run() # [end-omniverse-isaac-gym-envs-multi-threaded-parameters-jax] # [start-omniverse-isaac-gym-envs-multi-threaded-cli-torch] import threading # import the environment loader from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(multi_threaded=True, timeout=30) # ... # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run() # [end-omniverse-isaac-gym-envs-multi-threaded-cli-torch] # [start-omniverse-isaac-gym-envs-multi-threaded-cli-jax] import threading # import the environment loader from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load environment env = load_omniverse_isaacgym_env(multi_threaded=True, timeout=30) # ... # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run() # [end-omniverse-isaac-gym-envs-multi-threaded-cli-jax] # ============================================================================= # [start-isaac-orbit-envs-parameters-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaac_orbit_env # load environment env = load_isaac_orbit_env(task_name="Isaac-Cartpole-v0") # [end-isaac-orbit-envs-parameters-torch] # [start-isaac-orbit-envs-parameters-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaac_orbit_env # load environment env = load_isaac_orbit_env(task_name="Isaac-Cartpole-v0") # [end-isaac-orbit-envs-parameters-jax] # [start-isaac-orbit-envs-cli-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaac_orbit_env # load environment env = load_isaac_orbit_env() # [end-isaac-orbit-envs-cli-torch] # [start-isaac-orbit-envs-cli-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaac_orbit_env # load environment env = load_isaac_orbit_env() # [end-isaac-orbit-envs-cli-jax] # ============================================================================= # [start-isaac-gym-envs-preview-4-api] import isaacgymenvs env = isaacgymenvs.make(seed=0, task="Cartpole", num_envs=2000, sim_device="cuda:0", rl_device="cuda:0", graphics_device_id=0, headless=False) # [end-isaac-gym-envs-preview-4-api] # [start-isaac-gym-envs-preview-4-parameters-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview4 # load environment env = load_isaacgym_env_preview4(task_name="Cartpole") # [end-isaac-gym-envs-preview-4-parameters-torch] # [start-isaac-gym-envs-preview-4-parameters-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview4 # load environment env = load_isaacgym_env_preview4(task_name="Cartpole") # [end-isaac-gym-envs-preview-4-parameters-jax] # [start-isaac-gym-envs-preview-4-cli-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview4 # load environment env = load_isaacgym_env_preview4() # [end-isaac-gym-envs-preview-4-cli-torch] # [start-isaac-gym-envs-preview-4-cli-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview4 # load environment env = load_isaacgym_env_preview4() # [end-isaac-gym-envs-preview-4-cli-jax] # [start-isaac-gym-envs-preview-3-parameters-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview3 # load environment env = load_isaacgym_env_preview3(task_name="Cartpole") # [end-isaac-gym-envs-preview-3-parameters-torch] # [start-isaac-gym-envs-preview-3-parameters-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview3 # load environment env = load_isaacgym_env_preview3(task_name="Cartpole") # [end-isaac-gym-envs-preview-3-parameters-jax] # [start-isaac-gym-envs-preview-3-cli-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview3 # load environment env = load_isaacgym_env_preview3() # [end-isaac-gym-envs-preview-3-cli-torch] # [start-isaac-gym-envs-preview-3-cli-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview3 # load environment env = load_isaacgym_env_preview3() # [end-isaac-gym-envs-preview-3-cli-jax] # [start-isaac-gym-envs-preview-2-parameters-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview2 # load environment env = load_isaacgym_env_preview2(task_name="Cartpole") # [end-isaac-gym-envs-preview-2-parameters-torch] # [start-isaac-gym-envs-preview-2-parameters-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview2 # load environment env = load_isaacgym_env_preview2(task_name="Cartpole") # [end-isaac-gym-envs-preview-2-parameters-jax] # [start-isaac-gym-envs-preview-2-cli-torch] # import the environment loader from skrl.envs.loaders.torch import load_isaacgym_env_preview2 # load environment env = load_isaacgym_env_preview2() # [end-isaac-gym-envs-preview-2-cli-torch] # [start-isaac-gym-envs-preview-2-cli-jax] # import the environment loader from skrl.envs.loaders.jax import load_isaacgym_env_preview2 # load environment env = load_isaacgym_env_preview2() # [end-isaac-gym-envs-preview-2-cli-jax]
7,458
Python
26.625926
88
0.739877
Toni-SM/skrl/docs/source/snippets/agent.py
# [start-agent-base-class-torch] from typing import Union, Tuple, Dict, Any, Optional import gym, gymnasium import copy import torch from skrl.memories.torch import Memory from skrl.models.torch import Model from skrl.agents.torch import Agent CUSTOM_DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } class CUSTOM(Agent): def __init__(self, models: Dict[str, Model], memory: Optional[Union[Memory, Tuple[Memory]]] = None, observation_space: Optional[Union[int, Tuple[int], gym.Space, gymnasium.Space]] = None, action_space: Optional[Union[int, Tuple[int], gym.Space, gymnasium.Space]] = None, device: Optional[Union[str, torch.device]] = None, cfg: Optional[dict] = None) -> None: """Custom agent :param models: Models used by the agent :type models: dictionary of skrl.models.torch.Model :param memory: Memory to storage the transitions. If it is a tuple, the first element will be used for training and for the rest only the environment transitions will be added :type memory: skrl.memory.torch.Memory, list of skrl.memory.torch.Memory or None :param observation_space: Observation/state space or shape (default: None) :type observation_space: int, tuple or list of integers, gym.Space, gymnasium.Space or None, optional :param action_space: Action space or shape (default: None) :type action_space: int, tuple or list of integers, gym.Space, gymnasium.Space or None, optional :param device: Device on which a torch tensor is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or torch.device, optional :param cfg: Configuration dictionary :type cfg: dict """ _cfg = copy.deepcopy(CUSTOM_DEFAULT_CONFIG) _cfg.update(cfg if cfg is not None else {}) super().__init__(models=models, memory=memory, observation_space=observation_space, action_space=action_space, device=device, cfg=_cfg) # ======================================================================= # - get and process models from `self.models` # - populate `self.checkpoint_modules` dictionary for storing checkpoints # - parse configurations from `self.cfg` # - setup optimizers and learning rate scheduler # - set up preprocessors # ======================================================================= def init(self, trainer_cfg: Optional[Dict[str, Any]] = None) -> None: """Initialize the agent """ super().init(trainer_cfg=trainer_cfg) self.set_mode("eval") # ================================================================= # - create tensors in memory if required # - # create temporary variables needed for storage and computation # ================================================================= def act(self, states: torch.Tensor, timestep: int, timesteps: int) -> torch.Tensor: """Process the environment's states to make a decision (actions) using the main policy :param states: Environment's states :type states: torch.Tensor :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int :return: Actions :rtype: torch.Tensor """ # ====================================== # - sample random actions if required or # sample and return agent's actions # ====================================== def record_transition(self, states: torch.Tensor, actions: torch.Tensor, rewards: torch.Tensor, next_states: torch.Tensor, terminated: torch.Tensor, truncated: torch.Tensor, infos: Any, timestep: int, timesteps: int) -> None: """Record an environment transition in memory :param states: Observations/states of the environment used to make the decision :type states: torch.Tensor :param actions: Actions taken by the agent :type actions: torch.Tensor :param rewards: Instant rewards achieved by the current actions :type rewards: torch.Tensor :param next_states: Next observations/states of the environment :type next_states: torch.Tensor :param terminated: Signals to indicate that episodes have terminated :type terminated: torch.Tensor :param truncated: Signals to indicate that episodes have been truncated :type truncated: torch.Tensor :param infos: Additional information about the environment :type infos: Any type supported by the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ super().record_transition(states, actions, rewards, next_states, terminated, truncated, infos, timestep, timesteps) # ======================================== # - record agent's specific data in memory # ======================================== def pre_interaction(self, timestep: int, timesteps: int) -> None: """Callback called before the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== def post_interaction(self, timestep: int, timesteps: int) -> None: """Callback called after the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== # call parent's method for checkpointing and TensorBoard writing super().post_interaction(timestep, timesteps) def _update(self, timestep: int, timesteps: int) -> None: """Algorithm's main update step :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # =================================================== # - implement algorithm's update step # - record tracking data using `self.track_data(...)` # =================================================== # [end-agent-base-class-torch] # [start-agent-base-class-jax] from typing import Union, Tuple, Dict, Any, Optional import gym, gymnasium import copy import jaxlib import jax.numpy as jnp from skrl.memories.jax import Memory from skrl.models.jax import Model from skrl.resources.optimizers.jax import Adam from skrl.agents.jax import Agent CUSTOM_DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } class CUSTOM(Agent): def __init__(self, models: Dict[str, Model], memory: Optional[Union[Memory, Tuple[Memory]]] = None, observation_space: Optional[Union[int, Tuple[int], gym.Space, gymnasium.Space]] = None, action_space: Optional[Union[int, Tuple[int], gym.Space, gymnasium.Space]] = None, device: Optional[Union[str, jaxlib.xla_extension.Device]] = None, cfg: Optional[dict] = None) -> None: """Custom agent :param models: Models used by the agent :type models: dictionary of skrl.models.jax.Model :param memory: Memory to storage the transitions. If it is a tuple, the first element will be used for training and for the rest only the environment transitions will be added :type memory: skrl.memory.jax.Memory, list of skrl.memory.jax.Memory or None :param observation_space: Observation/state space or shape (default: None) :type observation_space: int, tuple or list of integers, gym.Space, gymnasium.Space or None, optional :param action_space: Action space or shape (default: None) :type action_space: int, tuple or list of integers, gym.Space, gymnasium.Space or None, optional :param device: Device on which a jax array is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or jaxlib.xla_extension.Device, optional :param cfg: Configuration dictionary :type cfg: dict """ _cfg = CUSTOM_DEFAULT_CONFIG _cfg.update(cfg if cfg is not None else {}) super().__init__(models=models, memory=memory, observation_space=observation_space, action_space=action_space, device=device, cfg=_cfg) # ======================================================================= # - get and process models from `self.models` # - populate `self.checkpoint_modules` dictionary for storing checkpoints # - parse configurations from `self.cfg` # - setup optimizers and learning rate scheduler # - set up preprocessors # ======================================================================= def init(self, trainer_cfg: Optional[Dict[str, Any]] = None) -> None: """Initialize the agent """ super().init(trainer_cfg=trainer_cfg) self.set_mode("eval") # ================================================================= # - create tensors in memory if required # - # create temporary variables needed for storage and computation # - set up models for just-in-time compilation with XLA # ================================================================= def act(self, states: jnp.ndarray, timestep: int, timesteps: int) -> jnp.ndarray: """Process the environment's states to make a decision (actions) using the main policy :param states: Environment's states :type states: jnp.ndarray :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int :return: Actions :rtype: jnp.ndarray """ # ====================================== # - sample random actions if required or # sample and return agent's actions # ====================================== def record_transition(self, states: jnp.ndarray, actions: jnp.ndarray, rewards: jnp.ndarray, next_states: jnp.ndarray, terminated: jnp.ndarray, truncated: jnp.ndarray, infos: Any, timestep: int, timesteps: int) -> None: """Record an environment transition in memory :param states: Observations/states of the environment used to make the decision :type states: jnp.ndarray :param actions: Actions taken by the agent :type actions: jnp.ndarray :param rewards: Instant rewards achieved by the current actions :type rewards: jnp.ndarray :param next_states: Next observations/states of the environment :type next_states: jnp.ndarray :param terminated: Signals to indicate that episodes have terminated :type terminated: jnp.ndarray :param truncated: Signals to indicate that episodes have been truncated :type truncated: jnp.ndarray :param infos: Additional information about the environment :type infos: Any type supported by the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ super().record_transition(states, actions, rewards, next_states, terminated, truncated, infos, timestep, timesteps) # ======================================== # - record agent's specific data in memory # ======================================== def pre_interaction(self, timestep: int, timesteps: int) -> None: """Callback called before the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== def post_interaction(self, timestep: int, timesteps: int) -> None: """Callback called after the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== # call parent's method for checkpointing and TensorBoard writing super().post_interaction(timestep, timesteps) def _update(self, timestep: int, timesteps: int) -> None: """Algorithm's main update step :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # =================================================== # - implement algorithm's update step # - record tracking data using `self.track_data(...)` # =================================================== # [end-agent-base-class-jax]
15,562
Python
42.472067
123
0.543182
Toni-SM/skrl/docs/source/snippets/tabular_model.py
# [start-definition-torch] class TabularModel(TabularMixin, Model): def __init__(self, observation_space, action_space, device=None, num_envs=1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) # [end-definition-torch] # ============================================================================= # [start-epsilon-greedy-torch] import torch from skrl.models.torch import Model, TabularMixin # define the model class EpilonGreedyPolicy(TabularMixin, Model): def __init__(self, observation_space, action_space, device, num_envs=1, epsilon=0.1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) self.epsilon = epsilon self.q_table = torch.ones((num_envs, self.num_observations, self.num_actions), dtype=torch.float32) def compute(self, inputs, role): states = inputs["states"] actions = torch.argmax(self.q_table[torch.arange(self.num_envs).view(-1, 1), states], dim=-1, keepdim=True).view(-1,1) indexes = (torch.rand(states.shape[0], device=self.device) < self.epsilon).nonzero().view(-1) if indexes.numel(): actions[indexes] = torch.randint(self.num_actions, (indexes.numel(), 1), device=self.device) return actions, {} # instantiate the model (assumes there is a wrapped environment: env) policy = EpilonGreedyPolicy(observation_space=env.observation_space, action_space=env.action_space, device=env.device, num_envs=env.num_envs, epsilon=0.15) # [end-epsilon-greedy-torch]
1,744
Python
39.581394
107
0.601491
Toni-SM/skrl/docs/source/snippets/multi_agent.py
# [start-multi-agent-base-class-torch] from typing import Union, Dict, Any, Optional, Sequence, Mapping import gym, gymnasium import copy import torch from skrl.memories.torch import Memory from skrl.models.torch import Model from skrl.multi_agents.torch import MultiAgent CUSTOM_DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } class CUSTOM(MultiAgent): def __init__(self, possible_agents: Sequence[str], models: Dict[str, Model], memories: Optional[Mapping[str, Memory]] = None, observation_spaces: Optional[Union[Mapping[str, int], Mapping[str, gym.Space], Mapping[str, gymnasium.Space]]] = None, action_spaces: Optional[Union[Mapping[str, int], Mapping[str, gym.Space], Mapping[str, gymnasium.Space]]] = None, device: Optional[Union[str, torch.device]] = None, cfg: Optional[dict] = None) -> None: """Custom multi-agent :param possible_agents: Name of all possible agents the environment could generate :type possible_agents: list of str :param models: Models used by the agents. External keys are environment agents' names. Internal keys are the models required by the algorithm :type models: nested dictionary of skrl.models.torch.Model :param memories: Memories to storage the transitions. :type memories: dictionary of skrl.memory.torch.Memory, optional :param observation_spaces: Observation/state spaces or shapes (default: ``None``) :type observation_spaces: dictionary of int, sequence of int, gym.Space or gymnasium.Space, optional :param action_spaces: Action spaces or shapes (default: ``None``) :type action_spaces: dictionary of int, sequence of int, gym.Space or gymnasium.Space, optional :param device: Device on which a torch tensor is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or torch.device, optional :param cfg: Configuration dictionary :type cfg: dict """ _cfg = copy.deepcopy(CUSTOM_DEFAULT_CONFIG) _cfg.update(cfg if cfg is not None else {}) super().__init__(possible_agents=possible_agents, models=models, memories=memories, observation_spaces=observation_spaces, action_spaces=action_spaces, device=device, cfg=_cfg) # ======================================================================= # - get and process models from `self.models` # - populate `self.checkpoint_modules` dictionary for storing checkpoints # - parse configurations from `self.cfg` # - setup optimizers and learning rate scheduler # - set up preprocessors # ======================================================================= def init(self, trainer_cfg: Optional[Dict[str, Any]] = None) -> None: """Initialize the agent """ super().init(trainer_cfg=trainer_cfg) self.set_mode("eval") # ================================================================= # - create tensors in memory if required # - # create temporary variables needed for storage and computation # ================================================================= def act(self, states: Mapping[str, torch.Tensor], timestep: int, timesteps: int) -> torch.Tensor: """Process the environment's states to make a decision (actions) using the main policies :param states: Environment's states :type states: dictionary of torch.Tensor :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int :return: Actions :rtype: torch.Tensor """ # ====================================== # - sample random actions if required or # sample and return agent's actions # ====================================== def record_transition(self, states: Mapping[str, torch.Tensor], actions: Mapping[str, torch.Tensor], rewards: Mapping[str, torch.Tensor], next_states: Mapping[str, torch.Tensor], terminated: Mapping[str, torch.Tensor], truncated: Mapping[str, torch.Tensor], infos: Mapping[str, Any], timestep: int, timesteps: int) -> None: """Record an environment transition in memory :param states: Observations/states of the environment used to make the decision :type states: dictionary of torch.Tensor :param actions: Actions taken by the agent :type actions: dictionary of torch.Tensor :param rewards: Instant rewards achieved by the current actions :type rewards: dictionary of torch.Tensor :param next_states: Next observations/states of the environment :type next_states: dictionary of torch.Tensor :param terminated: Signals to indicate that episodes have terminated :type terminated: dictionary of torch.Tensor :param truncated: Signals to indicate that episodes have been truncated :type truncated: dictionary of torch.Tensor :param infos: Additional information about the environment :type infos: dictionary of any supported type :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ super().record_transition(states, actions, rewards, next_states, terminated, truncated, infos, timestep, timesteps) # ======================================== # - record agent's specific data in memory # ======================================== def pre_interaction(self, timestep: int, timesteps: int) -> None: """Callback called before the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== def post_interaction(self, timestep: int, timesteps: int) -> None: """Callback called after the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== # call parent's method for checkpointing and TensorBoard writing super().post_interaction(timestep, timesteps) def _update(self, timestep: int, timesteps: int) -> None: """Algorithm's main update step :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # =================================================== # - implement algorithm's update step # - record tracking data using `self.track_data(...)` # =================================================== # [end-multi-agent-base-class-torch] # [start-multi-agent-base-class-jax] from typing import Union, Dict, Any, Optional, Sequence, Mapping import gym, gymnasium import copy import jaxlib import jax.numpy as jnp from skrl.memories.jax import Memory from skrl.models.jax import Model from skrl.resources.optimizers.jax import Adam from skrl.multi_agents.jax import MultiAgent CUSTOM_DEFAULT_CONFIG = { # ... "experiment": { "directory": "", # experiment's parent directory "experiment_name": "", # experiment name "write_interval": 250, # TensorBoard writing interval (timesteps) "checkpoint_interval": 1000, # interval for checkpoints (timesteps) "store_separately": False, # whether to store checkpoints separately "wandb": False, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } } class CUSTOM(MultiAgent): def __init__(self, possible_agents: Sequence[str], models: Dict[str, Model], memories: Optional[Mapping[str, Memory]] = None, observation_spaces: Optional[Union[Mapping[str, int], Mapping[str, gym.Space], Mapping[str, gymnasium.Space]]] = None, action_spaces: Optional[Union[Mapping[str, int], Mapping[str, gym.Space], Mapping[str, gymnasium.Space]]] = None, device: Optional[Union[str, jaxlib.xla_extension.Device]] = None, cfg: Optional[dict] = None) -> None: """Custom multi-agent :param possible_agents: Name of all possible agents the environment could generate :type possible_agents: list of str :param models: Models used by the agents. External keys are environment agents' names. Internal keys are the models required by the algorithm :type models: nested dictionary of skrl.models.torch.Model :param memories: Memories to storage the transitions. :type memories: dictionary of skrl.memory.torch.Memory, optional :param observation_spaces: Observation/state spaces or shapes (default: ``None``) :type observation_spaces: dictionary of int, sequence of int, gym.Space or gymnasium.Space, optional :param action_spaces: Action spaces or shapes (default: ``None``) :type action_spaces: dictionary of int, sequence of int, gym.Space or gymnasium.Space, optional :param device: Device on which a jax array is or will be allocated (default: ``None``). If None, the device will be either ``"cuda:0"`` if available or ``"cpu"`` :type device: str or jaxlib.xla_extension.Device, optional :param cfg: Configuration dictionary :type cfg: dict """ _cfg = copy.deepcopy(CUSTOM_DEFAULT_CONFIG) _cfg.update(cfg if cfg is not None else {}) super().__init__(possible_agents=possible_agents, models=models, memories=memories, observation_spaces=observation_spaces, action_spaces=action_spaces, device=device, cfg=_cfg) # ======================================================================= # - get and process models from `self.models` # - populate `self.checkpoint_modules` dictionary for storing checkpoints # - parse configurations from `self.cfg` # - setup optimizers and learning rate scheduler # - set up preprocessors # ======================================================================= def init(self, trainer_cfg: Optional[Dict[str, Any]] = None) -> None: """Initialize the agent """ super().init(trainer_cfg=trainer_cfg) self.set_mode("eval") # ================================================================= # - create tensors in memory if required # - # create temporary variables needed for storage and computation # ================================================================= def act(self, states: Mapping[str, jnp.ndarray], timestep: int, timesteps: int) -> jnp.ndarray: """Process the environment's states to make a decision (actions) using the main policies :param states: Environment's states :type states: dictionary of jnp.ndarray :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int :return: Actions :rtype: jnp.ndarray """ # ====================================== # - sample random actions if required or # sample and return agent's actions # ====================================== def record_transition(self, states: Mapping[str, jnp.ndarray], actions: Mapping[str, jnp.ndarray], rewards: Mapping[str, jnp.ndarray], next_states: Mapping[str, jnp.ndarray], terminated: Mapping[str, jnp.ndarray], truncated: Mapping[str, jnp.ndarray], infos: Mapping[str, Any], timestep: int, timesteps: int) -> None: """Record an environment transition in memory :param states: Observations/states of the environment used to make the decision :type states: dictionary of jnp.ndarray :param actions: Actions taken by the agent :type actions: dictionary of jnp.ndarray :param rewards: Instant rewards achieved by the current actions :type rewards: dictionary of jnp.ndarray :param next_states: Next observations/states of the environment :type next_states: dictionary of jnp.ndarray :param terminated: Signals to indicate that episodes have terminated :type terminated: dictionary of jnp.ndarray :param truncated: Signals to indicate that episodes have been truncated :type truncated: dictionary of jnp.ndarray :param infos: Additional information about the environment :type infos: dictionary of any type supported by the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ super().record_transition(states, actions, rewards, next_states, terminated, truncated, infos, timestep, timesteps) # ======================================== # - record agent's specific data in memory # ======================================== def pre_interaction(self, timestep: int, timesteps: int) -> None: """Callback called before the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== def post_interaction(self, timestep: int, timesteps: int) -> None: """Callback called after the interaction with the environment :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # ===================================== # - call `self.update(...)` if required # ===================================== # call parent's method for checkpointing and TensorBoard writing super().post_interaction(timestep, timesteps) def _update(self, timestep: int, timesteps: int) -> None: """Algorithm's main update step :param timestep: Current timestep :type timestep: int :param timesteps: Number of timesteps :type timesteps: int """ # =================================================== # - implement algorithm's update step # - record tracking data using `self.track_data(...)` # =================================================== # [end-multi-agent-base-class-jax]
16,574
Python
44.661157
135
0.556715
Toni-SM/skrl/docs/source/snippets/wrapping.py
# [pytorch-start-omniverse-isaacgym] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load the environment env = load_omniverse_isaacgym_env(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="omniverse-isaacgym")' # [pytorch-end-omniverse-isaacgym] # [jax-start-omniverse-isaacgym] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load the environment env = load_omniverse_isaacgym_env(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="omniverse-isaacgym")' # [jax-end-omniverse-isaacgym] # [pytorch-start-omniverse-isaacgym-mt] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_omniverse_isaacgym_env # load the multi-threaded environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="omniverse-isaacgym")' # [pytorch-end-omniverse-isaacgym-mt] # [jax-start-omniverse-isaacgym-mt] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_omniverse_isaacgym_env # load the multi-threaded environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="omniverse-isaacgym")' # [jax-end-omniverse-isaacgym-mt] # [pytorch-start-isaac-orbit] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_isaac_orbit_env # load the environment env = load_isaac_orbit_env(task_name="Isaac-Cartpole-v0") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaac-orbit")' # [pytorch-end-isaac-orbit] # [jax-start-isaac-orbit] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_isaac_orbit_env # load the environment env = load_isaac_orbit_env(task_name="Isaac-Cartpole-v0") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaac-orbit")' # [jax-end-isaac-orbit] # [pytorch-start-isaacgym-preview4-make] import isaacgymenvs # import the environment wrapper from skrl.envs.wrappers.torch import wrap_env # create/load the environment using the easy-to-use API from NVIDIA env = isaacgymenvs.make(seed=0, task="Cartpole", num_envs=512, sim_device="cuda:0", rl_device="cuda:0", graphics_device_id=0, headless=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview4")' # [pytorch-end-isaacgym-preview4-make] # [jax-start-isaacgym-preview4-make] import isaacgymenvs # import the environment wrapper from skrl.envs.wrappers.jax import wrap_env # create/load the environment using the easy-to-use API from NVIDIA env = isaacgymenvs.make(seed=0, task="Cartpole", num_envs=512, sim_device="cuda:0", rl_device="cuda:0", graphics_device_id=0, headless=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview4")' # [jax-end-isaacgym-preview4-make] # [pytorch-start-isaacgym-preview4] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_isaacgym_env_preview4 # load the environment env = load_isaacgym_env_preview4(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview4")' # [pytorch-end-isaacgym-preview4] # [jax-start-isaacgym-preview4] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_isaacgym_env_preview4 # load the environment env = load_isaacgym_env_preview4(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview4")' # [jax-end-isaacgym-preview4] # [pytorch-start-isaacgym-preview3] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_isaacgym_env_preview3 # load the environment env = load_isaacgym_env_preview3(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview3")' # [pytorch-end-isaacgym-preview3] # [jax-start-isaacgym-preview3] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_isaacgym_env_preview3 # load the environment env = load_isaacgym_env_preview3(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview3")' # [jax-end-isaacgym-preview3] # [pytorch-start-isaacgym-preview2] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_isaacgym_env_preview2 # load the environment env = load_isaacgym_env_preview2(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview2")' # [pytorch-end-isaacgym-preview2] # [jax-start-isaacgym-preview2] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_isaacgym_env_preview2 # load the environment env = load_isaacgym_env_preview2(task_name="Cartpole") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="isaacgym-preview2")' # [jax-end-isaacgym-preview2] # [pytorch-start-gym] # import the environment wrapper and gym from skrl.envs.wrappers.torch import wrap_env import gym # load the environment env = gym.make('Pendulum-v1') # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gym")' # [pytorch-end-gym] # [jax-start-gym] # import the environment wrapper and gym from skrl.envs.wrappers.jax import wrap_env import gym # load the environment env = gym.make('Pendulum-v1') # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gym")' # [jax-end-gym] # [pytorch-start-gym-vectorized] # import the environment wrapper and gym from skrl.envs.wrappers.torch import wrap_env import gym # load a vectorized environment env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gym")' # [pytorch-end-gym-vectorized] # [jax-start-gym-vectorized] # import the environment wrapper and gym from skrl.envs.wrappers.jax import wrap_env import gym # load a vectorized environment env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gym")' # [jax-end-gym-vectorized] # [pytorch-start-gymnasium] # import the environment wrapper and gymnasium from skrl.envs.wrappers.torch import wrap_env import gymnasium as gym # load the environment env = gym.make('Pendulum-v1') # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [pytorch-end-gymnasium] # [jax-start-gymnasium] # import the environment wrapper and gymnasium from skrl.envs.wrappers.jax import wrap_env import gymnasium as gym # load the environment env = gym.make('Pendulum-v1') # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [jax-end-gymnasium] # [pytorch-start-gymnasium-vectorized] # import the environment wrapper and gymnasium from skrl.envs.wrappers.torch import wrap_env import gymnasium as gym # load a vectorized environment env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [pytorch-end-gymnasium-vectorized] # [jax-start-gymnasium-vectorized] # import the environment wrapper and gymnasium from skrl.envs.wrappers.jax import wrap_env import gymnasium as gym # load a vectorized environment env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [jax-end-gymnasium-vectorized] # [pytorch-start-shimmy] # import the environment wrapper and gymnasium from skrl.envs.wrappers.torch import wrap_env import gymnasium as gym # load the environment (API conversion) env = gym.make("ALE/Pong-v5") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [pytorch-end-shimmy] # [jax-start-shimmy] # import the environment wrapper and gymnasium from skrl.envs.wrappers.jax import wrap_env import gymnasium as gym # load the environment (API conversion) env = gym.make("ALE/Pong-v5") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="gymnasium")' # [jax-end-shimmy] # [pytorch-start-deepmind] # import the environment wrapper and the deepmind suite from skrl.envs.wrappers.torch import wrap_env from dm_control import suite # load the environment env = suite.load(domain_name="cartpole", task_name="swingup") # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="dm")' # [pytorch-end-deepmind] # [pytorch-start-robosuite] # import the environment wrapper from skrl.envs.wrappers.torch import wrap_env # import the robosuite wrapper import robosuite from robosuite.controllers import load_controller_config # load the environment controller_config = load_controller_config(default_controller="OSC_POSE") env = robosuite.make("TwoArmLift", robots=["Sawyer", "Panda"], # load a Sawyer robot and a Panda robot gripper_types="default", # use default grippers per robot arm controller_configs=controller_config, # each arm is controlled using OSC env_configuration="single-arm-opposed", # (two-arm envs only) arms face each other has_renderer=True, # on-screen rendering render_camera="frontview", # visualize the "frontview" camera has_offscreen_renderer=False, # no off-screen rendering control_freq=20, # 20 hz control for applied actions horizon=200, # each episode terminates after 200 steps use_object_obs=True, # provide object observations to agent use_camera_obs=False, # don't provide image observations to agent reward_shaping=True) # use a dense reward signal for learning # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="robosuite")' # [pytorch-end-robosuite] # [start-bidexhands-torch] # import the environment wrapper and loader from skrl.envs.wrappers.torch import wrap_env from skrl.envs.loaders.torch import load_bidexhands_env # load the environment env = load_bidexhands_env(task_name="ShadowHandOver") # wrap the environment env = wrap_env(env, wrapper="bidexhands") # [end-bidexhands-torch] # [start-bidexhands-jax] # import the environment wrapper and loader from skrl.envs.wrappers.jax import wrap_env from skrl.envs.loaders.jax import load_bidexhands_env # load the environment env = load_bidexhands_env(task_name="ShadowHandOver") # wrap the environment env = wrap_env(env, wrapper="bidexhands") # [end-bidexhands-jax] # [start-pettingzoo-torch] # import the environment wrapper from skrl.envs.wrappers.torch import wrap_env # import a PettingZoo environment from pettingzoo.sisl import multiwalker_v9 # load the environment env = multiwalker_v9.parallel_env() # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="pettingzoo")' # [end-pettingzoo-torch] # [start-pettingzoo-jax] # import the environment wrapper from skrl.envs.wrappers.jax import wrap_env # import a PettingZoo environment from pettingzoo.sisl import multiwalker_v9 # load the environment env = multiwalker_v9.parallel_env() # wrap the environment env = wrap_env(env) # or 'env = wrap_env(env, wrapper="pettingzoo")' # [end-pettingzoo-jax]
12,845
Python
29.440758
104
0.712028
Toni-SM/skrl/docs/source/snippets/trainer.py
# [pytorch-start-base] from typing import Union, List, Optional import copy from skrl.envs.wrappers.torch import Wrapper from skrl.agents.torch import Agent from skrl.trainers.torch import Trainer CUSTOM_DEFAULT_CONFIG = { "timesteps": 100000, # number of timesteps to train for "headless": False, # whether to use headless mode (no rendering) "disable_progressbar": False, # whether to disable the progressbar. If None, disable on non-TTY "close_environment_at_exit": True, # whether to close the environment on normal program termination } class CustomTrainer(Trainer): def __init__(self, env: Wrapper, agents: Union[Agent, List[Agent], List[List[Agent]]], agents_scope: Optional[List[int]] = None, cfg: Optional[dict] = None) -> None: """ :param env: Environment to train on :type env: skrl.envs.wrappers.torch.Wrapper :param agents: Agents to train :type agents: Union[Agent, List[Agent]] :param agents_scope: Number of environments for each agent to train on (default: []) :type agents_scope: tuple or list of integers :param cfg: Configuration dictionary :type cfg: dict, optional """ _cfg = copy.deepcopy(CUSTOM_DEFAULT_CONFIG) _cfg.update(cfg if cfg is not None else {}) agents_scope = agents_scope if agents_scope is not None else [] super().__init__(env=env, agents=agents, agents_scope=agents_scope, cfg=_cfg) # ================================ # - init agents # ================================ def train(self) -> None: """Train the agents """ # ================================ # - run training loop # + call agents.pre_interaction(...) # + compute actions using agents.act(...) # + step environment using env.step(...) # + render scene using env.render(...) # + record environment transition in memory using agents.record_transition(...) # + call agents.post_interaction(...) # + reset environment using env.reset(...) # ================================ def eval(self) -> None: """Evaluate the agents """ # ================================ # - run evaluation loop # + compute actions using agents.act(...) # + step environment using env.step(...) # + render scene using env.render(...) # + call agents.post_interaction(...) parent method to write data to TensorBoard # + reset environment using env.reset(...) # ================================ # [pytorch-end-base] # [jax-start-base] from typing import Union, List, Optional import copy from skrl.envs.wrappers.jax import Wrapper from skrl.agents.jax import Agent from skrl.trainers.jax import Trainer CUSTOM_DEFAULT_CONFIG = { "timesteps": 100000, # number of timesteps to train for "headless": False, # whether to use headless mode (no rendering) "disable_progressbar": False, # whether to disable the progressbar. If None, disable on non-TTY "close_environment_at_exit": True, # whether to close the environment on normal program termination } class CustomTrainer(Trainer): def __init__(self, env: Wrapper, agents: Union[Agent, List[Agent], List[List[Agent]]], agents_scope: Optional[List[int]] = None, cfg: Optional[dict] = None) -> None: """ :param env: Environment to train on :type env: skrl.envs.wrappers.jax.Wrapper :param agents: Agents to train :type agents: Union[Agent, List[Agent]] :param agents_scope: Number of environments for each agent to train on (default: []) :type agents_scope: tuple or list of integers :param cfg: Configuration dictionary :type cfg: dict, optional """ _cfg = copy.deepcopy(CUSTOM_DEFAULT_CONFIG) _cfg.update(cfg if cfg is not None else {}) agents_scope = agents_scope if agents_scope is not None else [] super().__init__(env=env, agents=agents, agents_scope=agents_scope, cfg=_cfg) # ================================ # - init agents # ================================ def train(self) -> None: """Train the agents """ # ================================ # - run training loop # + call agents.pre_interaction(...) # + compute actions using agents.act(...) # + step environment using env.step(...) # + render scene using env.render(...) # + record environment transition in memory using agents.record_transition(...) # + call agents.post_interaction(...) # + reset environment using env.reset(...) # ================================ def eval(self) -> None: """Evaluate the agents """ # ================================ # - run evaluation loop # + compute actions using agents.act(...) # + step environment using env.step(...) # + render scene using env.render(...) # + call agents.post_interaction(...) parent method to write data to TensorBoard # + reset environment using env.reset(...) # ================================ # [jax-end-base] # ============================================================================= # [pytorch-start-sequential] from skrl.trainers.torch import SequentialTrainer # assuming there is an environment called 'env' # and an agent or a list of agents called 'agents' # create a sequential trainer cfg = {"timesteps": 50000, "headless": False} trainer = SequentialTrainer(env=env, agents=agents, cfg=cfg) # train the agent(s) trainer.train() # evaluate the agent(s) trainer.eval() # [pytorch-end-sequential] # [jax-start-sequential] from skrl.trainers.jax import SequentialTrainer # assuming there is an environment called 'env' # and an agent or a list of agents called 'agents' # create a sequential trainer cfg = {"timesteps": 50000, "headless": False} trainer = SequentialTrainer(env=env, agents=agents, cfg=cfg) # train the agent(s) trainer.train() # evaluate the agent(s) trainer.eval() # [jax-end-sequential] # ============================================================================= # [pytorch-start-parallel] from skrl.trainers.torch import ParallelTrainer # assuming there is an environment called 'env' # and an agent or a list of agents called 'agents' # create a sequential trainer cfg = {"timesteps": 50000, "headless": False} trainer = ParallelTrainer(env=env, agents=agents, cfg=cfg) # train the agent(s) trainer.train() # evaluate the agent(s) trainer.eval() # [pytorch-end-parallel] # ============================================================================= # [pytorch-start-step] from skrl.trainers.torch import StepTrainer # assuming there is an environment called 'env' # and an agent or a list of agents called 'agents' # create a sequential trainer cfg = {"timesteps": 50000, "headless": False} trainer = StepTrainer(env=env, agents=agents, cfg=cfg) # train the agent(s) for timestep in range(cfg["timesteps"]): trainer.train(timestep=timestep) # evaluate the agent(s) for timestep in range(cfg["timesteps"]): trainer.eval(timestep=timestep) # [pytorch-end-step] # [jax-start-step] from skrl.trainers.jax import StepTrainer # assuming there is an environment called 'env' # and an agent or a list of agents called 'agents' # create a sequential trainer cfg = {"timesteps": 50000, "headless": False} trainer = StepTrainer(env=env, agents=agents, cfg=cfg) # train the agent(s) for timestep in range(cfg["timesteps"]): trainer.train(timestep=timestep) # evaluate the agent(s) for timestep in range(cfg["timesteps"]): trainer.eval(timestep=timestep) # [jax-end-step] # ============================================================================= # [pytorch-start-manual-training] # [pytorch-end-manual-training] # [pytorch-start-manual-evaluation] # assuming there is an environment named 'env' # and an agent named 'agents' (or a state-preprocessor and a policy) states, infos = env.reset() for i in range(1000): # state-preprocessor + policy with torch.no_grad(): states = state_preprocessor(states) actions = policy.act({"states": states})[0] # step the environment next_states, rewards, terminated, truncated, infos = env.step(actions) # render the environment env.render() # check for termination/truncation if terminated.any() or truncated.any(): states, infos = env.reset() else: states = next_states # [pytorch-end-manual-evaluation] # [jax-start-manual-training] # [jax-end-manual-training] # [jax-start-manual-evaluation] # [jax-end-manual-evaluation]
8,996
Python
31.132143
105
0.587372
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/__init__.py
from .scripts.extension import *
32
Python
31.999968
32
0.8125
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/scripts/extension.py
import __future__ import os import sys import jedi import json import glob import socket import asyncio import traceback import subprocess import contextlib from io import StringIO from dis import COMPILER_FLAG_NAMES try: from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT except ImportError: PyCF_ALLOW_TOP_LEVEL_AWAIT = 0 import carb import omni.ext def _get_coroutine_flag() -> int: """Get the coroutine flag for the current Python version """ for k, v in COMPILER_FLAG_NAMES.items(): if v == "COROUTINE": return k return -1 COROUTINE_FLAG = _get_coroutine_flag() def _has_coroutine_flag(code) -> bool: """Check if the code has the coroutine flag set """ if COROUTINE_FLAG == -1: return False return bool(code.co_flags & COROUTINE_FLAG) def _get_compiler_flags() -> int: """Get the compiler flags for the current Python version """ flags = 0 for value in globals().values(): try: if isinstance(value, __future__._Feature): f = value.compiler_flag flags |= f except BaseException: pass flags = flags | PyCF_ALLOW_TOP_LEVEL_AWAIT return flags def _get_event_loop() -> asyncio.AbstractEventLoop: """Backward compatible function for getting the event loop """ try: if sys.version_info >= (3, 7): return asyncio.get_running_loop() else: return asyncio.get_event_loop() except RuntimeError: return asyncio.get_event_loop_policy().get_event_loop() class Extension(omni.ext.IExt): WINDOW_NAME = "Embedded Jupyter Notebook" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self, ext_id): self._globals = {**globals()} self._locals = self._globals self._server = None self._process = None self._settings = carb.settings.get_settings() self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) sys.path.append(os.path.join(self._extension_path, "data", "provisioners")) # get extension settings self._token = self._settings.get("/exts/semu.misc.jupyter_notebook/token") self._notebook_ip = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_ip") self._notebook_port = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_port") self._notebook_dir = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_dir") self._command_line_options = self._settings.get("/exts/semu.misc.jupyter_notebook/command_line_options") self._classic_notebook_interface = self._settings.get("/exts/semu.misc.jupyter_notebook/classic_notebook_interface") self._socket_port = self._settings.get("/exts/semu.misc.jupyter_notebook/socket_port") kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.jupyter_notebook/kill_processes_with_port_in_use") # menu item self._editor_menu = omni.kit.ui.get_editor_menu() if self._editor_menu: self._menu = self._editor_menu.add_item(Extension.MENU_PATH, self._show_notification, toggle=False, value=False) # shutdown stream self.shutdown_stream_event = omni.kit.app.get_app().get_shutdown_event_stream() \ .create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.jupyter_notebook", order=0) # ensure port is free if kill_processes_with_port_in_use: # windows if sys.platform == "win32": pids = [] cmd = ["netstat", "-ano"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line: if "listening".encode() in line.lower(): carb.log_info(f"Open port: {line.strip().decode()}") pids.append(line.strip().split(b" ")[-1].decode()) p.wait() for pid in pids: if not pid.isnumeric(): continue carb.log_warn(f"Forced process shutdown with PID {pid}") cmd = ["taskkill", "/PID", pid, "/F"] subprocess.Popen(cmd).wait() # linux elif sys.platform == "linux": pids = [] cmd = ["netstat", "-ltnup"] try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line: carb.log_info(f"Open port: {line.strip().decode()}") pids.append([chunk for chunk in line.strip().split(b" ") if b'/' in chunk][-1].decode().split("/")[0]) p.wait() except FileNotFoundError as e: carb.log_warn(f"Command (netstat) not available. Install it using `apt install net-tools`") for pid in pids: if not pid.isnumeric(): continue carb.log_warn(f"Forced process shutdown with PID {pid}") cmd = ["kill", "-9", pid] subprocess.Popen(cmd).wait() # create socket self._create_socket() # run jupyter notebook in a separate process self._launch_jupyter_process() # jedi (autocompletion) # application root path app_folder = carb.settings.get_settings().get_as_string("/app/folder") if not app_folder: app_folder = carb.tokens.get_tokens_interface().resolve("${app}") path = os.path.normpath(os.path.join(app_folder, os.pardir)) # get extension paths folders = [ "exts", "extscache", os.path.join("kit", "extensions"), os.path.join("kit", "exts"), os.path.join("kit", "extsPhysics"), os.path.join("kit", "extscore"), ] added_sys_path = [] for folder in folders: sys_paths = glob.glob(os.path.join(path, folder, "*")) for sys_path in sys_paths: if os.path.isdir(sys_path): added_sys_path.append(sys_path) # python environment python_exe = "python.exe" if sys.platform == "win32" else "bin/python3" environment_path = os.path.join(path, "kit", "python", python_exe) # jedi project carb.log_info("Autocompletion: jedi.Project") carb.log_info(f" |-- path: {path}") carb.log_info(f" |-- added_sys_path: {len(added_sys_path)} items") carb.log_info(f" |-- environment_path: {environment_path}") self._jedi_project = jedi.Project(path=path, environment_path=environment_path, added_sys_path=added_sys_path, load_unsafe_extensions=False) def on_shutdown(self): # clean extension paths from sys.path if self._extension_path is not None: sys.path.remove(os.path.join(self._extension_path, "data", "provisioners")) self._extension_path = None # clean up menu item if self._menu is not None: self._editor_menu.remove_item(self._menu) self._menu = None # close the socket if self._server: self._server.close() _get_event_loop().run_until_complete(self._server.wait_closed()) # close the jupyter notebook (external process) if self._process is not None: process_pid = self._process.pid try: self._process.terminate() # .kill() except OSError as e: if sys.platform == 'win32': if e.winerror != 5: raise else: from errno import ESRCH if not isinstance(e, ProcessLookupError) or e.errno != ESRCH: raise # make sure the process is not running anymore in Windows if sys.platform == 'win32': subprocess.call(['taskkill', '/F', '/T', '/PID', str(process_pid)]) # wait for the process to terminate self._process.wait() self._process = None # extension ui methods def _on_shutdown_event(self, event): if event.type == omni.kit.app.POST_QUIT_EVENT_TYPE: self.on_shutdown() def _show_notification(self, *args, **kwargs) -> None: """Show a Jupyter Notebook URL in the notification area """ display_url = "" if self._process is not None: notebook_txt = os.path.join(self._extension_path, "data", "launchers", "notebook.txt") if os.path.exists(notebook_txt): with open(notebook_txt, "r") as f: display_url = f.read() if display_url: notification = "Jupyter Notebook is running at:\n\n - " + display_url.replace(" or ", " - ") status=omni.kit.notification_manager.NotificationStatus.INFO else: notification = "Unable to identify Jupyter Notebook URL" status=omni.kit.notification_manager.NotificationStatus.WARNING ok_button = omni.kit.notification_manager.NotificationButtonInfo("OK", on_complete=None) omni.kit.notification_manager.post_notification(notification, hide_after_timeout=False, duration=0, status=status, button_infos=[ok_button]) print(notification) carb.log_info(notification) # internal socket methods def _create_socket(self) -> None: """Create a socket server to listen for incoming connections from the IPython kernel """ socket_txt = os.path.join(self._extension_path, "data", "launchers", "socket.txt") # delete socket.txt file if os.path.exists(socket_txt): os.remove(socket_txt) class ServerProtocol(asyncio.Protocol): def __init__(self, parent) -> None: super().__init__() self._parent = parent def connection_made(self, transport): peername = transport.get_extra_info('peername') carb.log_info('Connection from {}'.format(peername)) self.transport = transport def data_received(self, data): code = data.decode() # completion if code[:3] == "%!c": code = code[3:] asyncio.run_coroutine_threadsafe(self._parent._complete_code_async(code, self.transport), _get_event_loop()) # introspection elif code[:3] == "%!i": code = code[3:] pos = code.find('%') line, column = [int(i) for i in code[:pos].split(':')] code = code[pos + 1:] asyncio.run_coroutine_threadsafe(self._parent._introspect_code_async(code, line, column, self.transport), _get_event_loop()) # execution else: asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(code, self.transport), _get_event_loop()) async def server_task(): self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self), host="127.0.0.1", port=self._socket_port, family=socket.AF_INET, reuse_port=None if sys.platform == 'win32' else True) await self._server.start_serving() task = _get_event_loop().create_task(server_task()) # write the socket port to socket.txt file carb.log_info("Internal socket server is running at port {}".format(self._socket_port)) with open(socket_txt, "w") as f: f.write(str(self._socket_port)) async def _complete_code_async(self, statement: str, transport: asyncio.Transport) -> None: """Complete objects under the cursor and send the result to the IPython kernel :param statement: statement to complete :type statement: str :param transport: transport to send the result to the IPython kernel :type transport: asyncio.Transport :return: reply dictionary :rtype: dict """ # generate completions script = jedi.Script(statement, project=self._jedi_project) completions = script.complete() delta = completions[0].get_completion_prefix_length() if completions else 0 reply = {"matches": [c.name for c in completions], "delta": delta} # send the reply to the IPython kernel reply = json.dumps(reply) transport.write(reply.encode()) # close the connection transport.close() async def _introspect_code_async(self, statement: str, line: int, column: int, transport: asyncio.Transport) -> None: """Introspect code under the cursor and send the result to the IPython kernel :param statement: statement to introspect :type statement: str :param line: the line where the definition occurs :type line: int :param column: the column where the definition occurs :type column: int :param transport: transport to send the result to the IPython kernel :type transport: asyncio.Transport :return: reply dictionary :rtype: dict """ # generate introspection script = jedi.Script(statement, project=self._jedi_project) definitions = script.infer(line=line, column=column) reply = {"found": False, "data": "TODO"} if len(definitions): reply["found"] = True reply["data"] = definitions[0].docstring() # send the reply to the IPython kernel reply = json.dumps(reply) transport.write(reply.encode()) # close the connection transport.close() async def _exec_code_async(self, statement: str, transport: asyncio.Transport) -> None: """Execute the statement in the Omniverse scope and send the result to the IPython kernel :param statement: statement to execute :type statement: str :param transport: transport to send the result to the IPython kernel :type transport: asyncio.Transport :return: reply dictionary :rtype: dict """ _stdout = StringIO() try: with contextlib.redirect_stdout(_stdout): should_exec_code = True # try 'eval' first try: code = compile(statement, "<string>", "eval", flags= _get_compiler_flags(), dont_inherit=True) except SyntaxError: pass else: result = eval(code, self._globals, self._locals) should_exec_code = False # if 'eval' fails, try 'exec' if should_exec_code: code = compile(statement, "<string>", "exec", flags= _get_compiler_flags(), dont_inherit=True) result = eval(code, self._globals, self._locals) # await the result if it is a coroutine if _has_coroutine_flag(code): result = await result except Exception as e: # clean traceback _traceback = traceback.format_exc() _i = _traceback.find('\n File "<string>"') if _i != -1: _traceback = _traceback[_i + 20:] _traceback = _traceback.replace(", in <module>\n", "\n") # build reply dictionary reply = {"status": "error", "traceback": [_traceback], "ename": str(type(e).__name__), "evalue": str(e)} else: reply = {"status": "ok"} # add output to reply dictionary for printing reply["output"] = _stdout.getvalue() # send the reply to the IPython kernel reply = json.dumps(reply) transport.write(reply.encode()) # close the connection transport.close() # launch Jupyter Notebook methods def _launch_jupyter_process(self) -> None: """Launch the Jupyter notebook in a separate process """ # get packages path paths = [p for p in sys.path if "pip3-envs" in p] packages_txt = os.path.join(self._extension_path, "data", "launchers", "packages.txt") with open(packages_txt, "w") as f: f.write("\n".join(paths)) if sys.platform == 'win32': executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe")) else: executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3")) cmd = [executable_path, os.path.join(self._extension_path, "data", "launchers", "jupyter_launcher.py"), self._notebook_ip, str(self._notebook_port), self._token, str(self._classic_notebook_interface), self._notebook_dir, self._command_line_options] carb.log_info("Starting Jupyter server in separate process") carb.log_info(" |-- command: " + " ".join(cmd)) try: self._process = subprocess.Popen(cmd, cwd=os.path.join(self._extension_path, "data", "launchers")) except Exception as e: carb.log_error("Error starting Jupyter server: {}".format(e)) self._process = None
18,476
Python
40.521348
144
0.546872
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/jupyter_launcher.py
from typing import List import os import sys PACKAGES_PATH = [] SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) # add packages to sys.path with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f: for p in f.readlines(): p = p.strip() if p: PACKAGES_PATH.append(p) if p not in sys.path: print("Adding package to sys.path: {}".format(p)) sys.path.append(p) # add provisioners to sys.path sys.path.append(os.path.abspath(os.path.join(SCRIPT_DIR, "..", "provisioners"))) from jupyter_client.kernelspec import KernelSpecManager as _KernelSpecManager class KernelSpecManager(_KernelSpecManager): def __init__(self, *args, **kwargs): """Custom kernel spec manager to allow for loading of custom kernels """ super().__init__(*args, **kwargs) kernel_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "kernels")) if kernel_dir not in self.kernel_dirs: self.kernel_dirs.append(kernel_dir) def main(ip: str = "0.0.0.0", port: int = 8225, argv: List[str] = [], classic_notebook_interface: bool = False) -> None: """Entry point for launching Juptyter Notebook/Lab :param ip: Notebook server IP address (default: "0.0.0.0") :type code: str, optional :param port: Notebook server port number (default: 8225) :type code: int, optional :param argv: Command line arguments to pass to Jupyter Notebook/Lab (default: []) :type code: List of strings, optional :param classic_notebook_interface: Whether to use the classic notebook interface (default: False) If false, the Juptyter Lab interface will be used :type code: bool, optional """ # jupyter notebook if classic_notebook_interface: from notebook.notebookapp import NotebookApp app = NotebookApp(ip=ip, port=port, kernel_spec_manager_class=KernelSpecManager) app.initialize(argv=argv) # jupyter lab else: from jupyterlab.labapp import LabApp from jupyter_server.serverapp import ServerApp jpserver_extensions = {LabApp.get_extension_package(): True} find_extensions = LabApp.load_other_extensions if "jpserver_extensions" in LabApp.serverapp_config: jpserver_extensions.update(LabApp.serverapp_config["jpserver_extensions"]) LabApp.serverapp_config["jpserver_extensions"] = jpserver_extensions find_extensions = False app = ServerApp.instance(ip=ip, port=port, kernel_spec_manager_class=KernelSpecManager, jpserver_extensions=jpserver_extensions) app.aliases.update(LabApp.aliases) app.initialize(argv=argv, starter_extension=LabApp.name, find_extensions=find_extensions) # write url to file in script directory with open(os.path.join(SCRIPT_DIR, "notebook.txt"), "w") as f: f.write(app.display_url) app.start() if __name__ == "__main__": argv = sys.argv[1:] # testing the launcher if not len(argv): print("Testing the launcher") argv = ['0.0.0.0', # ip '8888', # port '', # token 'False', # classic_notebook_interface '', # notebook_dir '--allow-root --no-browser'] # extra arguments # get function arguments ip = argv[0] port = int(argv[1]) token = argv[2] classic_notebook_interface = argv[3] == "True" # buld notebook_dir if not argv[4]: notebook_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "notebooks")) notebook_dir = "--notebook-dir={}".format(notebook_dir) # build token if classic_notebook_interface: token = "--NotebookApp.token={}".format(token) else: token = "--ServerApp.token={}".format(token) # assets path app_dir = [] if not classic_notebook_interface: for p in PACKAGES_PATH: print("Checking package to app_dir: {}".format(p)) if os.path.exists(os.path.join(p, "share", "jupyter", "lab")): app_dir = ["--app-dir={}".format(os.path.join(p, "share", "jupyter", "lab"))] if os.path.exists(os.path.join(p, "jupyterlab", "static")): app_dir = ["--app-dir={}".format(os.path.join(p, "jupyterlab"))] if app_dir: break print("app_dir: {}".format(app_dir)) # clean up the argv argv = app_dir + [token] + [notebook_dir] + argv[5].split(" ") # run the launcher print("Starting Jupyter {} at {}:{}".format("Notebook" if classic_notebook_interface else "Lab", ip, port)) print(" with argv: {}".format(" ".join(argv))) main(ip=ip, port=port, argv=argv, classic_notebook_interface=classic_notebook_interface) # delete notebook.txt try: os.remove(os.path.join(SCRIPT_DIR, "notebook.txt")) except: pass
5,168
Python
33.925675
120
0.585526
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/ipykernel_launcher.py
import os import sys import json import socket import asyncio SOCKET_HOST = "127.0.0.1" SOCKET_PORT = 8224 PACKAGES_PATH = [] SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) # add packages to sys.path with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f: for p in f.readlines(): p = p.strip() if p: PACKAGES_PATH.append(p) if p not in sys.path: print("Adding package to sys.path: {}".format(p)) sys.path.append(p) from ipykernel.kernelbase import Kernel from ipykernel.kernelapp import IPKernelApp async def _send_and_recv(message): reader, writer = await asyncio.open_connection(host=SOCKET_HOST, port=SOCKET_PORT, family=socket.AF_INET) writer.write(message.encode()) await writer.drain() data = await reader.read() writer.close() await writer.wait_closed() return data.decode() def _get_line_column(code, cursor_pos): line = code.count('\n', 0, cursor_pos) + 1 last_newline_pos = code.rfind('\n', 0, cursor_pos) column = cursor_pos - last_newline_pos - 1 return line, column class EmbeddedKernel(Kernel): """Omniverse Kit Python wrapper kernels It re-use the IPython's kernel machinery https://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html """ # kernel info: https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info implementation = "Omniverse Kit (Python 3)" implementation_version = "0.1.0" language_info = { "name": "python", "version": "3.7", # TODO: get from Omniverse Kit "mimetype": "text/x-python", "file_extension": ".py", } banner = "Embedded Omniverse (Python 3)" help_links = [{"text": "semu.misc.jupyter_notebook", "url": "https://github.com/Toni-SM/semu.misc.jupyter_notebook"}] async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): """Execute user code """ # https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute execute_reply = {"status": "ok", "execution_count": self.execution_count, "payload": [], "user_expressions": {}} # no code if not code.strip(): return execute_reply # magic commands if code.startswith('%'): # TODO: process magic commands pass # python code try: data = await _send_and_recv(code) reply_content = json.loads(data) except Exception as e: # show network error in client print("\x1b[0;31m==================================================\x1b[0m") print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT)) print(e) print("\x1b[0;31m==================================================\x1b[0m") reply_content = {"status": "error", "output": "", "traceback": [], "ename": str(type(e).__name__), "evalue": str(e)} # code execution stdout: {"status": str, "output": str} if not silent: if reply_content["output"]: stream_content = {"name": "stdout", "text": reply_content["output"]} self.send_response(self.iopub_socket, "stream", stream_content) reply_content.pop("output", None) # code execution error: {"status": str("error"), "output": str, "traceback": list(str), "ename": str, "evalue": str} if reply_content["status"] == "error": self.send_response(self.iopub_socket, "error", reply_content) # update reply execute_reply["status"] = reply_content["status"] execute_reply["execution_count"] = self.execution_count, # the base class increments the execution count return execute_reply def do_debug_request(self, msg): return {} async def do_complete(self, code, cursor_pos): """Code completation """ # https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-completion complete_reply = {"status": "ok", "matches": [], "cursor_start": 0, "cursor_end": cursor_pos, "metadata": {}} # parse code code = code[:cursor_pos] if not code or code[-1] in [' ', '=', ':', '(', ')']: return complete_reply # generate completions try: data = await _send_and_recv("%!c" + code) reply_content = json.loads(data) except Exception as e: # show network error in client print("\x1b[0;31m==================================================\x1b[0m") print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT)) print(e) print("\x1b[0;31m==================================================\x1b[0m") reply_content = {"matches": [], "delta": cursor_pos} # update replay: {"matches": list(str), "delta": int} complete_reply["matches"] = reply_content["matches"] complete_reply["cursor_start"] = cursor_pos - reply_content["delta"] return complete_reply async def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()): """Object introspection """ # https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-inspection inspect_reply = {"status": "ok", "found": False, "data": {}, "metadata": {}} line, column = _get_line_column(code, cursor_pos) # generate introspection try: data = await _send_and_recv(f"%!i{line}:{column}%" + code) reply_content = json.loads(data) except Exception as e: # show network error in client print("\x1b[0;31m==================================================\x1b[0m") print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT)) print(e) print("\x1b[0;31m==================================================\x1b[0m") reply_content = {"found": False, "data": cursor_pos} # update replay: {"found": bool, "data": str} if reply_content["found"]: inspect_reply["found"] = reply_content["found"] inspect_reply["data"] = {"text/plain": reply_content["data"]} return inspect_reply if __name__ == "__main__": if sys.path[0] == "": del sys.path[0] # read socket port from file if os.path.exists(os.path.join(SCRIPT_DIR, "socket.txt")): with open(os.path.join(SCRIPT_DIR, "socket.txt"), "r") as f: SOCKET_PORT = int(f.read()) IPKernelApp.launch_instance(kernel_class=EmbeddedKernel)
7,057
Python
36.743315
128
0.530679
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3/provisioner_socket.py
from typing import Any, List import os import sys from jupyter_client.provisioning import LocalProvisioner from jupyter_client.connect import KernelConnectionInfo from jupyter_client.launcher import launch_kernel class Provisioner(LocalProvisioner): async def launch_kernel(self, cmd: List[str], **kwargs: Any) -> KernelConnectionInfo: # set paths if sys.platform == 'win32': cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe")) else: cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3")) cmd[1] = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "launchers", "ipykernel_launcher.py")) self.log.info("Launching kernel: %s", " ".join(cmd)) scrubbed_kwargs = LocalProvisioner._scrub_kwargs(kwargs) self.process = launch_kernel(cmd, **scrubbed_kwargs) pgid = None if hasattr(os, "getpgid"): try: pgid = os.getpgid(self.process.pid) except OSError: pass self.pid = self.process.pid self.pgid = pgid return self.connection_info
1,210
Python
34.617646
123
0.61405
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/compile_extension.py
import os import sys from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext # OV python (kit\python\include) if sys.platform == 'win32': python_library_dir = os.path.join(os.path.dirname(sys.executable), "include") elif sys.platform == 'linux': python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include") if not os.path.exists(python_library_dir): raise Exception("OV Python library directory not found: {}".format(python_library_dir)) ext_modules = [ Extension("_visualizer", [os.path.join("semu", "data", "visualizer", "visualizer.py")], library_dirs=[python_library_dir]), ] setup( name = 'semu.data.visualizer', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
825
Python
28.499999
91
0.682424
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/visualizer.py
import os import sys import carb import omni import omni.ui as ui try: import numpy as np except ImportError: print("numpy not found. Attempting to install...") omni.kit.pipapi.install("numpy") import numpy as np try: import matplotlib except ImportError: print("matplotlib not found. Attempting to install...") omni.kit.pipapi.install("matplotlib") import matplotlib try: import cv2 except ImportError: print("opencv-python not found. Attempting to install...") omni.kit.pipapi.install("opencv-python") import cv2 from matplotlib.figure import Figure from matplotlib.backend_bases import FigureManagerBase from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib._pylab_helpers import Gcf def acquire_visualizer_interface(ext_id: str = "") -> dict: """Acquire the visualizer interface :param ext_id: The extension id :type ext_id: str :returns: The interface :rtype: dict """ global _opencv_windows # add current path to sys.path to import the backend path = os.path.dirname(__file__) if path not in sys.path: sys.path.append(path) # get matplotlib backend matplotlib_backend = matplotlib.get_backend() if type(matplotlib_backend) is str: if matplotlib_backend.lower() == "agg": matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg") else: matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg") interface = {"matplotlib_backend": matplotlib_backend, "opencv_imshow": cv2.imshow, "opencv_waitKey": cv2.waitKey} # set custom matplotlib backend if os.path.basename(__file__).startswith("_visualizer"): matplotlib.use("module://_visualizer") else: print(">>>> [DEVELOPMENT] module://visualizer") matplotlib.use("module://visualizer") # set custom opencv methods _opencv_windows = {} cv2.imshow = _imshow cv2.waitKey = _waitKey return interface def release_visualizer_interface(interface: dict) -> None: """Release the visualizer interface :param interface: The interface to release :type interface: dict """ # restore default matplotlib backend try: matplotlib.use(interface.get("matplotlib_backend", \ carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg"))) except Exception as e: matplotlib.use("Agg") matplotlib.rcdefaults() # restore default opencv imshow try: cv2.imshow = interface.get("opencv_imshow", None) cv2.waitKey = interface.get("opencv_waitKey", None) except Exception as e: pass # destroy all opencv windows for window in _opencv_windows.values(): window.destroy() _opencv_windows.clear() # remove current path from sys.path path = os.path.dirname(__file__) if path in sys.path: sys.path.remove(path) # opencv backend _opencv_windows = {} def _imshow(winname: str, mat: np.ndarray) -> None: """Show the image :param winname: The window name :type winname: str :param mat: The image :type mat: np.ndarray """ if winname not in _opencv_windows: _opencv_windows[winname] = FigureManager(None, winname) _opencv_windows[winname].render_image(mat) def _waitKey(delay: int = 0) -> int: """Wait for a key press on the canvas :param delay: The delay in milliseconds :type delay: int :returns: The key code :rtype: int """ return -1 # matplotlib backend def draw_if_interactive(): """ For image backends - is not required. For GUI backends - this should be overridden if drawing should be done in interactive python mode. """ pass def show(*, block: bool = None) -> None: """Show all figures and enter the main loop For image backends - is not required. For GUI backends - show() is usually the last line of a pyplot script and tells the backend that it is time to draw. In interactive mode, this should do nothing :param block: If not None, the call will block until the figure is closed :type block: bool """ for manager in Gcf.get_all_fig_managers(): manager.show(block=block) def new_figure_manager(num: int, *args, FigureClass: type = Figure, **kwargs) -> 'FigureManagerOmniUi': """Create a new figure manager instance :param num: The figure number :type num: int :param args: The arguments to be passed to the Figure constructor :type args: tuple :param FigureClass: The class to use for creating the figure :type FigureClass: type :param kwargs: The keyword arguments to be passed to the Figure constructor :type kwargs: dict :returns: The figure manager instance :rtype: FigureManagerOmniUi """ return new_figure_manager_given_figure(num, FigureClass(*args, **kwargs)) def new_figure_manager_given_figure(num: int, figure: 'Figure') -> 'FigureManagerOmniUi': """Create a new figure manager instance for the given figure. :param num: The figure number :type num: int :param figure: The figure :type figure: Figure :returns: The figure manager instance :rtype: FigureManagerOmniUi """ canvas = FigureCanvasAgg(figure) manager = FigureManagerOmniUi(canvas, num) return manager class FigureManagerOmniUi(FigureManagerBase): def __init__(self, canvas: 'FigureCanvasBase', num: int) -> None: """Figure manager for the Omni UI backend :param canvas: The canvas :type canvas: FigureCanvasBase :param num: The figure number :type num: int """ if canvas is not None: super().__init__(canvas, num) self._window_title = "Figure {}".format(num) if type(num) is int else num self._byte_provider = None self._window = None def destroy(self) -> None: """Destroy the figure window""" try: self._byte_provider = None self._window = None except: pass def set_window_title(self, title: str) -> None: """Set the window title :param title: The title :type title: str """ self._window_title = title try: self._window.title = title except: pass def get_window_title(self) -> str: """Get the window title :returns: The window title :rtype: str """ return self._window_title def resize(self, w: int, h: int) -> None: """Resize the window :param w: The width :type w: int :param h: The height :type h: int """ print("[WARNING] resize() is not implemented") def show(self, *, block: bool = None) -> None: """Show the figure window :param block: If not None, the call will block until the figure is closed :type block: bool """ # draw canvas and get figure self.canvas.draw() image = np.asarray(self.canvas.buffer_rgba()) # show figure self.render_image(image=image, figsize=(self.canvas.figure.get_figwidth(), self.canvas.figure.get_figheight()), dpi=self.canvas.figure.get_dpi()) def render_image(self, image: np.ndarray, figsize: tuple = (6.4, 4.8), dpi: int = 100) -> None: """Set and display the image in the window (inner function) :param image: The image :type image: np.ndarray :param figsize: The figure size :type figsize: tuple :param dpi: The dpi :type dpi: int """ height, width = image.shape[:2] # convert image to 4-channel RGBA if image.ndim == 2: image = np.dstack((image, image, image, np.full((height, width, 1), 255, dtype=np.uint8))) elif image.ndim == 3: if image.shape[2] == 3: image = np.dstack((image, np.full((height, width, 1), 255, dtype=np.uint8))) # enable the window visibility if self._window is not None and not self._window.visible: self._window.visible = True # create the byte provider if self._byte_provider is None: self._byte_provider = ui.ByteImageProvider() self._byte_provider.set_bytes_data(image.flatten().data, [width, height]) # update the byte provider else: self._byte_provider.set_bytes_data(image.flatten().data, [width, height]) # create the window if self._window is None: self._window = ui.Window(self._window_title, width=int(figsize[0] * dpi), height=int(figsize[1] * dpi), visible=True) with self._window.frame: with ui.VStack(): ui.ImageWithProvider(self._byte_provider) # provide the standard names that backend.__init__ is expecting FigureCanvas = FigureCanvasAgg FigureManager = FigureManagerOmniUi
9,315
Python
29.544262
129
0.619431
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/scripts/extension.py
import omni.ext try: from .. import _visualizer except: print(">>>> [DEVELOPMENT] import visualizer") from .. import visualizer as _visualizer class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._interface = _visualizer.acquire_visualizer_interface(ext_id) def on_shutdown(self): _visualizer.release_visualizer_interface(self._interface)
393
Python
23.624999
74
0.692112
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/test_visualizer.py
import omni.kit.test class TestExtension(omni.kit.test.AsyncTestCaseFailOnLogError): async def setUp(self) -> None: pass async def tearDown(self) -> None: pass async def test_extension(self): pass
235
Python
20.454544
63
0.659574
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/__init__.py
from .test_visualizer import *
31
Python
14.999993
30
0.774194
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ros_bridge.py
import omni import carb import rospy import rosgraph _ROS_NODE_RUNNING = False def acquire_ros_bridge_interface(ext_id: str = "") -> 'RosBridge': """Acquire the RosBridge interface :param ext_id: The extension id :type ext_id: str :returns: The RosBridge interface :rtype: RosBridge """ return RosBridge() def release_ros_bridge_interface(bridge: 'RosBridge') -> None: """Release the RosBridge interface :param bridge: The RosBridge interface :type bridge: RosBridge """ bridge.shutdown() def is_ros_master_running() -> bool: """Check if the ROS master is running :returns: True if the ROS master is running, False otherwise :rtype: bool """ # check ROS master try: rosgraph.Master("/rostopic").getPid() except: return False return True def is_ros_node_running() -> bool: """Check if the ROS node is running :returns: True if the ROS node is running, False otherwise :rtype: bool """ return _ROS_NODE_RUNNING class RosBridge: def __init__(self) -> None: """Initialize the RosBridge interface """ self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/nodeName") # omni objects and interfaces self._timeline = omni.timeline.get_timeline_interface() # events self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event) # ROS node if is_ros_master_running(): self._init_ros_node() def shutdown(self) -> None: """Shutdown the RosBridge interface """ self._timeline_event = None rospy.signal_shutdown("semu.robotics.ros_bridge shutdown") def _init_ros_node(self) -> None: global _ROS_NODE_RUNNING """Initialize the ROS node """ try: rospy.init_node(self._node_name, disable_signals=False) _ROS_NODE_RUNNING = True print("[Info][semu.robotics.ros_bridge] {} node started".format(self._node_name)) except rospy.ROSException as e: print("[Error][semu.robotics.ros_bridge] {}: {}".format(self._node_name, e)) def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the timeline event :param event: Event :type event: carb.events._events.IEvent """ if event.type == int(omni.timeline.TimelineEventType.PLAY): if is_ros_master_running(): self._init_ros_node() elif event.type == int(omni.timeline.TimelineEventType.PAUSE): pass elif event.type == int(omni.timeline.TimelineEventType.STOP): pass
2,777
Python
27.639175
125
0.613972
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ActionGripperCommand.py
import omni from pxr import PhysxSchema from omni.isaac.dynamic_control import _dynamic_control from omni.isaac.core.utils.stage import get_stage_units import rospy import actionlib import control_msgs.msg try: from ... import _ros_bridge except: from ... import ros_bridge as _ros_bridge class InternalState: def __init__(self): """Internal state for the ROS1 GripperCommand node """ self.initialized = False self.dci = None self.usd_context = None self.timeline_event = None self.action_server = None self.articulation_path = "" self.gripper_joints_paths = [] self._articulation = _dynamic_control.INVALID_HANDLE self._joints = {} self._action_goal = None self._action_goal_handle = None self._action_start_time = None # TODO: add to schema? self._action_timeout = 10.0 self._action_position_threshold = 0.001 self._action_previous_position_sum = float("inf") # feedback / result self._action_result_message = control_msgs.msg.GripperCommandResult() self._action_feedback_message = control_msgs.msg.GripperCommandFeedback() def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the timeline event :param event: Event :type event: carb.events._events.IEvent """ if event.type == int(omni.timeline.TimelineEventType.PLAY): pass elif event.type == int(omni.timeline.TimelineEventType.PAUSE): pass elif event.type == int(omni.timeline.TimelineEventType.STOP): self.initialized = False self.shutdown_action_server() self._articulation = _dynamic_control.INVALID_HANDLE self._joints = {} self._action_goal = None self._action_goal_handle = None self._action_start_time = None def shutdown_action_server(self) -> None: """Shutdown the action server """ # omni.isaac.ros_bridge/noetic/lib/python3/dist-packages/actionlib/action_server.py print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: destroying action server") if self.action_server: if self.action_server.started: self.action_server.started = False self.action_server.status_pub.unregister() self.action_server.result_pub.unregister() self.action_server.feedback_pub.unregister() self.action_server.goal_sub.unregister() self.action_server.cancel_sub.unregister() del self.action_server self.action_server = None def _init_articulation(self) -> None: """Initialize the articulation and register joints """ # get articulation path = self.articulation_path self._articulation = self.dci.get_articulation(path) if self._articulation == _dynamic_control.INVALID_HANDLE: print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} is not an articulation".format(path)) return dof_props = self.dci.get_articulation_dof_properties(self._articulation) if dof_props is None: return upper_limits = dof_props["upper"] lower_limits = dof_props["lower"] has_limits = dof_props["hasLimits"] # get joints for i in range(self.dci.get_articulation_dof_count(self._articulation)): dof_ptr = self.dci.get_articulation_dof(self._articulation, i) if dof_ptr != _dynamic_control.DofType.DOF_NONE: # add only required joints if self.dci.get_dof_path(dof_ptr) in self.gripper_joints_paths: dof_name = self.dci.get_dof_name(dof_ptr) if dof_name not in self._joints: _joint = self.dci.find_articulation_joint(self._articulation, dof_name) self._joints[dof_name] = {"joint": _joint, "type": self.dci.get_joint_type(_joint), "dof": self.dci.find_articulation_dof(self._articulation, dof_name), "lower": lower_limits[i], "upper": upper_limits[i], "has_limits": has_limits[i]} if not self._joints: print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: no joints found in {}".format(path)) self.initialized = False def _set_joint_position(self, name: str, target_position: float) -> None: """Set the target position of a joint in the articulation :param name: The joint name :type name: str :param target_position: The target position :type target_position: float """ # clip target position if self._joints[name]["has_limits"]: target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"]) # scale target position for prismatic joints if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: target_position /= get_stage_units() # set target position self.dci.set_dof_position_target(self._joints[name]["dof"], target_position) def _get_joint_position(self, name: str) -> float: """Get the current position of a joint in the articulation :param name: The joint name :type name: str :return: The current position of the joint :rtype: float """ position = self.dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: return position * get_stage_units() return position def on_goal(self, goal_handle: 'actionlib.ServerGoalHandle') -> None: """Callback function for handling new goal requests :param goal_handle: The goal handle :type goal_handle: actionlib.ServerGoalHandle """ goal = goal_handle.get_goal() # reject if there is an active goal if self._action_goal is not None: print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: multiple goals not supported") goal_handle.set_rejected() return # store goal data self._action_goal = goal self._action_goal_handle = goal_handle self._action_start_time = rospy.get_time() self._action_previous_position_sum = float("inf") goal_handle.set_accepted() def on_cancel(self, goal_handle: 'actionlib.ServerGoalHandle') -> None: """Callback function for handling cancel requests :param goal_handle: The goal handle :type goal_handle: actionlib.ServerGoalHandle """ if self._action_goal is None: goal_handle.set_rejected() return self._action_goal = None self._action_goal_handle = None self._action_start_time = None self._action_previous_position_sum = float("inf") goal_handle.set_canceled() def step(self, dt: float) -> None: """Update step :param dt: Delta time :type dt: float """ if not self.initialized: return # init articulation if not self._joints: self._init_articulation() return # update articulation if self._action_goal is not None and self._action_goal_handle is not None: target_position = self._action_goal.command.position # set target self.dci.wake_up_articulation(self._articulation) for name in self._joints: self._set_joint_position(name, target_position) # end (position reached) position = 0 current_position_sum = 0 position_reached = True for name in self._joints: position = self._get_joint_position(name) current_position_sum += position if abs(position - target_position) > self._action_position_threshold: position_reached = False break if position_reached: self._action_goal = None self._action_result_message.position = position self._action_result_message.stalled = False self._action_result_message.reached_goal = True if self._action_goal_handle is not None: self._action_goal_handle.set_succeeded(self._action_result_message) self._action_goal_handle = None return # end (stalled) if abs(current_position_sum - self._action_previous_position_sum) < 1e-6: self._action_goal = None self._action_result_message.position = position self._action_result_message.stalled = True self._action_result_message.reached_goal = False if self._action_goal_handle is not None: self._action_goal_handle.set_succeeded(self._action_result_message) self._action_goal_handle = None return self._action_previous_position_sum = current_position_sum # end (timeout) time_passed = rospy.get_time() - self._action_start_time if time_passed >= self._action_timeout: self._action_goal = None if self._action_goal_handle is not None: self._action_goal_handle.set_aborted() self._action_goal_handle = None # TODO: send feedback # self._action_goal_handle.publish_feedback(self._action_feedback_message) class OgnROS1ActionGripperCommand: """This node provides the services to list, read and write prim's attributes """ @staticmethod def initialize(graph_context, node): pass @staticmethod def internal_state() -> InternalState: return InternalState() @staticmethod def compute(db) -> bool: if not _ros_bridge.is_ros_node_running(): return False if db.internal_state.initialized: db.internal_state.step(0) else: try: db.internal_state.usd_context = omni.usd.get_context() db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface() if db.internal_state.timeline_event is None: timeline = omni.timeline.get_timeline_interface() db.internal_state.timeline_event = timeline.get_timeline_event_stream() \ .create_subscription_to_pop(db.internal_state.on_timeline_event) def get_action_name(namespace, controller_name, action_namespace): controller_name = controller_name if controller_name.startswith("/") else "/" + controller_name action_namespace = action_namespace if action_namespace.startswith("/") else "/" + action_namespace return namespace if namespace else "" + controller_name + action_namespace def get_relationships(node, usd_context, attribute): stage = usd_context.get_stage() prim = stage.GetPrimAtPath(node.get_prim_path()) return prim.GetRelationship(attribute).GetTargets() # check for articulation path = db.inputs.targetPrim.path if not len(path): print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetPrim not set") return # check for articulation API stage = db.internal_state.usd_context.get_stage() if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI): print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} doesn't have PhysxArticulationAPI".format(path)) return db.internal_state.articulation_path = path # check for gripper joints relationships = get_relationships(db.node, db.internal_state.usd_context, "inputs:targetGripperJoints") paths = [relationship.GetPrimPath().pathString for relationship in relationships] if not paths: print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetGripperJoints not set") return db.internal_state.gripper_joints_paths = paths # create action server db.internal_state.shutdown_action_server() action_name = get_action_name(db.inputs.nodeNamespace, db.inputs.controllerName, db.inputs.actionNamespace) db.internal_state.action_server = actionlib.ActionServer(action_name, control_msgs.msg.GripperCommandAction, goal_cb=db.internal_state.on_goal, cancel_cb=db.internal_state.on_cancel, auto_start=False) db.internal_state.action_server.start() print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: register action {}".format(action_name)) except ConnectionRefusedError as error: print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: action server {} not started".format(action_name)) db.log_error(str(error)) db.internal_state.initialized = False return False except Exception as error: print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: error: {}".format(error)) db.log_error(str(error)) db.internal_state.initialized = False return False db.internal_state.initialized = True return True
14,448
Python
41.875371
135
0.576412
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ServiceAttribute.py
from typing import Any import json import asyncio import threading import omni import carb from pxr import Usd, Gf from omni.isaac.dynamic_control import _dynamic_control import rospy try: from ... import _ros_bridge except: from ... import ros_bridge as _ros_bridge class InternalState: def __init__(self): """Internal state for the ROS1 Attribute node """ self.initialized = False self.dci = None self.usd_context = None self.timeline_event = None self.GetPrims = None self.GetPrimAttributes = None self.GetPrimAttribute = None self.SetPrimAttribute = None self.srv_prims = None self.srv_attributes = None self.srv_getter = None self.srv_setter = None self._event = threading.Event() self._event.set() self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/eventTimeout") self.__set_attribute_using_asyncio = \ carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/setAttributeUsingAsyncio") print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: asyncio: {}".format(self.__set_attribute_using_asyncio)) print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: event timeout: {}".format(self.__event_timeout)) def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the timeline event :param event: Event :type event: carb.events._events.IEvent """ if event.type == int(omni.timeline.TimelineEventType.PLAY): pass elif event.type == int(omni.timeline.TimelineEventType.PAUSE): pass elif event.type == int(omni.timeline.TimelineEventType.STOP): self.initialized = False self.shutdown_services() def shutdown_services(self) -> None: """Shutdown the services """ if self.srv_prims is not None: print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_prims.resolved_name)) self.srv_prims.shutdown() self.srv_prims = None if self.srv_getter is not None: print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_getter.resolved_name)) self.srv_getter.shutdown() self.srv_getter = None if self.srv_attributes is not None: print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_attributes.resolved_name)) self.srv_attributes.shutdown() self.srv_attributes = None if self.srv_setter is not None: print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_setter.resolved_name)) self.srv_setter.shutdown() self.srv_setter = None async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None: """Set the attribute value using asyncio :param attribute: The prim's attribute to set :type attribute: pxr.Usd.Attribute :param attribute_value: The attribute value :type attribute_value: Any """ ret = attribute.Set(attribute_value) def process_setter_request(self, request: 'SetPrimAttribute.SetPrimAttributeRequest') -> 'SetPrimAttribute.SetPrimAttributeResponse': """Process the setter request :param request: The service request :type request: SetPrimAttribute.SetPrimAttributeRequest :return: The service response :rtype: SetPrimAttribute.SetPrimAttributeResponse """ response = self.SetPrimAttribute.SetPrimAttributeResponse() response.success = False stage = self.usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) if request.attribute and prim.HasAttribute(request.attribute): # attribute attribute = prim.GetAttribute(request.attribute) attribute_type = type(attribute.Get()).__name__ # value try: value = json.loads(request.value) attribute_value = None except json.JSONDecodeError: print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: invalid value: {}".format(request.value)) response.success = False response.message = "Invalid value '{}'".format(request.value) return response # parse data try: if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Quatd', 'Quatf', 'Quath']: attribute_value = type(attribute.Get())(*value) elif attribute_type in ['Matrix4d', 'Matrix4f']: attribute_value = type(attribute.Get())(value) elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'): attribute_value = type(attribute.Get())(value) elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'): if attribute_type.endswith("dArray"): attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value]) elif attribute_type.endswith("fArray"): attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value]) elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'): if attribute_type.endswith("dArray"): attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value]) elif attribute_type.endswith("fArray"): attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value]) elif attribute_type.endswith("hArray"): attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value]) elif attribute_type.endswith('Array'): attribute_value = type(attribute.Get())(value) elif attribute_type in ['AssetPath']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['NoneType']: pass else: attribute_value = type(attribute.Get())(value) # set attribute if attribute_value is not None: # set attribute usign asyncio if self.__set_attribute_using_asyncio: try: loop = asyncio.get_event_loop() except: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value)) loop.run_until_complete(future) response.success = True # set attribute in the physics event else: self._attribute = attribute self._value = attribute_value self._event.clear() response.success = self._event.wait(self.__event_timeout) if not response.success: response.message = "The timeout ({} s) for setting the attribute value has been reached" \ .format(self.__event_timeout) except Exception as e: print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: srv {} request for {} ({}: {}): {}" \ .format(self.srv_setter.resolved_name, request.path, request.attribute, value, e)) response.success = False response.message = str(e) else: response.message = "Prim has not attribute {}".format(request.attribute) else: response.message = "Invalid prim ({})".format(request.path) return response def process_getter_request(self, request: 'GetPrimAttribute.GetPrimAttributeRequest') -> 'GetPrimAttribute.GetPrimAttributeResponse': """Process the getter request :param request: The service request :type request: GetPrimAttribute.GetPrimAttributeRequest :return: The service response :rtype: GetPrimAttribute.GetPrimAttributeResponse """ response = self.GetPrimAttribute.GetPrimAttributeResponse() response.success = False stage = self.usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) if request.attribute and prim.HasAttribute(request.attribute): attribute = prim.GetAttribute(request.attribute) response.type = type(attribute.Get()).__name__ # parse data response.success = True if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(2)]) elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(3)]) elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(4)]) elif response.type in ['Quatd', 'Quatf', 'Quath']: data = attribute.Get() response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]]) elif response.type in ['Matrix4d', 'Matrix4f']: data = attribute.Get() response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \ for i in range(data.dimension[0])]) elif response.type.startswith('Vec') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[d[i] for i in range(len(d))] for d in data]) elif response.type.startswith('Matrix') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \ for i in range(d.dimension[0])] for d in data]) elif response.type.startswith('Quat') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data]) elif response.type.endswith('Array'): try: response.value = json.dumps(list(attribute.Get())) except Exception as e: print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow attribute type {}" \ .format(type(attribute.Get()))) print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)") response.success = False response.message = "Unknow type {}".format(type(attribute.Get())) elif response.type in ['AssetPath']: response.value = json.dumps(str(attribute.Get().path)) else: try: response.value = json.dumps(attribute.Get()) except Exception as e: print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow {}: {}" \ .format(type(attribute.Get()), attribute.Get())) print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)") response.success = False response.message = "Unknow type {}".format(type(attribute.Get())) else: response.message = "Prim has not attribute {}".format(request.attribute) else: response.message = "Invalid prim ({})".format(request.path) return response def process_attributes_request(self, request: 'GetPrimAttributes.GetPrimAttributesRequest') -> 'GetPrimAttributes.GetPrimAttributesResponse': """Process the 'get all attributes' request :param request: The service request :type request: GetPrimAttributes.GetPrimAttributesRequest :return: The service response :rtype: GetPrimAttributes.GetPrimAttributesResponse """ response = self.GetPrimAttributes.GetPrimAttributesResponse() response.success = False stage = self.usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) for attribute in prim.GetAttributes(): if attribute.GetNamespace(): response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName())) else: response.names.append(attribute.GetBaseName()) response.displays.append(attribute.GetDisplayName()) response.types.append(type(attribute.Get()).__name__) response.success = True else: response.message = "Invalid prim ({})".format(request.path) return response def process_prims_request(self, request: 'GetPrims.GetPrimsRequest') -> 'GetPrims.GetPrimsResponse': """Process the 'get all prims' request :param request: The service request :type request: GetPrims.GetPrimsRequest :return: The service response :rtype: GetPrims.GetPrimsResponse """ response = self.GetPrims.GetPrimsResponse() response.success = False stage = self.usd_context.get_stage() # get prims if not request.path or stage.GetPrimAtPath(request.path).IsValid(): path = request.path if request.path else "/" for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)): response.paths.append(str(prim.GetPath())) response.types.append(prim.GetTypeName()) response.success = True else: response.message = "Invalid search path ({})".format(request.path) return response def step(self, dt: float) -> None: """Update step :param dt: Delta time :type dt: float """ if not self.initialized: return if self.__set_attribute_using_asyncio: return if self.dci.is_simulating(): if not self._event.is_set(): if self._attribute is not None: ret = self._attribute.Set(self._value) self._event.set() class OgnROS1ServiceAttribute: """This node provides the services to list, read and write prim's attributes """ @staticmethod def initialize(graph_context, node): pass @staticmethod def internal_state() -> InternalState: return InternalState() @staticmethod def compute(db) -> bool: if not _ros_bridge.is_ros_node_running(): return False if db.internal_state.initialized: db.internal_state.step(0) else: try: db.internal_state.usd_context = omni.usd.get_context() db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface() if db.internal_state.timeline_event is None: timeline = omni.timeline.get_timeline_interface() db.internal_state.timeline_event = timeline.get_timeline_event_stream() \ .create_subscription_to_pop(db.internal_state.on_timeline_event) def get_service_name(namespace, name): service_namespace = namespace if namespace.startswith("/") else "/" + namespace service_name = name if name.startswith("/") else "/" + name return service_namespace if namespace else "" + service_name # load service definitions from add_on_msgs.srv import _GetPrims from add_on_msgs.srv import _GetPrimAttributes from add_on_msgs.srv import _GetPrimAttribute from add_on_msgs.srv import _SetPrimAttribute db.internal_state.GetPrims = _GetPrims db.internal_state.GetPrimAttributes = _GetPrimAttributes db.internal_state.GetPrimAttribute = _GetPrimAttribute db.internal_state.SetPrimAttribute = _SetPrimAttribute # create services db.internal_state.shutdown_services() service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.primsServiceName) db.internal_state.srv_prims = rospy.Service(service_name, db.internal_state.GetPrims.GetPrims, db.internal_state.process_prims_request) print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_prims.resolved_name)) service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributesServiceName) db.internal_state.srv_attributes = rospy.Service(service_name, db.internal_state.GetPrimAttributes.GetPrimAttributes, db.internal_state.process_attributes_request) print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_attributes.resolved_name)) service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributeServiceName) db.internal_state.srv_getter = rospy.Service(service_name, db.internal_state.GetPrimAttribute.GetPrimAttribute, db.internal_state.process_getter_request) print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_getter.resolved_name)) service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.setAttributeServiceName) db.internal_state.srv_setter = rospy.Service(service_name, db.internal_state.SetPrimAttribute.SetPrimAttribute, db.internal_state.process_setter_request) print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_setter.resolved_name)) except Exception as error: print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: error: {}".format(error)) db.log_error(str(error)) db.internal_state.initialized = False return False db.internal_state.initialized = True return True
20,602
Python
49.497549
145
0.557713
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/scripts/extension.py
import os import sys import carb import omni.ext import omni.graph.core as og try: from .. import _ros_bridge except: from .. import ros_bridge as _ros_bridge class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._rosbridge = None self._extension_path = None ext_manager = omni.kit.app.get_app().get_extension_manager() if ext_manager.is_extension_enabled("omni.isaac.ros2_bridge"): carb.log_error("ROS Bridge external extension cannot be enabled if ROS 2 Bridge is enabled") ext_manager.set_extension_enabled("semu.robotics.ros_bridge", False) return self._extension_path = ext_manager.get_extension_path(ext_id) sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages")) self._rosbridge = _ros_bridge.acquire_ros_bridge_interface(ext_id) og.register_ogn_nodes(__file__, "semu.robotics.ros_bridge") def on_shutdown(self): if self._extension_path is not None: sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages")) self._extension_path = None if self._rosbridge is not None: _ros_bridge.release_ros_bridge_interface(self._rosbridge) self._rosbridge = None
1,345
Python
36.388888
109
0.646097
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_SetPrimAttribute.py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from add_on_msgs/SetPrimAttributeRequest.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class SetPrimAttributeRequest(genpy.Message): _md5sum = "c72cd1009a2d47b7e1ab3f88d1ff98e3" _type = "add_on_msgs/SetPrimAttributeRequest" _has_header = False # flag to mark the presence of a Header object _full_text = """string path # prim path string attribute # attribute name string value # attribute value (as JSON) """ __slots__ = ['path','attribute','value'] _slot_types = ['string','string','string'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: path,attribute,value :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(SetPrimAttributeRequest, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.path is None: self.path = '' if self.attribute is None: self.attribute = '' if self.value is None: self.value = '' else: self.path = '' self.attribute = '' self.value = '' def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self.path length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.attribute length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.value length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.path = str[start:end].decode('utf-8', 'rosmsg') else: self.path = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.attribute = str[start:end].decode('utf-8', 'rosmsg') else: self.attribute = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.value = str[start:end].decode('utf-8', 'rosmsg') else: self.value = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self.path length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.attribute length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.value length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.path = str[start:end].decode('utf-8', 'rosmsg') else: self.path = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.attribute = str[start:end].decode('utf-8', 'rosmsg') else: self.attribute = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.value = str[start:end].decode('utf-8', 'rosmsg') else: self.value = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from add_on_msgs/SetPrimAttributeResponse.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class SetPrimAttributeResponse(genpy.Message): _md5sum = "937c9679a518e3a18d831e57125ea522" _type = "add_on_msgs/SetPrimAttributeResponse" _has_header = False # flag to mark the presence of a Header object _full_text = """bool success # indicate a successful execution of the service string message # informational, e.g. for error messages """ __slots__ = ['success','message'] _slot_types = ['bool','string'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: success,message :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(SetPrimAttributeResponse, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.success is None: self.success = False if self.message is None: self.message = '' else: self.success = False self.message = '' def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self.success buff.write(_get_struct_B().pack(_x)) _x = self.message length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 1 (self.success,) = _get_struct_B().unpack(str[start:end]) self.success = bool(self.success) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.message = str[start:end].decode('utf-8', 'rosmsg') else: self.message = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self.success buff.write(_get_struct_B().pack(_x)) _x = self.message length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 1 (self.success,) = _get_struct_B().unpack(str[start:end]) self.success = bool(self.success) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.message = str[start:end].decode('utf-8', 'rosmsg') else: self.message = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_B = None def _get_struct_B(): global _struct_B if _struct_B is None: _struct_B = struct.Struct("<B") return _struct_B class SetPrimAttribute(object): _type = 'add_on_msgs/SetPrimAttribute' _md5sum = 'd15a408481ab068b790f599b3a64ee47' _request_class = SetPrimAttributeRequest _response_class = SetPrimAttributeResponse
11,604
Python
32.157143
145
0.606429
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_GetPrimAttributes.py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from add_on_msgs/GetPrimAttributesRequest.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetPrimAttributesRequest(genpy.Message): _md5sum = "1d00cd540af97efeb6b1589112fab63e" _type = "add_on_msgs/GetPrimAttributesRequest" _has_header = False # flag to mark the presence of a Header object _full_text = """string path # prim path """ __slots__ = ['path'] _slot_types = ['string'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: path :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetPrimAttributesRequest, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.path is None: self.path = '' else: self.path = '' def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self.path length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.path = str[start:end].decode('utf-8', 'rosmsg') else: self.path = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self.path length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.path = str[start:end].decode('utf-8', 'rosmsg') else: self.path = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from add_on_msgs/GetPrimAttributesResponse.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetPrimAttributesResponse(genpy.Message): _md5sum = "0c128a464ca5b41e4dd660a9d06a2cfb" _type = "add_on_msgs/GetPrimAttributesResponse" _has_header = False # flag to mark the presence of a Header object _full_text = """string[] names # list of attribute base names (name used to Get or Set an attribute) string[] displays # list of attribute display names (name displayed in Property tab) string[] types # list of attribute data types bool success # indicate a successful execution of the service string message # informational, e.g. for error messages """ __slots__ = ['names','displays','types','success','message'] _slot_types = ['string[]','string[]','string[]','bool','string'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: names,displays,types,success,message :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetPrimAttributesResponse, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.names is None: self.names = [] if self.displays is None: self.displays = [] if self.types is None: self.types = [] if self.success is None: self.success = False if self.message is None: self.message = '' else: self.names = [] self.displays = [] self.types = [] self.success = False self.message = '' def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: length = len(self.names) buff.write(_struct_I.pack(length)) for val1 in self.names: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) length = len(self.displays) buff.write(_struct_I.pack(length)) for val1 in self.displays: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) length = len(self.types) buff.write(_struct_I.pack(length)) for val1 in self.types: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) _x = self.success buff.write(_get_struct_B().pack(_x)) _x = self.message length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.names = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.names.append(val1) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.displays = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.displays.append(val1) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.types = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.types.append(val1) start = end end += 1 (self.success,) = _get_struct_B().unpack(str[start:end]) self.success = bool(self.success) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.message = str[start:end].decode('utf-8', 'rosmsg') else: self.message = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: length = len(self.names) buff.write(_struct_I.pack(length)) for val1 in self.names: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) length = len(self.displays) buff.write(_struct_I.pack(length)) for val1 in self.displays: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) length = len(self.types) buff.write(_struct_I.pack(length)) for val1 in self.types: length = len(val1) if python3 or type(val1) == unicode: val1 = val1.encode('utf-8') length = len(val1) buff.write(struct.Struct('<I%ss'%length).pack(length, val1)) _x = self.success buff.write(_get_struct_B().pack(_x)) _x = self.message length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.names = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.names.append(val1) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.displays = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.displays.append(val1) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.types = [] for i in range(0, length): start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: val1 = str[start:end].decode('utf-8', 'rosmsg') else: val1 = str[start:end] self.types.append(val1) start = end end += 1 (self.success,) = _get_struct_B().unpack(str[start:end]) self.success = bool(self.success) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.message = str[start:end].decode('utf-8', 'rosmsg') else: self.message = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_B = None def _get_struct_B(): global _struct_B if _struct_B is None: _struct_B = struct.Struct("<B") return _struct_B class GetPrimAttributes(object): _type = 'add_on_msgs/GetPrimAttributes' _md5sum = 'c58d65c0fb14e3af9f2c6842bf315d01' _request_class = GetPrimAttributesRequest _response_class = GetPrimAttributesResponse
14,453
Python
32.381062
145
0.592126
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/__init__.py
from ._GetPrimAttribute import * from ._GetPrimAttributes import * from ._GetPrims import * from ._SetPrimAttribute import *
125
Python
24.199995
33
0.776
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/__init__.py
from .test_ros_bridge import *
31
Python
14.999993
30
0.741935
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/test_ros_bridge.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 # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import semu.robotics.ros_bridge # 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 TestROSBridge(omni.kit.test.AsyncTestCaseFailOnLogError): # 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_ros_bridge(self): print("test_ros_bridge - TODO") pass
919
Python
38.999998
142
0.724701
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/ros2_bridge.py
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 import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.action import ActionServer, CancelResponse, GoalResponse from trajectory_msgs.msg import JointTrajectoryPoint import semu.usd.schemas.RosBridgeSchema as ROSSchema import semu.usd.schemas.RosControlBridgeSchema as ROSControlSchema # message types GetPrims = None GetPrimAttributes = None GetPrimAttribute = None SetPrimAttribute = None FollowJointTrajectory = None GripperCommand = None def acquire_ros2_bridge_interface(ext_id: str = "") -> 'Ros2Bridge': """ Acquire the Ros2Bridge interface :param ext_id: The extension id :type ext_id: str :returns: The Ros2Bridge interface :rtype: Ros2Bridge """ global GetPrims, GetPrimAttributes, GetPrimAttribute, SetPrimAttribute, FollowJointTrajectory, GripperCommand from add_on_msgs.srv import GetPrims as get_prims_srv from add_on_msgs.srv import GetPrimAttributes as get_prim_attributes_srv from add_on_msgs.srv import GetPrimAttribute as get_prim_attribute_srv from add_on_msgs.srv import SetPrimAttribute as set_prim_attribute_srv from control_msgs.action import FollowJointTrajectory as follow_joint_trajectory_action from control_msgs.action import GripperCommand as gripper_command_action GetPrims = get_prims_srv GetPrimAttributes = get_prim_attributes_srv GetPrimAttribute = get_prim_attribute_srv SetPrimAttribute = set_prim_attribute_srv FollowJointTrajectory = follow_joint_trajectory_action GripperCommand = gripper_command_action rclpy.init() bridge = Ros2Bridge() executor = rclpy.executors.MultiThreadedExecutor() executor.add_node(bridge) threading.Thread(target=executor.spin).start() return bridge def release_ros2_bridge_interface(bridge: 'Ros2Bridge') -> None: """ Release the Ros2Bridge interface :param bridge: The Ros2Bridge interface :type bridge: Ros2Bridge """ bridge.shutdown() class Ros2Bridge(Node): def __init__(self) -> None: """Initialize the Ros2Bridge interface """ self._components = [] self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/nodeName") super().__init__(self._node_name) # omni objects and interfaces self._usd_context = omni.usd.get_context() 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) def shutdown(self) -> None: """Shutdown the Ros2Bridge interface """ self._update_event = None self._timeline_event = None self._stage_event = None self._stop_components() self.destroy_node() rclpy.shutdown() def _get_ros_bridge_schemas(self) -> List['ROSSchema.RosBridgeComponent']: """Get the ROS bridge schemas in the current stage :returns: The ROS bridge schemas :rtype: list of RosBridgeComponent """ schemas = [] stage = self._usd_context.get_stage() for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath("/")): if prim.GetTypeName() == "RosAttribute": schemas.append(ROSSchema.RosAttribute(prim)) elif prim.GetTypeName() == "RosControlFollowJointTrajectory": schemas.append(ROSControlSchema.RosControlFollowJointTrajectory(prim)) elif prim.GetTypeName() == "RosControlGripperCommand": schemas.append(ROSControlSchema.RosControlGripperCommand(prim)) return schemas def _stop_components(self) -> None: """Stop all components """ for component in self._components: component.stop() def _reload_components(self) -> None: """Reload all components """ # stop components self._stop_components() # load components self._components = [] self._skip_update_step = True for schema in self._get_ros_bridge_schemas(): if schema.__class__.__name__ == "RosAttribute": self._components.append(RosAttribute(self, self._usd_context, schema, self._dci)) elif schema.__class__.__name__ == "RosControlFollowJointTrajectory": self._components.append(RosControlFollowJointTrajectory(self, self._usd_context, schema, self._dci)) elif schema.__class__.__name__ == "RosControlGripperCommand": self._components.append(RosControllerGripperCommand(self, self._usd_context, schema, self._dci)) def _on_update_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the kit update event :param event: Event :type event: carb.events._events.IEvent """ if self._timeline.is_playing(): for component in self._components: if self._skip_update_step: self._skip_update_step = False return # start components if not component.started: component.start() return # step component.update_step(event.payload["dt"]) def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the timeline event :param event: Event :type event: carb.events._events.IEvent """ # reload components if event.type == int(omni.timeline.TimelineEventType.PLAY): self._reload_components() print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components reloaded") # stop components elif event.type == int(omni.timeline.TimelineEventType.STOP) or event.type == int(omni.timeline.TimelineEventType.PAUSE): self._stop_components() print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components stopped") def _on_stage_event(self, event: 'carb.events._events.IEvent') -> None: """Handle the stage event :param event: The stage event :type event: carb.events._events.IEvent """ pass def _on_physics_event(self, step: float) -> None: """Handle the physics event :param step: The physics step :type step: float """ for component in self._components: component.physics_step(step) class RosController: def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent') -> None: """Base class for RosController :param node: ROS2 node :type node: Node :param usd_context: USD context :type usd_context: omni.usd._usd.UsdContext :param schema: The ROS bridge schema :type schema: ROSSchema.RosBridgeComponent """ self._node = node self._usd_context = usd_context self._schema = schema self.started = False def start(self) -> None: """Start the component """ raise NotImplementedError def stop(self) -> None: """Stop the component """ print("[Info][semu.robotics.ros2_bridge] RosController: stopping {}".format(self._schema.__class__.__name__)) self.started = False def update_step(self, dt: float) -> None: """Kit update step :param dt: The delta time :type dt: float """ raise NotImplementedError def physics_step(self, dt: float) -> None: """Physics update step :param dt: The physics delta time :type dt: float """ raise NotImplementedError class RosAttribute(RosController): def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent', dci: 'omni.isaac.dynamic_control.DynamicControl') -> None: """RosAttribute interface :param node: The ROS node :type node: rclpy.node.Node :param usd_context: USD context :type usd_context: omni.usd._usd.UsdContext :param schema: The ROS bridge schema :type schema: ROSSchema.RosAttribute :param dci: The dynamic control interface :type dci: omni.isaac.dynamic_control.DynamicControl """ super().__init__(node, usd_context, schema) self._dci = dci self._srv_prims = None self._srv_attributes = None self._srv_getter = None self._srv_setter = None self._value = None self._attribute = None self._event = threading.Event() self._event.set() self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/eventTimeout") self.__set_attribute_using_asyncio = \ carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/setAttributeUsingAsyncio") print("[Info][semu.robotics.ros2_bridge] RosAttribute: asyncio: {}".format(self.__set_attribute_using_asyncio)) print("[Info][semu.robotics.ros2_bridge] RosAttribute: event timeout: {}".format(self.__event_timeout)) async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None: """Set the attribute value using asyncio :param attribute: The prim's attribute to set :type attribute: pxr.Usd.Attribute :param attribute_value: The attribute value :type attribute_value: Any """ ret = attribute.Set(attribute_value) def _process_setter_request(self, request: 'SetPrimAttribute.Request', response: 'SetPrimAttribute.Response') -> 'SetPrimAttribute.Response': """Process the setter request :param request: The service request :type request: SetPrimAttribute.Request :param response: The service response :type response: SetPrimAttribute.Response :return: The service response :rtype: SetPrimAttribute.Response """ response.success = False if self._schema.GetEnabledAttr().Get(): stage = self._usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) if request.attribute and prim.HasAttribute(request.attribute): # attribute attribute = prim.GetAttribute(request.attribute) attribute_type = type(attribute.Get()).__name__ # value try: value = json.loads(request.value) attribute_value = None except json.JSONDecodeError: print("[Error][semu.robotics.ros2_bridge] RosAttribute: invalid value: {}".format(request.value)) response.success = False response.message = "Invalid value '{}'".format(request.value) return response # parse data try: if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['Quatd', 'Quatf', 'Quath']: attribute_value = type(attribute.Get())(*value) elif attribute_type in ['Matrix4d', 'Matrix4f']: attribute_value = type(attribute.Get())(value) elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'): attribute_value = type(attribute.Get())(value) elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'): if attribute_type.endswith("dArray"): attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value]) elif attribute_type.endswith("fArray"): attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value]) elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'): if attribute_type.endswith("dArray"): attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value]) elif attribute_type.endswith("fArray"): attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value]) elif attribute_type.endswith("hArray"): attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value]) elif attribute_type.endswith('Array'): attribute_value = type(attribute.Get())(value) elif attribute_type in ['AssetPath']: attribute_value = type(attribute.Get())(value) elif attribute_type in ['NoneType']: pass else: attribute_value = type(attribute.Get())(value) # set attribute if attribute_value is not None: # set attribute usign asyncio if self.__set_attribute_using_asyncio: try: loop = asyncio.get_event_loop() except: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value)) loop.run_until_complete(future) response.success = True # set attribute in the physics event else: self._attribute = attribute self._value = attribute_value self._event.clear() response.success = self._event.wait(self.__event_timeout) if not response.success: response.message = "The timeout ({} s) for setting the attribute value has been reached" \ .format(self.__event_timeout) except Exception as e: print("[Error][semu.robotics.ros2_bridge] RosAttribute: srv {} request for {} ({}: {}): {}" \ .format(self._srv_setter.resolved_name, request.path, request.attribute, value, e)) response.success = False response.message = str(e) else: response.message = "Prim has not attribute {}".format(request.attribute) else: response.message = "Invalid prim ({})".format(request.path) else: response.message = "RosAttribute prim is not enabled" return response def _process_getter_request(self, request: 'GetPrimAttribute.Request', response: 'GetPrimAttribute.Response') -> 'GetPrimAttribute.Response': """Process the getter request :param request: The service request :type request: GetPrimAttribute.Request :param response: The service response :type response: GetPrimAttribute.Response :return: The service response :rtype: GetPrimAttribute.Response """ response.success = False if self._schema.GetEnabledAttr().Get(): stage = self._usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) if request.attribute and prim.HasAttribute(request.attribute): attribute = prim.GetAttribute(request.attribute) response.type = type(attribute.Get()).__name__ # parse data response.success = True if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(2)]) elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(3)]) elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']: data = attribute.Get() response.value = json.dumps([data[i] for i in range(4)]) elif response.type in ['Quatd', 'Quatf', 'Quath']: data = attribute.Get() response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]]) elif response.type in ['Matrix4d', 'Matrix4f']: data = attribute.Get() response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \ for i in range(data.dimension[0])]) elif response.type.startswith('Vec') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[d[i] for i in range(len(d))] for d in data]) elif response.type.startswith('Matrix') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \ for i in range(d.dimension[0])] for d in data]) elif response.type.startswith('Quat') and response.type.endswith('Array'): data = attribute.Get() response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data]) elif response.type.endswith('Array'): try: response.value = json.dumps(list(attribute.Get())) except Exception as e: print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow attribute type {}" \ .format(type(attribute.Get()))) print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)") response.success = False response.message = "Unknow type {}".format(type(attribute.Get())) elif response.type in ['AssetPath']: response.value = json.dumps(str(attribute.Get().path)) else: try: response.value = json.dumps(attribute.Get()) except Exception as e: print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow {}: {}" \ .format(type(attribute.Get()), attribute.Get())) print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)") response.success = False response.message = "Unknow type {}".format(type(attribute.Get())) else: response.message = "Prim has not attribute {}".format(request.attribute) else: response.message = "Invalid prim ({})".format(request.path) else: response.message = "RosAttribute prim is not enabled" return response def _process_attributes_request(self, request: 'GetPrimAttributes.Request', response: 'GetPrimAttributes.Response') -> 'GetPrimAttributes.Response': """Process the 'get all attributes' request :param request: The service request :type request: GetPrimAttributes.Request :param response: The service response :type response: GetPrimAttributes.Response :return: The service response :rtype: GetPrimAttributes.Response """ response.success = False if self._schema.GetEnabledAttr().Get(): stage = self._usd_context.get_stage() # get prim if stage.GetPrimAtPath(request.path).IsValid(): prim = stage.GetPrimAtPath(request.path) for attribute in prim.GetAttributes(): if attribute.GetNamespace(): response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName())) else: response.names.append(attribute.GetBaseName()) response.displays.append(attribute.GetDisplayName()) response.types.append(type(attribute.Get()).__name__) response.success = True else: response.message = "Invalid prim ({})".format(request.path) else: response.message = "RosAttribute prim is not enabled" return response def _process_prims_request(self, request: 'GetPrims.Request', response: 'GetPrims.Response') -> 'GetPrims.Response': """Process the 'get all prims' request :param request: The service request :type request: GetPrims.Request :param response: The service response :type response: GetPrims.Response :return: The service response :rtype: GetPrims.Response """ response.success = False if self._schema.GetEnabledAttr().Get(): stage = self._usd_context.get_stage() # get prims if not request.path or stage.GetPrimAtPath(request.path).IsValid(): path = request.path if request.path else "/" for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)): response.paths.append(str(prim.GetPath())) response.types.append(prim.GetTypeName()) response.success = True else: response.message = "Invalid search path ({})".format(request.path) else: response.message = "RosAttribute prim is not enabled" return response def start(self) -> None: """Start the services """ print("[Info][semu.robotics.ros2_bridge] RosAttribute: starting {}".format(self._schema.__class__.__name__)) service_name = self._schema.GetPrimsSrvTopicAttr().Get() self._srv_prims = self._node.create_service(GetPrims, service_name, self._process_prims_request) print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_prims.srv_name)) service_name = self._schema.GetGetAttrSrvTopicAttr().Get() self._srv_getter = self._node.create_service(GetPrimAttribute, service_name, self._process_getter_request) print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_getter.srv_name)) service_name = self._schema.GetAttributesSrvTopicAttr().Get() self._srv_attributes = self._node.create_service(GetPrimAttributes, service_name, self._process_attributes_request) print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_attributes.srv_name)) service_name = self._schema.GetSetAttrSrvTopicAttr().Get() self._srv_setter = self._node.create_service(SetPrimAttribute, service_name, self._process_setter_request) print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_setter.srv_name)) self.started = True def stop(self) -> None: """Stop the services """ if self._srv_prims is not None: print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_prims.srv_name)) self._node.destroy_service(self._srv_prims) self._srv_prims = None if self._srv_getter is not None: print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_getter.srv_name)) self._node.destroy_service(self._srv_getter) self._srv_getter = None if self._srv_attributes is not None: print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_attributes.srv_name)) self._node.destroy_service(self._srv_attributes) self._srv_attributes = None if self._srv_setter is not None: print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_setter.srv_name)) self._node.destroy_service(self._srv_setter) self._srv_setter = None super().stop() def update_step(self, dt: float) -> None: """Kit update step :param dt: The delta time :type dt: float """ pass def physics_step(self, dt: float) -> None: """Physics update step :param dt: The physics delta time :type dt: float """ if not self.started: return if self.__set_attribute_using_asyncio: return if self._dci.is_simulating(): if not self._event.is_set(): if self._attribute is not None: ret = self._attribute.Set(self._value) self._event.set() class RosControlFollowJointTrajectory(RosController): def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent', dci: 'omni.isaac.dynamic_control.DynamicControl') -> None: """FollowJointTrajectory interface :param node: The ROS node :type node: rclpy.node.Node :param usd_context: The USD context :type usd_context: omni.usd._usd.UsdContext :param schema: The schema :type schema: ROSSchema.RosBridgeComponent :param dci: The dynamic control interface :type dci: omni.isaac.dynamic_control.DynamicControl """ super().__init__(node, usd_context, schema) self._dci = dci self._articulation = _dynamic_control.INVALID_HANDLE self._joints = {} self._action_server = None self._action_dt = 0.05 self._action_goal = None self._action_goal_handle = None self._action_start_time = None self._action_point_index = 1 # feedback / result self._action_result_message = None self._action_feedback_message = FollowJointTrajectory.Feedback() def start(self) -> None: """Start the action server """ print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: starting {}" \ .format(self._schema.__class__.__name__)) # get attributes and relationships action_namespace = self._schema.GetActionNamespaceAttr().Get() controller_name = self._schema.GetControllerNameAttr().Get() relationships = self._schema.GetArticulationPrimRel().GetTargets() if not len(relationships): print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: empty relationships") return # check for articulation API stage = self._usd_context.get_stage() path = relationships[0].GetPrimPath().pathString if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI): print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} doesn't have PhysxArticulationAPI".format(path)) return # start action server self._action_server = ActionServer(self._node, FollowJointTrajectory, controller_name + action_namespace, execute_callback=self._on_execute, goal_callback=self._on_goal, cancel_callback=self._on_cancel, handle_accepted_callback=self._on_handle_accepted) print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: register action {}" \ .format(controller_name + action_namespace)) self.started = True def stop(self) -> None: """Stop the action server """ super().stop() self._articulation = _dynamic_control.INVALID_HANDLE # destroy action server if self._action_server is not None: print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: destroy action server: {}" \ .format(self._schema.GetPrim().GetPath())) # self._action_server.destroy() self._action_server = None self._action_goal_handle = None self._action_goal = None def _duration_to_seconds(self, duration: Duration) -> float: """Convert a ROS2 Duration to seconds :param duration: The ROS2 Duration :type duration: Duration :return: The duration in seconds :rtype: float """ return Duration.from_msg(duration).nanoseconds / 1e9 def _init_articulation(self) -> None: """Initialize the articulation and register joints """ # get articulation relationships = self._schema.GetArticulationPrimRel().GetTargets() path = relationships[0].GetPrimPath().pathString self._articulation = self._dci.get_articulation(path) if self._articulation == _dynamic_control.INVALID_HANDLE: print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} is not an articulation".format(path)) return dof_props = self._dci.get_articulation_dof_properties(self._articulation) if dof_props is None: return upper_limits = dof_props["upper"] lower_limits = dof_props["lower"] has_limits = dof_props["hasLimits"] # get joints for i in range(self._dci.get_articulation_dof_count(self._articulation)): dof_ptr = self._dci.get_articulation_dof(self._articulation, i) if dof_ptr != _dynamic_control.DofType.DOF_NONE: dof_name = self._dci.get_dof_name(dof_ptr) if dof_name not in self._joints: _joint = self._dci.find_articulation_joint(self._articulation, dof_name) self._joints[dof_name] = {"joint": _joint, "type": self._dci.get_joint_type(_joint), "dof": self._dci.find_articulation_dof(self._articulation, dof_name), "lower": lower_limits[i], "upper": upper_limits[i], "has_limits": has_limits[i]} if not self._joints: print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: no joints found in {}".format(path)) self.started = False def _set_joint_position(self, name: str, target_position: float) -> None: """Set the target position of a joint in the articulation :param name: The joint name :type name: str :param target_position: The target position :type target_position: float """ # clip target position if self._joints[name]["has_limits"]: target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"]) # scale target position for prismatic joints if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: target_position /= get_stage_units() # set target position self._dci.set_dof_position_target(self._joints[name]["dof"], target_position) def _get_joint_position(self, name: str) -> float: """Get the current position of a joint in the articulation :param name: The joint name :type name: str :return: The current position of the joint :rtype: float """ position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: return position * get_stage_units() return position def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None: """Callback function for handling newly accepted goals :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle """ goal_handle.execute() def _on_goal(self, goal: 'FollowJointTrajectory.Goal') -> 'rclpy.action.server.GoalResponse': """Callback function for handling new goal requests :param goal: The goal :type goal: FollowJointTrajectory.Goal :return: Whether the goal was accepted :rtype: rclpy.action.server.GoalResponse """ # reject if joints don't match for name in goal.trajectory.joint_names: if name not in self._joints: print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: joints don't match ({} not in {})" \ .format(name, list(self._joints.keys()))) return GoalResponse.REJECT # reject if there is an active goal if self._action_goal is not None: print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: multiple goals not supported") return GoalResponse.REJECT # check initial position if goal.trajectory.points[0].time_from_start: initial_point = JointTrajectoryPoint(positions=[self._get_joint_position(name) for name in goal.trajectory.joint_names], time_from_start=Duration().to_msg()) goal.trajectory.points.insert(0, initial_point) # reset internal data self._action_goal_handle = None self._action_start_time = None self._action_result_message = None # store goal data self._action_goal = goal return GoalResponse.ACCEPT def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse': """Callback function for handling cancel requests :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle :return: Whether the goal was canceled :rtype: rclpy.action.server.CancelResponse """ if self._action_goal is None: return CancelResponse.REJECT # reset internal data self._action_goal = None self._action_goal_handle = None self._action_start_time = None self._action_result_message = None goal_handle.destroy() return CancelResponse.ACCEPT def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'FollowJointTrajectory.Result': """Callback function for processing accepted goals :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle :return: The result of the goal execution :rtype: FollowJointTrajectory.Result """ # reset internal data self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9 self._action_result_message = None # set goal self._action_goal_handle = goal_handle # wait for the goal to be executed while self._action_result_message is None: if self._action_goal is None: result = FollowJointTrajectory.Result() result.error_code = result.INVALID_GOAL return result time.sleep(self._action_dt) self._action_goal = None self._action_goal_handle = None return self._action_result_message def update_step(self, dt: float) -> None: """Kit update step :param dt: The delta time :type dt: float """ pass def physics_step(self, dt: float) -> None: """Physics update step :param dt: The physics delta time :type dt: float """ if not self.started: return # init articulation if not self._joints: self._init_articulation() return # update articulation if self._action_goal is not None and self._action_goal_handle is not None: self._action_dt = dt # end of trajectory if self._action_point_index >= len(self._action_goal.trajectory.points): self._action_goal = None self._action_result_message = FollowJointTrajectory.Result() self._action_result_message.error_code = self._action_result_message.SUCCESSFUL if self._action_goal_handle is not None: self._action_goal_handle.succeed() self._action_goal_handle = None return previous_point = self._action_goal.trajectory.points[self._action_point_index - 1] current_point = self._action_goal.trajectory.points[self._action_point_index] time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time # set target using linear interpolation if time_passed <= self._duration_to_seconds(current_point.time_from_start): ratio = (time_passed - self._duration_to_seconds(previous_point.time_from_start)) \ / (self._duration_to_seconds(current_point.time_from_start) \ - self._duration_to_seconds(previous_point.time_from_start)) self._dci.wake_up_articulation(self._articulation) for i, name in enumerate(self._action_goal.trajectory.joint_names): side = -1 if current_point.positions[i] < previous_point.positions[i] else 1 target_position = previous_point.positions[i] \ + side * ratio * abs(current_point.positions[i] - previous_point.positions[i]) self._set_joint_position(name, target_position) # send feedback else: self._action_point_index += 1 self._action_feedback_message.joint_names = list(self._action_goal.trajectory.joint_names) self._action_feedback_message.actual.positions = [self._get_joint_position(name) \ for name in self._action_goal.trajectory.joint_names] self._action_feedback_message.actual.time_from_start = Duration(seconds=time_passed).to_msg() if self._action_goal_handle is not None: self._action_goal_handle.publish_feedback(self._action_feedback_message) class RosControllerGripperCommand(RosController): def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent', dci: 'omni.isaac.dynamic_control.DynamicControl') -> None: """GripperCommand interface :param node: The ROS node :type node: rclpy.node.Node :param usd_context: The USD context :type usd_context: omni.usd._usd.UsdContext :param schema: The ROS bridge schema :type schema: ROSSchema.RosBridgeComponent :param dci: The dynamic control interface :type dci: omni.isaac.dynamic_control.DynamicControl """ super().__init__(node, usd_context, schema) self._dci = dci self._articulation = _dynamic_control.INVALID_HANDLE self._joints = {} self._action_server = None self._action_dt = 0.05 self._action_goal = None self._action_goal_handle = None self._action_start_time = None # TODO: add to schema? self._action_timeout = 10.0 self._action_position_threshold = 0.001 self._action_previous_position_sum = float("inf") # feedback / result self._action_result_message = None self._action_feedback_message = GripperCommand.Feedback() def start(self) -> None: """Start the action server """ print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: starting {}" \ .format(self._schema.__class__.__name__)) # get attributes and relationships action_namespace = self._schema.GetActionNamespaceAttr().Get() controller_name = self._schema.GetControllerNameAttr().Get() relationships = self._schema.GetArticulationPrimRel().GetTargets() if not len(relationships): print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: empty relationships") return elif len(relationships) == 1: print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: relationship is not a group") return # check for articulation API stage = self._usd_context.get_stage() path = relationships[0].GetPrimPath().pathString if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI): print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} doesn't have PhysxArticulationAPI".format(path)) return # start action server self._action_server = ActionServer(self._node, GripperCommand, controller_name + action_namespace, execute_callback=self._on_execute, goal_callback=self._on_goal, cancel_callback=self._on_cancel, handle_accepted_callback=self._on_handle_accepted) print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: register action {}" \ .format(controller_name + action_namespace)) self.started = True def stop(self) -> None: """Stop the action server """ super().stop() self._articulation = _dynamic_control.INVALID_HANDLE # destroy action server if self._action_server is not None: print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: destroy action server: {}" \ .format(self._schema.GetPrim().GetPath())) # self._action_server.destroy() self._action_server = None self._action_goal_handle = None self._action_goal = None def _duration_to_seconds(self, duration: Duration) -> float: """Convert a ROS2 Duration to seconds :param duration: The ROS2 Duration :type duration: Duration :return: The duration in seconds :rtype: float """ return Duration.from_msg(duration).nanoseconds / 1e9 def _init_articulation(self) -> None: """Initialize the articulation and register joints """ # get articulation relationships = self._schema.GetArticulationPrimRel().GetTargets() path = relationships[0].GetPrimPath().pathString self._articulation = self._dci.get_articulation(path) if self._articulation == _dynamic_control.INVALID_HANDLE: print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} is not an articulation".format(path)) return dof_props = self._dci.get_articulation_dof_properties(self._articulation) if dof_props is None: return upper_limits = dof_props["upper"] lower_limits = dof_props["lower"] has_limits = dof_props["hasLimits"] # get joints # TODO: move to another relationship in the schema paths = [relationship.GetPrimPath().pathString for relationship in relationships[1:]] for i in range(self._dci.get_articulation_dof_count(self._articulation)): dof_ptr = self._dci.get_articulation_dof(self._articulation, i) if dof_ptr != _dynamic_control.DofType.DOF_NONE: # add only required joints if self._dci.get_dof_path(dof_ptr) in paths: dof_name = self._dci.get_dof_name(dof_ptr) if dof_name not in self._joints: _joint = self._dci.find_articulation_joint(self._articulation, dof_name) self._joints[dof_name] = {"joint": _joint, "type": self._dci.get_joint_type(_joint), "dof": self._dci.find_articulation_dof(self._articulation, dof_name), "lower": lower_limits[i], "upper": upper_limits[i], "has_limits": has_limits[i]} if not self._joints: print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: no joints found in {}".format(path)) self.started = False def _set_joint_position(self, name: str, target_position: float) -> None: """Set the target position of a joint in the articulation :param name: The joint name :type name: str :param target_position: The target position :type target_position: float """ # clip target position if self._joints[name]["has_limits"]: target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"]) # scale target position for prismatic joints if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: target_position /= get_stage_units() # set target position self._dci.set_dof_position_target(self._joints[name]["dof"], target_position) def _get_joint_position(self, name: str) -> float: """Get the current position of a joint in the articulation :param name: The joint name :type name: str :return: The current position of the joint :rtype: float """ position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC: return position * get_stage_units() return position def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None: """Callback function for handling newly accepted goals :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle """ goal_handle.execute() def _on_goal(self, goal: 'GripperCommand.Goal') -> 'rclpy.action.server.GoalResponse': """Callback function for handling new goal requests :param goal: The goal :type goal: GripperCommand.Goal :return: Whether the goal was accepted :rtype: rclpy.action.server.GoalResponse """ # reject if there is an active goal if self._action_goal is not None: print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: multiple goals not supported") return GoalResponse.REJECT # reset internal data self._action_goal = None self._action_goal_handle = None self._action_start_time = None self._action_result_message = None self._action_previous_position_sum = float("inf") return GoalResponse.ACCEPT def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse': """Callback function for handling cancel requests :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle :return: Whether the goal was canceled :rtype: rclpy.action.server.CancelResponse """ if self._action_goal is None: return CancelResponse.REJECT # reset internal data self._action_goal = None self._action_goal_handle = None self._action_start_time = None self._action_result_message = None self._action_previous_position_sum = float("inf") goal_handle.destroy() return CancelResponse.ACCEPT def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'GripperCommand.Result': """Callback function for processing accepted goals :param goal_handle: The goal handle :type goal_handle: rclpy.action.server.ServerGoalHandle :return: The result of the goal execution :rtype: GripperCommand.Result """ # reset internal data self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9 self._action_result_message = None self._action_previous_position_sum = float("inf") # set goal self._action_goal_handle = goal_handle self._action_goal = goal_handle.request # wait for the goal to be executed while self._action_result_message is None: if self._action_goal is None: return GripperCommand.Result() time.sleep(self._action_dt) self._action_goal = None self._action_goal_handle = None return self._action_result_message def update_step(self, dt: float) -> None: """Kit update step :param dt: The delta time :type dt: float """ pass def physics_step(self, dt: float) -> None: """Physics update step :param dt: The physics delta time :type dt: float """ if not self.started: return # init articulation if not self._joints: self._init_articulation() return # update articulation if self._action_goal is not None and self._action_goal_handle is not None: self._action_dt = dt target_position = self._action_goal.command.position # set target self._dci.wake_up_articulation(self._articulation) for name in self._joints: self._set_joint_position(name, target_position) # end (position reached) position = 0 current_position_sum = 0 position_reached = True for name in self._joints: position = self._get_joint_position(name) current_position_sum += position if abs(position - target_position) > self._action_position_threshold: position_reached = False break if position_reached: self._action_result_message = GripperCommand.Result() self._action_result_message.position = position self._action_result_message.stalled = False self._action_result_message.reached_goal = True if self._action_goal_handle is not None: self._action_goal_handle.succeed() self._action_goal_handle = None return # end (stalled) if abs(current_position_sum - self._action_previous_position_sum) < 1e-6: self._action_result_message = GripperCommand.Result() self._action_result_message.position = position self._action_result_message.stalled = True self._action_result_message.reached_goal = False if self._action_goal_handle is not None: self._action_goal_handle.succeed() self._action_goal_handle = None return self._action_previous_position_sum = current_position_sum # end (timeout) time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time if time_passed >= self._action_timeout: self._action_result_message = GripperCommand.Result() if self._action_goal_handle is not None: self._action_goal_handle.abort() self._action_goal_handle = None # TODO: send feedback # self._action_goal_handle.publish_feedback(self._action_feedback_message)
55,059
Python
43.619125
141
0.576945
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/scripts/extension.py
import os import sys import carb import omni.ext try: from .. import _ros2_bridge except: print(">>>> [DEVELOPMENT] import ros2_bridge") from .. import ros2_bridge as _ros2_bridge class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._ros2bridge = None self._extension_path = None ext_manager = omni.kit.app.get_app().get_extension_manager() if ext_manager.is_extension_enabled("omni.isaac.ros_bridge"): carb.log_error("ROS 2 Bridge external extension cannot be enabled if ROS Bridge is enabled") ext_manager.set_extension_enabled("semu.robotics.ros2_bridge", False) return self._extension_path = ext_manager.get_extension_path(ext_id) sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "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._ros2bridge = _ros2_bridge.acquire_ros2_bridge_interface(ext_id) def on_shutdown(self): if self._extension_path is not None: sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "packages")) self._extension_path = None if self._ros2bridge is not None: _ros2_bridge.release_ros2_bridge_interface(self._ros2bridge) self._ros2bridge = None
1,574
Python
39.384614
118
0.635959
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_calibration_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:srv/QueryCalibrationState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_QueryCalibrationState_Request(type): """Metaclass of message 'QueryCalibrationState_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState_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__query_calibration_state__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__request cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__request @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 QueryCalibrationState_Request(metaclass=Metaclass_QueryCalibrationState_Request): """Message class 'QueryCalibrationState_Request'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) 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__)) 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 return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_QueryCalibrationState_Response(type): """Metaclass of message 'QueryCalibrationState_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState_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__query_calibration_state__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__response cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__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 QueryCalibrationState_Response(metaclass=Metaclass_QueryCalibrationState_Response): """Message class 'QueryCalibrationState_Response'.""" __slots__ = [ '_is_calibrated', ] _fields_and_field_types = { 'is_calibrated': '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.is_calibrated = kwargs.get('is_calibrated', 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.is_calibrated != other.is_calibrated: 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 is_calibrated(self): """Message field 'is_calibrated'.""" return self._is_calibrated @is_calibrated.setter def is_calibrated(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'is_calibrated' field must be of type 'bool'" self._is_calibrated = value class Metaclass_QueryCalibrationState(type): """Metaclass of service 'QueryCalibrationState'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__query_calibration_state from control_msgs.srv import _query_calibration_state if _query_calibration_state.Metaclass_QueryCalibrationState_Request._TYPE_SUPPORT is None: _query_calibration_state.Metaclass_QueryCalibrationState_Request.__import_type_support__() if _query_calibration_state.Metaclass_QueryCalibrationState_Response._TYPE_SUPPORT is None: _query_calibration_state.Metaclass_QueryCalibrationState_Response.__import_type_support__() class QueryCalibrationState(metaclass=Metaclass_QueryCalibrationState): from control_msgs.srv._query_calibration_state import QueryCalibrationState_Request as Request from control_msgs.srv._query_calibration_state import QueryCalibrationState_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
9,936
Python
37.219231
134
0.598631
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/__init__.py
from control_msgs.srv._query_calibration_state import QueryCalibrationState # noqa: F401 from control_msgs.srv._query_trajectory_state import QueryTrajectoryState # noqa: F401
178
Python
58.666647
89
0.820225
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_trajectory_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:srv/QueryTrajectoryState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_QueryTrajectoryState_Request(type): """Metaclass of message 'QueryTrajectoryState_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState_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__query_trajectory_state__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__request cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__request from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 QueryTrajectoryState_Request(metaclass=Metaclass_QueryTrajectoryState_Request): """Message class 'QueryTrajectoryState_Request'.""" __slots__ = [ '_time', ] _fields_and_field_types = { 'time': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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__)) from builtin_interfaces.msg import Time self.time = kwargs.get('time', Time()) 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.time != other.time: 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 time(self): """Message field 'time'.""" return self._time @time.setter def time(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'time' field must be a sub message of type 'Time'" self._time = value # Import statements for member types # Member 'position' # Member 'velocity' # Member 'acceleration' import array # noqa: E402, I100 # already imported above # import rosidl_parser.definition class Metaclass_QueryTrajectoryState_Response(type): """Metaclass of message 'QueryTrajectoryState_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState_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__query_trajectory_state__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__response cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__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 QueryTrajectoryState_Response(metaclass=Metaclass_QueryTrajectoryState_Response): """Message class 'QueryTrajectoryState_Response'.""" __slots__ = [ '_success', '_message', '_name', '_position', '_velocity', '_acceleration', ] _fields_and_field_types = { 'success': 'boolean', 'message': 'string', 'name': 'sequence<string>', 'position': 'sequence<double>', 'velocity': 'sequence<double>', 'acceleration': 'sequence<double>', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # 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()) self.message = kwargs.get('message', str()) self.name = kwargs.get('name', []) self.position = array.array('d', kwargs.get('position', [])) self.velocity = array.array('d', kwargs.get('velocity', [])) self.acceleration = array.array('d', kwargs.get('acceleration', [])) 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 if self.message != other.message: return False if self.name != other.name: return False if self.position != other.position: return False if self.velocity != other.velocity: return False if self.acceleration != other.acceleration: 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 @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value @property def name(self): """Message field 'name'.""" return self._name @name.setter def name(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'name' field must be a set or sequence and each value of type 'str'" self._name = value @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'position' array.array() must have the type code of 'd'" self._position = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'position' field must be a set or sequence and each value of type 'float'" self._position = array.array('d', value) @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'velocity' array.array() must have the type code of 'd'" self._velocity = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'velocity' field must be a set or sequence and each value of type 'float'" self._velocity = array.array('d', value) @property def acceleration(self): """Message field 'acceleration'.""" return self._acceleration @acceleration.setter def acceleration(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'acceleration' array.array() must have the type code of 'd'" self._acceleration = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'acceleration' field must be a set or sequence and each value of type 'float'" self._acceleration = array.array('d', value) class Metaclass_QueryTrajectoryState(type): """Metaclass of service 'QueryTrajectoryState'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__query_trajectory_state from control_msgs.srv import _query_trajectory_state if _query_trajectory_state.Metaclass_QueryTrajectoryState_Request._TYPE_SUPPORT is None: _query_trajectory_state.Metaclass_QueryTrajectoryState_Request.__import_type_support__() if _query_trajectory_state.Metaclass_QueryTrajectoryState_Response._TYPE_SUPPORT is None: _query_trajectory_state.Metaclass_QueryTrajectoryState_Response.__import_type_support__() class QueryTrajectoryState(metaclass=Metaclass_QueryTrajectoryState): from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Request as Request from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
16,687
Python
36.927273
134
0.579613
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_joint_trajectory.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/JointTrajectory.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTrajectory_Goal(type): """Metaclass of message 'JointTrajectory_Goal'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__goal cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__goal from trajectory_msgs.msg import JointTrajectory if JointTrajectory.__class__._TYPE_SUPPORT is None: JointTrajectory.__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 JointTrajectory_Goal(metaclass=Metaclass_JointTrajectory_Goal): """Message class 'JointTrajectory_Goal'.""" __slots__ = [ '_trajectory', ] _fields_and_field_types = { 'trajectory': 'trajectory_msgs/JointTrajectory', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # 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__)) from trajectory_msgs.msg import JointTrajectory self.trajectory = kwargs.get('trajectory', JointTrajectory()) 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.trajectory != other.trajectory: 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 trajectory(self): """Message field 'trajectory'.""" return self._trajectory @trajectory.setter def trajectory(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectory assert \ isinstance(value, JointTrajectory), \ "The 'trajectory' field must be a sub message of type 'JointTrajectory'" self._trajectory = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_Result(type): """Metaclass of message 'JointTrajectory_Result'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__result cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__result @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 JointTrajectory_Result(metaclass=Metaclass_JointTrajectory_Result): """Message class 'JointTrajectory_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) 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__)) 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 return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_Feedback(type): """Metaclass of message 'JointTrajectory_Feedback'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback @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 JointTrajectory_Feedback(metaclass=Metaclass_JointTrajectory_Feedback): """Message class 'JointTrajectory_Feedback'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) 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__)) 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 return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_SendGoal_Request(type): """Metaclass of message 'JointTrajectory_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal_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__action__joint_trajectory__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__request from control_msgs.action import JointTrajectory if JointTrajectory.Goal.__class__._TYPE_SUPPORT is None: JointTrajectory.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 JointTrajectory_SendGoal_Request(metaclass=Metaclass_JointTrajectory_SendGoal_Request): """Message class 'JointTrajectory_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/JointTrajectory_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Goal'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._joint_trajectory import JointTrajectory_Goal self.goal = kwargs.get('goal', JointTrajectory_Goal()) 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.goal_id != other.goal_id: return False if self.goal != other.goal: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Goal assert \ isinstance(value, JointTrajectory_Goal), \ "The 'goal' field must be a sub message of type 'JointTrajectory_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_SendGoal_Response(type): """Metaclass of message 'JointTrajectory_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal_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__action__joint_trajectory__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 JointTrajectory_SendGoal_Response(metaclass=Metaclass_JointTrajectory_SendGoal_Response): """Message class 'JointTrajectory_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) 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.accepted != other.accepted: return False if self.stamp != other.stamp: 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 accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_JointTrajectory_SendGoal(type): """Metaclass of service 'JointTrajectory_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__send_goal from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response.__import_type_support__() class JointTrajectory_SendGoal(metaclass=Metaclass_JointTrajectory_SendGoal): from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Request as Request from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_GetResult_Request(type): """Metaclass of message 'JointTrajectory_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult_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__action__joint_trajectory__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 JointTrajectory_GetResult_Request(metaclass=Metaclass_JointTrajectory_GetResult_Request): """Message class 'JointTrajectory_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) 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.goal_id != other.goal_id: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_GetResult_Response(type): """Metaclass of message 'JointTrajectory_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult_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__action__joint_trajectory__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__response from control_msgs.action import JointTrajectory if JointTrajectory.Result.__class__._TYPE_SUPPORT is None: JointTrajectory.Result.__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 JointTrajectory_GetResult_Response(metaclass=Metaclass_JointTrajectory_GetResult_Response): """Message class 'JointTrajectory_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/JointTrajectory_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Result'), # 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.status = kwargs.get('status', int()) from control_msgs.action._joint_trajectory import JointTrajectory_Result self.result = kwargs.get('result', JointTrajectory_Result()) 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.status != other.status: return False if self.result != other.result: 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 status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Result assert \ isinstance(value, JointTrajectory_Result), \ "The 'result' field must be a sub message of type 'JointTrajectory_Result'" self._result = value class Metaclass_JointTrajectory_GetResult(type): """Metaclass of service 'JointTrajectory_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__get_result from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Request._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult_Request.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Response._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult_Response.__import_type_support__() class JointTrajectory_GetResult(metaclass=Metaclass_JointTrajectory_GetResult): from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Request as Request from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_FeedbackMessage(type): """Metaclass of message 'JointTrajectory_FeedbackMessage'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback_message from control_msgs.action import JointTrajectory if JointTrajectory.Feedback.__class__._TYPE_SUPPORT is None: JointTrajectory.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 JointTrajectory_FeedbackMessage(metaclass=Metaclass_JointTrajectory_FeedbackMessage): """Message class 'JointTrajectory_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/JointTrajectory_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Feedback'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._joint_trajectory import JointTrajectory_Feedback self.feedback = kwargs.get('feedback', JointTrajectory_Feedback()) 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.goal_id != other.goal_id: return False if self.feedback != other.feedback: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Feedback assert \ isinstance(value, JointTrajectory_Feedback), \ "The 'feedback' field must be a sub message of type 'JointTrajectory_Feedback'" self._feedback = value class Metaclass_JointTrajectory(type): """Metaclass of action 'JointTrajectory'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__joint_trajectory from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_SendGoal._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_GetResult._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage.__import_type_support__() class JointTrajectory(metaclass=Metaclass_JointTrajectory): # The goal message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Goal as Goal # The result message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Result as Result # The feedback message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._joint_trajectory import JointTrajectory_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._joint_trajectory import JointTrajectory_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
45,957
Python
37.717776
134
0.595274
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/__init__.py
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory # noqa: F401 from control_msgs.action._gripper_command import GripperCommand # noqa: F401 from control_msgs.action._joint_trajectory import JointTrajectory # noqa: F401 from control_msgs.action._point_head import PointHead # noqa: F401 from control_msgs.action._single_joint_position import SingleJointPosition # noqa: F401
408
Python
67.166655
92
0.811275
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_gripper_command.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/GripperCommand.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GripperCommand_Goal(type): """Metaclass of message 'GripperCommand_Goal'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__goal cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__goal from control_msgs.msg import GripperCommand if GripperCommand.__class__._TYPE_SUPPORT is None: GripperCommand.__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 GripperCommand_Goal(metaclass=Metaclass_GripperCommand_Goal): """Message class 'GripperCommand_Goal'.""" __slots__ = [ '_command', ] _fields_and_field_types = { 'command': 'control_msgs/GripperCommand', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'GripperCommand'), # 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__)) from control_msgs.msg import GripperCommand self.command = kwargs.get('command', GripperCommand()) 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.command != other.command: 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 command(self): """Message field 'command'.""" return self._command @command.setter def command(self, value): if __debug__: from control_msgs.msg import GripperCommand assert \ isinstance(value, GripperCommand), \ "The 'command' field must be a sub message of type 'GripperCommand'" self._command = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_Result(type): """Metaclass of message 'GripperCommand_Result'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__result cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__result @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 GripperCommand_Result(metaclass=Metaclass_GripperCommand_Result): """Message class 'GripperCommand_Result'.""" __slots__ = [ '_position', '_effort', '_stalled', '_reached_goal', ] _fields_and_field_types = { 'position': 'double', 'effort': 'double', 'stalled': 'boolean', 'reached_goal': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 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.position = kwargs.get('position', float()) self.effort = kwargs.get('effort', float()) self.stalled = kwargs.get('stalled', bool()) self.reached_goal = kwargs.get('reached_goal', 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.position != other.position: return False if self.effort != other.effort: return False if self.stalled != other.stalled: return False if self.reached_goal != other.reached_goal: 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 position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def effort(self): """Message field 'effort'.""" return self._effort @effort.setter def effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'effort' field must be of type 'float'" self._effort = value @property def stalled(self): """Message field 'stalled'.""" return self._stalled @stalled.setter def stalled(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'stalled' field must be of type 'bool'" self._stalled = value @property def reached_goal(self): """Message field 'reached_goal'.""" return self._reached_goal @reached_goal.setter def reached_goal(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'reached_goal' field must be of type 'bool'" self._reached_goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_Feedback(type): """Metaclass of message 'GripperCommand_Feedback'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback @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 GripperCommand_Feedback(metaclass=Metaclass_GripperCommand_Feedback): """Message class 'GripperCommand_Feedback'.""" __slots__ = [ '_position', '_effort', '_stalled', '_reached_goal', ] _fields_and_field_types = { 'position': 'double', 'effort': 'double', 'stalled': 'boolean', 'reached_goal': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 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.position = kwargs.get('position', float()) self.effort = kwargs.get('effort', float()) self.stalled = kwargs.get('stalled', bool()) self.reached_goal = kwargs.get('reached_goal', 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.position != other.position: return False if self.effort != other.effort: return False if self.stalled != other.stalled: return False if self.reached_goal != other.reached_goal: 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 position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def effort(self): """Message field 'effort'.""" return self._effort @effort.setter def effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'effort' field must be of type 'float'" self._effort = value @property def stalled(self): """Message field 'stalled'.""" return self._stalled @stalled.setter def stalled(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'stalled' field must be of type 'bool'" self._stalled = value @property def reached_goal(self): """Message field 'reached_goal'.""" return self._reached_goal @reached_goal.setter def reached_goal(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'reached_goal' field must be of type 'bool'" self._reached_goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_SendGoal_Request(type): """Metaclass of message 'GripperCommand_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal_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__action__gripper_command__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__request from control_msgs.action import GripperCommand if GripperCommand.Goal.__class__._TYPE_SUPPORT is None: GripperCommand.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 GripperCommand_SendGoal_Request(metaclass=Metaclass_GripperCommand_SendGoal_Request): """Message class 'GripperCommand_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/GripperCommand_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Goal'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._gripper_command import GripperCommand_Goal self.goal = kwargs.get('goal', GripperCommand_Goal()) 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.goal_id != other.goal_id: return False if self.goal != other.goal: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Goal assert \ isinstance(value, GripperCommand_Goal), \ "The 'goal' field must be a sub message of type 'GripperCommand_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_SendGoal_Response(type): """Metaclass of message 'GripperCommand_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal_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__action__gripper_command__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 GripperCommand_SendGoal_Response(metaclass=Metaclass_GripperCommand_SendGoal_Response): """Message class 'GripperCommand_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) 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.accepted != other.accepted: return False if self.stamp != other.stamp: 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 accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_GripperCommand_SendGoal(type): """Metaclass of service 'GripperCommand_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__send_goal from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_SendGoal_Request._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal_Request.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_SendGoal_Response._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal_Response.__import_type_support__() class GripperCommand_SendGoal(metaclass=Metaclass_GripperCommand_SendGoal): from control_msgs.action._gripper_command import GripperCommand_SendGoal_Request as Request from control_msgs.action._gripper_command import GripperCommand_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_GetResult_Request(type): """Metaclass of message 'GripperCommand_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult_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__action__gripper_command__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 GripperCommand_GetResult_Request(metaclass=Metaclass_GripperCommand_GetResult_Request): """Message class 'GripperCommand_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) 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.goal_id != other.goal_id: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_GetResult_Response(type): """Metaclass of message 'GripperCommand_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult_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__action__gripper_command__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__response from control_msgs.action import GripperCommand if GripperCommand.Result.__class__._TYPE_SUPPORT is None: GripperCommand.Result.__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 GripperCommand_GetResult_Response(metaclass=Metaclass_GripperCommand_GetResult_Response): """Message class 'GripperCommand_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/GripperCommand_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Result'), # 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.status = kwargs.get('status', int()) from control_msgs.action._gripper_command import GripperCommand_Result self.result = kwargs.get('result', GripperCommand_Result()) 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.status != other.status: return False if self.result != other.result: 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 status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Result assert \ isinstance(value, GripperCommand_Result), \ "The 'result' field must be a sub message of type 'GripperCommand_Result'" self._result = value class Metaclass_GripperCommand_GetResult(type): """Metaclass of service 'GripperCommand_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__get_result from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_GetResult_Request._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult_Request.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_GetResult_Response._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult_Response.__import_type_support__() class GripperCommand_GetResult(metaclass=Metaclass_GripperCommand_GetResult): from control_msgs.action._gripper_command import GripperCommand_GetResult_Request as Request from control_msgs.action._gripper_command import GripperCommand_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_FeedbackMessage(type): """Metaclass of message 'GripperCommand_FeedbackMessage'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback_message from control_msgs.action import GripperCommand if GripperCommand.Feedback.__class__._TYPE_SUPPORT is None: GripperCommand.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 GripperCommand_FeedbackMessage(metaclass=Metaclass_GripperCommand_FeedbackMessage): """Message class 'GripperCommand_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/GripperCommand_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Feedback'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._gripper_command import GripperCommand_Feedback self.feedback = kwargs.get('feedback', GripperCommand_Feedback()) 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.goal_id != other.goal_id: return False if self.feedback != other.feedback: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Feedback assert \ isinstance(value, GripperCommand_Feedback), \ "The 'feedback' field must be a sub message of type 'GripperCommand_Feedback'" self._feedback = value class Metaclass_GripperCommand(type): """Metaclass of action 'GripperCommand'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__gripper_command from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_SendGoal._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_GetResult._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_FeedbackMessage._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_FeedbackMessage.__import_type_support__() class GripperCommand(metaclass=Metaclass_GripperCommand): # The goal message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Goal as Goal # The result message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Result as Result # The feedback message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._gripper_command import GripperCommand_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._gripper_command import GripperCommand_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._gripper_command import GripperCommand_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
50,417
Python
36.653473
134
0.587718
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_single_joint_position.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/SingleJointPosition.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_SingleJointPosition_Goal(type): """Metaclass of message 'SingleJointPosition_Goal'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__goal cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__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 SingleJointPosition_Goal(metaclass=Metaclass_SingleJointPosition_Goal): """Message class 'SingleJointPosition_Goal'.""" __slots__ = [ '_position', '_min_duration', '_max_velocity', ] _fields_and_field_types = { 'position': 'double', 'min_duration': 'builtin_interfaces/Duration', 'max_velocity': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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.position = kwargs.get('position', float()) from builtin_interfaces.msg import Duration self.min_duration = kwargs.get('min_duration', Duration()) self.max_velocity = kwargs.get('max_velocity', float()) 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.position != other.position: return False if self.min_duration != other.min_duration: return False if self.max_velocity != other.max_velocity: 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 position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def min_duration(self): """Message field 'min_duration'.""" return self._min_duration @min_duration.setter def min_duration(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'min_duration' field must be a sub message of type 'Duration'" self._min_duration = value @property def max_velocity(self): """Message field 'max_velocity'.""" return self._max_velocity @max_velocity.setter def max_velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_velocity' field must be of type 'float'" self._max_velocity = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_Result(type): """Metaclass of message 'SingleJointPosition_Result'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__result cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__result @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 SingleJointPosition_Result(metaclass=Metaclass_SingleJointPosition_Result): """Message class 'SingleJointPosition_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) 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__)) 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 return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_Feedback(type): """Metaclass of message 'SingleJointPosition_Feedback'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__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 SingleJointPosition_Feedback(metaclass=Metaclass_SingleJointPosition_Feedback): """Message class 'SingleJointPosition_Feedback'.""" __slots__ = [ '_header', '_position', '_velocity', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'position': 'double', 'velocity': 'double', 'error': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.position = kwargs.get('position', float()) self.velocity = kwargs.get('velocity', float()) self.error = kwargs.get('error', float()) 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.header != other.header: return False if self.position != other.position: return False if self.velocity != other.velocity: return False if self.error != other.error: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'velocity' field must be of type 'float'" self._velocity = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_SendGoal_Request(type): """Metaclass of message 'SingleJointPosition_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal_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__action__single_joint_position__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__request from control_msgs.action import SingleJointPosition if SingleJointPosition.Goal.__class__._TYPE_SUPPORT is None: SingleJointPosition.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 SingleJointPosition_SendGoal_Request(metaclass=Metaclass_SingleJointPosition_SendGoal_Request): """Message class 'SingleJointPosition_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/SingleJointPosition_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Goal'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._single_joint_position import SingleJointPosition_Goal self.goal = kwargs.get('goal', SingleJointPosition_Goal()) 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.goal_id != other.goal_id: return False if self.goal != other.goal: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Goal assert \ isinstance(value, SingleJointPosition_Goal), \ "The 'goal' field must be a sub message of type 'SingleJointPosition_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_SendGoal_Response(type): """Metaclass of message 'SingleJointPosition_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal_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__action__single_joint_position__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 SingleJointPosition_SendGoal_Response(metaclass=Metaclass_SingleJointPosition_SendGoal_Response): """Message class 'SingleJointPosition_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) 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.accepted != other.accepted: return False if self.stamp != other.stamp: 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 accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_SingleJointPosition_SendGoal(type): """Metaclass of service 'SingleJointPosition_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__send_goal from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response.__import_type_support__() class SingleJointPosition_SendGoal(metaclass=Metaclass_SingleJointPosition_SendGoal): from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Request as Request from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_GetResult_Request(type): """Metaclass of message 'SingleJointPosition_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult_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__action__single_joint_position__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 SingleJointPosition_GetResult_Request(metaclass=Metaclass_SingleJointPosition_GetResult_Request): """Message class 'SingleJointPosition_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) 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.goal_id != other.goal_id: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_GetResult_Response(type): """Metaclass of message 'SingleJointPosition_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult_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__action__single_joint_position__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__response from control_msgs.action import SingleJointPosition if SingleJointPosition.Result.__class__._TYPE_SUPPORT is None: SingleJointPosition.Result.__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 SingleJointPosition_GetResult_Response(metaclass=Metaclass_SingleJointPosition_GetResult_Response): """Message class 'SingleJointPosition_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/SingleJointPosition_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Result'), # 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.status = kwargs.get('status', int()) from control_msgs.action._single_joint_position import SingleJointPosition_Result self.result = kwargs.get('result', SingleJointPosition_Result()) 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.status != other.status: return False if self.result != other.result: 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 status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Result assert \ isinstance(value, SingleJointPosition_Result), \ "The 'result' field must be a sub message of type 'SingleJointPosition_Result'" self._result = value class Metaclass_SingleJointPosition_GetResult(type): """Metaclass of service 'SingleJointPosition_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__get_result from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Request._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult_Request.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Response._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult_Response.__import_type_support__() class SingleJointPosition_GetResult(metaclass=Metaclass_SingleJointPosition_GetResult): from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Request as Request from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_FeedbackMessage(type): """Metaclass of message 'SingleJointPosition_FeedbackMessage'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback_message from control_msgs.action import SingleJointPosition if SingleJointPosition.Feedback.__class__._TYPE_SUPPORT is None: SingleJointPosition.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 SingleJointPosition_FeedbackMessage(metaclass=Metaclass_SingleJointPosition_FeedbackMessage): """Message class 'SingleJointPosition_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/SingleJointPosition_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Feedback'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._single_joint_position import SingleJointPosition_Feedback self.feedback = kwargs.get('feedback', SingleJointPosition_Feedback()) 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.goal_id != other.goal_id: return False if self.feedback != other.feedback: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Feedback assert \ isinstance(value, SingleJointPosition_Feedback), \ "The 'feedback' field must be a sub message of type 'SingleJointPosition_Feedback'" self._feedback = value class Metaclass_SingleJointPosition(type): """Metaclass of action 'SingleJointPosition'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__single_joint_position from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_SendGoal._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_GetResult._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage.__import_type_support__() class SingleJointPosition(metaclass=Metaclass_SingleJointPosition): # The goal message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Goal as Goal # The result message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Result as Result # The feedback message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._single_joint_position import SingleJointPosition_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._single_joint_position import SingleJointPosition_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
50,584
Python
37.703137
134
0.595821
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_follow_joint_trajectory.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/FollowJointTrajectory.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_FollowJointTrajectory_Goal(type): """Metaclass of message 'FollowJointTrajectory_Goal'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__goal cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from control_msgs.msg import JointTolerance if JointTolerance.__class__._TYPE_SUPPORT is None: JointTolerance.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectory if JointTrajectory.__class__._TYPE_SUPPORT is None: JointTrajectory.__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 FollowJointTrajectory_Goal(metaclass=Metaclass_FollowJointTrajectory_Goal): """Message class 'FollowJointTrajectory_Goal'.""" __slots__ = [ '_trajectory', '_path_tolerance', '_goal_tolerance', '_goal_time_tolerance', ] _fields_and_field_types = { 'trajectory': 'trajectory_msgs/JointTrajectory', 'path_tolerance': 'sequence<control_msgs/JointTolerance>', 'goal_tolerance': 'sequence<control_msgs/JointTolerance>', 'goal_time_tolerance': 'builtin_interfaces/Duration', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # 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__)) from trajectory_msgs.msg import JointTrajectory self.trajectory = kwargs.get('trajectory', JointTrajectory()) self.path_tolerance = kwargs.get('path_tolerance', []) self.goal_tolerance = kwargs.get('goal_tolerance', []) from builtin_interfaces.msg import Duration self.goal_time_tolerance = kwargs.get('goal_time_tolerance', Duration()) 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.trajectory != other.trajectory: return False if self.path_tolerance != other.path_tolerance: return False if self.goal_tolerance != other.goal_tolerance: return False if self.goal_time_tolerance != other.goal_time_tolerance: 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 trajectory(self): """Message field 'trajectory'.""" return self._trajectory @trajectory.setter def trajectory(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectory assert \ isinstance(value, JointTrajectory), \ "The 'trajectory' field must be a sub message of type 'JointTrajectory'" self._trajectory = value @property def path_tolerance(self): """Message field 'path_tolerance'.""" return self._path_tolerance @path_tolerance.setter def path_tolerance(self, value): if __debug__: from control_msgs.msg import JointTolerance from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, JointTolerance) for v in value) and True), \ "The 'path_tolerance' field must be a set or sequence and each value of type 'JointTolerance'" self._path_tolerance = value @property def goal_tolerance(self): """Message field 'goal_tolerance'.""" return self._goal_tolerance @goal_tolerance.setter def goal_tolerance(self, value): if __debug__: from control_msgs.msg import JointTolerance from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, JointTolerance) for v in value) and True), \ "The 'goal_tolerance' field must be a set or sequence and each value of type 'JointTolerance'" self._goal_tolerance = value @property def goal_time_tolerance(self): """Message field 'goal_time_tolerance'.""" return self._goal_time_tolerance @goal_time_tolerance.setter def goal_time_tolerance(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'goal_time_tolerance' field must be a sub message of type 'Duration'" self._goal_time_tolerance = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_Result(type): """Metaclass of message 'FollowJointTrajectory_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { 'SUCCESSFUL': 0, 'INVALID_GOAL': -1, 'INVALID_JOINTS': -2, 'OLD_HEADER_TIMESTAMP': -3, 'PATH_TOLERANCE_VIOLATED': -4, 'GOAL_TOLERANCE_VIOLATED': -5, } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__result cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__result @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 { 'SUCCESSFUL': cls.__constants['SUCCESSFUL'], 'INVALID_GOAL': cls.__constants['INVALID_GOAL'], 'INVALID_JOINTS': cls.__constants['INVALID_JOINTS'], 'OLD_HEADER_TIMESTAMP': cls.__constants['OLD_HEADER_TIMESTAMP'], 'PATH_TOLERANCE_VIOLATED': cls.__constants['PATH_TOLERANCE_VIOLATED'], 'GOAL_TOLERANCE_VIOLATED': cls.__constants['GOAL_TOLERANCE_VIOLATED'], } @property def SUCCESSFUL(self): """Message constant 'SUCCESSFUL'.""" return Metaclass_FollowJointTrajectory_Result.__constants['SUCCESSFUL'] @property def INVALID_GOAL(self): """Message constant 'INVALID_GOAL'.""" return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_GOAL'] @property def INVALID_JOINTS(self): """Message constant 'INVALID_JOINTS'.""" return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_JOINTS'] @property def OLD_HEADER_TIMESTAMP(self): """Message constant 'OLD_HEADER_TIMESTAMP'.""" return Metaclass_FollowJointTrajectory_Result.__constants['OLD_HEADER_TIMESTAMP'] @property def PATH_TOLERANCE_VIOLATED(self): """Message constant 'PATH_TOLERANCE_VIOLATED'.""" return Metaclass_FollowJointTrajectory_Result.__constants['PATH_TOLERANCE_VIOLATED'] @property def GOAL_TOLERANCE_VIOLATED(self): """Message constant 'GOAL_TOLERANCE_VIOLATED'.""" return Metaclass_FollowJointTrajectory_Result.__constants['GOAL_TOLERANCE_VIOLATED'] class FollowJointTrajectory_Result(metaclass=Metaclass_FollowJointTrajectory_Result): """ Message class 'FollowJointTrajectory_Result'. Constants: SUCCESSFUL INVALID_GOAL INVALID_JOINTS OLD_HEADER_TIMESTAMP PATH_TOLERANCE_VIOLATED GOAL_TOLERANCE_VIOLATED """ __slots__ = [ '_error_code', '_error_string', ] _fields_and_field_types = { 'error_code': 'int32', 'error_string': 'string', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int32'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # 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.error_code = kwargs.get('error_code', int()) self.error_string = kwargs.get('error_string', str()) 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.error_code != other.error_code: return False if self.error_string != other.error_string: 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 error_code(self): """Message field 'error_code'.""" return self._error_code @error_code.setter def error_code(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'error_code' field must be of type 'int'" assert value >= -2147483648 and value < 2147483648, \ "The 'error_code' field must be an integer in [-2147483648, 2147483647]" self._error_code = value @property def error_string(self): """Message field 'error_string'.""" return self._error_string @error_string.setter def error_string(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'error_string' field must be of type 'str'" self._error_string = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_Feedback(type): """Metaclass of message 'FollowJointTrajectory_Feedback'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectoryPoint if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None: JointTrajectoryPoint.__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 FollowJointTrajectory_Feedback(metaclass=Metaclass_FollowJointTrajectory_Feedback): """Message class 'FollowJointTrajectory_Feedback'.""" __slots__ = [ '_header', '_joint_names', '_desired', '_actual', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'desired': 'trajectory_msgs/JointTrajectoryPoint', 'actual': 'trajectory_msgs/JointTrajectoryPoint', 'error': 'trajectory_msgs/JointTrajectoryPoint', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) from trajectory_msgs.msg import JointTrajectoryPoint self.desired = kwargs.get('desired', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.actual = kwargs.get('actual', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.error = kwargs.get('error', JointTrajectoryPoint()) 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.header != other.header: return False if self.joint_names != other.joint_names: return False if self.desired != other.desired: return False if self.actual != other.actual: return False if self.error != other.error: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def desired(self): """Message field 'desired'.""" return self._desired @desired.setter def desired(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'desired' field must be a sub message of type 'JointTrajectoryPoint'" self._desired = value @property def actual(self): """Message field 'actual'.""" return self._actual @actual.setter def actual(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'actual' field must be a sub message of type 'JointTrajectoryPoint'" self._actual = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'error' field must be a sub message of type 'JointTrajectoryPoint'" self._error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_SendGoal_Request(type): """Metaclass of message 'FollowJointTrajectory_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal_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__action__follow_joint_trajectory__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__request from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Goal.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 FollowJointTrajectory_SendGoal_Request(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Request): """Message class 'FollowJointTrajectory_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/FollowJointTrajectory_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Goal'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal self.goal = kwargs.get('goal', FollowJointTrajectory_Goal()) 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.goal_id != other.goal_id: return False if self.goal != other.goal: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal assert \ isinstance(value, FollowJointTrajectory_Goal), \ "The 'goal' field must be a sub message of type 'FollowJointTrajectory_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_SendGoal_Response(type): """Metaclass of message 'FollowJointTrajectory_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal_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__action__follow_joint_trajectory__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 FollowJointTrajectory_SendGoal_Response(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Response): """Message class 'FollowJointTrajectory_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) 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.accepted != other.accepted: return False if self.stamp != other.stamp: 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 accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_FollowJointTrajectory_SendGoal(type): """Metaclass of service 'FollowJointTrajectory_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__send_goal from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response.__import_type_support__() class FollowJointTrajectory_SendGoal(metaclass=Metaclass_FollowJointTrajectory_SendGoal): from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Request as Request from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_GetResult_Request(type): """Metaclass of message 'FollowJointTrajectory_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult_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__action__follow_joint_trajectory__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 FollowJointTrajectory_GetResult_Request(metaclass=Metaclass_FollowJointTrajectory_GetResult_Request): """Message class 'FollowJointTrajectory_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) 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.goal_id != other.goal_id: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_GetResult_Response(type): """Metaclass of message 'FollowJointTrajectory_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult_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__action__follow_joint_trajectory__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__response from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Result.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Result.__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 FollowJointTrajectory_GetResult_Response(metaclass=Metaclass_FollowJointTrajectory_GetResult_Response): """Message class 'FollowJointTrajectory_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/FollowJointTrajectory_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Result'), # 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.status = kwargs.get('status', int()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result self.result = kwargs.get('result', FollowJointTrajectory_Result()) 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.status != other.status: return False if self.result != other.result: 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 status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result assert \ isinstance(value, FollowJointTrajectory_Result), \ "The 'result' field must be a sub message of type 'FollowJointTrajectory_Result'" self._result = value class Metaclass_FollowJointTrajectory_GetResult(type): """Metaclass of service 'FollowJointTrajectory_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__get_result from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response.__import_type_support__() class FollowJointTrajectory_GetResult(metaclass=Metaclass_FollowJointTrajectory_GetResult): from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Request as Request from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_FeedbackMessage(type): """Metaclass of message 'FollowJointTrajectory_FeedbackMessage'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback_message from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Feedback.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 FollowJointTrajectory_FeedbackMessage(metaclass=Metaclass_FollowJointTrajectory_FeedbackMessage): """Message class 'FollowJointTrajectory_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/FollowJointTrajectory_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Feedback'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback self.feedback = kwargs.get('feedback', FollowJointTrajectory_Feedback()) 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.goal_id != other.goal_id: return False if self.feedback != other.feedback: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback assert \ isinstance(value, FollowJointTrajectory_Feedback), \ "The 'feedback' field must be a sub message of type 'FollowJointTrajectory_Feedback'" self._feedback = value class Metaclass_FollowJointTrajectory(type): """Metaclass of action 'FollowJointTrajectory'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__follow_joint_trajectory from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage.__import_type_support__() class FollowJointTrajectory(metaclass=Metaclass_FollowJointTrajectory): # The goal message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal as Goal # The result message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result as Result # The feedback message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
59,208
Python
38.764271
149
0.603179
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_point_head.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/PointHead.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_PointHead_Goal(type): """Metaclass of message 'PointHead_Goal'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__goal cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from geometry_msgs.msg import PointStamped if PointStamped.__class__._TYPE_SUPPORT is None: PointStamped.__class__.__import_type_support__() from geometry_msgs.msg import Vector3 if Vector3.__class__._TYPE_SUPPORT is None: Vector3.__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 PointHead_Goal(metaclass=Metaclass_PointHead_Goal): """Message class 'PointHead_Goal'.""" __slots__ = [ '_target', '_pointing_axis', '_pointing_frame', '_min_duration', '_max_velocity', ] _fields_and_field_types = { 'target': 'geometry_msgs/PointStamped', 'pointing_axis': 'geometry_msgs/Vector3', 'pointing_frame': 'string', 'min_duration': 'builtin_interfaces/Duration', 'max_velocity': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'PointStamped'), # noqa: E501 rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'Vector3'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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__)) from geometry_msgs.msg import PointStamped self.target = kwargs.get('target', PointStamped()) from geometry_msgs.msg import Vector3 self.pointing_axis = kwargs.get('pointing_axis', Vector3()) self.pointing_frame = kwargs.get('pointing_frame', str()) from builtin_interfaces.msg import Duration self.min_duration = kwargs.get('min_duration', Duration()) self.max_velocity = kwargs.get('max_velocity', float()) 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.target != other.target: return False if self.pointing_axis != other.pointing_axis: return False if self.pointing_frame != other.pointing_frame: return False if self.min_duration != other.min_duration: return False if self.max_velocity != other.max_velocity: 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 target(self): """Message field 'target'.""" return self._target @target.setter def target(self, value): if __debug__: from geometry_msgs.msg import PointStamped assert \ isinstance(value, PointStamped), \ "The 'target' field must be a sub message of type 'PointStamped'" self._target = value @property def pointing_axis(self): """Message field 'pointing_axis'.""" return self._pointing_axis @pointing_axis.setter def pointing_axis(self, value): if __debug__: from geometry_msgs.msg import Vector3 assert \ isinstance(value, Vector3), \ "The 'pointing_axis' field must be a sub message of type 'Vector3'" self._pointing_axis = value @property def pointing_frame(self): """Message field 'pointing_frame'.""" return self._pointing_frame @pointing_frame.setter def pointing_frame(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'pointing_frame' field must be of type 'str'" self._pointing_frame = value @property def min_duration(self): """Message field 'min_duration'.""" return self._min_duration @min_duration.setter def min_duration(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'min_duration' field must be a sub message of type 'Duration'" self._min_duration = value @property def max_velocity(self): """Message field 'max_velocity'.""" return self._max_velocity @max_velocity.setter def max_velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_velocity' field must be of type 'float'" self._max_velocity = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_Result(type): """Metaclass of message 'PointHead_Result'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__result cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__result @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 PointHead_Result(metaclass=Metaclass_PointHead_Result): """Message class 'PointHead_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) 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__)) 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 return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_Feedback(type): """Metaclass of message 'PointHead_Feedback'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback @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 PointHead_Feedback(metaclass=Metaclass_PointHead_Feedback): """Message class 'PointHead_Feedback'.""" __slots__ = [ '_pointing_angle_error', ] _fields_and_field_types = { 'pointing_angle_error': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # 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.pointing_angle_error = kwargs.get('pointing_angle_error', float()) 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.pointing_angle_error != other.pointing_angle_error: 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 pointing_angle_error(self): """Message field 'pointing_angle_error'.""" return self._pointing_angle_error @pointing_angle_error.setter def pointing_angle_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'pointing_angle_error' field must be of type 'float'" self._pointing_angle_error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_SendGoal_Request(type): """Metaclass of message 'PointHead_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal_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__action__point_head__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__request from control_msgs.action import PointHead if PointHead.Goal.__class__._TYPE_SUPPORT is None: PointHead.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 PointHead_SendGoal_Request(metaclass=Metaclass_PointHead_SendGoal_Request): """Message class 'PointHead_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/PointHead_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Goal'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._point_head import PointHead_Goal self.goal = kwargs.get('goal', PointHead_Goal()) 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.goal_id != other.goal_id: return False if self.goal != other.goal: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Goal assert \ isinstance(value, PointHead_Goal), \ "The 'goal' field must be a sub message of type 'PointHead_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_SendGoal_Response(type): """Metaclass of message 'PointHead_SendGoal_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal_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__action__point_head__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__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 PointHead_SendGoal_Response(metaclass=Metaclass_PointHead_SendGoal_Response): """Message class 'PointHead_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # 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.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) 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.accepted != other.accepted: return False if self.stamp != other.stamp: 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 accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_PointHead_SendGoal(type): """Metaclass of service 'PointHead_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__send_goal from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_SendGoal_Request._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal_Request.__import_type_support__() if _point_head.Metaclass_PointHead_SendGoal_Response._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal_Response.__import_type_support__() class PointHead_SendGoal(metaclass=Metaclass_PointHead_SendGoal): from control_msgs.action._point_head import PointHead_SendGoal_Request as Request from control_msgs.action._point_head import PointHead_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_GetResult_Request(type): """Metaclass of message 'PointHead_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult_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__action__point_head__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 PointHead_GetResult_Request(metaclass=Metaclass_PointHead_GetResult_Request): """Message class 'PointHead_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) 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.goal_id != other.goal_id: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_GetResult_Response(type): """Metaclass of message 'PointHead_GetResult_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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult_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__action__point_head__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__response from control_msgs.action import PointHead if PointHead.Result.__class__._TYPE_SUPPORT is None: PointHead.Result.__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 PointHead_GetResult_Response(metaclass=Metaclass_PointHead_GetResult_Response): """Message class 'PointHead_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/PointHead_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Result'), # 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.status = kwargs.get('status', int()) from control_msgs.action._point_head import PointHead_Result self.result = kwargs.get('result', PointHead_Result()) 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.status != other.status: return False if self.result != other.result: 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 status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Result assert \ isinstance(value, PointHead_Result), \ "The 'result' field must be a sub message of type 'PointHead_Result'" self._result = value class Metaclass_PointHead_GetResult(type): """Metaclass of service 'PointHead_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__get_result from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_GetResult_Request._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult_Request.__import_type_support__() if _point_head.Metaclass_PointHead_GetResult_Response._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult_Response.__import_type_support__() class PointHead_GetResult(metaclass=Metaclass_PointHead_GetResult): from control_msgs.action._point_head import PointHead_GetResult_Request as Request from control_msgs.action._point_head import PointHead_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_FeedbackMessage(type): """Metaclass of message 'PointHead_FeedbackMessage'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback_message from control_msgs.action import PointHead if PointHead.Feedback.__class__._TYPE_SUPPORT is None: PointHead.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__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 PointHead_FeedbackMessage(metaclass=Metaclass_PointHead_FeedbackMessage): """Message class 'PointHead_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/PointHead_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Feedback'), # 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__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._point_head import PointHead_Feedback self.feedback = kwargs.get('feedback', PointHead_Feedback()) 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.goal_id != other.goal_id: return False if self.feedback != other.feedback: 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 goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Feedback assert \ isinstance(value, PointHead_Feedback), \ "The 'feedback' field must be a sub message of type 'PointHead_Feedback'" self._feedback = value class Metaclass_PointHead(type): """Metaclass of action 'PointHead'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__point_head from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_SendGoal._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal.__import_type_support__() if _point_head.Metaclass_PointHead_GetResult._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult.__import_type_support__() if _point_head.Metaclass_PointHead_FeedbackMessage._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_FeedbackMessage.__import_type_support__() class PointHead(metaclass=Metaclass_PointHead): # The goal message defined in the action definition. from control_msgs.action._point_head import PointHead_Goal as Goal # The result message defined in the action definition. from control_msgs.action._point_head import PointHead_Result as Result # The feedback message defined in the action definition. from control_msgs.action._point_head import PointHead_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._point_head import PointHead_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._point_head import PointHead_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._point_head import PointHead_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
48,726
Python
36.656105
134
0.583959
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_interface_value.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/InterfaceValue.idl # generated code does not contain a copyright notice # Import statements for member types # Member 'values' import array # noqa: E402, I100 import rosidl_parser.definition # noqa: E402, I100 class Metaclass_InterfaceValue(type): """Metaclass of message 'InterfaceValue'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.InterfaceValue') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__interface_value cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__interface_value cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__interface_value cls._TYPE_SUPPORT = module.type_support_msg__msg__interface_value cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__interface_value @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 InterfaceValue(metaclass=Metaclass_InterfaceValue): """Message class 'InterfaceValue'.""" __slots__ = [ '_interface_names', '_values', ] _fields_and_field_types = { 'interface_names': 'sequence<string>', 'values': 'sequence<double>', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # 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.interface_names = kwargs.get('interface_names', []) self.values = array.array('d', kwargs.get('values', [])) 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.interface_names != other.interface_names: return False if self.values != other.values: 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 interface_names(self): """Message field 'interface_names'.""" return self._interface_names @interface_names.setter def interface_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'interface_names' field must be a set or sequence and each value of type 'str'" self._interface_names = value @property def values(self): """Message field 'values'.""" return self._values @values.setter def values(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'values' array.array() must have the type code of 'd'" self._values = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'values' field must be a set or sequence and each value of type 'float'" self._values = array.array('d', value)
6,387
Python
36.57647
134
0.571473
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_trajectory_controller_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointTrajectoryControllerState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTrajectoryControllerState(type): """Metaclass of message 'JointTrajectoryControllerState'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointTrajectoryControllerState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_trajectory_controller_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_trajectory_controller_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_trajectory_controller_state cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_trajectory_controller_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_trajectory_controller_state from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectoryPoint if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None: JointTrajectoryPoint.__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 JointTrajectoryControllerState(metaclass=Metaclass_JointTrajectoryControllerState): """Message class 'JointTrajectoryControllerState'.""" __slots__ = [ '_header', '_joint_names', '_desired', '_actual', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'desired': 'trajectory_msgs/JointTrajectoryPoint', 'actual': 'trajectory_msgs/JointTrajectoryPoint', 'error': 'trajectory_msgs/JointTrajectoryPoint', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) from trajectory_msgs.msg import JointTrajectoryPoint self.desired = kwargs.get('desired', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.actual = kwargs.get('actual', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.error = kwargs.get('error', JointTrajectoryPoint()) 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.header != other.header: return False if self.joint_names != other.joint_names: return False if self.desired != other.desired: return False if self.actual != other.actual: return False if self.error != other.error: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def desired(self): """Message field 'desired'.""" return self._desired @desired.setter def desired(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'desired' field must be a sub message of type 'JointTrajectoryPoint'" self._desired = value @property def actual(self): """Message field 'actual'.""" return self._actual @actual.setter def actual(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'actual' field must be a sub message of type 'JointTrajectoryPoint'" self._actual = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'error' field must be a sub message of type 'JointTrajectoryPoint'" self._error = value
8,648
Python
37.44
134
0.591351
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_tolerance.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointTolerance.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTolerance(type): """Metaclass of message 'JointTolerance'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointTolerance') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_tolerance cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_tolerance cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_tolerance cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_tolerance cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_tolerance @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 JointTolerance(metaclass=Metaclass_JointTolerance): """Message class 'JointTolerance'.""" __slots__ = [ '_name', '_position', '_velocity', '_acceleration', ] _fields_and_field_types = { 'name': 'string', 'position': 'double', 'velocity': 'double', 'acceleration': 'double', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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()) self.position = kwargs.get('position', float()) self.velocity = kwargs.get('velocity', float()) self.acceleration = kwargs.get('acceleration', float()) 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.position != other.position: return False if self.velocity != other.velocity: return False if self.acceleration != other.acceleration: 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 position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'velocity' field must be of type 'float'" self._velocity = value @property def acceleration(self): """Message field 'acceleration'.""" return self._acceleration @acceleration.setter def acceleration(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'acceleration' field must be of type 'float'" self._acceleration = value
6,075
Python
32.755555
134
0.560329
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_pid_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/PidState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_PidState(type): """Metaclass of message 'PidState'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.PidState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__pid_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__pid_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__pid_state cls._TYPE_SUPPORT = module.type_support_msg__msg__pid_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__pid_state from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__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 PidState(metaclass=Metaclass_PidState): """Message class 'PidState'.""" __slots__ = [ '_header', '_timestep', '_error', '_error_dot', '_p_error', '_i_error', '_d_error', '_p_term', '_i_term', '_d_term', '_i_max', '_i_min', '_output', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'timestep': 'builtin_interfaces/Duration', 'error': 'double', 'error_dot': 'double', 'p_error': 'double', 'i_error': 'double', 'd_error': 'double', 'p_term': 'double', 'i_term': 'double', 'd_term': 'double', 'i_max': 'double', 'i_min': 'double', 'output': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) from builtin_interfaces.msg import Duration self.timestep = kwargs.get('timestep', Duration()) self.error = kwargs.get('error', float()) self.error_dot = kwargs.get('error_dot', float()) self.p_error = kwargs.get('p_error', float()) self.i_error = kwargs.get('i_error', float()) self.d_error = kwargs.get('d_error', float()) self.p_term = kwargs.get('p_term', float()) self.i_term = kwargs.get('i_term', float()) self.d_term = kwargs.get('d_term', float()) self.i_max = kwargs.get('i_max', float()) self.i_min = kwargs.get('i_min', float()) self.output = kwargs.get('output', float()) 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.header != other.header: return False if self.timestep != other.timestep: return False if self.error != other.error: return False if self.error_dot != other.error_dot: return False if self.p_error != other.p_error: return False if self.i_error != other.i_error: return False if self.d_error != other.d_error: return False if self.p_term != other.p_term: return False if self.i_term != other.i_term: return False if self.d_term != other.d_term: return False if self.i_max != other.i_max: return False if self.i_min != other.i_min: return False if self.output != other.output: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def timestep(self): """Message field 'timestep'.""" return self._timestep @timestep.setter def timestep(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'timestep' field must be a sub message of type 'Duration'" self._timestep = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value @property def error_dot(self): """Message field 'error_dot'.""" return self._error_dot @error_dot.setter def error_dot(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error_dot' field must be of type 'float'" self._error_dot = value @property def p_error(self): """Message field 'p_error'.""" return self._p_error @p_error.setter def p_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p_error' field must be of type 'float'" self._p_error = value @property def i_error(self): """Message field 'i_error'.""" return self._i_error @i_error.setter def i_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_error' field must be of type 'float'" self._i_error = value @property def d_error(self): """Message field 'd_error'.""" return self._d_error @d_error.setter def d_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd_error' field must be of type 'float'" self._d_error = value @property def p_term(self): """Message field 'p_term'.""" return self._p_term @p_term.setter def p_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p_term' field must be of type 'float'" self._p_term = value @property def i_term(self): """Message field 'i_term'.""" return self._i_term @i_term.setter def i_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_term' field must be of type 'float'" self._i_term = value @property def d_term(self): """Message field 'd_term'.""" return self._d_term @d_term.setter def d_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd_term' field must be of type 'float'" self._d_term = value @property def i_max(self): """Message field 'i_max'.""" return self._i_max @i_max.setter def i_max(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_max' field must be of type 'float'" self._i_max = value @property def i_min(self): """Message field 'i_min'.""" return self._i_min @i_min.setter def i_min(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_min' field must be of type 'float'" self._i_min = value @property def output(self): """Message field 'output'.""" return self._output @output.setter def output(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'output' field must be of type 'float'" self._output = value
11,681
Python
31.181818
134
0.532061
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_controller_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointControllerState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointControllerState(type): """Metaclass of message 'JointControllerState'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointControllerState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_controller_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_controller_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_controller_state cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_controller_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_controller_state from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__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 JointControllerState(metaclass=Metaclass_JointControllerState): """Message class 'JointControllerState'.""" __slots__ = [ '_header', '_set_point', '_process_value', '_process_value_dot', '_error', '_time_step', '_command', '_p', '_i', '_d', '_i_clamp', '_antiwindup', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'set_point': 'double', 'process_value': 'double', 'process_value_dot': 'double', 'error': 'double', 'time_step': 'double', 'command': 'double', 'p': 'double', 'i': 'double', 'd': 'double', 'i_clamp': 'double', 'antiwindup': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.set_point = kwargs.get('set_point', float()) self.process_value = kwargs.get('process_value', float()) self.process_value_dot = kwargs.get('process_value_dot', float()) self.error = kwargs.get('error', float()) self.time_step = kwargs.get('time_step', float()) self.command = kwargs.get('command', float()) self.p = kwargs.get('p', float()) self.i = kwargs.get('i', float()) self.d = kwargs.get('d', float()) self.i_clamp = kwargs.get('i_clamp', float()) self.antiwindup = kwargs.get('antiwindup', 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.header != other.header: return False if self.set_point != other.set_point: return False if self.process_value != other.process_value: return False if self.process_value_dot != other.process_value_dot: return False if self.error != other.error: return False if self.time_step != other.time_step: return False if self.command != other.command: return False if self.p != other.p: return False if self.i != other.i: return False if self.d != other.d: return False if self.i_clamp != other.i_clamp: return False if self.antiwindup != other.antiwindup: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def set_point(self): """Message field 'set_point'.""" return self._set_point @set_point.setter def set_point(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'set_point' field must be of type 'float'" self._set_point = value @property def process_value(self): """Message field 'process_value'.""" return self._process_value @process_value.setter def process_value(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'process_value' field must be of type 'float'" self._process_value = value @property def process_value_dot(self): """Message field 'process_value_dot'.""" return self._process_value_dot @process_value_dot.setter def process_value_dot(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'process_value_dot' field must be of type 'float'" self._process_value_dot = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value @property def time_step(self): """Message field 'time_step'.""" return self._time_step @time_step.setter def time_step(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'time_step' field must be of type 'float'" self._time_step = value @property def command(self): """Message field 'command'.""" return self._command @command.setter def command(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'command' field must be of type 'float'" self._command = value @property def p(self): """Message field 'p'.""" return self._p @p.setter def p(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p' field must be of type 'float'" self._p = value @property def i(self): """Message field 'i'.""" return self._i @i.setter def i(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i' field must be of type 'float'" self._i = value @property def d(self): """Message field 'd'.""" return self._d @d.setter def d(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd' field must be of type 'float'" self._d = value @property def i_clamp(self): """Message field 'i_clamp'.""" return self._i_clamp @i_clamp.setter def i_clamp(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_clamp' field must be of type 'float'" self._i_clamp = value @property def antiwindup(self): """Message field 'antiwindup'.""" return self._antiwindup @antiwindup.setter def antiwindup(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'antiwindup' field must be of type 'bool'" self._antiwindup = value
11,020
Python
31.606509
134
0.54274
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/__init__.py
from control_msgs.msg._dynamic_joint_state import DynamicJointState # noqa: F401 from control_msgs.msg._gripper_command import GripperCommand # noqa: F401 from control_msgs.msg._interface_value import InterfaceValue # noqa: F401 from control_msgs.msg._joint_controller_state import JointControllerState # noqa: F401 from control_msgs.msg._joint_jog import JointJog # noqa: F401 from control_msgs.msg._joint_tolerance import JointTolerance # noqa: F401 from control_msgs.msg._joint_trajectory_controller_state import JointTrajectoryControllerState # noqa: F401 from control_msgs.msg._pid_state import PidState # noqa: F401
630
Python
69.111103
108
0.803175
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_gripper_command.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/GripperCommand.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GripperCommand(type): """Metaclass of message 'GripperCommand'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.GripperCommand') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__gripper_command cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__gripper_command cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__gripper_command cls._TYPE_SUPPORT = module.type_support_msg__msg__gripper_command cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__gripper_command @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 GripperCommand(metaclass=Metaclass_GripperCommand): """Message class 'GripperCommand'.""" __slots__ = [ '_position', '_max_effort', ] _fields_and_field_types = { 'position': 'double', 'max_effort': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # 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.position = kwargs.get('position', float()) self.max_effort = kwargs.get('max_effort', float()) 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.position != other.position: return False if self.max_effort != other.max_effort: 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 position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def max_effort(self): """Message field 'max_effort'.""" return self._max_effort @max_effort.setter def max_effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_effort' field must be of type 'float'" self._max_effort = value
4,935
Python
33.760563
134
0.565147
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_dynamic_joint_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/DynamicJointState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_DynamicJointState(type): """Metaclass of message 'DynamicJointState'.""" _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('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.DynamicJointState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__dynamic_joint_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__dynamic_joint_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__dynamic_joint_state cls._TYPE_SUPPORT = module.type_support_msg__msg__dynamic_joint_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__dynamic_joint_state from control_msgs.msg import InterfaceValue if InterfaceValue.__class__._TYPE_SUPPORT is None: InterfaceValue.__class__.__import_type_support__() from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__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 DynamicJointState(metaclass=Metaclass_DynamicJointState): """Message class 'DynamicJointState'.""" __slots__ = [ '_header', '_joint_names', '_interface_values', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'interface_values': 'sequence<control_msgs/InterfaceValue>', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'InterfaceValue')), # 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__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) self.interface_values = kwargs.get('interface_values', []) 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.header != other.header: return False if self.joint_names != other.joint_names: return False if self.interface_values != other.interface_values: 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 header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def interface_values(self): """Message field 'interface_values'.""" return self._interface_values @interface_values.setter def interface_values(self, value): if __debug__: from control_msgs.msg import InterfaceValue from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, InterfaceValue) for v in value) and True), \ "The 'interface_values' field must be a set or sequence and each value of type 'InterfaceValue'" self._interface_values = value
7,379
Python
37.4375
149
0.577585
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_set_prim_attribute.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/SetPrimAttribute.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_SetPrimAttribute_Request(type): """Metaclass of message 'SetPrimAttribute_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('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute_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__set_prim_attribute__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__request cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__request @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 SetPrimAttribute_Request(metaclass=Metaclass_SetPrimAttribute_Request): """Message class 'SetPrimAttribute_Request'.""" __slots__ = [ '_path', '_attribute', '_value', ] _fields_and_field_types = { 'path': 'string', 'attribute': 'string', 'value': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # 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.path = kwargs.get('path', str()) self.attribute = kwargs.get('attribute', str()) self.value = kwargs.get('value', str()) 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.path != other.path: return False if self.attribute != other.attribute: return False if self.value != other.value: 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 path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value @property def attribute(self): """Message field 'attribute'.""" return self._attribute @attribute.setter def attribute(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'attribute' field must be of type 'str'" self._attribute = value @property def value(self): """Message field 'value'.""" return self._value @value.setter def value(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'value' field must be of type 'str'" self._value = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SetPrimAttribute_Response(type): """Metaclass of message 'SetPrimAttribute_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('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute_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__set_prim_attribute__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__response cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__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 SetPrimAttribute_Response(metaclass=Metaclass_SetPrimAttribute_Response): """Message class 'SetPrimAttribute_Response'.""" __slots__ = [ '_success', '_message', ] _fields_and_field_types = { 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # 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()) self.message = kwargs.get('message', str()) 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 if self.message != other.message: 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 @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_SetPrimAttribute(type): """Metaclass of service 'SetPrimAttribute'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__set_prim_attribute from add_on_msgs.srv import _set_prim_attribute if _set_prim_attribute.Metaclass_SetPrimAttribute_Request._TYPE_SUPPORT is None: _set_prim_attribute.Metaclass_SetPrimAttribute_Request.__import_type_support__() if _set_prim_attribute.Metaclass_SetPrimAttribute_Response._TYPE_SUPPORT is None: _set_prim_attribute.Metaclass_SetPrimAttribute_Response.__import_type_support__() class SetPrimAttribute(metaclass=Metaclass_SetPrimAttribute): from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Request as Request from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
11,863
Python
34.309524
134
0.573717
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/__init__.py
from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute # noqa: F401 from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes # noqa: F401 from add_on_msgs.srv._get_prims import GetPrims # noqa: F401 from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute # noqa: F401
301
Python
59.399988
80
0.777409
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prims.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrims.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrims_Request(type): """Metaclass of message 'GetPrims_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('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_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__get_prims__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__request @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 GetPrims_Request(metaclass=Metaclass_GetPrims_Request): """Message class 'GetPrims_Request'.""" __slots__ = [ '_path', ] _fields_and_field_types = { 'path': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # 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.path = kwargs.get('path', str()) 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.path != other.path: 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 path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrims_Response(type): """Metaclass of message 'GetPrims_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('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_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__get_prims__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__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 GetPrims_Response(metaclass=Metaclass_GetPrims_Response): """Message class 'GetPrims_Response'.""" __slots__ = [ '_paths', '_types', '_success', '_message', ] _fields_and_field_types = { 'paths': 'sequence<string>', 'types': 'sequence<string>', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # 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.paths = kwargs.get('paths', []) self.types = kwargs.get('types', []) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) 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.paths != other.paths: return False if self.types != other.types: return False if self.success != other.success: return False if self.message != other.message: 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 paths(self): """Message field 'paths'.""" return self._paths @paths.setter def paths(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'paths' field must be a set or sequence and each value of type 'str'" self._paths = value @property def types(self): """Message field 'types'.""" return self._types @types.setter def types(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'types' field must be a set or sequence and each value of type 'str'" self._types = value @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 @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrims(type): """Metaclass of service 'GetPrims'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prims from add_on_msgs.srv import _get_prims if _get_prims.Metaclass_GetPrims_Request._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Request.__import_type_support__() if _get_prims.Metaclass_GetPrims_Response._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Response.__import_type_support__() class GetPrims(metaclass=Metaclass_GetPrims): from add_on_msgs.srv._get_prims import GetPrims_Request as Request from add_on_msgs.srv._get_prims import GetPrims_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
12,577
Python
34.331461
134
0.563091
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/test_ros2_bridge.py
try: import omni.kit.test TestCase = omni.kit.test.AsyncTestCaseFailOnLogError except: class TestCase: pass import json import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.action import ActionClient from action_msgs.msg import GoalStatus from trajectory_msgs.msg import JointTrajectoryPoint from control_msgs.action import FollowJointTrajectory from control_msgs.action import GripperCommand import add_on_msgs.srv # 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 TestROS2Bridge(TestCase): # 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_ros2_bridge(self): pass class TestROS2BridgeNode(Node): def __init__(self): super().__init__('test_ros2_bridge') self.get_attribute_service_name = '/get_attribute' self.set_attribute_service_name = '/set_attribute' self.gripper_command_action_name = "/panda_hand_controller/gripper_command" self.follow_joint_trajectory_action_name = "/panda_arm_controller/follow_joint_trajectory" self.get_attribute_client = self.create_client(add_on_msgs.srv.GetPrimAttribute, self.get_attribute_service_name) self.set_attribute_client = self.create_client(add_on_msgs.srv.SetPrimAttribute, self.set_attribute_service_name) self.gripper_command_client = ActionClient(self, GripperCommand, self.gripper_command_action_name) self.follow_joint_trajectory_client = ActionClient(self, FollowJointTrajectory, self.follow_joint_trajectory_action_name) self.follow_joint_trajectory_goal_msg = FollowJointTrajectory.Goal() self.follow_joint_trajectory_goal_msg.path_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_time_tolerance = Duration().to_msg() self.follow_joint_trajectory_goal_msg.trajectory.header.frame_id = "panda_link0" self.follow_joint_trajectory_goal_msg.trajectory.joint_names = ["panda_joint1", "panda_joint2", "panda_joint3", "panda_joint4", "panda_joint5", "panda_joint6", "panda_joint7"] self.follow_joint_trajectory_goal_msg.trajectory.points = [ JointTrajectoryPoint(positions=[0.012, -0.5689, 0.0, -2.8123, 0.0, 3.0367, 0.741], time_from_start=Duration(seconds=0, nanoseconds=0).to_msg()), JointTrajectoryPoint(positions=[0.011073551914608105, -0.5251352171920526, 6.967729509163362e-06, -2.698296723677182, 7.613460540484924e-06, 2.93314462685839, 0.6840062390114862], time_from_start=Duration(seconds=0, nanoseconds= 524152995).to_msg()), JointTrajectoryPoint(positions=[0.010147103829216212, -0.48137043438410526, 1.3935459018326723e-05, -2.5842934473543644, 1.5226921080969849e-05, 2.82958925371678, 0.6270124780229722], time_from_start=Duration(seconds=1, nanoseconds= 48305989).to_msg()), JointTrajectoryPoint(positions=[0.009220655743824318, -0.43760565157615794, 2.0903188527490087e-05, -2.4702901710315466, 2.2840381621454772e-05, 2.72603388057517, 0.5700187170344584], time_from_start=Duration(seconds=1, nanoseconds= 572458984).to_msg()), JointTrajectoryPoint(positions=[0.008294207658432425, -0.39384086876821056, 2.7870918036653447e-05, -2.3562868947087283, 3.0453842161939697e-05, 2.6224785074335597, 0.5130249560459446], time_from_start=Duration(seconds=2, nanoseconds= 96611978).to_msg()), JointTrajectoryPoint(positions=[0.00736775957304053, -0.3500760859602632, 3.483864754581681e-05, -2.2422836183859105, 3.806730270242462e-05, 2.518923134291949, 0.45603119505743067], time_from_start=Duration(seconds=2, nanoseconds= 620764973).to_msg()), JointTrajectoryPoint(positions=[0.006441311487648636, -0.30631130315231586, 4.1806377054980174e-05, -2.1282803420630927, 4.5680763242909544e-05, 2.415367761150339, 0.3990374340689168], time_from_start=Duration(seconds=3, nanoseconds= 144917968).to_msg()), JointTrajectoryPoint(positions=[0.005514863402256743, -0.2625465203443685, 4.877410656414353e-05, -2.014277065740275, 5.3294223783394466e-05, 2.311812388008729, 0.34204367308040295], time_from_start=Duration(seconds=3, nanoseconds= 669070962).to_msg()), JointTrajectoryPoint(positions=[0.004588415316864848, -0.2187817375364211, 5.5741836073306894e-05, -1.900273789417457, 6.0907684323879394e-05, 2.208257014867119, 0.28504991209188907], time_from_start=Duration(seconds=4, nanoseconds= 193223957).to_msg()), ] self.gripper_command_open_goal_msg = GripperCommand.Goal() self.gripper_command_open_goal_msg.command.position = 0.03990753115697298 self.gripper_command_open_goal_msg.command.max_effort = 0.0 self.gripper_command_close_goal_msg = GripperCommand.Goal() self.gripper_command_close_goal_msg.command.position = 8.962388141080737e-05 self.gripper_command_close_goal_msg.command.max_effort = 0.0 if __name__ == '__main__': rclpy.init() node = TestROS2BridgeNode() # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (with obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is True assert result.result.reached_goal is False assert abs(result.result.position - 0.0295) < 1e-3 # open gripper command future = node.gripper_command_client.send_goal_async(node.gripper_command_open_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0389) < 1e-3 # ==== Attribute ==== assert node.get_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.get_attribute_service_name) assert node.set_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.set_attribute_service_name) request_get_attribute = add_on_msgs.srv.GetPrimAttribute.Request() request_get_attribute.path = "/Cylinder" request_get_attribute.attribute = "physics:collisionEnabled" request_set_attribute = add_on_msgs.srv.SetPrimAttribute.Request() request_set_attribute.path = request_get_attribute.path request_set_attribute.attribute = request_get_attribute.attribute request_set_attribute.value = json.dumps(False) # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is True # disable obstacle collision shape future = node.set_attribute_client.call_async(request_set_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is False # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (without obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0) < 1e-3 # ==== Follow Joint Trajectory ==== assert node.follow_joint_trajectory_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.follow_joint_trajectory_action_name) # move to goal future = node.follow_joint_trajectory_client.send_goal_async(node.follow_joint_trajectory_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=10.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.error_code == result.result.SUCCESSFUL print("Test passed")
9,613
Python
52.116022
268
0.730885
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/__init__.py
from .test_ros2_bridge import *
32
Python
15.499992
31
0.75
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/semu/misc/vscode/scripts/extension.py
import __future__ import sys import json import time import types import socket import asyncio import threading import traceback import contextlib import subprocess from io import StringIO from dis import COMPILER_FLAG_NAMES try: from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT except ImportError: PyCF_ALLOW_TOP_LEVEL_AWAIT = 0 import carb import omni.ext _udp_server = None _udp_clients = [] def _log_info(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_INFO, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Info][{mod}] {msg}".encode(), client) def _log_warn(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_WARN, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Warning][{mod}] {msg}".encode(), client) def _log_error(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_ERROR, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Error][{mod}] {msg}".encode(), client) def _get_coroutine_flag() -> int: """Get the coroutine flag for the current Python version """ for k, v in COMPILER_FLAG_NAMES.items(): if v == "COROUTINE": return k return -1 COROUTINE_FLAG = _get_coroutine_flag() def _has_coroutine_flag(code) -> bool: """Check if the code has the coroutine flag set """ if COROUTINE_FLAG == -1: return False return bool(code.co_flags & COROUTINE_FLAG) def _get_compiler_flags() -> int: """Get the compiler flags for the current Python version """ flags = 0 for value in globals().values(): try: if isinstance(value, __future__._Feature): f = value.compiler_flag flags |= f except BaseException: pass flags = flags | PyCF_ALLOW_TOP_LEVEL_AWAIT return flags def _get_event_loop() -> asyncio.AbstractEventLoop: """Backward compatible function for getting the event loop """ try: if sys.version_info >= (3, 7): return asyncio.get_running_loop() else: return asyncio.get_event_loop() except RuntimeError: return asyncio.get_event_loop_policy().get_event_loop() class Extension(omni.ext.IExt): WINDOW_NAME = "Embedded VS Code" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self, ext_id): self._globals = {**globals()} self._locals = self._globals # get extension settings self._settings = carb.settings.get_settings() self._socket_ip = self._settings.get("/exts/semu.misc.vscode/socket_ip") self._socket_port = self._settings.get("/exts/semu.misc.vscode/socket_port") self._carb_logging = self._settings.get("/exts/semu.misc.vscode/carb_logging") kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.vscode/kill_processes_with_port_in_use") # menu item self._editor_menu = omni.kit.ui.get_editor_menu() if self._editor_menu: self._menu = self._editor_menu.add_item(Extension.MENU_PATH, self._show_notification, toggle=False, value=False) # shutdown stream self.shutdown_stream_ebent = omni.kit.app.get_app().get_shutdown_event_stream() \ .create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.vscode", order=0) # ensure port is free if kill_processes_with_port_in_use: if sys.platform == "win32": pids = [] cmd = ["netstat", "-ano"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: if str(self._socket_port).encode() in line: pids.append(line.strip().split(b" ")[-1].decode()) p.wait() for pid in pids: carb.log_warn(f"Forced process shutdown with PID {pid}") cmd = ["taskkill", "/PID", pid, "/F"] subprocess.Popen(cmd).wait() # create socket self._socket_last_error = "" self._server = None self._create_socket() # carb logging to VS Code if self._carb_logging: # create UDP socket self._udp_server_running = False threading.Thread(target=self._create_udp_socket).start() # checkpoint carb log functions self._carb_log_info = types.FunctionType(carb.log_info.__code__, carb.log_info.__globals__, carb.log_info.__name__, carb.log_info.__defaults__, carb.log_info.__closure__) self._carb_log_warn = types.FunctionType(carb.log_warn.__code__, carb.log_warn.__globals__, carb.log_warn.__name__, carb.log_warn.__defaults__, carb.log_warn.__closure__) self._carb_log_error = types.FunctionType(carb.log_error.__code__, carb.log_error.__globals__, carb.log_error.__name__, carb.log_error.__defaults__, carb.log_error.__closure__) # override carb log functions carb.log_info = types.FunctionType(_log_info.__code__, _log_info.__globals__, _log_info.__name__, _log_info.__defaults__, _log_info.__closure__) carb.log_warn = types.FunctionType(_log_warn.__code__, _log_warn.__globals__, _log_warn.__name__, _log_warn.__defaults__, _log_warn.__closure__) carb.log_error = types.FunctionType(_log_error.__code__, _log_error.__globals__, _log_error.__name__, _log_error.__defaults__, _log_error.__closure__) def on_shutdown(self): global _udp_server, _udp_clients # restore carb log functions if self._carb_logging: carb.log_info = self._carb_log_info carb.log_warn = self._carb_log_warn carb.log_error = self._carb_log_error # clean up menu item if self._menu is not None: try: self._editor_menu.remove_item(self._menu) except: self._editor_menu.remove_item(Extension.MENU_PATH) self._menu = None # close the socket if self._server: self._server.close() _get_event_loop().run_until_complete(self._server.wait_closed()) # close the UDP socket if self._carb_logging: _udp_server = None _udp_clients = [] # wait for the UDP socket to close while self._udp_server_running: time.sleep(0.1) # extension ui methods def _on_shutdown_event(self, event): if event.type == omni.kit.app.POST_QUIT_EVENT_TYPE: self.on_shutdown() def _show_notification(self, *args, **kwargs) -> None: """Show extension data in the notification area """ if self._server is None: notification = "Unable to start the socket server at {}:{}. {}".format(self._socket_ip, self._socket_port, self._socket_last_error) status=omni.kit.notification_manager.NotificationStatus.WARNING else: notification = "Embedded VS Code socket server is running at {}:{}.\nUDP socket server for carb logging is {}"\ .format(self._socket_ip, self._socket_port, "enabled" if self._carb_logging else "disabled") status=omni.kit.notification_manager.NotificationStatus.INFO ok_button = omni.kit.notification_manager.NotificationButtonInfo("OK", on_complete=None) omni.kit.notification_manager.post_notification(notification, hide_after_timeout=False, duration=0, status=status, button_infos=[ok_button]) print(notification) carb.log_info(notification) # internal socket methods def _create_udp_socket(self) -> None: """Create the UDP socket for broadcasting carb logging """ global _udp_server, _udp_clients self._udp_server_running = True with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as _server: try: _server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) _server.bind((self._socket_ip, self._socket_port)) _server.setblocking(False) _server.settimeout(0.1) except Exception as e: _udp_server = None _udp_clients = [] carb.log_error(str(e)) self._udp_server_running = False return _udp_server = _server _udp_clients = [] while _udp_server is not None: try: _, addr = _server.recvfrom(1024) if addr not in _udp_clients: _udp_clients.append(addr) except socket.timeout: pass except Exception as e: carb.log_error("UDP server error: {}".format(e)) break self._udp_server_running = False def _create_socket(self) -> None: """Create a socket server to listen for incoming connections from the client """ class ServerProtocol(asyncio.Protocol): def __init__(self, parent) -> None: super().__init__() self._parent = parent def connection_made(self, transport): peername = transport.get_extra_info('peername') self.transport = transport def data_received(self, data): asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(data.decode(), self.transport), _get_event_loop()) async def server_task(): try: self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self), host=self._socket_ip, port=self._socket_port, family=socket.AF_INET, reuse_port=None if sys.platform == 'win32' else True) except Exception as e: self._server = None self._socket_last_error = str(e) carb.log_error(str(e)) return await self._server.start_serving() task = _get_event_loop().create_task(server_task()) async def _exec_code_async(self, statement: str, transport: asyncio.Transport) -> None: """Execute the statement in the Omniverse scope and send the result to the client :param statement: statement to execute :type statement: str :param transport: transport to send the result to the client :type transport: asyncio.Transport :return: reply dictionary as expected by the client :rtype: dict """ _stdout = StringIO() try: with contextlib.redirect_stdout(_stdout): should_exec_code = True # try 'eval' first try: code = compile(statement, "<string>", "eval", flags= _get_compiler_flags(), dont_inherit=True) except SyntaxError: pass else: result = eval(code, self._globals, self._locals) should_exec_code = False # if 'eval' fails, try 'exec' if should_exec_code: code = compile(statement, "<string>", "exec", flags= _get_compiler_flags(), dont_inherit=True) result = eval(code, self._globals, self._locals) # await the result if it is a coroutine if _has_coroutine_flag(code): result = await result except Exception as e: # clean traceback _traceback = traceback.format_exc() _i = _traceback.find('\n File "<string>"') if _i != -1: _traceback = _traceback[_i + 20:] _traceback = _traceback.replace(", in <module>\n", "\n") # build reply dictionary reply = {"status": "error", "traceback": [_traceback], "ename": str(type(e).__name__), "evalue": str(e)} else: reply = {"status": "ok"} # add output to reply dictionary for printing reply["output"] = _stdout.getvalue() if reply["output"].endswith('\n'): reply["output"] = reply["output"][:-1] # send the reply to the client reply = json.dumps(reply) transport.write(reply.encode()) # close the connection transport.close()
14,679
Python
39.66482
143
0.501328
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_snippet.py
import json title = "TITLE" description = "DESCRIPTION" # placehorlders syntax: ${1:foo}, ${2:bar}, $0. # placeholder traversal order is ascending by number, starting from one. # zero is an optional special case that always comes last, # and exits snippet mode with the cursor at the specified position snippet = """ CODE """ # generate entry print() print(json.dumps({"title": title, "description": description, "snippet":snippet[1:]}, # remove first line break indent=4)) print()
547
Python
21.833332
72
0.641682
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_commands_merge.py
import os import json def merge(snippets, app): for s in app["snippets"]: exists = False for ss in snippets: if s["title"] == ss["title"]: exists = True break # add section if not exists: print(" |-- new: {} ({})".format(s["title"], len(s["snippets"]))) snippets.append(s) # update section else: print(" |-- update: {} ({} <- {})".format(s["title"], len(ss["snippets"]), len(s["snippets"]))) for subs in s["snippets"]: exists = False for subss in ss["snippets"]: if subs["title"] == subss["title"]: exists = True break if not exists: print(" | |-- add:", subs["title"]) ss["snippets"].append(subs) snippets = [] # merge print("CREATE") with open(os.path.join("commands", "kit-commands-create.json")) as f: merge(snippets, json.load(f)) print("CODE") with open(os.path.join("commands", "kit-commands-code.json")) as f: merge(snippets, json.load(f)) print("ISAAC SIM") with open(os.path.join("commands", "kit-commands-isaac-sim.json")) as f: merge(snippets, json.load(f)) # sort snippets snippets = sorted(snippets, key=lambda d: d["title"]) for s in snippets: s["snippets"] = sorted(s["snippets"], key=lambda d: d["title"]) # save snippets with open("kit-commands.json", "w") as f: json.dump({"snippets": snippets}, f, indent=0) print("done")
1,618
Python
27.403508
108
0.508035
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_isaac_sim.py
import json import inspect from types import FunctionType from pxr import Sdf def args_annotations(method): signature = inspect.signature(method) args = [] annotations = [] return_val = signature.return_annotation return_val = class_fullname(return_val) if return_val != type(inspect.Signature.empty) else "None" return_val = "" if return_val in ["inspect._empty", "None"] else return_val for parameter in signature.parameters.values(): if parameter.name in ["self", "args", "kwargs"]: continue # arg if type(parameter.default) == type(inspect.Parameter.empty): args.append("{}={}".format(parameter.name, parameter.name)) else: default_value = parameter.default if type(parameter.default) is str: default_value = '"{}"'.format(parameter.default) elif type(parameter.default) is Sdf.Path: if parameter.default == Sdf.Path.emptyPath: default_value = "Sdf.Path.emptyPath" else: default_value = 'Sdf.Path("{}")'.format(parameter.default) elif inspect.isclass(parameter.default): default_value = class_fullname(parameter.default) args.append("{}={}".format(parameter.name, default_value)) # annotation if parameter.annotation == inspect.Parameter.empty: annotations.append("") else: annotations.append(class_fullname(parameter.annotation)) return args, annotations, return_val def class_fullname(c): try: module = c.__module__ if module == 'builtins': return c.__name__ return module + '.' + c.__name__ except: return str(c) def get_class(klass, object_name): class_name = klass.__qualname__ args, annotations, _ = args_annotations(klass.__init__) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' spaces = len(object_name) + 3 + len(class_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = klass.__doc__.replace("\n ", "\n") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] while " " in description: description = description.replace(" ", " ") except Exception as e: description = None if not description: description = "" snippet = '{} = {}({}'.format(object_name, class_name, arguments_as_string) + "\n" return { "title": class_name, "description": description, "snippet": snippet } def get_methods(klass, object_name): method_names = sorted([x for x, y in klass.__dict__.items() if type(y) == FunctionType and not x.startswith("__")]) snippets = [] for method_name in method_names: if method_name.startswith("_") or method_name.startswith("__"): continue args, annotations, return_val = args_annotations(klass.__dict__[method_name]) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' return_var_name = "" if method_name.startswith("get_"): return_var_name = method_name[4:] + " = " spaces = len(return_var_name) + len(object_name) + 1 + len(method_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = klass.__dict__[method_name].__doc__.replace("\n ", "\n") while " " in description: description = description.replace(" ", " ") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] if description.endswith("\n "): description = description[:-2] except Exception as e: description = None if not description: description = "" if return_var_name: snippet = '{}{}.{}({}'.format(return_var_name, object_name, method_name, arguments_as_string) + "\n" else: snippet = '{}.{}({}'.format(object_name, method_name, arguments_as_string) + "\n" snippets.append({ "title": method_name, "description": description, "snippet": snippet }) return snippets def get_functions(module, module_name, exclude_functions=[]): functions = inspect.getmembers(module, inspect.isfunction) snippets = [] for function in functions: function_name = function[0] if function_name.startswith("_") or function_name.startswith("__"): continue if function_name in exclude_functions: continue args, annotations, return_val = args_annotations(function[1]) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' return_var_name = "" if return_val: return_var_name = "value = " spaces = len(return_var_name) + len(module_name) + 1 + len(function_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = function[1].__doc__.replace("\n ", "\n") while " " in description: description = description.replace(" ", " ") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] if description.endswith("\n "): description = description[:-2] except Exception as e: description = None if not description: description = "" if return_var_name: snippet = '{}{}.{}({}'.format(return_var_name, module_name, function_name, arguments_as_string) + "\n" else: snippet = '{}.{}({}'.format(module_name, function_name, arguments_as_string) + "\n" snippets.append({ "title": function_name, "description": description, "snippet": snippet }) return snippets from omni.isaac.core.articulations import Articulation, ArticulationGripper, ArticulationSubset, ArticulationView from omni.isaac.core.controllers import ArticulationController, BaseController, BaseGripperController from omni.isaac.core.loggers import DataLogger from omni.isaac.core.materials import OmniGlass, OmniPBR, ParticleMaterial, ParticleMaterialView, PhysicsMaterial, PreviewSurface, VisualMaterial from omni.isaac.core.objects import DynamicCapsule, DynamicCone, DynamicCuboid, DynamicCylinder, DynamicSphere from omni.isaac.core.objects import FixedCapsule, FixedCone, FixedCuboid, FixedCylinder, FixedSphere, GroundPlane from omni.isaac.core.objects import VisualCapsule, VisualCone, VisualCuboid, VisualCylinder, VisualSphere from omni.isaac.core.physics_context import PhysicsContext from omni.isaac.core.prims import BaseSensor, ClothPrim, ClothPrimView, GeometryPrim, GeometryPrimView, ParticleSystem, ParticleSystemView, RigidContactView, RigidPrim, RigidPrimView, XFormPrim, XFormPrimView from omni.isaac.core.robots import Robot, RobotView from omni.isaac.core.scenes import Scene, SceneRegistry from omni.isaac.core.simulation_context import SimulationContext from omni.isaac.core.world import World from omni.isaac.core.tasks import BaseTask, FollowTarget, PickPlace, Stacking from omni.isaac.core.prims._impl.single_prim_wrapper import _SinglePrimWrapper import omni.isaac.core.utils.bounds as utils_bounds import omni.isaac.core.utils.carb as utils_carb import omni.isaac.core.utils.collisions as utils_collisions import omni.isaac.core.utils.constants as utils_constants import omni.isaac.core.utils.distance_metrics as utils_distance_metrics import omni.isaac.core.utils.extensions as utils_extensions import omni.isaac.core.utils.math as utils_math import omni.isaac.core.utils.mesh as utils_mesh import omni.isaac.core.utils.nucleus as utils_nucleus import omni.isaac.core.utils.numpy as utils_numpy import omni.isaac.core.utils.physics as utils_physics import omni.isaac.core.utils.prims as utils_prims import omni.isaac.core.utils.random as utils_random import omni.isaac.core.utils.render_product as utils_render_product import omni.isaac.core.utils.rotations as utils_rotations import omni.isaac.core.utils.semantics as utils_semantics import omni.isaac.core.utils.stage as utils_stage import omni.isaac.core.utils.string as utils_string import omni.isaac.core.utils.transformations as utils_transformations import omni.isaac.core.utils.torch as utils_torch import omni.isaac.core.utils.types as utils_types import omni.isaac.core.utils.viewports as utils_viewports import omni.isaac.core.utils.xforms as utils_xforms # from omni.isaac.dynamic_control import _dynamic_control # _dynamic_control_interface = _dynamic_control.acquire_dynamic_control_interface() from omni.isaac.ui import ui_utils from omni.isaac.kit import SimulationApp # core snippets = [] # articulations subsnippets = [] s0 = get_class(Articulation, "articulation") s1 = get_methods(Articulation, "articulation") s2 = get_methods(_SinglePrimWrapper, "articulation") subsnippets.append({"title": "Articulation", "snippets": [s0] + s1 + s2}) s0 = get_class(ArticulationGripper, "articulation_gripper") s1 = get_methods(ArticulationGripper, "articulation_gripper") subsnippets.append({"title": "ArticulationGripper", "snippets": [s0] + s1}) s0 = get_class(ArticulationSubset, "articulation_subset") s1 = get_methods(ArticulationSubset, "articulation_subset") subsnippets.append({"title": "ArticulationSubset", "snippets": [s0] + s1}) s0 = get_class(ArticulationView, "articulation_view") s1 = get_methods(ArticulationView, "articulation_view") s2 = get_methods(XFormPrimView, "articulation_view") subsnippets.append({"title": "ArticulationView", "snippets": [s0] + s1 + s2}) snippets.append({"title": "Articulations", "snippets": subsnippets}) # controllers subsnippets = [] s0 = get_class(ArticulationController, "articulation_controller") s1 = get_methods(ArticulationController, "articulation_controller") subsnippets.append({"title": "ArticulationController", "snippets": [s0] + s1}) s0 = get_class(BaseController, "base_controller") s1 = get_methods(BaseController, "base_controller") subsnippets.append({"title": "BaseController", "snippets": [s0] + s1}) s0 = get_class(BaseGripperController, "base_gripper_controller") s1 = get_methods(BaseGripperController, "base_gripper_controller") subsnippets.append({"title": "BaseGripperController", "snippets": [s0] + s1}) snippets.append({"title": "Controllers", "snippets": subsnippets}) # loggers s0 = get_class(DataLogger, "data_logger") s1 = get_methods(DataLogger, "data_logger") snippets.append({"title": "DataLogger", "snippets": [s0] + s1}) # materials subsnippets = [] s0 = get_class(OmniGlass, "omni_glass") s1 = get_methods(OmniGlass, "omni_glass") subsnippets.append({"title": "OmniGlass", "snippets": [s0] + s1}) s0 = get_class(OmniPBR, "omni_pbr") s1 = get_methods(OmniPBR, "omni_pbr") subsnippets.append({"title": "OmniPBR", "snippets": [s0] + s1}) s0 = get_class(ParticleMaterial, "particle_material") s1 = get_methods(ParticleMaterial, "particle_material") subsnippets.append({"title": "ParticleMaterial", "snippets": [s0] + s1}) s0 = get_class(ParticleMaterialView, "particle_material_view") s1 = get_methods(ParticleMaterialView, "particle_material_view") subsnippets.append({"title": "ParticleMaterialView", "snippets": [s0] + s1}) s0 = get_class(PhysicsMaterial, "physics_material") s1 = get_methods(PhysicsMaterial, "physics_material") subsnippets.append({"title": "PhysicsMaterial", "snippets": [s0] + s1}) s0 = get_class(PreviewSurface, "preview_surface") s1 = get_methods(PreviewSurface, "preview_surface") subsnippets.append({"title": "PreviewSurface", "snippets": [s0] + s1}) s0 = get_class(VisualMaterial, "visual_material") s1 = get_methods(VisualMaterial, "visual_material") subsnippets.append({"title": "VisualMaterial", "snippets": [s0] + s1}) snippets.append({"title": "Materials", "snippets": subsnippets}) # objects subsnippets = [] s0 = get_class(DynamicCapsule, "dynamic_capsule") s1 = get_methods(DynamicCapsule, "dynamic_capsule") s2 = get_methods(RigidPrim, "dynamic_capsule") s3 = get_methods(VisualCapsule, "dynamic_capsule") s4 = get_methods(GeometryPrim, "dynamic_capsule") s5 = get_methods(_SinglePrimWrapper, "dynamic_capsule") subsnippets.append({"title": "DynamicCapsule", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCone, "dynamic_cone") s1 = get_methods(DynamicCone, "dynamic_cone") s2 = get_methods(RigidPrim, "dynamic_cone") s3 = get_methods(VisualCone, "dynamic_cone") s4 = get_methods(GeometryPrim, "dynamic_cone") s5 = get_methods(_SinglePrimWrapper, "dynamic_cone") subsnippets.append({"title": "DynamicCone", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCuboid, "dynamic_cuboid") s1 = get_methods(DynamicCuboid, "dynamic_cuboid") s2 = get_methods(RigidPrim, "dynamic_cuboid") s3 = get_methods(VisualCuboid, "dynamic_cuboid") s4 = get_methods(GeometryPrim, "dynamic_cuboid") s5 = get_methods(_SinglePrimWrapper, "dynamic_cuboid") subsnippets.append({"title": "DynamicCuboid", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCylinder, "dynamic_cylinder") s1 = get_methods(DynamicCylinder, "dynamic_cylinder") s2 = get_methods(RigidPrim, "dynamic_cylinder") s3 = get_methods(VisualCylinder, "dynamic_cylinder") s4 = get_methods(GeometryPrim, "dynamic_cylinder") s5 = get_methods(_SinglePrimWrapper, "dynamic_cylinder") subsnippets.append({"title": "DynamicCylinder", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicSphere, "dynamic_sphere") s1 = get_methods(DynamicSphere, "dynamic_sphere") s2 = get_methods(RigidPrim, "dynamic_sphere") s3 = get_methods(VisualSphere, "dynamic_sphere") s4 = get_methods(GeometryPrim, "dynamic_sphere") s5 = get_methods(_SinglePrimWrapper, "dynamic_sphere") subsnippets.append({"title": "DynamicSphere", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(FixedCapsule, "fixed_capsule") s1 = get_methods(VisualCapsule, "fixed_capsule") s2 = get_methods(GeometryPrim, "fixed_capsule") s3 = get_methods(_SinglePrimWrapper, "fixed_capsule") subsnippets.append({"title": "FixedCapsule", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCone, "fixed_cone") s1 = get_methods(VisualCone, "fixed_cone") s2 = get_methods(GeometryPrim, "fixed_cone") s3 = get_methods(_SinglePrimWrapper, "fixed_cone") subsnippets.append({"title": "FixedCone", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCuboid, "fixed_cuboid") s1 = get_methods(VisualCuboid, "fixed_cuboid") s2 = get_methods(GeometryPrim, "fixed_cuboid") s3 = get_methods(_SinglePrimWrapper, "fixed_cuboid") subsnippets.append({"title": "FixedCuboid", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCylinder, "fixed_cylinder") s1 = get_methods(VisualCylinder, "fixed_cylinder") s2 = get_methods(GeometryPrim, "fixed_cylinder") s3 = get_methods(_SinglePrimWrapper, "fixed_cylinder") subsnippets.append({"title": "FixedCylinder", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedSphere, "fixed_sphere") s1 = get_methods(VisualSphere, "fixed_sphere") s2 = get_methods(GeometryPrim, "fixed_sphere") s3 = get_methods(_SinglePrimWrapper, "fixed_sphere") subsnippets.append({"title": "FixedSphere", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(GroundPlane, "ground_plane") s1 = get_methods(GroundPlane, "ground_plane") subsnippets.append({"title": "GroundPlane", "snippets": [s0] + s1}) s0 = get_class(VisualCapsule, "visual_capsule") s1 = get_methods(VisualCapsule, "visual_capsule") s2 = get_methods(GeometryPrim, "visual_capsule") s3 = get_methods(_SinglePrimWrapper, "visual_capsule") subsnippets.append({"title": "VisualCapsule", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCone, "visual_cone") s1 = get_methods(VisualCone, "visual_cone") s2 = get_methods(GeometryPrim, "visual_cone") s3 = get_methods(_SinglePrimWrapper, "visual_cone") subsnippets.append({"title": "VisualCone", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCuboid, "visual_cuboid") s1 = get_methods(VisualCuboid, "visual_cuboid") s2 = get_methods(GeometryPrim, "visual_cuboid") s3 = get_methods(_SinglePrimWrapper, "visual_cuboid") subsnippets.append({"title": "VisualCuboid", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCylinder, "visual_cylinder") s1 = get_methods(VisualCylinder, "visual_cylinder") s2 = get_methods(GeometryPrim, "visual_cylinder") s3 = get_methods(_SinglePrimWrapper, "visual_cylinder") subsnippets.append({"title": "VisualCylinder", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualSphere, "visual_sphere") s1 = get_methods(VisualSphere, "visual_sphere") s2 = get_methods(GeometryPrim, "visual_sphere") s3 = get_methods(_SinglePrimWrapper, "visual_sphere") subsnippets.append({"title": "VisualSphere", "snippets": [s0] + s1 + s2 + s3}) snippets.append({"title": "Objects", "snippets": subsnippets}) # physics_context s0 = get_class(PhysicsContext, "physics_context") s1 = get_methods(PhysicsContext, "physics_context") snippets.append({"title": "PhysicsContext", "snippets": [s0] + s1}) # prims subsnippets = [] s0 = get_class(BaseSensor, "base_sensor") s1 = get_methods(BaseSensor, "base_sensor") s2 = get_methods(_SinglePrimWrapper, "base_sensor") subsnippets.append({"title": "BaseSensor", "snippets": [s0] + s1 + s2}) s0 = get_class(ClothPrim, "cloth_prim") s1 = get_methods(ClothPrim, "cloth_prim") s2 = get_methods(_SinglePrimWrapper, "cloth_prim") subsnippets.append({"title": "ClothPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(ClothPrimView, "cloth_prim_view") s1 = get_methods(ClothPrimView, "cloth_prim_view") s2 = get_methods(XFormPrimView, "cloth_prim_view") subsnippets.append({"title": "ClothPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(GeometryPrim, "geometry_prim") s1 = get_methods(GeometryPrim, "geometry_prim") s2 = get_methods(_SinglePrimWrapper, "geometry_prim") subsnippets.append({"title": "GeometryPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(GeometryPrimView, "geometry_prim_view") s1 = get_methods(GeometryPrimView, "geometry_prim_view") s2 = get_methods(XFormPrimView, "geometry_prim_view") subsnippets.append({"title": "GeometryPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(ParticleSystem, "particle_system") s1 = get_methods(ParticleSystem, "particle_system") subsnippets.append({"title": "ParticleSystem", "snippets": [s0] + s1}) s0 = get_class(ParticleSystemView, "particle_system_view") s1 = get_methods(ParticleSystemView, "particle_system_view") subsnippets.append({"title": "ParticleSystemView", "snippets": [s0] + s1}) s0 = get_class(RigidContactView, "rigid_contact_view") s1 = get_methods(RigidContactView, "rigid_contact_view") subsnippets.append({"title": "RigidContactView", "snippets": [s0] + s1}) s0 = get_class(RigidPrim, "rigid_prim") s1 = get_methods(RigidPrim, "rigid_prim") s2 = get_methods(_SinglePrimWrapper, "rigid_prim") subsnippets.append({"title": "RigidPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(RigidPrimView, "rigid_prim_view") s1 = get_methods(RigidPrimView, "rigid_prim_view") s2 = get_methods(XFormPrimView, "rigid_prim_view") subsnippets.append({"title": "RigidPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(XFormPrim, "xform_prim") s1 = get_methods(XFormPrim, "xform_prim") s2 = get_methods(_SinglePrimWrapper, "xform_prim") subsnippets.append({"title": "XFormPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(XFormPrimView, "xform_prim_view") s1 = get_methods(XFormPrimView, "xform_prim_view") subsnippets.append({"title": "XFormPrimView", "snippets": [s0] + s1}) snippets.append({"title": "Prims", "snippets": subsnippets}) # robots subsnippets = [] s0 = get_class(Robot, "robot") s1 = get_methods(Robot, "robot") s2 = get_methods(Articulation, "robot") s3 = get_methods(_SinglePrimWrapper, "robot") subsnippets.append({"title": "Robot", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(RobotView, "robot_view") s1 = get_methods(RobotView, "robot_view") s2 = get_methods(ArticulationView, "robot_view") s3 = get_methods(XFormPrimView, "robot_view") subsnippets.append({"title": "RobotView", "snippets": [s0] + s1 + s2 + s3}) snippets.append({"title": "Robots", "snippets": subsnippets}) # scenes subsnippets = [] s0 = get_class(Scene, "scene") s1 = get_methods(Scene, "scene") subsnippets.append({"title": "Scene", "snippets": [s0] + s1}) s0 = get_class(SceneRegistry, "scene_registry") s1 = get_methods(SceneRegistry, "scene_registry") subsnippets.append({"title": "SceneRegistry", "snippets": [s0] + s1}) snippets.append({"title": "Scenes", "snippets": subsnippets}) # simulation_context s0 = get_class(SimulationContext, "simulation_context") s1 = get_methods(SimulationContext, "simulation_context") snippets.append({"title": "SimulationContext", "snippets": [s0] + s1}) # world s0 = get_class(World, "world") s1 = get_methods(World, "world") s2 = get_methods(SimulationContext, "world") snippets.append({"title": "World", "snippets": [s0] + s1 + s2}) # tasks subsnippets = [] s0 = get_class(BaseTask, "base_task") s1 = get_methods(BaseTask, "base_task") subsnippets.append({"title": "BaseTask", "snippets": [s0] + s1}) s0 = get_class(FollowTarget, "follow_target") s1 = get_methods(FollowTarget, "follow_target") s2 = get_methods(BaseTask, "follow_target") subsnippets.append({"title": "FollowTarget", "snippets": [s0] + s1 + s2}) s0 = get_class(PickPlace, "pick_place") s1 = get_methods(PickPlace, "pick_place") s2 = get_methods(BaseTask, "pick_place") subsnippets.append({"title": "PickPlace", "snippets": [s0] + s1 + s2}) s0 = get_class(Stacking, "stacking") s1 = get_methods(Stacking, "stacking") s2 = get_methods(BaseTask, "stacking") subsnippets.append({"title": "Stacking", "snippets": [s0] + s1 + s2}) snippets.append({"title": "Tasks", "snippets": subsnippets}) # core utils snippets_utils = [] s0 = get_functions(utils_bounds, "bounds_utils", exclude_functions=["get_prim_at_path"]) snippets_utils.append({"title": "Bounds", "snippets": s0}) s0 = get_functions(utils_carb, "carb_utils") snippets_utils.append({"title": "Carb", "snippets": s0}) s0 = get_functions(utils_collisions, "collisions_utils", exclude_functions=["get_current_stage"]) snippets_utils.append({"title": "Collisions", "snippets": s0}) s0 = get_functions(utils_constants, "constants_utils") snippets_utils.append({"title": "Constants", "snippets": [{"title": "AXES_INDICES", "description": "Mapping from axis name to axis ID", "snippet": "AXES_INDICES\n"}, {"title": "AXES_TOKEN", "description": "Mapping from axis name to axis USD token", "snippet": "AXES_TOKEN\n"}]}) s0 = get_functions(utils_distance_metrics, "distance_metrics_utils") snippets_utils.append({"title": "Distance Metrics", "snippets": s0}) s0 = get_functions(utils_extensions, "extensions_utils") snippets_utils.append({"title": "Extensions", "snippets": s0}) s0 = get_functions(utils_math, "math_utils") snippets_utils.append({"title": "Math", "snippets": s0}) s0 = get_functions(utils_mesh, "mesh_utils", exclude_functions=["get_stage_units", "get_relative_transform"]) snippets_utils.append({"title": "Mesh", "snippets": s0}) s0 = get_functions(utils_nucleus, "nucleus_utils", exclude_functions=["namedtuple", "urlparse", "get_version"]) snippets_utils.append({"title": "Nucleus", "snippets": s0}) s0 = get_functions(utils_numpy, "numpy_utils") snippets_utils.append({"title": "Numpy", "snippets": s0}) s0 = get_functions(utils_physics, "physics_utils", exclude_functions=["get_current_stage"]) snippets_utils.append({"title": "Physics", "snippets": s0}) s0 = get_functions(utils_prims, "prims_utils", exclude_functions=["add_reference_to_stage", "get_current_stage", "find_root_prim_path_from_regex", "add_update_semantics"]) snippets_utils.append({"title": "Prims", "snippets": s0}) s0 = get_functions(utils_random, "random_utils", exclude_functions=["get_world_pose_from_relative", "get_translation_from_target", "euler_angles_to_quat"]) snippets_utils.append({"title": "Random", "snippets": s0}) s0 = get_functions(utils_render_product, "render_product_utils", exclude_functions=["set_prim_hide_in_stage_window", "set_prim_no_delete", "get_current_stage"]) snippets_utils.append({"title": "Render Product", "snippets": s0}) s0 = get_functions(utils_rotations, "rotations_utils") snippets_utils.append({"title": "Rotations", "snippets": s0}) s0 = get_functions(utils_semantics, "semantics_utils") snippets_utils.append({"title": "Semantics", "snippets": s0}) s0 = get_functions(utils_stage, "stage_utils") snippets_utils.append({"title": "Stage", "snippets": s0}) s0 = get_functions(utils_string, "string_utils") snippets_utils.append({"title": "String", "snippets": s0}) s0 = get_functions(utils_transformations, "transformations_utils", exclude_functions=["gf_quat_to_np_array"]) snippets_utils.append({"title": "Transformations", "snippets": s0}) s0 = get_functions(utils_torch, "torch_utils") snippets_utils.append({"title": "Torch", "snippets": s0}) subsnippets = [] s0 = get_class(utils_types.ArticulationAction, "articulation_action") s1 = get_methods(utils_types.ArticulationAction, "articulation_action") subsnippets.append({"title": "ArticulationAction", "snippets": [s0] + s1}) s0 = get_class(utils_types.ArticulationActions, "articulation_actions") subsnippets.append(s0) s0 = get_class(utils_types.DataFrame, "data_frame") s1 = get_methods(utils_types.DataFrame, "data_frame") subsnippets.append({"title": "DataFrame", "snippets": [s0] + s1}) s0 = get_class(utils_types.DOFInfo, "dof_Info") subsnippets.append(s0) s0 = get_class(utils_types.DynamicState, "dynamic_state") subsnippets.append(s0) s0 = get_class(utils_types.DynamicsViewState, "dynamics_view_state") subsnippets.append(s0) s0 = get_class(utils_types.JointsState, "joints_state") subsnippets.append(s0) s0 = get_class(utils_types.XFormPrimState, "xform_prim_state") subsnippets.append(s0) s0 = get_class(utils_types.XFormPrimViewState, "xform_prim_view_state") subsnippets.append(s0) s0 = get_functions(utils_types, "types_utils") snippets_utils.append({"title": "Types", "snippets": subsnippets}) s0 = get_functions(utils_viewports, "viewports_utils", exclude_functions=["get_active_viewport", "get_current_stage", "set_prim_hide_in_stage_window", "set_prim_no_delete"]) snippets_utils.append({"title": "Viewports", "snippets": s0}) s0 = get_functions(utils_xforms, "xforms_utils") snippets_utils.append({"title": "XForms", "snippets": s0}) # ui utils snippets_ui_utils = [] s0 = get_functions(ui_utils, "ui_utils") snippets_ui_utils.append({"title": "UI Utils", "snippets": s0}) # SimulationApp snippets_simulation_app = [] s0 = get_class(SimulationApp, "simulation_app") s1 = get_methods(SimulationApp, "simulation_app") snippets_simulation_app.append({"title": "SimulationApp", "snippets": [s0] + s1}) with open("isaac-sim-snippets-core.json", "w") as f: json.dump(snippets, f, indent=0) with open("isaac-sim-snippets-utils.json", "w") as f: json.dump(snippets_utils, f, indent=0) with open("isaac-sim-snippets-ui-utils.json", "w") as f: json.dump(snippets_ui_utils, f, indent=0) with open("isaac-sim-snippets-simulation-app.json", "w") as f: json.dump(snippets_simulation_app, f, indent=0) print("DONE")
28,986
Python
39.037293
208
0.677706
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_commands_app.py
import json import inspect import collections count = 0 snippets = [] snippets_by_extensions_depth = 2 snippets_by_extensions = collections.defaultdict(list) def class_fullname(c): try: module = c.__module__ if module == 'builtins': return c.__name__ return module + '.' + c.__name__ except: return str(c) from pxr import Sdf commands = omni.kit.commands.get_commands() for k, v in commands.items(): # count += 1 # print() # if count > 20: # break if v: command_class = list(v.values())[0] command_extension = list(v.keys())[0] spec = inspect.getfullargspec(command_class.__init__) signature = inspect.signature(command_class.__init__) command = command_class.__qualname__ command_args = [] command_annotations = [] for parameter in signature.parameters.values(): if parameter.name in ["self", "args", "kwargs"]: continue # arg if type(parameter.default) == type(inspect.Parameter.empty): command_args.append("{}={}".format(parameter.name, parameter.name)) else: default_value = parameter.default if type(parameter.default) is str: default_value = '"{}"'.format(parameter.default) elif type(parameter.default) is Sdf.Path: if parameter.default == Sdf.Path.emptyPath: default_value = "Sdf.Path.emptyPath" else: default_value = 'Sdf.Path("{}")'.format(parameter.default) elif inspect.isclass(parameter.default): default_value = class_fullname(parameter.default) command_args.append("{}={}".format(parameter.name, default_value)) # annotation if parameter.annotation == inspect.Parameter.empty: command_annotations.append("") else: command_annotations.append(class_fullname(parameter.annotation)) # build snippet arguments_as_string = '")' if command_args: arguments_as_string = '",\n' for i, arg, annotation in zip(range(len(command_args)), command_args, command_annotations): is_last = i >= len(command_args) - 1 if annotation: arguments_as_string += " " * 26 + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * 26 + "{}{}".format(arg, ")" if is_last else ",\n") title = command try: description = command_class.__doc__.replace("\n ", "\n").replace(" **Command**", "") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] while " " in description: description = description.replace(" ", " ") description = "[{}]\n\n".format(command_extension) + description except Exception as e: description = None if not description: description = "[{}]".format(command_extension) snippet = 'omni.kit.commands.execute("{}{}'.format(command, arguments_as_string) + "\n" # storage snippet (all) snippets.append({"title": title, "description": description, "snippet": snippet}) # storage snippet (by extension) command_extension = ".".join(command_extension.split(".")[:snippets_by_extensions_depth]) snippets_by_extensions[command_extension].append({"title": title, "description": description, "snippet": snippet}) snippets = [] for title, snippets_by_extension in snippets_by_extensions.items(): snippets.append({"title": title, "snippets": snippets_by_extension}) with open("kit-commands.json", "w") as f: json.dump({"snippets": snippets}, f, indent=0) print("done")
4,069
Python
37.396226
145
0.561317
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/compile_extension.py
import os import sys from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext # OV python (kit\python\include) if sys.platform == 'win32': python_library_dir = os.path.join(os.path.dirname(sys.executable), "include") elif sys.platform == 'linux': python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include") if not os.path.exists(python_library_dir): raise Exception("OV Python library directory not found: {}".format(python_library_dir)) ext_modules = [ Extension("_openxr", [os.path.join("semu", "xr", "openxr", "openxr.py")], library_dirs=[python_library_dir]), ] for ext in ext_modules: ext.cython_directives = {'language_level': "3"} setup( name = 'semu.xr.openxr', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
882
Python
27.48387
91
0.673469
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/pybind11_ext.py
import os import sys from distutils.core import setup from pybind11.setup_helpers import Pybind11Extension, build_ext # OV python (kit\python\include) if sys.platform == 'win32': python_library_dir = os.path.join(os.path.dirname(sys.executable), "include") elif sys.platform == 'linux': python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "lib") if not os.path.exists(python_library_dir): raise Exception("OV Python library directory not found: {}".format(python_library_dir)) ext_modules = [ Pybind11Extension("xrlib_p", ["pybind11_wrapper.cpp"], include_dirs=[os.path.join(os.getcwd(), "thirdparty", "openxr", "include"), os.path.join(os.getcwd(), "thirdparty", "opengl", "include"), os.path.join(os.getcwd(), "thirdparty", "sdl2")], library_dirs=[os.path.join(os.getcwd(), "thirdparty", "openxr", "lib"), os.path.join(os.getcwd(), "thirdparty", "opengl", "lib"), os.path.join(os.getcwd(), "thirdparty", "sdl2", "lib"), python_library_dir], libraries=["openxr_loader", "GL", "SDL2"], extra_link_args=["-Wl,-rpath=./bin"], undef_macros=["CTYPES", "APPLICATION"]), ] setup( name = 'openxr-lib', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
1,527
Python
40.297296
97
0.542895
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/openxr.py
from typing import Union, Callable import os import sys import ctypes import cv2 import numpy import numpy as np if __name__ != "__main__": import pxr import omni from pxr import UsdGeom, Gf, Usd from omni.syntheticdata import sensors, _syntheticdata else: class pxr: class Gf: Vec3d = lambda x,y,z: (x,y,z) Quatd = lambda w,x,y,z: (w,x,y,z) class Usd: Prim = None class UsdGeom: pass class Sdf: Path = None Gf = pxr.Gf # constants XR_KHR_OPENGL_ENABLE_EXTENSION_NAME = "XR_KHR_opengl_enable" XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME = "XR_KHR_opengl_es_enable" XR_KHR_VULKAN_ENABLE_EXTENSION_NAME = "XR_KHR_vulkan_enable" XR_KHR_D3D11_ENABLE_EXTENSION_NAME = "XR_KHR_D3D11_enable" XR_KHR_D3D12_ENABLE_EXTENSION_NAME = "XR_KHR_D3D12_enable" XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY = 1 XR_FORM_FACTOR_HANDHELD_DISPLAY = 2 XR_ENVIRONMENT_BLEND_MODE_OPAQUE = 1 XR_ENVIRONMENT_BLEND_MODE_ADDITIVE = 2 XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND = 3 XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO = 1 XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO = 2 XR_REFERENCE_SPACE_TYPE_VIEW = 1 # +Y up, +X to the right, and -Z forward XR_REFERENCE_SPACE_TYPE_LOCAL = 2 # +Y up, +X to the right, and -Z forward XR_REFERENCE_SPACE_TYPE_STAGE = 3 # +Y up, and the X and Z axes aligned with the rectangle edges XR_ACTION_TYPE_BOOLEAN_INPUT = 1 XR_ACTION_TYPE_FLOAT_INPUT = 2 XR_ACTION_TYPE_VECTOR2F_INPUT = 3 XR_ACTION_TYPE_POSE_INPUT = 4 XR_ACTION_TYPE_VIBRATION_OUTPUT = 100 XR_NO_DURATION = 0 XR_INFINITE_DURATION = 2**32 XR_MIN_HAPTIC_DURATION = -1 XR_FREQUENCY_UNSPECIFIED = 0 def acquire_openxr_interface(disable_openxr: bool = False): return OpenXR(disable_openxr) def release_openxr_interface(xr): if xr is not None: xr.destroy() xr = None # structures (ctypes) XrActionType = ctypes.c_int XrStructureType = ctypes.c_int class XrQuaternionf(ctypes.Structure): _fields_ = [('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float), ('w', ctypes.c_float)] class XrVector3f(ctypes.Structure): _fields_ = [('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float)] class XrPosef(ctypes.Structure): _fields_ = [('orientation', XrQuaternionf), ('position', XrVector3f)] class XrFovf(ctypes.Structure): _fields_ = _fields_ = [('angleLeft', ctypes.c_float), ('angleRight', ctypes.c_float), ('angleUp', ctypes.c_float), ('angleDown', ctypes.c_float)] class XrView(ctypes.Structure): _fields_ = [('type', XrStructureType), ('next', ctypes.c_void_p), ('pose', XrPosef), ('fov', XrFovf)] class XrViewConfigurationView(ctypes.Structure): _fields_ = [('type', XrStructureType), ('next', ctypes.c_void_p), ('recommendedImageRectWidth', ctypes.c_uint32), ('maxImageRectWidth', ctypes.c_uint32), ('recommendedImageRectHeight', ctypes.c_uint32), ('maxImageRectHeight', ctypes.c_uint32), ('recommendedSwapchainSampleCount', ctypes.c_uint32), ('maxSwapchainSampleCount', ctypes.c_uint32)] class ActionState(ctypes.Structure): _fields_ = [('type', XrActionType), ('path', ctypes.c_char_p), ('isActive', ctypes.c_bool), ('stateBool', ctypes.c_bool), ('stateFloat', ctypes.c_float), ('stateVectorX', ctypes.c_float), ('stateVectorY', ctypes.c_float)] class ActionPoseState(ctypes.Structure): _fields_ = [('type', XrActionType), ('path', ctypes.c_char_p), ('isActive', ctypes.c_bool), ('pose', XrPosef)] class OpenXR: def __init__(self, disable_openxr: bool = False) -> None: self._disable_openxr = disable_openxr if self._disable_openxr: print("[WARNING] Extension launched with OpenXR support disabled") self._lib = None self._app = None self._graphics = None self._use_ctypes = False # views self._prim_left = None self._prim_right = None self._frame_left = None self._frame_right = None self._viewport_window_left = None self._viewport_window_right = None self._meters_per_unit = 1.0 self._reference_position = Gf.Vec3d(0, 0, 0) self._reference_rotation = Gf.Vec3d(0, 0, 0) self._rectification_quat_left = Gf.Quatd(1, 0, 0, 0) self._rectification_quat_right = Gf.Quatd(1, 0, 0, 0) self._viewport_interface = None self._transform_fit = None self._transform_flip = None # callbacks self._callback_action_events = {} self._callback_action_pose_events = {} self._callback_middle_render = None self._callback_render = None def init(self, graphics: str = "OpenGL", use_ctypes: bool = False) -> bool: """ Init OpenXR application by loading the related libraries Parameters ---------- graphics: str OpenXR graphics API supported by the runtime (OpenGL, OpenGLES, Vulkan, D3D11, D3D12). Note: At the moment only OpenGL is available use_ctypes: bool, optional If true, use ctypes as C/C++ interface instead of pybind11 (default) Returns ------- bool True if initialization was successful, otherwise False """ # get viewport interface try: self._viewport_interface = omni.kit.viewport.get_viewport_interface() except Exception as e: print("[INFO] Using legacy viewport interface") self._viewport_interface = omni.kit.viewport_legacy.get_viewport_interface() # TODO: what about no graphic API (only controllers for example)? self._use_ctypes = use_ctypes # graphics API if graphics in ["OpenGL", XR_KHR_OPENGL_ENABLE_EXTENSION_NAME]: self._graphics = XR_KHR_OPENGL_ENABLE_EXTENSION_NAME elif graphics in ["OpenGLES", XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME]: self._graphics = XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME raise NotImplementedError("OpenGLES graphics API is not implemented yet") elif graphics in ["Vulkan", XR_KHR_VULKAN_ENABLE_EXTENSION_NAME]: self._graphics = XR_KHR_VULKAN_ENABLE_EXTENSION_NAME raise NotImplementedError("Vulkan graphics API is not implemented yet") elif graphics in ["D3D11", XR_KHR_D3D11_ENABLE_EXTENSION_NAME]: self._graphics = XR_KHR_D3D11_ENABLE_EXTENSION_NAME raise NotImplementedError("D3D11 graphics API is not implemented yet") elif graphics in ["D3D12", XR_KHR_D3D12_ENABLE_EXTENSION_NAME]: self._graphics = XR_KHR_D3D12_ENABLE_EXTENSION_NAME raise NotImplementedError("D3D12 graphics API is not implemented yet") else: raise ValueError("Invalid graphics API ({}). Valid graphics APIs are OpenGL, OpenGLES, Vulkan, D3D11, D3D12".format(graphics)) # libraries path if __name__ == "__main__": extension_path = os.getcwd()[:os.getcwd().find("/semu/xr/openxr")] else: extension_path = __file__[:__file__.find("/semu/xr/openxr")] if self._disable_openxr: return True try: # ctypes if self._use_ctypes: ctypes.PyDLL(os.path.join(extension_path, "bin", "libGL.so"), mode = ctypes.RTLD_GLOBAL) ctypes.PyDLL(os.path.join(extension_path, "bin", "libSDL2.so"), mode = ctypes.RTLD_GLOBAL) ctypes.PyDLL(os.path.join(extension_path, "bin", "libopenxr_loader.so"), mode = ctypes.RTLD_GLOBAL) self._lib = ctypes.PyDLL(os.path.join(extension_path, "bin", "xrlib_c.so"), mode = ctypes.RTLD_GLOBAL) self._app = self._lib.openXrApplication() print("[INFO] OpenXR initialized using ctypes interface") # pybind11 else: sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY) sys.path.append(os.path.join(extension_path, "bin")) # change cwd tmp_dir= os.getcwd() os.chdir(extension_path) #import library import xrlib_p #restore cwd os.chdir(tmp_dir) self._lib = xrlib_p self._app = xrlib_p.OpenXrApplication() print("[INFO] OpenXR initialized using pybind11 interface") except Exception as e: print("[ERROR] OpenXR initialization:", e) return False return True def destroy(self) -> bool: """ Destroy OpenXR application Returns ------- bool True if destruction was successful, otherwise False """ if self._app is not None: if self._use_ctypes: return bool(self._lib.destroy(self._app)) else: return self._app.destroy() self._lib = None self._app = None return True def is_session_running(self) -> bool: """ OpenXR session's running status Returns ------- bool Return True if the OpenXR session is running, False otherwise """ if self._disable_openxr: return True if self._use_ctypes: return bool(self._lib.isSessionRunning(self._app)) else: return self._app.isSessionRunning() def create_instance(self, application_name: str = "Omniverse (XR)", engine_name: str = "", api_layers: list = [], extensions: list = []) -> bool: """ Create an OpenXR instance to allow communication with an OpenXR runtime OpenXR internal function calls: - xrEnumerateApiLayerProperties - xrEnumerateInstanceExtensionProperties - xrCreateInstance Parameters ---------- application_name: str, optional Name of the OpenXR application (default: 'Omniverse (VR)') engine_name: str, optional Name of the engine (if any) used to create the application (empty by default) api_layers: list of str, optional [API layers](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#api-layers) to be inserted between the OpenXR application and the runtime implementation. extensions: list of str, optional [Extensions](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#extensions) to be loaded. Note: At the moment only the graphic extensions are configured. Note: The graphics API selected during initialization (init) is automatically included in the extensions to be loaded. Returns ------- bool True if the instance has been created successfully, otherwise False """ if self._disable_openxr: return True if self._graphics not in extensions: extensions += [self._graphics] if self._use_ctypes: # format API layes requested_api_layers = (ctypes.c_char_p * len(api_layers))() requested_api_layers[:] = [layer.encode('utf-8') for layer in api_layers] # format extensions requested_extensions = (ctypes.c_char_p * len(extensions))() requested_extensions[:] = [extension.encode('utf-8') for extension in extensions] return bool(self._lib.createInstance(self._app, ctypes.create_string_buffer(application_name.encode('utf-8')), ctypes.create_string_buffer(engine_name.encode('utf-8')), requested_api_layers, len(api_layers), requested_extensions, len(extensions))) else: return self._app.createInstance(application_name, engine_name, api_layers, extensions) def get_system(self, form_factor: int = 1, blend_mode: int = 1, view_configuration_type: int = 2) -> bool: """ Obtain the system represented by a collection of related devices at runtime OpenXR internal function calls: - xrGetSystem - xrGetInstanceProperties - xrGetSystemProperties - xrEnumerateViewConfigurations - xrGetViewConfigurationProperties - xrEnumerateViewConfigurationViews - xrEnumerateEnvironmentBlendModes - xrCreateActionSet (actionSetName: 'actionset', localizedActionSetName: 'localized_actionset') Parameters ---------- form_factor: {XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY}, optional Desired [form factor](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#form_factor_description) from XrFormFactor enum (default: XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY) blend_mode: {XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND}, optional Desired environment [blend mode](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#environment_blend_mode) from XrEnvironmentBlendMode enum (default: XR_ENVIRONMENT_BLEND_MODE_OPAQUE) view_configuration_type: {XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO}, optional Primary [view configuration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#view_configurations) type from XrViewConfigurationType enum (default: XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO) Returns ------- bool True if the system has been obtained successfully, otherwise False """ # check form_factor if not form_factor in [XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY]: raise ValueError("Invalid form factor ({}). Valid form factors are XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY ({}), XR_FORM_FACTOR_HANDHELD_DISPLAY ({})" \ .format(form_factor, XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_FORM_FACTOR_HANDHELD_DISPLAY)) # check blend_mode if not blend_mode in [XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND]: raise ValueError("Invalid blend mode ({}). Valid blend modes are XR_ENVIRONMENT_BLEND_MODE_OPAQUE ({}), XR_ENVIRONMENT_BLEND_MODE_ADDITIVE ({}), XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND ({})" \ .format(blend_mode, XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND)) # check view_configuration_type if not view_configuration_type in [XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO]: raise ValueError("Invalid view configuration type ({}). Valid view configuration types are XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO ({}), XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO ({})" \ .format(view_configuration_type, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO)) if self._disable_openxr: return True if self._use_ctypes: return bool(self._lib.getSystem(self._app, form_factor, blend_mode, view_configuration_type)) else: return self._app.getSystem(form_factor, blend_mode, view_configuration_type) def create_session(self) -> bool: """ Create an OpenXR session that represents an application's intention to display XR content OpenXR internal function calls: - xrCreateSession - xrEnumerateReferenceSpaces - xrCreateReferenceSpace - xrGetReferenceSpaceBoundsRect - xrSuggestInteractionProfileBindings - xrAttachSessionActionSets - xrCreateActionSpace - xrEnumerateSwapchainFormats - xrCreateSwapchain - xrEnumerateSwapchainImages Returns ------- bool True if the session has been created successfully, otherwise False """ if self._disable_openxr: return True if self._use_ctypes: return bool(self._lib.createSession(self._app)) else: return self._app.createSession() def poll_events(self) -> bool: """ [Event polling](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#event-polling) and processing OpenXR internal function calls: - xrPollEvent - xrBeginSession - xrEndSession Returns ------- bool False if the running session needs to end (due to the user closing or switching the application, etc.), otherwise False """ if self._disable_openxr: return True if self._use_ctypes: exit_loop = ctypes.c_bool(False) result = bool(self._lib.pollEvents(self._app, ctypes.byref(exit_loop))) return result and not exit_loop.value else: result = self._app.pollEvents() return result[0] and not result[1] def poll_actions(self) -> bool: """ [Action](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_action_overview) polling OpenXR internal function calls: - xrSyncActions - xrGetActionStateBoolean - xrGetActionStateFloat - xrGetActionStateVector2f - xrGetActionStatePose Returns ------- bool True if there is no error during polling, otherwise False """ if self._disable_openxr: return True if self._use_ctypes: requested_action_states = (ActionState * len(self._callback_action_events.keys()))() result = bool(self._lib.pollActions(self._app, requested_action_states, len(requested_action_states))) for state in requested_action_states: value = None if not state.type: break if state.type == XR_ACTION_TYPE_BOOLEAN_INPUT: value = state.stateBool elif state.type == XR_ACTION_TYPE_FLOAT_INPUT: value = state.stateFloat elif state.type == XR_ACTION_TYPE_VECTOR2F_INPUT: value = (state.stateVectorX, state.stateVectorY) elif state.type == XR_ACTION_TYPE_POSE_INPUT: continue elif state.type == XR_ACTION_TYPE_VIBRATION_OUTPUT: continue self._callback_action_events[state.path.decode("utf-8")](state.path.decode("utf-8"), value) return result else: result = self._app.pollActions() for state in result[1]: value = None if state["type"] == XR_ACTION_TYPE_BOOLEAN_INPUT: value = state["stateBool"] elif state["type"] == XR_ACTION_TYPE_FLOAT_INPUT: value = state["stateFloat"] elif state["type"] == XR_ACTION_TYPE_VECTOR2F_INPUT: value = (state["stateVectorX"], state["stateVectorY"]) elif state["type"] == XR_ACTION_TYPE_POSE_INPUT: continue elif state["type"] == XR_ACTION_TYPE_VIBRATION_OUTPUT: continue self._callback_action_events[state["path"]](state["path"], value) return result[0] def render_views(self, reference_space: int = 2) -> bool: """ Present rendered images to the user's views according to the selected reference space OpenXR internal function calls: - xrWaitFrame - xrBeginFrame - xrLocateSpace - xrLocateViews - xrAcquireSwapchainImage - xrWaitSwapchainImage - xrReleaseSwapchainImage - xrEndFrame Parameters ---------- reference_space: {XR_REFERENCE_SPACE_TYPE_VIEW, XR_REFERENCE_SPACE_TYPE_LOCAL, XR_REFERENCE_SPACE_TYPE_STAGE}, optional Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from XrReferenceSpaceType enum used to render the images (default: XR_REFERENCE_SPACE_TYPE_LOCAL) Returns ------- bool True if there is no error during rendering, otherwise False """ if self._callback_render is None: print("[INFO] No callback has been established for rendering events. Internal callback will be used") self.subscribe_render_event() if self._disable_openxr: # test sensor reading if self._viewport_window_left is not None: frame_left = sensors.get_rgb(self._viewport_window_left) cv2.imshow("frame_left {}".format(frame_left.shape), frame_left) cv2.waitKey(1) if self._viewport_window_right is not None: frame_right = sensors.get_rgb(self._viewport_window_right) cv2.imshow("frame_right {}".format(frame_right.shape), frame_right) cv2.waitKey(1) return True if self._use_ctypes: requested_action_pose_states = (ActionPoseState * len(self._callback_action_pose_events.keys()))() result = bool(self._lib.renderViews(self._app, reference_space, requested_action_pose_states, len(requested_action_pose_states))) for state in requested_action_pose_states: value = None if state.type == XR_ACTION_TYPE_POSE_INPUT and state.isActive: value = (Gf.Vec3d(state.pose.position.x, -state.pose.position.z, state.pose.position.y) / self._meters_per_unit, Gf.Quatd(state.pose.orientation.w, state.pose.orientation.x, state.pose.orientation.y, state.pose.orientation.z)) self._callback_action_pose_events[state.path.decode("utf-8")](state.path.decode("utf-8"), value) return result else: result = self._app.renderViews(reference_space) for state in result[1]: value = None if state["type"] == XR_ACTION_TYPE_POSE_INPUT and state["isActive"]: value = (Gf.Vec3d(state["pose"]["position"]["x"], -state["pose"]["position"]["z"], state["pose"]["position"]["y"]) / self._meters_per_unit, Gf.Quatd(state["pose"]["orientation"]["w"], state["pose"]["orientation"]["x"], state["pose"]["orientation"]["y"], state["pose"]["orientation"]["z"])) self._callback_action_pose_events[state["path"]](state["path"], value) return result[0] # action utilities def subscribe_action_event(self, path: str, callback: Union[Callable[[str, object], None], None] = None, action_type: Union[int, None] = None, reference_space: Union[int, None] = 2) -> bool: """ Create an action given a path and subscribe a callback function to the update event of this action If action_type is None the action type will be automatically defined by parsing the last segment of the path according to the following policy: - XR_ACTION_TYPE_BOOLEAN_INPUT: /click, /touch - XR_ACTION_TYPE_FLOAT_INPUT: /value, /force - XR_ACTION_TYPE_VECTOR2F_INPUT: /x, /y - XR_ACTION_TYPE_POSE_INPUT: /pose - XR_ACTION_TYPE_VIBRATION_OUTPUT: /haptic, /haptic_left, /haptic_right, /haptic_left_trigger, /haptic_right_trigger The callback function (a callable object) should have only the following 2 parameters: - path: str The complete path (user path and subpath) of the action that invokes the callback - value: bool, float, tuple(float, float), tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd) The current state of the action according to its type - XR_ACTION_TYPE_BOOLEAN_INPUT: bool - XR_ACTION_TYPE_FLOAT_INPUT: float - XR_ACTION_TYPE_VECTOR2F_INPUT (x, y): tuple(float, float) - XR_ACTION_TYPE_POSE_INPUT (position (in stage unit), rotation as quaternion): tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd) XR_ACTION_TYPE_VIBRATION_OUTPUT actions will not invoke their callback function. In this case the callback must be None XR_ACTION_TYPE_POSE_INPUT also specifies, through the definition of the reference_space parameter, the reference space used to retrieve the pose The collection of available paths corresponds to the following [interaction profiles](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-interaction-profiles): - [Khronos Simple Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_khronos_simple_controller_profile) - [Google Daydream Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_google_daydream_controller_profile) - [HTC Vive Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_controller_profile) - [HTC Vive Pro](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_pro_profile) - [Microsoft Mixed Reality Motion Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_mixed_reality_motion_controller_profile) - [Microsoft Xbox Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_xbox_controller_profile) - [Oculus Go Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_go_controller_profile) - [Oculus Touch Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_touch_controller_profile) - [Valve Index Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_valve_index_controller_profile) OpenXR internal function calls: - xrCreateAction Parameters ---------- path: str Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action callback: callable object (2 parameters) or None for XR_ACTION_TYPE_VIBRATION_OUTPUT Callback invoked when the state of the action changes action_type: {XR_ACTION_TYPE_BOOLEAN_INPUT, XR_ACTION_TYPE_FLOAT_INPUT, XR_ACTION_TYPE_VECTOR2F_INPUT, XR_ACTION_TYPE_POSE_INPUT, XR_ACTION_TYPE_VIBRATION_OUTPUT} or None, optional Action [type](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrActionType) from XrActionType enum (default: None) reference_space: {XR_REFERENCE_SPACE_TYPE_VIEW, XR_REFERENCE_SPACE_TYPE_LOCAL, XR_REFERENCE_SPACE_TYPE_STAGE}, optional Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from XrReferenceSpaceType enum used to retrieve the pose (default: XR_REFERENCE_SPACE_TYPE_LOCAL) Returns ------- bool True if there is no error during action creation, otherwise False """ if action_type is None: if path.split("/")[-1] in ["click", "touch"]: action_type = XR_ACTION_TYPE_BOOLEAN_INPUT elif path.split("/")[-1] in ["value", "force"]: action_type = XR_ACTION_TYPE_FLOAT_INPUT elif path.split("/")[-1] in ["x", "y"]: action_type = XR_ACTION_TYPE_VECTOR2F_INPUT elif path.split("/")[-1] in ["pose"]: action_type = XR_ACTION_TYPE_POSE_INPUT elif path.split("/")[-1] in ["haptic", "haptic_left", "haptic_right", "haptic_left_trigger", "haptic_right_trigger"]: action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT else: raise ValueError("The action type cannot be retrieved from the path {}".format(path)) if callback is None and action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT: raise ValueError("The callback was not defined") self._callback_action_events[path] = callback if action_type == XR_ACTION_TYPE_POSE_INPUT: self._callback_action_pose_events[path] = callback if self._disable_openxr: return True if self._use_ctypes: return bool(self._lib.addAction(self._app, ctypes.create_string_buffer(path.encode('utf-8')), action_type, reference_space)) else: return self._app.addAction(path, action_type, reference_space) def apply_haptic_feedback(self, path: str, haptic_feedback: dict = {}) -> bool: """ Apply a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) to a device defined by a path (user path and subpath) OpenXR internal function calls: - xrApplyHapticFeedback Parameters ---------- path: str Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action haptic_feedback: dict A python dictionary containing the field names and value of a XrHapticBaseHeader-based structure. Note: At the moment the only haptics type supported is the unextended OpenXR [XrHapticVibration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrHapticVibration) Returns ------- bool True if there is no error during the haptic feedback application, otherwise False """ amplitude = haptic_feedback.get("amplitude", 0.5) duration = haptic_feedback.get("duration", XR_MIN_HAPTIC_DURATION) frequency = haptic_feedback.get("frequency", XR_FREQUENCY_UNSPECIFIED) if self._disable_openxr: return True if self._use_ctypes: amplitude = ctypes.c_float(amplitude) duration = ctypes.c_int64(duration) frequency = ctypes.c_float(frequency) return bool(self._lib.applyHapticFeedback(self._app, ctypes.create_string_buffer(path.encode('utf-8')), amplitude, duration, frequency)) else: return self._app.applyHapticFeedback(path, amplitude, duration, frequency) def stop_haptic_feedback(self, path: str) -> bool: """ Stop a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) applied to a device defined by a path (user path and subpath) OpenXR internal function calls: - xrStopHapticFeedback Parameters ---------- path: str Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action Returns ------- bool True if there is no error during the haptic feedback stop, otherwise False """ if self._disable_openxr: return True if self._use_ctypes: return bool(self._lib.stopHapticFeedback(self._app, ctypes.create_string_buffer(path.encode('utf-8')))) else: return self._app.stopHapticFeedback(path) # view utilities def setup_mono_view(self, camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/camera", camera_properties: dict = {"focalLength": 10}) -> None: """ Setup Omniverse viewport and camera for monoscopic rendering This method obtains the viewport window for the given camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given camera does not exist, a new camera is created with the same path and set to the recommended resolution of the display device Parameters ---------- camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional Omniverse camera prim or path (default: '/OpenXR/Cameras/camera') camera_properties: dict Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: {"focalLength": 10}) """ self.setup_stereo_view(camera, None, camera_properties) def setup_stereo_view(self, left_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/left_camera", right_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim, None] = "/OpenXR/Cameras/right_camera", camera_properties: dict = {"focalLength": 10}) -> None: """ Setup Omniverse viewports and cameras for stereoscopic rendering This method obtains the viewport window for each camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given cameras do not exist, new cameras are created with the same path and set to the recommended resolution of the display device Parameters ---------- left_camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional Omniverse left camera prim or path (default: '/OpenXR/Cameras/left_camera') right_camera: str, pxr.Sdf.Path or pxr.Usd.Prim, optional Omniverse right camera prim or path (default: '/OpenXR/Cameras/right_camera') camera_properties: dict Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: {"focalLength": 10}) """ def get_or_create_vieport_window(camera, teleport=True, window_size=(400, 300), resolution=(1280, 720)): window = None camera = str(camera.GetPath() if type(camera) is Usd.Prim else camera) # get viewport window for interface in self._viewport_interface.get_instance_list(): w = self._viewport_interface.get_viewport_window(interface) if camera == w.get_active_camera(): window = w # check visibility if not w.is_visible(): w.set_visible(True) break # create viewport window if not exist if window is None: window = self._viewport_interface.get_viewport_window(self._viewport_interface.create_instance()) window.set_window_size(*window_size) window.set_active_camera(camera) window.set_texture_resolution(*resolution) if teleport: window.set_camera_position(camera, 1.0, 1.0, 1.0, True) window.set_camera_target(camera, 0.0, 0.0, 0.0, True) return window stage = omni.usd.get_context().get_stage() # left camera teleport_camera = False self._prim_left = None if type(left_camera) is Usd.Prim: self._prim_left = left_camera elif stage.GetPrimAtPath(left_camera).IsValid(): self._prim_left = stage.GetPrimAtPath(left_camera) else: teleport_camera = True self._prim_left = stage.DefinePrim(omni.usd.get_stage_next_free_path(stage, left_camera, False), "Camera") self._viewport_window_left = get_or_create_vieport_window(self._prim_left, teleport=teleport_camera) # right camera teleport_camera = False self._prim_right = None if right_camera is not None: if type(right_camera) is Usd.Prim: self._prim_right = right_camera elif stage.GetPrimAtPath(right_camera).IsValid(): self._prim_right = stage.GetPrimAtPath(right_camera) else: teleport_camera = True self._prim_right = stage.DefinePrim(omni.usd.get_stage_next_free_path(stage, right_camera, False), "Camera") self._viewport_window_right = get_or_create_vieport_window(self._prim_right, teleport=teleport_camera) # set recommended resolution resolutions = self.get_recommended_resolutions() if len(resolutions) and self._viewport_window_left is not None: self._viewport_window_left.set_texture_resolution(*resolutions[0]) if len(resolutions) == 2 and self._viewport_window_right is not None: self._viewport_window_right.set_texture_resolution(*resolutions[1]) # set camera properties for property in camera_properties: self._prim_left.GetAttribute(property).Set(camera_properties[property]) if right_camera is not None: self._prim_right.GetAttribute(property).Set(camera_properties[property]) # enable sensors if self._viewport_window_left is not None: sensors.enable_sensors(self._viewport_window_left, [_syntheticdata.SensorType.Rgb]) if self._viewport_window_right is not None: sensors.enable_sensors(self._viewport_window_right, [_syntheticdata.SensorType.Rgb]) def get_recommended_resolutions(self) -> tuple: """ Get the recommended resolution of the display device Returns ------- tuple Tuple containing the recommended resolutions (width, height) of each device view. If the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye """ if self._disable_openxr: return ([512, 512], [1024, 1024]) if self._use_ctypes: num_views = self._lib.getViewConfigurationViewsSize(self._app) views = (XrViewConfigurationView * num_views)() if self._lib.getViewConfigurationViews(self._app, views, num_views): return [(view.recommendedImageRectWidth, view.recommendedImageRectHeight) for view in views] else: return tuple([]) else: return tuple([(view["recommendedImageRectWidth"], view["recommendedImageRectHeight"]) for view in self._app.getViewConfigurationViews()]) def set_reference_system_pose(self, position: Union[pxr.Gf.Vec3d, None] = None, rotation: Union[pxr.Gf.Vec3d, None] = None) -> None: """ Set the pose of the origin of the reference system Parameters ---------- position: pxr.Gf.Vec3d or None, optional Cartesian position (in stage unit) (default: None) rotation: pxr.Gf.Vec3d or None, optional Rotation (in degress) on each axis (default: None) """ self._reference_position = position self._reference_rotation = rotation def set_stereo_rectification(self, x: float = 0, y: float = 0, z: float = 0) -> None: """ Set the angle (in radians) of the rotation axes for stereoscopic view rectification Parameters ---------- x: float, optional Angle (in radians) of the X-axis (default: 0) y: float, optional Angle (in radians) of the Y-axis (default: 0) x: float, optional Angle (in radians) of the Z-axis (default: 0) """ self._rectification_quat_left = pxr.Gf.Quatd(1, 0, 0, 0) self._rectification_quat_right = pxr.Gf.Quatd(1, 0, 0, 0) if x: # w,x,y,z = cos(a/2), sin(a/2), 0, 0 self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(x/2), np.sin(x/2), 0, 0) self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-x/2), np.sin(-x/2), 0, 0) if y: # w,x,y,z = cos(a/2), 0, sin(a/2), 0 self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(y/2), 0, np.sin(y/2), 0) self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-y/2), 0, np.sin(-y/2), 0) if z: # w,x,y,z = cos(a/2), 0, 0, sin(a/2) self._rectification_quat_left *= pxr.Gf.Quatd(np.cos(z/2), 0, 0, np.sin(z/2)) self._rectification_quat_right *= pxr.Gf.Quatd(np.cos(-z/2), 0, 0, np.sin(-z/2)) def set_meters_per_unit(self, meters_per_unit: float): """ Specify the meters per unit to be applied to transformations E.g. 1 meter: 1.0, 1 centimeter: 0.01 Parameters ---------- meters_per_unit: float Meters per unit """ assert meters_per_unit != 0 self._meters_per_unit = meters_per_unit def set_frame_transformations(self, fit: bool = False, flip: Union[int, tuple, None] = None) -> None: """ Specify the transformations to be applied to the rendered images Parameters ---------- fit: bool, optional Adjust each rendered image to the recommended resolution of the display device by cropping and scaling the image from its center (default: False) OpenCV.resize method with INTER_LINEAR interpolation will be used to scale the image to the recommended resolution flip: int, tuple or None, optional Flip each image around vertical (0), horizontal (1), or both axes (0,1) (default: None) """ self._transform_fit = fit self._transform_flip = flip def teleport_prim(self, prim: pxr.Usd.Prim, position: pxr.Gf.Vec3d, rotation: pxr.Gf.Quatd, reference_position: Union[pxr.Gf.Vec3d, None] = None, reference_rotation: Union[pxr.Gf.Vec3d, None] = None) -> None: """ Teleport the prim specified by the given transformation (position and rotation) Parameters ---------- prim: pxr.Usd.Prim Target prim position: pxr.Gf.Vec3d Cartesian position (in stage unit) used to transform the prim rotation: pxr.Gf.Quatd Rotation (as quaternion) used to transform the prim reference_position: pxr.Gf.Vec3d or None, optional Cartesian position (in stage unit) used as reference system (default: None) reference_rotation: pxr.Gf.Vec3d or None, optional Rotation (in degress) on each axis used as reference system (default: None) """ properties = prim.GetPropertyNames() # reference position if reference_position is not None: if "xformOp:translate" in properties or "xformOp:translation" in properties: prim.GetAttribute("xformOp:translate").Set(reference_position + position) else: print("[INFO] Create UsdGeom.XformOp.TypeTranslate for", prim.GetPath()) UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "").Set(reference_position + position) else: if "xformOp:translate" in properties or "xformOp:translation" in properties: prim.GetAttribute("xformOp:translate").Set(position) else: print("[INFO] Create UsdGeom.XformOp.TypeTranslate for", prim.GetPath()) UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "").Set(position) # reference rotation if reference_rotation is not None: if "xformOp:rotate" in properties: prim.GetAttribute("xformOp:rotate").Set(reference_rotation) elif "xformOp:rotateXYZ" in properties: try: prim.GetAttribute("xformOp:rotateXYZ").Set(reference_rotation) except: prim.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3f(reference_rotation)) else: print("[INFO] Create UsdGeom.XformOp.TypeRotateXYZ for", prim.GetPath()) UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.PrecisionDouble, "").Set(reference_rotation) # transform transform_matrix = Gf.Matrix4d() transform_matrix.SetIdentity() # transform_matrix.SetTranslateOnly(position) transform_matrix.SetRotateOnly(Gf.Rotation(rotation)) if "xformOp:transform" in properties: prim.GetAttribute("xformOp:transform").Set(transform_matrix) else: print("[INFO] Create UsdGeom.XformOp.TypeTransform for", prim.GetPath()) UsdGeom.Xformable(prim).AddXformOp(UsdGeom.XformOp.TypeTransform, UsdGeom.XformOp.PrecisionDouble, "").Set(transform_matrix) def subscribe_render_event(self, callback=None) -> None: """ Subscribe a callback function to the render event The callback function (a callable object) should have only the following 3 parameters: - num_views: int The number of views to render: mono (1), stereo (2) - views: tuple of XrView structure A [XrView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrView) structure contains the view pose and projection state necessary to render a image. The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye) - configuration_views: tuple of XrViewConfigurationView structure A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view). The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye) The callback function must call the set_frames function to pass to the selected graphics API the image or images to be rendered If the callback is None, an internal callback will be used to render the views. This internal callback updates the pose of the cameras according to the specified reference system, gets the images from the previously configured viewports and invokes the set_frames function to render the views. Parameters ---------- callback: callable object (3 parameters) or None, optional Callback invoked on each render event (default: None) """ def _middle_callback(num_views, views, configuration_views): _views = [] for v in views: tmp = XrView() tmp.type = v["type"] tmp.next = None tmp.pose = XrPosef() tmp.pose.position.x = v["pose"]["position"]["x"] tmp.pose.position.y = v["pose"]["position"]["y"] tmp.pose.position.z = v["pose"]["position"]["z"] tmp.pose.orientation.x = v["pose"]["orientation"]["x"] tmp.pose.orientation.y = v["pose"]["orientation"]["y"] tmp.pose.orientation.z = v["pose"]["orientation"]["z"] tmp.pose.orientation.w = v["pose"]["orientation"]["w"] tmp.fov = XrFovf() tmp.fov.angleLeft = v["fov"]["angleLeft"] tmp.fov.angleRight = v["fov"]["angleRight"] tmp.fov.angleUp = v["fov"]["angleUp"] tmp.fov.angleDown = v["fov"]["angleDown"] _views.append(tmp) _configuration_views = [] for v in configuration_views: tmp = XrViewConfigurationView() tmp.type = v["type"] tmp.next = None tmp.recommendedImageRectWidth = v["recommendedImageRectWidth"] tmp.recommendedImageRectHeight = v["recommendedImageRectHeight"] tmp.maxImageRectWidth = v["maxImageRectWidth"] tmp.maxImageRectHeight = v["maxImageRectHeight"] tmp.recommendedSwapchainSampleCount = v["recommendedSwapchainSampleCount"] tmp.maxSwapchainSampleCount = v["maxSwapchainSampleCount"] _configuration_views.append(tmp) self._callback_render(num_views, _views, _configuration_views) def _internal_render(num_views, views, configuration_views): # teleport left camera position = views[0].pose.position rotation = views[0].pose.orientation position = Gf.Vec3d(position.x, -position.z, position.y) / self._meters_per_unit rotation = Gf.Quatd(rotation.w, rotation.x, rotation.y, rotation.z) * self._rectification_quat_left self.teleport_prim(self._prim_left, position, rotation, self._reference_position, self._reference_rotation) # teleport right camera if num_views == 2: position = views[1].pose.position rotation = views[1].pose.orientation position = Gf.Vec3d(position.x, -position.z, position.y) / self._meters_per_unit rotation = Gf.Quatd(rotation.w, rotation.x, rotation.y, rotation.z) * self._rectification_quat_right self.teleport_prim(self._prim_right, position, rotation, self._reference_position, self._reference_rotation) # set frames try: frame_left = sensors.get_rgb(self._viewport_window_left) frame_right = sensors.get_rgb(self._viewport_window_right) if num_views == 2 else None self.set_frames(configuration_views, frame_left, frame_right) except Exception as e: print("[ERROR]", str(e)) self._callback_render = callback if callback is None: self._callback_render = _internal_render if self._disable_openxr: return if self._use_ctypes: self._callback_middle_render = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.POINTER(XrView), ctypes.POINTER(XrViewConfigurationView))(self._callback_render) self._lib.setRenderCallback(self._app, self._callback_middle_render) else: self._callback_middle_render = _middle_callback self._app.setRenderCallback(self._callback_middle_render) def set_frames(self, configuration_views: list, left: numpy.ndarray, right: numpy.ndarray = None) -> bool: """ Pass to the selected graphics API the images to be rendered in the views In the case of stereoscopic devices, the parameters left and right represent the left eye and right eye respectively. To pass an image to the graphic API of monoscopic devices only the parameter left should be used (the parameter right must be None) This function will apply to each image the transformations defined by the set_frame_transformations function if they were specified Parameters ---------- configuration_views: tuple of XrViewConfigurationView structure A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view) left: numpy.ndarray RGB or RGBA image (numpy.uint8) right: numpy.ndarray or None RGB or RGBA image (numpy.uint8) Returns ------- bool True if there is no error during the passing to the selected graphics API, otherwise False """ use_rgba = True if left.shape[2] == 4 else False if self._disable_openxr: return True if self._use_ctypes: self._frame_left = self._transform(configuration_views[0], left) if right is None: return bool(self._lib.setFrames(self._app, self._frame_left.shape[1], self._frame_left.shape[0], self._frame_left.ctypes.data_as(ctypes.c_void_p), 0, 0, None, use_rgba)) else: self._frame_right = self._transform(configuration_views[1], right) return bool(self._lib.setFrames(self._app, self._frame_left.shape[1], self._frame_left.shape[0], self._frame_left.ctypes.data_as(ctypes.c_void_p), self._frame_right.shape[1], self._frame_right.shape[0], self._frame_right.ctypes.data_as(ctypes.c_void_p), use_rgba)) else: self._frame_left = self._transform(configuration_views[0], left) if right is None: return self._app.setFrames(self._frame_left, np.array(None), use_rgba) else: self._frame_right = self._transform(configuration_views[1], right) return self._app.setFrames(self._frame_left, self._frame_right, use_rgba) def _transform(self, configuration_view: XrViewConfigurationView, frame: np.ndarray) -> np.ndarray: transformed = False if self._transform_flip is not None: transformed = True frame = np.flip(frame, axis=self._transform_flip) if self._transform_fit: transformed = True current_ratio = frame.shape[1] / frame.shape[0] recommended_ratio = configuration_view.recommendedImageRectWidth / configuration_view.recommendedImageRectHeight recommended_size = (configuration_view.recommendedImageRectWidth, configuration_view.recommendedImageRectHeight) if current_ratio > recommended_ratio: m = int(abs(recommended_ratio * frame.shape[0] - frame.shape[1]) / 2) frame = cv2.resize(frame[:, m:-m] if m else frame, recommended_size, interpolation=cv2.INTER_LINEAR) else: m = int(abs(frame.shape[1] / recommended_ratio - frame.shape[0]) / 2) frame = cv2.resize(frame[m:-m, :] if m else frame, recommended_size, interpolation=cv2.INTER_LINEAR) return np.array(frame, copy=True) if transformed else frame if __name__ == "__main__": import cv2 import time import argparse parser = argparse.ArgumentParser() parser.add_argument('--ctypes', default=False, action="store_true", help='use ctypes instead of pybind11') args = parser.parse_args() _xr = acquire_openxr_interface() _xr.init(use_ctypes=args.ctypes) ready = False end = False def callback_action_pose(path, value): print(path, value) return def callback_action(path, value): if path in ["/user/hand/left/input/menu/click", "/user/hand/right/input/menu/click"]: # print(path, value) print(_xr.apply_haptic_feedback("/user/hand/left/output/haptic", {"duration": 1000000})) print(_xr.apply_haptic_feedback("/user/hand/right/output/haptic", {"duration": 1000000})) if _xr.create_instance(): if _xr.get_system(): _xr.subscribe_action_event("/user/head/input/volume_up/click", callback=callback_action) _xr.subscribe_action_event("/user/head/input/volume_down/click", callback=callback_action) _xr.subscribe_action_event("/user/head/input/mute_mic/click", callback=callback_action) _xr.subscribe_action_event("/user/hand/left/input/trigger/value", callback=callback_action) _xr.subscribe_action_event("/user/hand/right/input/trigger/value", callback=callback_action) _xr.subscribe_action_event("/user/hand/left/input/menu/click", callback=callback_action) _xr.subscribe_action_event("/user/hand/right/input/menu/click", callback=callback_action) _xr.subscribe_action_event("/user/hand/left/input/grip/pose", callback=callback_action_pose, reference_space=XR_REFERENCE_SPACE_TYPE_LOCAL) _xr.subscribe_action_event("/user/hand/right/input/grip/pose", callback=callback_action_pose, reference_space=XR_REFERENCE_SPACE_TYPE_LOCAL) _xr.subscribe_action_event("/user/hand/left/output/haptic", callback=callback_action) _xr.subscribe_action_event("/user/hand/right/output/haptic", callback=callback_action) if _xr.create_session(): ready = True else: print("[ERROR]:", "createSession") else: print("[ERROR]:", "getSystem") else: print("[ERROR]:", "createInstance") if ready: cap = cv2.VideoCapture("/home/argus/Videos/xr/xr/sample.mp4") def callback_render(num_views, views, configuration_views): pass # global end # ret, frame = cap.read() # if ret: # if num_views == 2: # frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # _xr.set_frames(configuration_views, frame, frame1) # # show frame # k = 0.25 # frame = cv2.resize(np.hstack((frame, frame1)), (int(2*k*frame.shape[1]), int(k*frame.shape[0]))) # cv2.imshow('frame', frame) # if cv2.waitKey(1) & 0xFF == ord('q'): # exit() # else: # end = True _xr.subscribe_render_event(callback_render) # while(cap.isOpened() or not end): for i in range(10000000): if _xr.poll_events(): if _xr.is_session_running(): if not _xr.poll_actions(): print("[ERROR]:", "pollActions") break if not _xr.render_views(): print("[ERROR]:", "renderViews") break else: print("wait for is_session_running()") time.sleep(0.1) else: break print("END")
58,615
Python
47.928214
301
0.61387
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/scripts/extension.py
import gc import carb import omni.ext try: import cv2 except: omni.kit.pipapi.install("opencv-python") try: from .. import _openxr as _openxr except: print(">>>> [DEVELOPMENT] import openxr") from .. import openxr as _openxr __all__ = ["Extension", "_openxr"] class Extension(omni.ext.IExt): def on_startup(self, ext_id): # get extension settings self._settings = carb.settings.get_settings() disable_openxr = self._settings.get("/exts/semu.xr.openxr/disable_openxr") self._xr = _openxr.acquire_openxr_interface(disable_openxr=disable_openxr) def on_shutdown(self): _openxr.release_openxr_interface(self._xr) gc.collect()
703
Python
24.142856
82
0.657183
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/tests/__init__.py
from .test_openxr import *
27
Python
12.999994
26
0.740741
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr/tests/test_openxr.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 # Import extension python module we are testing with absolute import path, as if we are external user (other extension) from semu.xr.openxr import _openxr import cv2 import time import numpy as np # 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 TestOpenXR(omni.kit.test.AsyncTestCaseFailOnLogError): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass def render(self, num_frames, width, height, color): self._frame = np.ones((height, width, 3), dtype=np.uint8) self._frame = cv2.circle(self._frame, (int(width / 2), int(height / 2)), int(np.min([width, height]) / 4), color, int(0.05 * np.min([width, height]))) self._frame = cv2.circle(self._frame, (int(width / 3), int(height / 3)), int(0.1 * np.min([width, height])), color, -1) start_time = time.clock() for i in range(num_frames): if self._xr.poll_events(): if self._xr.is_session_running(): if not self._xr.poll_actions(): print("[ERROR]:", "pollActions") return if not self._xr.render_views(): print("[ERROR]:", "renderViews") return end_time = time.clock() delta = end_time - start_time print("----------") print("FPS: {} ({} frames / {} seconds)".format(num_frames / delta, num_frames, delta)) print("RESOLUTION: {} x {}".format(self._frame.shape[1], self._frame.shape[0])) # Actual test, notice it is "async" function, so "await" can be used if needed async def test_openxr(self): self._xr = _openxr.acquire_openxr_interface() self._xr.init() ready = False if self._xr.create_instance(): if self._xr.get_system(): if self._xr.create_action_set(): if self._xr.create_session(): ready = True else: print("[ERROR]:", "createSession") else: print("[ERROR]:", "createActionSet") else: print("[ERROR]:", "getSystem") else: print("[ERROR]:", "createInstance") if ready: for i in range(1000): if self._xr.poll_events(): if self._xr.is_session_running(): if not self._xr.poll_actions(): print("[ERROR]:", "pollActions") break # if ready: # def callback_render(num_views, views, configuration_views): # self._xr.set_frames(configuration_views, self._frame, self._frame, self._transform) # self._xr.subscribe_render_event(callback_render) # num_frames = 100 # print("") # print("transform = True") # self._transform = True # self.render(num_frames=num_frames, width=1560, height=1732, color=(255,0,0)) # self.render(num_frames=num_frames, width=1280, height=720, color=(0,255,0)) # self.render(num_frames=num_frames, width=500, height=500, color=(0,0,255)) # print("") # print("transform = False") # self._transform = False # self.render(num_frames=num_frames, width=1560, height=1732, color=(255,0,0)) # self.render(num_frames=num_frames, width=1280, height=720, color=(0,255,0)) # self.render(num_frames=num_frames, width=500, height=500, color=(0,0,255)) # print("") # _openxr.release_openxr_interface(self._xr) # self._xr = None
4,250
Python
40.271844
142
0.527529
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/semu/xr/openxr_ui/scripts/extension.py
import math import weakref import pxr import omni import carb import omni.ext import omni.ui as ui from pxr import UsdGeom from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription from semu.xr.openxr import _openxr class Extension(omni.ext.IExt): def on_startup(self, ext_id): # get extension settings self._settings = carb.settings.get_settings() self._disable_openxr = self._settings.get("/exts/semu.xr.openxr/disable_openxr") self._window = None self._menu_items = [MenuItemDescription(name="OpenXR UI", onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] add_menu_items(self._menu_items, "Add-ons") self._xr = None self._ready = False self._timeline = omni.timeline.get_timeline_interface() self._physx_subs = omni.physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step) def on_shutdown(self): self._physx_subs = None remove_menu_items(self._menu_items, "Add-ons") self._window = None def _get_reference_space(self): reference_space = [_openxr.XR_REFERENCE_SPACE_TYPE_VIEW, _openxr.XR_REFERENCE_SPACE_TYPE_LOCAL, _openxr.XR_REFERENCE_SPACE_TYPE_STAGE] return reference_space[self._xr_settings_reference_space.model.get_item_value_model().as_int] def _get_origin_pose(self): space_origin_position = [self._xr_settings_space_origin_position.model.get_item_value_model(i).as_float for i in self._xr_settings_space_origin_position.model.get_item_children()] space_origin_rotation = [self._xr_settings_space_origin_rotation.model.get_item_value_model(i).as_int for i in self._xr_settings_space_origin_rotation.model.get_item_children()] return {"position": pxr.Gf.Vec3d(*space_origin_position), "rotation": pxr.Gf.Vec3d(*space_origin_rotation)} def _get_frame_transformations(self): transform_fit = self._xr_settings_transform_fit.model.get_value_as_bool() transform_flip = [None, 0, 1, (0,1)] transform_flip = transform_flip[self._xr_settings_transform_flip.model.get_item_value_model().as_int] return {"fit": transform_fit, "flip": transform_flip} def _get_stereo_rectification(self): return [self._xr_settings_stereo_rectification.model.get_item_value_model(i).as_float * math.pi / 180.0 for i in self._xr_settings_stereo_rectification.model.get_item_children()] def _menu_callback(self): self._build_ui() def _on_start_openxr(self): # get parameters from ui graphics = [_openxr.XR_KHR_OPENGL_ENABLE_EXTENSION_NAME] graphics = graphics[self._xr_settings_graphics_api.model.get_item_value_model().as_int] form_factor = [_openxr.XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, _openxr.XR_FORM_FACTOR_HANDHELD_DISPLAY] form_factor = form_factor[self._xr_settings_form_factor.model.get_item_value_model().as_int] blend_mode = [_openxr.XR_ENVIRONMENT_BLEND_MODE_OPAQUE, _openxr.XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, _openxr.XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND] blend_mode = blend_mode[self._xr_settings_blend_mode.model.get_item_value_model().as_int] view_configuration_type = [_openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO] view_configuration_type = view_configuration_type[self._xr_settings_view_configuration_type.model.get_item_value_model().as_int] # disable static parameters ui self._xr_settings_graphics_api.enabled = False self._xr_settings_form_factor.enabled = False self._xr_settings_blend_mode.enabled = False self._xr_settings_view_configuration_type.enabled = False if self._xr is None: self._xr = _openxr.acquire_openxr_interface(disable_openxr=self._disable_openxr) if not self._xr.init(graphics=graphics, use_ctypes=False): print("[ERROR] OpenXR.init with graphics: {}".format(graphics)) # set stage unit stage = omni.usd.get_context().get_stage() self._xr.set_meters_per_unit(UsdGeom.GetStageMetersPerUnit(stage)) # setup OpenXR application using default and ui parameters if self._xr.create_instance(): if self._xr.get_system(form_factor=form_factor, blend_mode=blend_mode, view_configuration_type=view_configuration_type): # create session and define interaction profiles if self._xr.create_session(): # setup cameras and viewports and prepare rendering using the internal callback if view_configuration_type == _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO: self._xr.setup_mono_view() elif view_configuration_type == _openxr.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO: self._xr.setup_stereo_view() # enable/disable buttons self._ui_start_xr.enabled = False self._ui_stop_xr.enabled = True # play self._timeline.play() self._ready = True return else: print("[ERROR] OpenXR.create_session") else: print("[ERROR] OpenXR.get_system with form_factor: {}, blend_mode: {}, view_configuration_type: {}".format(form_factor, blend_mode, view_configuration_type)) else: print("[ERROR] OpenXR.create_instance") self._on_stop_openxr() def _on_stop_openxr(self): self._ready = False _openxr.release_openxr_interface(self._xr) self._xr = None # enable static parameters ui self._xr_settings_graphics_api.enabled = True self._xr_settings_form_factor.enabled = True self._xr_settings_blend_mode.enabled = True self._xr_settings_view_configuration_type.enabled = True # enable/disable buttons self._ui_start_xr.enabled = True self._ui_stop_xr.enabled = False def _on_simulation_step(self, step): if self._ready and self._xr is not None: # origin self._xr.set_reference_system_pose(**self._get_origin_pose()) # transformation and rectification self._xr.set_stereo_rectification(*self._get_stereo_rectification()) self._xr.set_frame_transformations(**self._get_frame_transformations()) # action and rendering loop if not self._xr.poll_events(): self._on_stop_openxr() return if self._xr.is_session_running(): if not self._xr.poll_actions(): self._on_stop_openxr() return if not self._xr.render_views(self._get_reference_space()): self._on_stop_openxr() return def _build_ui(self): if not self._window: self._window = ui.Window(title="OpenXR UI", width=300, height=375, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM) with self._window.frame: with ui.VStack(): ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Graphics API:", width=85, tooltip="OpenXR graphics API supported by the runtime") self._xr_settings_graphics_api = ui.ComboBox(0, "OpenGL") ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Form factor:", width=80, tooltip="XrFormFactor enum. HEAD_MOUNTED_DISPLAY: the tracked display is attached to the user's head. HANDHELD_DISPLAY: the tracked display is held in the user's hand, independent from the user's head") self._xr_settings_form_factor = ui.ComboBox(0, "Head Mounted Display", "Handheld Display") ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Blend mode:", width=80, tooltip="XrEnvironmentBlendMode enum. OPAQUE: display the composition layers with no view of the physical world behind them. ADDITIVE: additively blend the composition layers with the real world behind the display. ALPHA BLEND: alpha-blend the composition layers with the real world behind the display") self._xr_settings_blend_mode = ui.ComboBox(0, "Opaque", "Additive", "Alpha blend") ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("View configuration type:", width=145, tooltip="XrViewConfigurationType enum. MONO: one primary display (e.g. an AR phone's screen). STEREO: two primary displays, which map to a left-eye and right-eye view") self._xr_settings_view_configuration_type = ui.ComboBox(1, "Mono", "Stereo") ui.Spacer(height=5) ui.Separator(height=1, width=0) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Space origin:", width=85) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label(" |-- Position (in stage unit):", width=165, tooltip="Cartesian position (in stage unit) used as reference origin") self._xr_settings_space_origin_position = ui.MultiFloatDragField(0.0, 0.0, 0.0, step=0.1) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label(" |-- Rotation (XYZ):", width=110, tooltip="Rotation (in degress) on each axis used as reference origin") self._xr_settings_space_origin_rotation = ui.MultiIntDragField(0, 0, 0, min=-180, max=180) ui.Spacer(height=5) with ui.HStack(height=0): style = {"Tooltip": {"width": 50, "word-wrap": "break-word"}} ui.Label("Reference space (views):", width=145, tooltip="XrReferenceSpaceType enum. VIEW: track the view origin for the primary viewer. LOCAL: establish a world-locked origin. STAGE: runtime-defined space that can be walked around on", style=style) self._xr_settings_reference_space = ui.ComboBox(1, "View", "Local", "Stage") ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Stereo rectification (x,y,z):", width=150, tooltip="Angle (in degrees) on each rotation axis for stereoscopic rectification") self._xr_settings_stereo_rectification = ui.MultiFloatDragField(0.0, 0.0, 0.0, min=-10, max=10, step=0.1) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("Frame transformations:") ui.Spacer(height=5) with ui.HStack(height=0): ui.Label(" |-- Fit:", width=45, tooltip="Adjust each rendered image to the recommended resolution of the display device by cropping and scaling the image from its center") self._xr_settings_transform_fit = ui.CheckBox() ui.Spacer(height=5) with ui.HStack(height=0): ui.Label(" |-- Flip:", width=45, tooltip="Flip each image with respect to its view") self._xr_settings_transform_flip = ui.ComboBox(0, "None", "Vertical", "Horizontal", "Both") ui.Spacer(height=5) ui.Separator(height=1, width=0) ui.Spacer(height=5) with ui.HStack(height=0): self._ui_start_xr = ui.Button("Start OpenXR", height=0, clicked_fn=self._on_start_openxr) self._ui_stop_xr = ui.Button("Stop OpenXR", height=0, clicked_fn=self._on_stop_openxr) self._ui_stop_xr.enabled = False
12,268
Python
55.800926
361
0.593332
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer.py
# Copyright (c) 2018-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. # import omni.kit.widget.imageview as imageview import omni.ui as ui from .singleton import singleton @singleton class ViewerWindows: """This object keeps all the Image Viewper windows""" def __init__(self): self.__windows = {} def open_window(self, filepath: str) -> ui.Window: """Open ImageViewer window with the image file opened in it""" if filepath in self.__windows: window = self.__windows[filepath] window.visible = True else: window = ImageViewer(filepath) # When window is closed, remove it from the list window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f)) self.__windows[filepath] = window return window def close(self, filepath): """Close and remove spacific window""" del self.__windows[filepath] def close_all(self): """Close and remove all windows""" self.__windows = {} class ImageViewer(ui.Window): """The window with Image Viewer""" def __init__(self, filename: str, **kwargs): if "width" not in kwargs: kwargs["width"] = 640 if "height" not in kwargs: kwargs["height"] = 480 super().__init__(filename, **kwargs) self.frame.set_style({"Window": {"background_color": 0xFF000000, "border_width": 0}}) self.frame.set_build_fn(self.__build_window) self.__filename = filename def __build_window(self): """Called to build the widgets of the window""" # For now it's only one single widget imageview.ImageView(self.__filename, smooth_zoom=True, style={"ImageView": {"background_color": 0xFF000000}}) def destroy(self): pass
2,181
Python
33.093749
117
0.644658
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_utils.py
# Copyright (c) 2018-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. # import omni.kit.app def is_extension_loaded(extansion_name: str) -> bool: """ Returns True if the extension with the given name is loaded. """ def is_ext(ext_id: str, extension_name: str) -> bool: id_name = omni.ext.get_extension_name(ext_id) return id_name == extension_name app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() extensions = ext_manager.get_extensions() loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None) return bool(loaded)
1,015
Python
35.285713
108
0.721182
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/content_menu.py
# Copyright (c) 2018-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. # from .imageviewer import ViewerWindows from .imageviewer_utils import is_extension_loaded def content_available(): """ Returns True if the extension "omni.kit.window.content_browser" is loaded. """ return is_extension_loaded("omni.kit.window.content_browser") class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to view image files. """ def __init__(self, version: int = 2): if version != 2: raise RuntimeError("Only version 2 is supported") content_window = self._get_content_window() if content_window: view_menu_name = "Show Image" self.__view_menu_subscription = content_window.add_file_open_handler( view_menu_name, lambda file_path: self._on_show_triggered(view_menu_name, file_path), self._is_show_visible, ) else: self.__view_menu_subscription = None def _get_content_window(self): try: import omni.kit.window.content_browser as content except ImportError: return None return content.get_content_window() def _is_show_visible(self, content_url): """True if we can show the menu item View Image""" # List of available formats: carb/source/plugins/carb.imaging/Imaging.cpp return any( content_url.endswith(f".{ext}") for ext in ["bmp", "dds", "exr", "gif", "hdr", "jpeg", "jpg", "png", "psd", "svg", "tga"] ) def _on_show_triggered(self, menu, value): """Start watching for the layer and run the editor""" ViewerWindows().open_window(value) def destroy(self): """Stop all watchers and remove the menu from the content browser""" if self.__view_menu_subscription: content_window = self._get_content_window() if content_window: content_window.delete_file_open_handler(self.__view_menu_subscription) self.__view_menu_subscription = None ViewerWindows().close_all()
2,572
Python
36.289855
101
0.640747
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_extension.py
# Copyright (c) 2018-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. # import omni.ext from .content_menu import content_available from .content_menu import ContentMenu class ImageViewerExtension(omni.ext.IExt): def __init__(self): super().__init__() self.__imageviewer = None self.__extensions_subscription = None # noqa: PLW0238 self.__content_menu = None def on_startup(self, ext_id): # Setup a callback when any extension is loaded/unloaded app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self.__extensions_subscription = ( # noqa: PLW0238 ext_manager.get_change_event_stream().create_subscription_to_pop( self._on_event, name="omni.kit.window.imageviewer" ) ) self.__content_menu = None self._on_event(None) def _on_event(self, event): """Called when any extension is loaded/unloaded""" if self.__content_menu: if not content_available(): self.__content_menu.destroy() self.__content_menu = None else: if content_available(): self.__content_menu = ContentMenu() def on_shutdown(self): if self.__imageviewer: self.__imageviewer.destroy() self.__imageviewer = None self.__extensions_subscription = None # noqa: PLW0238 if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None
1,922
Python
33.963636
77
0.632154
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/singleton.py
# Copyright (c) 2018-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. # def singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
697
Python
32.238094
76
0.725968
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/tests/imageviewer_test.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 pathlib import Path from omni.ui.tests.test_base import OmniUiTest import omni.kit import omni.ui as ui from ..imageviewer import ViewerWindows class TestImageViewer(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window() # noqa: PLW0612, F841 await omni.kit.app.get_app().next_update_async() viewer = ViewerWindows().open_window(f"{self._golden_img_dir.joinpath('lenna.png')}") viewer.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE viewer.position_x = 0 viewer.position_y = 0 viewer.width = 256 viewer.height = 256 # One frame to show the window and another to build the frame # And a dozen frames more to let the asset load for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir)
1,817
Python
36.10204
110
0.693451
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/__init__.py
from .audio_recorder_window import *
37
Python
17.999991
36
0.783784
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/audio_recorder_window.py
# 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. # import carb.audio import omni.audiorecorder import omni.kit.ui import omni.ui import threading import time import re import asyncio from typing import Callable from omni.kit.window.filepicker import FilePickerDialog class AudioRecorderWindowExtension(omni.ext.IExt): """Audio Recorder Window Extension""" class ComboModel(omni.ui.AbstractItemModel): class ComboItem(omni.ui.AbstractItem): def __init__(self, text): super().__init__() self.model = omni.ui.SimpleStringModel(text) def __init__(self): super().__init__() self._options = [ ["16 bit PCM", carb.audio.SampleFormat.PCM16], ["24 bit PCM", carb.audio.SampleFormat.PCM24], ["32 bit PCM", carb.audio.SampleFormat.PCM32], ["float PCM", carb.audio.SampleFormat.PCM_FLOAT], ["Vorbis", carb.audio.SampleFormat.VORBIS], ["FLAC", carb.audio.SampleFormat.FLAC], ["Opus", carb.audio.SampleFormat.OPUS], ] self._current_index = omni.ui.SimpleIntModel() self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._items = [AudioRecorderWindowExtension.ComboModel.ComboItem(text) for (text, value) in self._options] def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def set_value(self, value): for i in range(0, len(self._options)): if self._options[i][1] == value: self._current_index.as_int = i break def get_value(self): return self._options[self._current_index.as_int][1] class FieldModel(omni.ui.AbstractValueModel): def __init__(self): super(AudioRecorderWindowExtension.FieldModel, self).__init__() self._value = "" def get_value_as_string(self): return self._value def begin_edit(self): pass def set_value(self, value): self._value = value self._value_changed() def end_edit(self): pass def get_value(self): return self._value def _choose_file_clicked(self): # pragma: no cover dialog = FilePickerDialog( "Select File", apply_button_label="Select", click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname), ) dialog.show() def _on_file_pick(self, dialog: FilePickerDialog, filename: str, dirname: str): # pragma: no cover path = "" if dirname: path = f"{dirname}/{filename}" elif filename: path = filename dialog.hide() self._file_field.model.set_value(path) def _menu_callback(self, a, b): self._window.visible = not self._window.visible def _read_callback(self, data): # pragma: no cover self._display_buffer[self._display_buffer_index] = data self._display_buffer_index = (self._display_buffer_index + 1) % self._display_len buf = [] for i in range(self._display_len): buf += self._display_buffer[(self._display_buffer_index + i) % self._display_len] width = 512 height = 128 img = omni.audiorecorder.draw_waveform_from_blob_int16( input=buf, channels=1, width=width, height=height, fg_color=[0.89, 0.54, 0.14, 1.0], bg_color=[0.0, 0.0, 0.0, 0.0], ) self._waveform_image_provider.set_bytes_data(img, [width, height]) def _close_error_window(self): self._error_window.visible = False def _record_clicked(self): if self._recording: self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"}) self._recorder.stop_recording() self._recording = False else: result = self._recorder.begin_recording_int16( filename=self._file_field_model.get_value(), callback=self._read_callback, output_format=self._format_model.get_value(), buffer_length=200, period=25, length_type=carb.audio.UnitType.MILLISECONDS, ) if result: self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"}) self._recording = True else: # pragma: no cover self._error_window = omni.ui.Window( "Audio Recorder Error", width=400, height=0, flags=omni.ui.WINDOW_FLAGS_NO_DOCKING ) with self._error_window.frame: with omni.ui.VStack(): with omni.ui.HStack(): omni.ui.Spacer() self._error_window_label = omni.ui.Label( "Failed to start recording. The file path may be incorrect or the device may be inaccessible.", word_wrap=True, width=380, alignment=omni.ui.Alignment.CENTER, ) omni.ui.Spacer() with omni.ui.HStack(): omni.ui.Spacer() self._error_window_ok_button = omni.ui.Button( width=64, height=32, clicked_fn=self._close_error_window, text="ok" ) omni.ui.Spacer() def _stop_clicked(self): pass def _create_tooltip(self, text): """Create a tooltip in a fixed style""" with omni.ui.VStack(width=400): omni.ui.Label(text, word_wrap=True) def on_startup(self): self._display_len = 8 self._display_buffer = [[0] for i in range(self._display_len)] self._display_buffer_index = 0 # self._ticker_pos = 0; self._recording = False self._recorder = omni.audiorecorder.create_audio_recorder() self._window = omni.ui.Window("Audio Recorder", width=600, height=240) with self._window.frame: with omni.ui.VStack(height=0, spacing=8): # file dialogue with omni.ui.HStack(): omni.ui.Button( width=32, height=32, clicked_fn=self._choose_file_clicked, style={"image_url": "resources/glyphs/folder.svg"}, ) self._file_field_model = AudioRecorderWindowExtension.FieldModel() self._file_field = omni.ui.StringField(self._file_field_model, height=32) # waveform with omni.ui.HStack(height=128): omni.ui.Spacer() self._waveform_image_provider = omni.ui.ByteImageProvider() self._waveform_image = omni.ui.ImageWithProvider( self._waveform_image_provider, width=omni.ui.Percent(95), height=omni.ui.Percent(100), fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, ) omni.ui.Spacer() # buttons with omni.ui.HStack(): with omni.ui.ZStack(): omni.ui.Spacer() self._anim_label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER) with omni.ui.VStack(): omni.ui.Spacer() self._format_model = AudioRecorderWindowExtension.ComboModel() self._format = omni.ui.ComboBox( self._format_model, height=0, tooltip_fn=lambda: self._create_tooltip( "The format for the output file." + "The PCM formats will output as a WAVE file (.wav)." + "FLAC will output as a FLAC file (.flac)." + "Vorbis and Opus will output as an Ogg file (.ogg/.oga)." ), ) omni.ui.Spacer() self._record_button = omni.ui.Button( width=32, height=32, clicked_fn=self._record_clicked, style={"image_url": "resources/glyphs/audio_record.svg"}, ) omni.ui.Spacer() # add a callback to open the window self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Audio Recorder", self._menu_callback) self._window.visible = False def on_shutdown(self): # pragma: no cover self._recorder = None self._window = None self._menuEntry = None
9,750
Python
38.477733
127
0.521436
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/__init__.py
from .test_audiorecorder_window import * # pragma: no cover
61
Python
29.999985
60
0.754098
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/test_audiorecorder_window.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.ui as ui import omni.usd import omni.timeline import carb.tokens import carb.audio from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test #from omni.ui_query import OmniUIQuery import pathlib import asyncio import tempfile import os import platform class TestAudioRecorderWindow(OmniUiTest): # pragma: no cover async def _dock_window(self, win): await self.docked_test_window( window=win._window, width=600, height=240) #def _dump_ui_tree(self, root): # print("DUMP UI TREE START") # #windows = omni.ui.Workspace.get_windows() # #children = [windows[0].frame] # children = [root.frame] # print(str(dir(root.frame))) # def recurse(children, path=""): # for c in children: # name = path + "/" + type(c).__name__ # print(name) # if isinstance(c, omni.ui.ComboBox): # print(str(dir(c))) # recurse(omni.ui.Inspector.get_children(c), name) # recurse(children) # print("DUMP UI TREE END") # Before running each test async def setUp(self): await super().setUp() extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audiorecorder}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_img_dir = self._test_path.joinpath("golden") # open the dropdown window_menu = omni.kit.ui_test.get_menubar().find_menu("Window") self.assertIsNotNone(window_menu) await window_menu.click() # click the Audio Recorder entry to open it rec_menu = omni.kit.ui_test.get_menubar().find_menu("Audio Recorder") self.assertIsNotNone(rec_menu) await rec_menu.click() #self._dump_ui_tree(omni.kit.ui_test.find("Audio Recorder").window) # After running each test async def tearDown(self): await super().tearDown() self._rec = None async def _test_just_opened(self): win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png") async def _test_recording(self): # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) iface = carb.audio.acquire_data_interface() self.assertIsNotNone(iface) win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) file_name_textbox = win.find("**/StringField[*]") self.assertIsNotNone(file_name_textbox) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, "test.wav") # type our file path into the textbox await file_name_textbox.click() await file_name_textbox.input(str(path)) # the user hit the record button await record_button.click() await asyncio.sleep(1.0) # change the text in the textbox so we'll have something constant # for the image comparison await file_name_textbox.input("soundstorm_song.wav") await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png") # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) # grab these again just in case window docking broke it win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) # the user hit the stop button await record_button.click() await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png") # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) # grab these again just in case window docking broke it win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) file_name_textbox = win.find("**/StringField[*]") self.assertIsNotNone(file_name_textbox) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) format_combobox = win.find("**/ComboBox[*]") self.assertIsNotNone(format_combobox) # analyze the data sound = iface.create_sound_from_file(path, streaming=True) self.assertIsNotNone(sound) fmt = sound.get_format() self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM16) pcm = sound.get_buffer_as_int16() for i in range(len(pcm)): self.assertEqual(pcm[i], 0); sound = None # close it # try again with a different format # FIXME: We should not be manipulating the model directly, but ui_test # doesn't have a way to find any of the box item to click on, # and ComboBoxes don't respond to keyboard input either. format_combobox.model.set_value(carb.audio.SampleFormat.VORBIS) path2 = os.path.join(temp_dir, "test.oga") await file_name_textbox.input(str(path2)) # the user hit the record button await record_button.click() await asyncio.sleep(1.0) # the user hit the stop button await record_button.click() # analyze the data sound = iface.create_sound_from_file(str(path2), streaming=True) self.assertIsNotNone(sound) fmt = sound.get_format() self.assertEqual(fmt.format, carb.audio.SampleFormat.VORBIS) pcm = sound.get_buffer_as_int16() for i in range(len(pcm)): self.assertEqual(pcm[i], 0); sound = None # close it async def test_all(self): await self._test_just_opened() await self._test_recording()
7,060
Python
34.129353
111
0.616856
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/__init__.py
from .commands.usd_commands import *
37
Python
17.999991
36
0.783784
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/__init__.py
from .usd_commands import * from .parenting_commands import *
62
Python
19.999993
33
0.774194
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/parenting_commands.py
import omni.kit.commands import omni.usd from typing import List from pxr import Sdf class ParentPrimsCommand(omni.kit.commands.Command): def __init__( self, parent_path: str, child_paths: List[str], on_move_fn: callable = None, keep_world_transform: bool = True ): """ Move prims into children of "parent" primitives undoable **Command**. Args: parent_path: prim path to become parent of child_paths child_paths: prim paths to become children of parent_prim keep_world_transform: If it needs to keep the world transform after parenting. """ self._parent_path = parent_path self._child_paths = child_paths.copy() self._on_move_fn = on_move_fn self._keep_world_transform = keep_world_transform def do(self): with omni.kit.undo.group(): for path in self._child_paths: path_to = self._parent_path + "/" + Sdf.Path(path).name omni.kit.commands.execute( "MovePrim", path_from=path, path_to=path_to, on_move_fn=self._on_move_fn, destructive=False, keep_world_transform=self._keep_world_transform ) def undo(self): pass class UnparentPrimsCommand(omni.kit.commands.Command): def __init__( self, paths: List[str], on_move_fn: callable = None, keep_world_transform: bool = True ): """ Move prims into "/" primitives undoable **Command**. Args: paths: prim path to become parent of child_paths keep_world_transform: If it needs to keep the world transform after parenting. """ self._paths = paths.copy() self._on_move_fn = on_move_fn self._keep_world_transform = keep_world_transform def do(self): with omni.kit.undo.group(): for path in self._paths: path_to = "/" + Sdf.Path(path).name omni.kit.commands.execute( "MovePrim", path_from=path, path_to=path_to, on_move_fn=self._on_move_fn, destructive=False, keep_world_transform=self._keep_world_transform ) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
2,518
Python
29.349397
90
0.53892
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/usd_commands.py
import omni.kit.commands import omni.usd from typing import List from pxr import Sdf class TogglePayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command): def __init__(self, selected_paths: List[str]): """ Toggles the load/unload payload of the selected primitives undoable **Command**. Args: selected_paths: Old selected prim paths. """ self._stage = omni.usd.get_context().get_stage() self._selected_paths = selected_paths.copy() def _toggle_load(self): for selected_path in self._selected_paths: selected_prim = self._stage.GetPrimAtPath(selected_path) if selected_prim.IsLoaded(): selected_prim.Unload() else: selected_prim.Load() def do(self): self._toggle_load() def undo(self): self._toggle_load() class SetPayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command): def __init__(self, selected_paths: List[str], value: bool): """ Set the load/unload payload of the selected primitives undoable **Command**. Args: selected_paths: Old selected prim paths. value: True = load, False = unload """ self._stage = omni.usd.get_context().get_stage() self._selected_paths = selected_paths.copy() self._processed_path = set() self._value = value self._is_undo = False def _set_load(self): if self._is_undo: paths = self._processed_path else: paths = self._selected_paths for selected_path in paths: selected_prim = self._stage.GetPrimAtPath(selected_path) if (selected_prim.IsLoaded() and self._value) or (not selected_prim.IsLoaded() and not self._value): if selected_path in self._processed_path: self._processed_path.remove(selected_path) continue if self._value: selected_prim.Load() else: selected_prim.Unload() self._processed_path.add(selected_path) def do(self): self._set_load() def undo(self): self._is_undo = True self._value = not self._value self._set_load() self._value = not self._value self._processed_path = set() self._is_undo = False omni.kit.commands.register_all_commands_in_module(__name__)
2,457
Python
29.725
112
0.582825
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/__init__.py
from .test_command_usd import *
32
Python
15.499992
31
0.75
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/test_command_usd.py
import carb import omni.kit.test import omni.kit.undo import omni.kit.commands import omni.usd from pxr import Sdf, Usd def get_stage_default_prim_path(stage): if stage.HasDefaultPrim(): return stage.GetDefaultPrim().GetPath() else: return Sdf.Path.absoluteRootPath class TestCommandUsd(omni.kit.test.AsyncTestCase): async def test_toggle_payload_selected(self): carb.log_info("Test TogglePayLoadLoadSelectedPrimsCommand") await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() selection = usd_context.get_selection() stage = usd_context.get_stage() default_prim_path = get_stage_default_prim_path(stage) payload1 = Usd.Stage.CreateInMemory("payload1.usd") payload1.DefinePrim("/payload1/scope1", "Xform") payload1.DefinePrim("/payload1/scope1/xform", "Cube") payload2 = Usd.Stage.CreateInMemory("payload2.usd") payload2.DefinePrim("/payload2/scope2", "Xform") payload2.DefinePrim("/payload2/scope2/xform", "Cube") payload3 = Usd.Stage.CreateInMemory("payload3.usd") payload3.DefinePrim("/payload3/scope3", "Xform") payload3.DefinePrim("/payload3/scope3/xform", "Cube") payload4 = Usd.Stage.CreateInMemory("payload4.usd") payload4.DefinePrim("/payload4/scope4", "Xform") payload4.DefinePrim("/payload4/scope4/xform", "Cube") ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform") ps1.GetPayloads().AddPayload( Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1")) ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform") ps2.GetPayloads().AddPayload( Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2")) ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform") ps3.GetPayloads().AddPayload( Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3")) ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform") ps4.GetPayloads().AddPayload( Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4")) # unload everything stage.Unload() self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # if nothing selected, payload state should not change. selection.clear_selected_prim_paths() paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # load payload1 selection.set_selected_prim_paths( [ ps1.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(ps1.IsLoaded()) # unload payload1 omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps1.IsLoaded()) # load payload1, 2 and 3. 4 will load selection.set_selected_prim_paths( [ ps1.GetPath().pathString, ps2.GetPath().pathString, ps3.GetPath().pathString, ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(ps1.IsLoaded()) self.assertTrue(ps2.IsLoaded()) self.assertTrue(ps3.IsLoaded()) self.assertTrue(ps4.IsLoaded()) # unload 4 selection.set_selected_prim_paths( [ ps4.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps4.IsLoaded()) # undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # redo omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) async def test_set_payload_selected(self): carb.log_info("Test SetPayLoadLoadSelectedPrimsCommand") await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() selection = usd_context.get_selection() stage = usd_context.get_stage() default_prim_path = get_stage_default_prim_path(stage) payload1 = Usd.Stage.CreateInMemory("payload1.usd") payload1.DefinePrim("/payload1/scope1", "Xform") payload1.DefinePrim("/payload1/scope1/xform", "Cube") payload2 = Usd.Stage.CreateInMemory("payload2.usd") payload2.DefinePrim("/payload2/scope2", "Xform") payload2.DefinePrim("/payload2/scope2/xform", "Cube") payload3 = Usd.Stage.CreateInMemory("payload3.usd") payload3.DefinePrim("/payload3/scope3", "Xform") payload3.DefinePrim("/payload3/scope3/xform", "Cube") payload4 = Usd.Stage.CreateInMemory("payload4.usd") payload4.DefinePrim("/payload4/scope4", "Xform") payload4.DefinePrim("/payload4/scope4/xform", "Cube") ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform") ps1.GetPayloads().AddPayload( Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1")) ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform") ps2.GetPayloads().AddPayload( Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2")) ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform") ps3.GetPayloads().AddPayload( Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3")) ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform") ps4.GetPayloads().AddPayload( Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4")) # unload everything stage.Unload() self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # if nothing selected, payload state should not change. selection.clear_selected_prim_paths() paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # load payload1 selection.set_selected_prim_paths( [ ps1.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) # unload payload1 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps1.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps1.IsLoaded()) # load payload1, 2 and 3. 4 will load selection.set_selected_prim_paths( [ ps1.GetPath().pathString, ps2.GetPath().pathString, ps3.GetPath().pathString, ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) self.assertTrue(ps2.IsLoaded()) self.assertTrue(ps3.IsLoaded()) self.assertTrue(ps4.IsLoaded()) selection.set_selected_prim_paths( [ ps4.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() # reload 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps4.IsLoaded()) # unload 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) # undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # redo omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) omni.kit.undo.undo() self.assertTrue(not ps4.IsLoaded()) omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # -1 self.assertTrue(ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 0 self.assertTrue(ps4.IsLoaded()) omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) omni.kit.undo.redo() self.assertTrue(ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 1 self.assertTrue(not ps4.IsLoaded()) # 1 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) # 1 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 # triple undo omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 2 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 3 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 5 self.assertTrue(ps4.IsLoaded()) # 5 omni.kit.undo.undo() self.assertTrue(not ps4.IsLoaded()) # 4 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 3 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 2 # more undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # -1
11,219
Python
39.215054
104
0.635618
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/style.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["welcome_widget_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.welcome_widget_attribute_bg = cl("#1f2124") cl.welcome_widget_attribute_fg = cl("#0f1115") cl.welcome_widget_hovered = cl("#FFFFFF") cl.welcome_widget_text = cl("#CCCCCC") fl.welcome_widget_attr_hspacing = 10 fl.welcome_widget_attr_spacing = 1 fl.welcome_widget_group_spacing = 2 url.welcome_widget_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg" url.welcome_widget_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg" # The main style dict welcome_widget_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.welcome_widget_attr_spacing, "margin_width": fl.welcome_widget_attr_hspacing, }, "Label::title": {"alignment": ui.Alignment.CENTER, "color": cl.welcome_widget_text, "font_size": 30}, "Label::attribute_name:hovered": {"color": cl.welcome_widget_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Slider::attribute_int:hovered": {"color": cl.welcome_widget_hovered}, "Slider": { "background_color": cl.welcome_widget_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.welcome_widget_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.welcome_widget_hovered}, "Slider::attribute_vector:hovered": {"color": cl.welcome_widget_hovered}, "Slider::attribute_color:hovered": {"color": cl.welcome_widget_hovered}, "CollapsableFrame::group": {"margin_height": fl.welcome_widget_group_spacing}, "Image::collapsable_opened": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_opened}, "Image::collapsable_closed": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_closed}, }
2,636
Python
43.694915
112
0.715478
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/extension.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWindowExtension"] import asyncio import carb import omni.ext import omni.ui as ui from typing import Optional class WelcomeWindowExtension(omni.ext.IExt): """The entry point for Welcome Window""" WINDOW_NAME = "Welcome Window" # MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): self.__window: Optional["WelcomeWindow"] = None self.__widget: Optional["WelcomeWidget"] = None self.__render_loading: Optional["ViewportReady"] = None self.show_welcome(True) def on_shutdown(self): self._menu = None if self.__window: self.__window.destroy() self.__window = None if self.__widget: self.__widget.destroy() self.__widget = None def show_welcome(self, visible: bool): in_viewport = carb.settings.get_settings().get("/exts/omni.kit.window.welcome/embedInViewport") if in_viewport and not self.__window: self.__show_widget(visible) else: self.__show_window(visible) if not visible and self.__render_loading: self.__render_loading = None def __get_buttons(self) -> dict: return { "Create Empty Scene": self.__create_empty_scene, "Open Last Saved Scene": None, "Browse Scenes": None } def __destroy_object(self, object): # Hide it immediately object.visible = False # And destroy it in the future async def destroy_object(object): await omni.kit.app.get_app().next_update_async() object.destroy() asyncio.ensure_future(destroy_object(object)) def __show_window(self, visible: bool): if visible and self.__window is None: from .window import WelcomeWindow self.__window = WelcomeWindow(WelcomeWindowExtension.WINDOW_NAME, width=500, height=300, buttons=self.__get_buttons()) elif self.__window and not visible: self.__destroy_object(self.__window) self.__window = None elif self.__window: self.__window.visible = True def __show_widget(self, visible: bool): if visible and self.__widget is None: async def add_to_viewport(): try: from omni.kit.viewport.utility import get_active_viewport_window from .widget import WelcomeWidget viewport_window = get_active_viewport_window() with viewport_window.get_frame("omni.kit.window.welcome"): self.__widget = WelcomeWidget(self.__get_buttons(), add_background=True) except (ImportError, AttributeError): # Fallback to Welcome window self.__show_window(visible) asyncio.ensure_future(add_to_viewport()) elif self.__widget and not visible: self.__destroy_object(self.__widget) self.__widget = None elif self.__widget: self.__widget.visible = True def __button_clicked(self): self.show_welcome(False) def __create_empty_scene(self, renderer: Optional[str] = None): self.__button_clicked() settings = carb.settings.get_settings() ext_manager = omni.kit.app.get_app().get_extension_manager() if renderer is None: renderer = settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer") if not renderer: return ext_manager.set_extension_enabled_immediate("omni.kit.viewport.bundle", True) if renderer == "iray": ext_manager.set_extension_enabled_immediate(f"omni.hydra.rtx", True) ext_manager.set_extension_enabled_immediate(f"omni.hydra.{renderer}", True) else: ext_manager.set_extension_enabled_immediate(f"omni.kit.viewport.{renderer}", True) async def _new_stage_async(): if settings.get("/exts/omni.kit.window.welcome/showRenderLoading"): from .render_loading import start_render_loading_ui self.__render_loading = start_render_loading_ui(ext_manager, renderer) await omni.kit.app.get_app().next_update_async() import omni.kit.stage_templates as stage_templates stage_templates.new_stage(template=None) await omni.kit.app.get_app().next_update_async() from omni.kit.viewport.utility import get_active_viewport get_active_viewport().set_hd_engine(renderer) asyncio.ensure_future(_new_stage_async())
5,066
Python
37.097744
130
0.617055
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/render_loading.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["start_render_loading_ui"] def start_render_loading_ui(ext_manager, renderer: str): import carb import time time_begin = time.time() carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False) ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True) from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate class TimerDelegate(ViewportReadyDelegate): def __init__(self, time_begin): super().__init__() self.__timer_start = time.time() self.__vp_ready_cost = self.__timer_start - time_begin @property def font_size(self) -> float: return 48 @property def message(self) -> str: rtx_mode = { "RaytracedLighting": "Real-Time", "PathTracing": "Interactive (Path Tracing)", "LightspeedAperture": "Aperture (Game Path Tracer)" }.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time") renderer_label = { "rtx": f"RTX - {rtx_mode}", "iray": "RTX - Accurate (Iray)", "pxr": "Pixar Storm", "index": "RTX - Scientific (IndeX)" }.get(renderer, renderer) return f"Waiting for {renderer_label} to start" def on_complete(self): rtx_load_time = time.time() - self.__timer_start super().on_complete() print(f"Time until pixel: {rtx_load_time}") print(f"ViewportReady cost: {self.__vp_ready_cost}") return ViewportReady(TimerDelegate(time_begin))
2,121
Python
37.581817
92
0.619991
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWidget"] import carb import omni.kit.app import omni.ui as ui from typing import Callable, Optional class WelcomeWidget(): """The class that represents the window""" def __init__(self, buttons: dict, style: Optional[dict] = None, button_size: Optional[tuple] = None, add_background: bool = False): if style is None: from .style import welcome_widget_style style = welcome_widget_style if button_size is None: button_size = (150, 100) self.__add_background = add_background # Save the button_size for later use self.__buttons = buttons self.__button_size = button_size # Create the top-level ui.Frame self.__frame: ui.Frame = ui.Frame() # Apply the style to all the widgets of this window self.__frame.style = style # Set the function that is called to build widgets when the window is visible self.__frame.set_build_fn(self.create_ui) def destroy(self): # It will destroy all the children if self.__frame: self.__frame.destroy() self.__frame = None def create_label(self): ui.Label("Select Stage", name="title") def create_button(self, label: str, width: float, height: float, clicked_fn: Callable): ui.Button(label, width=width, height=height, clicked_fn=clicked_fn) def create_buttons(self, width: float, height: float): for label, clicked_fn in self.__buttons.items(): self.create_button(label, width=width, height=height, clicked_fn=clicked_fn) def create_background(self): bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color') if bg_color: omni.ui.Rectangle(style={"background_color": bg_color}) def create_ui(self): with ui.ZStack(): if self.__add_background: self.create_background() with ui.HStack(): ui.Spacer(width=20) with ui.VStack(): ui.Spacer() self.create_label() ui.Spacer(height=20) with ui.HStack(height=100): ui.Spacer() self.create_buttons(self.__button_size[0], self.__button_size[1]) ui.Spacer() ui.Spacer() ui.Spacer(width=20) @property def visible(self): return self.__frame.visible if self.__frame else None @visible.setter def visible(self, visible: bool): if self.__frame: self.__frame.visible = visible elif visible: import carb carb.log_error("Cannot make WelcomeWidget visible after it was destroyed")
3,244
Python
36.29885
135
0.608508
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/window.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWindow"] from .widget import WelcomeWidget from typing import Optional import omni.ui as ui class WelcomeWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, buttons: dict, *args, **kwargs): super().__init__(title, *args, **kwargs) self.__buttons = buttons self.__widget: Optional[WelcomeWidget] = None # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self.__build_fn) def __destroy_widget(self): if self.__widget: self.__widget.destroy() self.__widget = None def __build_fn(self): # Destroy any existing WelcomeWidget self.__destroy_widget() # Add the Welcomwidget self.__widget = WelcomeWidget(self.__buttons) def destroy(self): # It will destroy all the children self.__destroy_widget() super().destroy() @property def wlcome_widget(self): return self.__widget
1,477
Python
31.130434
85
0.668246
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestWidget"] from omni.kit.window.welcome.widget import WelcomeWidget import omni.kit.app import omni.kit.test import omni.ui as ui class TestWidget(omni.kit.test.AsyncTestCase): async def test_general(self): """Create a widget and make sure there are no errors""" window = ui.Window("Test") with window.frame: WelcomeWidget(buttons={}) await omni.kit.app.get_app().next_update_async()
879
Python
32.846153
76
0.737201
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_window.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestWindow"] from omni.kit.window.welcome.window import WelcomeWindow import omni.kit.app import omni.kit.test class TestWindow(omni.kit.test.AsyncTestCase): async def test_general(self): """Create a window and make sure there are no errors""" window = WelcomeWindow("Welcome Window Test", buttons={}) await omni.kit.app.get_app().next_update_async()
823
Python
36.454544
76
0.755772
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/delegate.py
# Copyright (c) 2018-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. # import abc class SearchDelegate: def __init__(self): self._search_dir = None @property def visible(self): return True # pragma: no cover @property def enabled(self): """Enable/disable Widget""" return True # pragma: no cover @property def search_dir(self): return self._search_dir # pragma: no cover @search_dir.setter def search_dir(self, search_dir: str): self._search_dir = search_dir # pragma: no cover @abc.abstractmethod def build_ui(self): pass # pragma: no cover @abc.abstractmethod def destroy(self): pass # pragma: no cover
1,098
Python
26.474999
76
0.678506
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/style.py
# Copyright (c) 2018-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. # import carb import omni.ui as ui from pathlib import Path try: THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: THEME = None finally: THEME = THEME or "NvidiaDark" CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}") THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails") def get_style(): if THEME == "NvidiaLight": BACKGROUND_COLOR = 0xFF535354 BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E BACKGROUND_DISABLED_COLOR = 0xFF666666 TEXT_COLOR = 0xFF8D760D TEXT_HINT_COLOR = 0xFFD6D6D6 SEARCH_BORDER_COLOR = 0xFFC9974C SEARCH_HOVER_COLOR = 0xFFB8B8B8 SEARCH_CLOSE_COLOR = 0xFF858585 SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC else: BACKGROUND_COLOR = 0xFF23211F BACKGROUND_SELECTED_COLOR = 0xFF8A8777 BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A BACKGROUND_DISABLED_COLOR = 0xFF666666 TEXT_COLOR = 0xFF9E9E9E TEXT_HINT_COLOR = 0xFF4A4A4A SEARCH_BORDER_COLOR = 0xFFC9974C SEARCH_HOVER_COLOR = 0xFF3A3A3A SEARCH_CLOSE_COLOR = 0xFF858585 SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC style = { "Button": { "background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0 }, "Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR}, "Button.Label": {"color": TEXT_COLOR}, "Field": {"background_color": 0x0, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER}, "Label": {"background_color": 0x0, "color": TEXT_COLOR}, "Rectangle": {"background_color": 0x0}, "SearchField": { "background_color": 0, "border_radius": 0, "border_width": 0, "background_selected_color": BACKGROUND_COLOR, "margin": 0, "padding": 4, "alignment": ui.Alignment.LEFT_CENTER, }, "SearchField.Frame": { "background_color": BACKGROUND_COLOR, "border_radius": 0.0, "border_color": 0, "border_width": 2, }, "SearchField.Frame:selected": { "background_color": BACKGROUND_COLOR, "border_radius": 0, "border_color": SEARCH_BORDER_COLOR, "border_width": 2, }, "SearchField.Frame:disabled": { "background_color": BACKGROUND_DISABLED_COLOR, }, "SearchField.Hint": {"color": TEXT_HINT_COLOR}, "SearchField.Button": {"background_color": 0x0, "margin_width": 2, "padding": 4}, "SearchField.Button.Image": {"color": TEXT_HINT_COLOR}, "SearchField.Clear": {"background_color": 0x0, "padding": 4}, "SearchField.Clear:hovered": {"background_color": SEARCH_HOVER_COLOR}, "SearchField.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": SEARCH_CLOSE_COLOR}, "SearchField.Word": {"background_color": SEARCH_TEXT_BACKGROUND_COLOR}, "SearchField.Word.Label": {"color": TEXT_COLOR}, "SearchField.Word.Button": {"background_color": 0, "padding": 2}, "SearchField.Word.Button.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": TEXT_COLOR}, } return style
4,013
Python
39.959183
148
0.62771