file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
RoboEagles4828/offseason2023/rio/POC/limitswitch_test/robot.py | import wpilib
class MyRobot(wpilib.TimedRobot):
def robotInit(self):
print("Initalizing")
self.limitSwitch = wpilib.DigitalInput(0)
self.pastState = 0
self.timer = wpilib.Timer
self.input = wpilib.Joystick(0)
def teleopInit(self):
print("Entering teleop")
def teleopPeriodic(self):
if (self.limitSwitch.get() != self.pastState):
print(f"State Changed from {self.pastState} to {self.limitSwitch.get()}")
self.pastState = self.limitSwitch.get()
def teleopExit(self):
print("Exitted teleop")
if __name__ == "__main__":
wpilib.run(MyRobot) | 650 | Python | 26.124999 | 85 | 0.616923 |
RoboEagles4828/edna2023/docker-compose.yml | version: "3.6"
services:
main_control:
# image: "ghcr.io/roboeagles4828/developer-environment:6"
image: "ghcr.io/roboeagles4828/jetson:3"
network_mode: "host"
environment:
- ROS_DOMAIN_ID=0
- FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml
deploy:
restart_policy:
condition: unless-stopped
delay: 2s
max_attempts: 3
window: 120s
entrypoint: ["/bin/bash", "-c", "/opt/workspace/docker/jetson/entrypoint.sh"]
working_dir: /opt/workspace
user: admin
volumes:
- ${HOME}/edna2023:/opt/workspace
zed_cam:
image: ghcr.io/roboeagles4828/jetson-zed:1
network_mode: "host"
privileged: true
runtime: nvidia
environment:
- ROS_DOMAIN_ID=0
- RMW_IMPLEMENTATION=rmw_fastrtps_cpp
- FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml
- ROS_NAMESPACE=real
volumes:
- /usr/bin/tegrastats:/usr/bin/tegrastats
- /tmp/argus_socket:/tmp/argus_socket
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4
- /usr/local/cuda-11.4/targets/aarch64-linux/include:/usr/local/cuda-11.4/targets/aarch64-linux/include
- /usr/lib/aarch64-linux-gnu/tegra:/usr/lib/aarch64-linux-gnu/tegra
- /usr/src/jetson_multimedia_api:/usr/src/jetson_multimedia_api
- /opt/nvidia/nsight-systems-cli:/opt/nvidia/nsight-systems-cli
- /opt/nvidia/vpi2:/opt/nvidia/vpi2
- /usr/share/vpi2:/usr/share/vpi2
- /run/jtop.sock:/run/jtop.sock:ro
- /dev/*:/dev/*
- ${HOME}/edna2023/scripts/config/SN39192289.conf:/usr/local/zed/settings/SN39192289.conf
- ${HOME}/edna2023/src/edna_bringup/launch/zed2i.launch.py:/root/ros2_ws/src/zed-ros2-wrapper/zed_wrapper/launch/zed2i.launch.py
depends_on:
- main_control
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
command: ["ros2", "launch", "zed_wrapper", "zed2i.launch.py"]
| 2,714 | YAML | 45.016948 | 137 | 0.673545 |
RoboEagles4828/edna2023/ZED.md | # Setting up the ZED Camera with ROS2 Galactic
## Chapter One: Downloading and Installing the Packages
This assumes that you already have a working install of [ROS2 Galactic](https://docs.ros.org/en/galactic/index.html) and the [ZED SDK](https://www.stereolabs.com/developers/release/). You're going to need to go to the [ZED ROS2 Wrapper](https://github.com/stereolabs/zed-ros2-wrapper) and follow the installation insructions to add it here. However, before running `rosdep install`, you'll need to go into the src/ folder and move all of the packages inside of the zed-ros2-wrapper folder into the root src folder.
**WARNING: INCREDIBLY HACKY FIX AHEAD**
*If you're having problems with anything, this is probably the cause of it*
If you try to `colcon build` at this point, you're going to run into some strange error having to do with install/zed_components/lib/libzed_camera_component.so regarding tf2::doTransform. Now, if you're willing to look into why this is erroring, please feel free to fix the code, but if you want a fast and simple solution, then just do this.
Go into src/zed_components/src/zed_camera/src/zed_camera_component.cpp, and scroll down to line 6333. Comment that line out, save the file, and continue on with the rest of this.
Once you've done that, you're also going to need the [ZED ROS2 Examples](https://github.com/stereolabs/zed-ros2-examples) for the 3D bounding boxes to display in RViz2. Go ahead and download their repository, making sure to take the packages out of the folder and put it in src/ directly.
With all of that done, you can finally run `colcon build`.
## Chapter Two: Running RViz2
Now that everything is set up and you ran into no errors whatsoever, you can run it!
Running `ros2 launch zed_wrapper zed2i.launch.py` (make sure to source ros2 and the local install at install/local_setup.bash first) will start a ROS topic publishing out the camera information!
You can also run `ros2 launch zed_display_rviz2 display_zed2i.launch.py` to open RViz2 with the default ZED configuration (useful for the next step).
## Chapter Three: Ordinary Object Detection
If you just want to enable object detection temporarily, then you can run `ros2 service call /zed2i/zed_node/enable_obj_det std_stvs/srv/SetBool data:\ true`. This command will enable object detection for the currently running ROS node.
However, if you want object detection to be on by default, then go into src/zed_wrapper/config/common.yaml, and change line 107 to be true.
(You can also mess with the other object detection settings here).
Now if you open RViz2 with the default ZED settings, you can see the bounding boxes going around the real world things! (You can also add the point cloud from the topic to see it even better).
## Chapter Four: Custom Object Detection
Unfortunately, custom object detection is *not* currently included in the ROS2 wrapper for the ZED SDK. This could be done by modifying the `zed_wrapper` package manually to add in a supported detection algorithm like Yolo or OpenCV. For us, we ran out of time to get this working during the season, but the above steps can give you a starting point. For more information, head over to [the ZED SDK](https://github.com/stereolabs/zed-sdk/tree/master/object%20detection/custom%20detector/cpp/tensorrt_yolov5_v6.0) and look at their code. | 3,338 | Markdown | 91.749997 | 536 | 0.781905 |
RoboEagles4828/edna2023/README.md | 
# Requirements
- Ubuntu 22.04
- [Visual Studio Code](https://code.visualstudio.com/)
- RTX Enabled NVIDIA GPU
- (Optional) An Xbox controller
# Installation
### 1. Install Graphics Drivers
Simply run `sudo apt-get install nvidia-driver-525` in order to install the NVIDIA graphics driver for Ubuntu!
### 2. Local Setup
- **Install Docker and Nvidia Docker**
Running `./scripts/local-setup.sh` should install the requirements for this repository to run! At some point during running, it may prompt you for a `ROS_NAMESPACE`, which you can read more about [here](https://docs.ros.org/en/foxy/Tutorials/Intermediate/Launch/Using-ROS2-Launch-For-Large-Projects.html#namespaces). Make sure to restart your machine once the script is done running!
- **Install Remote Development VS Code Extension**
This repository requires the [Remote Development](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack) extension pack. Make sure to install it in the VSCode extensions window!
- **Reopen in Devcontainer**
Once installed, you can open the command pallate by pressing <kbd>F1</kbd>, and running the command `Reopen in Container` in order to open the devcontainer. This might take a while, but once it's finished you should see a message appear in a console stating some helpful commands, along with a list of connected controllers and your `ROS_NAMESPACE` which you set up earlier.
### 3. (Optional) ROS Setup
For the robot to run correctly, both in the simulation and in the real world, we use ROS2 in order to communicate between all of the parts of our project!
- **Building the project**
The entire project is built as a colcon task, so you can run it by pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> in VSCode, or by running `colcon build --symlink-install` in order to build all of the ROS2 packages.
To confirm that this worked, you can simply open a new terminal, and the warning message reminding you to build should be gone!
# Running the Robot
<details><summary><b style="font-size:1.5em">In the simulation</b></summary>
### 1. (Optional) Installing Omniverse Server
Omniverse is a NVIDIA product which allows for programs to cache their information quickly and reliably. It's not needed, but can save a lot on load times!
- **Download Omniverse Launcher**
https://www.nvidia.com/en-us/omniverse/download/
- **Run Omniverse**
`chmod +x omniverse-launcher-linux.AppImage`
`./omniverse-launcher-linux.AppImage`
- **Install Cache and Nucleus Server**
Click on the "Exchange" tab, and search for "Cache", which should return only one result. Nucleus Server should already be installing by default. Wait until both are downloaded and installed before continuing.
### 2. Isaac Container Setup
- **Create Shaders**
Isaac uses RTX heavily in order to accurately render graphics, which takes some powerful shaders. In order to get Isaac to build the shaders, run `isaac-setup` inside the devcontainer in order to start compilation of shaders.
- **Launch Isaac**
In order to actually start the simulation, just run the command `isaac` inside the devcontainer in order to start Isaac. It might take a while on first launch, but you should see the simulation window pop up eventually.
- **Load the robot**
As you should be able to see, there's currently nothing *in* Isaac. It should be showing an empty scene with a popup window to the top left labeled "Import URDF" with a button that says "Load". If you press it, you should see the 2023 playing field appear, along with a brightly colored robot in the center!
### 3. Start the simulation
- **Start Isaac**
Inside of Isaac, you should see a bar with a play button to the left. Click on it, or press <kbd>Space</kbd> in order to start the simulation. If everything works correctly, you should see the robot fall to the ground and be ready for movement!
- **Start the ROS2 Control Node**
In order to get the robot to move around, you're going to need to plug in a controller and start the control node, something that you can do easily by running `launch isaac` inside the devcontainer.
If all goes well, you'll be able to move the robot around with the joystick! See [Controls]() for more details on how to drive the robot.
</details>
<details><summary><b style="font-size:1em">Simulating the RoboRIO</b></summary>
The National Instruments [RoboRIO](https://www.ni.com/en-us/shop/model/roborio.html) is a required computer for the FRC competitions, and as such, all of our code to physically move robot parts has to be run through it.
In order to run this simulator, you'll have to navigate to the `rio/` before running the following commands.
- **Installing RobotPy**
First, run `pip install -r requirements.txt` in order to install robotpy and the other dependencies that the simulator needs.
- **Running the sim**
Once you have the dependencies installed, all you'll have to do is run `python3 robot.py sim` to open the RoboRIO simulator.
To read more on the simulator, check out their docs [here](https://robotpy.readthedocs.io/en/stable/guide/simulator.html)!
</details>
<details><summary><b style="font-size:1.5em">In real life</b></summary>
### 1. Setting up the robot
If you want to actually set up the robot, check out [Setting up the Robot]() in order to get the onboard coprocessor running.
However, for debugging purposes, sometimes its easier to bypass this.
- **Running the Robot**
To run the robot code, make sure you're connected to your robots' network, and run the command `launch real` inside the devcontianer in order to start the robot code.
In order to debug and visualize the robot remotely, we use [rviz](https://github.com/ros2/rviz) in order to view joint poses and other ROS information published from the robot.
- **Starting rviz**
Luckily, we have another quick launch in order to start a preconfigured rviz, so you can simply open a new terminal (separate from the one running `launch real`), and run `launch rviz`. This should open up a new rviz window with the robot inside. You may need to change some of the namespaces in the window, as when running the real robot, the namespace will switch to be `real` instead of whatever you entered in the setup script.
### 2. Driving the Robot
When it comes to driving the robot, you'll need a Driver Station, which we have two separate options to use.
- **NI Driver Station**
In order to run your robot during the competition, you'll need the official National Instruments Driver Station, with all alternatives being disallowed during competitions. For this, you're going to have to have a separate computer running Windows in order to install the [FRC Game Tools](https://www.ni.com/en-us/support/downloads/drivers/download.frc-game-tools.html), which installs the Driver Station as a part of it.
- **Conductor**
Despite the National Instruments driver station being the only officially supported Driver, there are some community made alternatives that you can use! We recommend using [Conductor](https://github.com/Redrield/Conductor), as it's one of the most feature complete community alternatives out there, and runs fully on linux, meaning that you don't need a separate computer, and you can run everything on just one computer!
Once you have a driver station setup, you should be able to enable teleop mode with an Xbox controller connected, and the robot should move when you move the joystick! See [Controls]() for more details on how to drive the robot.
</details>
<details><summary><b style="font-size:1.5em">Debugging the robot</b></summary>
In order to debug the robot, we built our own debugger in Python and PyQT!
### 1. Launching the debugger
Simply run `launch rio-debug` in order to open the debugger!
### 2. Using the debugger
- **Reading in published joint states**
The joint states that are published from the robot to your computer are represented by the slider bars and buttons. Buttons are a togglable state where the output should be one of two values, whereas the sliders are joints where the output should be one of a range of values, usually used for wheels or other motors.
You can tell the current joint state from the robot by looking at the top slider bar, as it will reflect the actual position of the joint on the robot. For the buttons, the color of the button represents the stater of the joint, with green meaning that the state from the robot is the same as the current state from your computer, and yellow meaning that they are not the same.
You can also tell the states of the joints based on the boxes to the left of them, which should contain the exact numbers recieved from ROS.
- **Publishing out your own joint commands**
To publish out your own joint commands, simply use the bottom slider, or click on the buttons in order to edit the joint state being broadcast out to the robot!
</details>
# Gallery



# Setting up your own robot
> An incredibly difficult task which we've only done once or twice. This documentation is currently untested! Here be dragons!
## Requirements
- A National Instruments RoboRIO
- An NVIDIA Jetson Xavier
- A lot of patience
## Setting up the RoboRIO
Because of how our repository is built on the [RobotPy](https://robotpy.readthedocs.io/) framework, you're going to need to install RobotPy.
> Important Note: You'll have to follow these steps on your **host machine**, as there's currently a bug where RobotPy's deployment script does not work inside of the devcontainer.
### 1. Installing RobotPy
Installing robotpy is as simple as navigating to the `rio/` directory and running `pip install -r requirements.txt` in order to install the dependencies of robotpy.
### 2. Installing RobotPy onto the RoboRIO
Unfortunately, this step is somewhat outside of the scope of this tutorial. We recommend you follow RobotPy's [official setup guide](https://robotpy.readthedocs.io/en/stable/install/robot.html) for installing `robotpy-installer` and getting python onto the RIO.
However, there is one thing not covered by the tutorial. You will have to run `robotpy-installer download [package]` and `robotpy-installer install [package]` for the `wpilib` and `rosbags` packages respectively.
### 3. Deploying to the RoboRIO
To deploy to the RoboRIO, you'll need to connect your computer to the RIO, either over USB or over the network. Once you're connected you can run `python3 robot.py deploy` in order to flash the script onto the RoboRIO. | 10,637 | Markdown | 70.878378 | 431 | 0.768638 |
RoboEagles4828/edna2023/src/edna_tests/setup.py | from setuptools import setup
package_name = 'edna_tests'
setup(
name=package_name,
version='0.0.1',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='roboeagles',
maintainer_email='[email protected]',
description='Test robot functions',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'joint-arm = edna_tests.publish_joint_arm_command:main',
'joint-drive = edna_tests.publish_joint_drive_command:main',
'publish-twist = edna_tests.publish_twist_command:main',
'run-tests = edna_tests.run_tests_command:main',
'arm-tests = edna_tests.arm_tests:main'
],
},
) | 926 | Python | 29.899999 | 72 | 0.602592 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/publish_joint_drive_command.py | import rclpy
from rclpy.node import Node
import math
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_drive_joint_commands')
self.publisher_ = self.create_publisher(JointState, '/real/real_joint_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
cmds = JointState()
cmds.name = [
'front_left_wheel_joint',
'front_right_wheel_joint',
'rear_left_wheel_joint',
'rear_right_wheel_joint',
'front_left_axle_joint',
'front_right_axle_joint',
'rear_left_axle_joint',
'rear_right_axle_joint'
]
rad = math.pi
cmds.velocity = [
0.0,
0.0,
0.0,
0.0,
0.0, #ignore
0.0, #ignore
0.0, #ignore
0.0, #ignore
]
cmds.position = [
0.0, #ignore
0.0, #ignore
0.0, #ignore
0.0, #ignore
rad,
0.0,
0.0,
0.0
]
# position_cmds.position = []
self.publisher_.publish(cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,746 | Python | 23.263889 | 92 | 0.507446 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/publish_twist_command.py | import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, Vector3
class PublishTwistCmd(Node):
def __init__(self):
super().__init__('publish_twist_commands')
self.publisher_ = self.create_publisher(Twist, 'swerve_controller/cmd_vel_unstamped', 10)
timer_period = 0.1 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
twist = Twist()
twist.linear.x = 2.0
twist.linear.y = 0.0
twist.angular.z = 0.0
self.publisher_.publish(twist)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishTwistCmd()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 868 | Python | 22.486486 | 97 | 0.599078 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/arm_tests.py | import rclpy
import time
from .joint_test import TesterNode
# ROS Topics
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_TOPIC_NAME = '/real/real_arm_commands'
PUBLISH_INTERVAL = .5 # seconds
# Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
TESTS = [
# Here's where you define your tests, in the same style as this one.
# {"positions": [0.0]*6, "time": 3.0},
# Toggle pistons one at a time (to true)
{"positions": [0.0]*4 + [0.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [0.5] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [1.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*6, "time": 10.0},
]
JOINT_NAMES = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
def main():
rclpy.init()
testerNode = TesterNode(
tests=TESTS,
joint_names=JOINT_NAMES,
joint_range=[8, 14],
pub_topic_name=PUBLISH_TOPIC_NAME,
sub_topic_name=SUBSCRIBE_TOPIC_NAME,
pub_interval=PUBLISH_INTERVAL,
pass_tolerance=PASS_TOLERANCE,
warn_tolerance=WARN_TOLERANCE)
rclpy.spin(testerNode)
if __name__ == '__main__':
main() | 1,267 | Python | 22.481481 | 72 | 0.589582 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/run_tests_command.py | import rclpy
from rclpy.node import Node
import math
import time
from rclpy.action import ActionClient
from action_tutorials_interfaces.action import Fibonacci
from sensor_msgs.msg import JointState
import logging
vel_cmds = JointState()
rad = math.pi
vel_cmds.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.name = [
'front_left_wheel_joint',
'front_left_axle_joint',
'front_right_wheel_joint',
'front_right_axle_joint',
'rear_left_wheel_joint',
'rear_left_axle_joint',
'rear_right_wheel_joint',
'rear_right_axle_joint']
test_return = JointState()
class RunTests(Node):
def __init__(self):
super().__init__('run_tests')
self.publisher_ = self.create_publisher(
JointState,
'real_joint_commands',
10
)
timer_period = 0.1
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
self.subscription = self.create_subscription(
JointState,
'real_joint_states',
self.listener_callback,
10
)
self.subscription
self.get_logger().info('Testing: ...')
def timer_callback(self):
self.publisher_.publish(vel_cmds)
time.sleep(0.1)
self.i+=1
def listener_callback(self, msg):
test_return = msg
def check(msg, test, test_fail):
count = 0
working = True
for x in msg.velocity:
if (abs(msg.velocity[count] / 1000 - vel_cmds.velocity[count]) > 0.001 or abs(msg.position[count] / 1000 - vel_cmds.position[count]) > 0.001):
working = False
count+=1
if not working:
print(test_fail)
else:
print(test)
def test1(node):
vel_cmds.velocity=[rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Wheel is Spinning!', 'ERROR: Front Left Wheel is NOT spinning, something is wrong!')
def test2(node):
vel_cmds.position=[0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Axle is Spinning!', 'ERROR: Front Left Axle is NOT spinning, something is wrong!')
def test3(node):
vel_cmds.velocity=[0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Wheel is Spinning!', 'ERROR: Front Right Wheel is NOT spinning, something is wrong!')
def test4(node):
vel_cmds.position=[0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Axle is Spinning!', 'ERROR: Front Right Axle is NOT spinning, something is wrong!')
def test5(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Wheel is Spinning!', 'ERROR: Rear Left Wheel is NOT spinning, something is wrong!')
def test6(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Axle is Spinning!', 'ERROR: Rear Left Axle is NOT spinning, something is wrong!')
def test7(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Wheel is Spinning!', 'ERROR: Rear Right Wheel is NOT spinning, something is wrong!')
def test8(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Axle is Spinning!', 'ERROR: Rear Right Axle is NOT spinning, something is wrong!')
def main(args=None):
rclpy.init(args=args)
node = RunTests()
rclpy.spin_once(node)
test1(node)
test2(node)
test3(node)
test4(node)
test5(node)
test6(node)
test7(node)
test8(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main() | 4,771 | Python | 32.138889 | 154 | 0.590442 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/joint_test.py | import time
from rclpy.node import Node
from sensor_msgs.msg import JointState
# COLORS
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
RESET = "\033[0m"
# Default ROS values
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_INTERVAL = .5 # seconds
# Default Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
SCALING_FACTOR_FIX = 10000
class TesterNode(Node):
def __init__(self, tests, joint_names, joint_range, pub_topic_name, sub_topic_name=SUBSCRIBE_TOPIC_NAME, pub_interval=PUBLISH_INTERVAL, pass_tolerance=PASS_TOLERANCE, warn_tolerance=WARN_TOLERANCE):
super().__init__('arm_tester')
# Constructor Arguments
self.TESTS = tests
self.JOINT_NAMES = joint_names
self.JOINT_RANGE = joint_range
self.SUBSCRIBE_TOPIC_NAME = sub_topic_name
self.PUBLISH_TOPIC_NAME = pub_topic_name
self.PUBLISH_INTERVAL = pub_interval
self.PASS_TOLERANCE = pass_tolerance
self.WARN_TOLERANCE = warn_tolerance
self.currentTest = 0
self.testStatus = []
self.lastPositions = [None]*6
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.recieving = True
self.startTime = time.time()
self.subscription = self.create_subscription(JointState, self.SUBSCRIBE_TOPIC_NAME, self.recieve, 10)
self.publisher = self.create_publisher(JointState, self.PUBLISH_TOPIC_NAME, 10)
self.publishTimer = self.create_timer(self.PUBLISH_INTERVAL, self.publish)
def publish(self):
msg = JointState()
msg.name = self.JOINT_NAMES
msg.position = self.TESTS[self.currentTest]["positions"]
self.publisher.publish(msg)
self.doTests()
def doTests(self):
if not(self.recieving):
# Start running the next test
self.currentTest += 1
if self.currentTest > len(self.TESTS)-1:
print("\nTests Finished")
for index, test in enumerate(self.testStatus):
print(f"{RED if test['fail'] > 0 else YELLOW if test['warn'] > 0 else GREEN}Test {index} {'FAILED' if test['fail'] > 0 else 'PASSED'} {'with WARNINGS' if test['warn'] > 0 else ''}{RESET}")
exit(0) # shutting down rclpy just kills the node and hangs the process, without actually stopping the program
else:
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.lastPositions = [None]*6
self.recieving = True
self.startTime = time.time()
else:
# Check if the current test should end...
timeleft = time.time() - self.startTime
print(f"\rRunning Test {self.currentTest} ({round(self.TESTS[self.currentTest]['time'] - timeleft, 2)}s remaining)", end='')
if time.time() - self.startTime > self.TESTS[self.currentTest]["time"]:
self.recieving = False
self.testStatus.append({"pass": 0, "warn": 0, "fail": 0})
print(f"\rTest {self.currentTest} Completed ")
self.printResults()
print()
def recieve(self, msg : JointState):
if self.recieving:
self.lastPositions = [i / SCALING_FACTOR_FIX for i in msg.position[self.JOINT_RANGE[0]:self.JOINT_RANGE[1]]]
def testFinished(self):
if not self.recieving:
return
self.recieving = False
self.destroy_timer(self.publishTimer)
self.i += 1
def printResults(self):
for index, position in enumerate(self.lastPositions):
if position is None:
print(f"{RED}FAILED: Did not recieve any positions from the robot!{RESET}")
self.testStatus[self.currentTest]["fail"] += 1
continue
difference = abs(self.expectedPositions[index] - position)
if difference == 0:
print(f"{GREEN}Joint {index} PASSED{RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.PASS_TOLERANCE:
print(f"{GREEN}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.WARN_TOLERANCE:
print(f"{YELLOW}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["warn"] += 1
else:
print(f"{RED}FAILED: Expected position {self.expectedPositions[index]}, got {position}{RESET}")
self.testStatus[self.currentTest]["fail"] += 1 | 4,791 | Python | 43.785046 | 208 | 0.604467 |
RoboEagles4828/edna2023/src/edna_tests/edna_tests/publish_joint_arm_command.py | import rclpy
from rclpy.node import Node
import math
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_arm_joint_commands')
self.publisher_ = self.create_publisher(JointState, '/real/real_arm_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
# velocity_cmds = JointState()
position_cmds = JointState()
position_cmds.name = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
# position_cmds.name = []
# rad = math.pi
# velocity_cmds.velocity = [ 0.0 ] * 8
position_cmds.position = [
0.0, # Either a 0 (down) or a 1 (up)
0.0, # Either a 0 (fully back) or a 1 (fully extended)
0.0, # Either a 0 (open) or a 1 (closed)
0.0, # Value between 0.0 (fully back) and 2.0 (fully extended) (will be converted on their end, so just take the motor value and multiply it by two)
0.0 # Value between 0.0 (fully down) and 1.0 (fully up)
]
# position_cmds.position = []
self.publisher_.publish(position_cmds)
# self.publisher_.publish(position_cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,931 | Python | 28.723076 | 165 | 0.568099 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/setup.py | from setuptools import setup
package_name = 'joint_trajectory_teleop'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='admin',
maintainer_email='[email protected]',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'joint_trajectory_teleop = joint_trajectory_teleop.joint_trajectory_teleop:main',
],
},
)
| 728 | Python | 25.999999 | 93 | 0.619505 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
| 884 | Python | 33.03846 | 74 | 0.725113 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
| 803 | Python | 32.499999 | 74 | 0.743462 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_copyright.main import main
import pytest
# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 962 | Python | 36.03846 | 93 | 0.751559 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/joint_trajectory_teleop/yaml_test.py | import yaml
yaml_path = '/workspaces/edna2023/src/edna_bringup/config/xbox-real.yaml'
with open(yaml_path, 'r') as f:
yaml = yaml.safe_load(f)
yaml = yaml['/*']['joint_trajectory_teleop_node']['ros__parameters']
print(str(yaml['function_mapping']['elevator_loading_station']['button'])) | 291 | Python | 40.71428 | 74 | 0.707904 |
RoboEagles4828/edna2023/src/joint_trajectory_teleop/joint_trajectory_teleop/joint_trajectory_teleop.py | import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, QoSHistoryPolicy, QoSDurabilityPolicy, QoSReliabilityPolicy
from rclpy import logging
import math
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from sensor_msgs.msg import Joy
import os
from rclpy.qos import QoSDurabilityPolicy, QoSHistoryPolicy, QoSReliabilityPolicy, QoSProfile
import time
import yaml
ENABLE_THROTTLE = True
class toggleButton():
def __init__(self, button, isAxis=False):
self.last_button = 0.0
self.flag = False
self.button = button
self.isAxis = isAxis
def toggle(self, buttons_list):
currentButton = buttons_list[self.button]
if self.isAxis:
# currentButton = currentButton / 10000 if currentButton > 1 else currentButton
if currentButton == -10000.0 and self.last_button != -10000.0:
self.flag = not self.flag
self.last_button = currentButton
return self.flag
else:
self.last_button = currentButton
return self.flag
if currentButton == 1.0 and self.last_button == 0.0:
self.flag = not self.flag
self.last_button = currentButton
return self.flag
else:
self.last_button = currentButton
return self.flag
class PublishTrajectoryMsg(Node):
def __init__(self):
super().__init__('publish_trajectory_msg')
# Joint Map
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
# Publishers and Subscribers
self.publisher_ = self.create_publisher(JointTrajectory, 'joint_trajectory_controller/joint_trajectory', 10)
self.subscriber = self.create_subscription(Joy, 'joy', self.controller_callback, 10)
self.timer_period = 0.5 # seconds
# Load yaml
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml')
with open(self.yaml_path, 'r') as f:
self.yaml = yaml.safe_load(f)
# Macros
self.functions = [self.elevator_loading_station, self.skis_up, self.elevator_mid_level, self.elevator_high_level, self.top_gripper_control, self.elevator_pivot_control, self.top_slider_control]
# Variables
self.cmds: JointTrajectory = JointTrajectory()
self.position_cmds: JointTrajectoryPoint = JointTrajectoryPoint()
self.position_cmds.positions = [0.0] * len(self.joints)
self.cmds.joint_names = self.joints
self.joint_map = self.yaml['joint_mapping']
self.logger = logging.get_logger('JOINT-TRAJCECTORY-TELEOP')
self.toggle_buttons = {}
self.last_cmd = JointTrajectory()
self.joint_limits = self.yaml["joint_limits"]
# Create Toggle Buttons
for function in self.functions:
buttonName = self.yaml['function_mapping'][function.__name__]['button']
button = self.yaml['controller_mapping'][buttonName]
toggle = self.yaml['function_mapping'][function.__name__]['toggle']
isAxis = "axis" in buttonName.lower()
if toggle:
self.toggle_buttons[function.__name__] = toggleButton(button, isAxis)
def controller_callback(self, joystick: Joy):
for function in self.functions:
buttonName = self.yaml['function_mapping'][function.__name__]['button']
button = self.yaml['controller_mapping'][buttonName]
toggle = self.yaml['function_mapping'][function.__name__]['toggle']
if toggle:
tglBtn = self.toggle_buttons[function.__name__]
if tglBtn.isAxis:
button = tglBtn.toggle(joystick.axes)
else:
button = tglBtn.toggle(joystick.buttons)
else:
button = joystick.buttons[button]
function(button)
self.publisher_.publish(self.cmds)
# Macros
def elevator_loading_station(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.056
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.056
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def skis_up(self, button_val: int):
#TODO: Tweak the values
self.position_cmds.positions[int(self.joint_map['bottom_intake_joint'])] = button_val
self.cmds.points = [self.position_cmds]
def elevator_mid_level(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.336
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.336
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
self.cmds.points = [self.position_cmds]
def elevator_high_level(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def top_gripper_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_left_arm_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"]
self.cmds.points = [self.position_cmds]
def elevator_pivot_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"]["max"]
else:
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def top_slider_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
self.cmds.points = [self.position_cmds]
def main(args=None):
rclpy.init(args=args)
node = PublishTrajectoryMsg()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 8,659 | Python | 40.238095 | 201 | 0.618778 |
RoboEagles4828/edna2023/src/swerve_hardware/swerve_hardware.xml | <library path="swerve_hardware">
<class name="swerve_hardware/IsaacDriveHardware"
type="swerve_hardware::IsaacDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface to talk with Isaac Sim robot drive train.
</description>
</class>
<class name="swerve_hardware/TestDriveHardware"
type="swerve_hardware::TestDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface for testing a connected controller.
</description>
</class>
<class name="swerve_hardware/RealDriveHardware"
type="swerve_hardware::RealDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface for testing a connected controller.
</description>
</class>
</library> | 925 | XML | 37.583332 | 83 | 0.714595 |
RoboEagles4828/edna2023/src/swerve_hardware/src/isaac_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/isaac_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
hardware_interface::CallbackReturn IsaacDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
node_ = rclcpp::Node::make_shared("isaac_hardware_interface");
// PUBLISHER SETUP
isaac_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_isaac_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
isaac_publisher_);
// SUBSCRIBER SETUP
const sensor_msgs::msg::JointState empty_joint_state;
auto qos = rclcpp::QoS(1);
qos.best_effort();
received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state));
isaac_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos,
[this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void
{
if (!subscriber_is_active_) {
RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive");
return;
}
received_joint_msg_ptr_.set(std::move(msg));
});
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// 8 positions states, 4 axle positions 4 wheel positions
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 8 velocity states, 4 axle velocity 4 wheel velocity
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 wheel velocity commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 axle position commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY));
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> IsaacDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> IsaacDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn IsaacDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
subscriber_is_active_ = true;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn IsaacDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Deactivating ...please wait...");
subscriber_is_active_ = false;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
double IsaacDriveHardware::convertToRosPosition(double isaac_position)
{
// Isaac goes from -2pi to 2pi, we want -pi to pi
if (isaac_position > M_PI) {
return isaac_position - 2.0 * M_PI;
} else if (isaac_position < -M_PI) {
return isaac_position + 2.0 * M_PI;
}
return isaac_position;
}
hardware_interface::return_type IsaacDriveHardware::read(const rclcpp::Time & time, const rclcpp::Duration & /*period*/)
{
rclcpp::spin_some(node_);
std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg;
received_joint_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds());
return hardware_interface::return_type::ERROR;
}
auto names = last_command_msg->name;
auto positions = last_command_msg->position;
auto velocities = last_command_msg->velocity;
for (auto i = 0u; i < joint_names_.size(); i++) {
for (auto j = 0u; j < names.size(); j++) {
if (strcmp(names[j].c_str(), info_.joints[i].name.c_str()) == 0) {
hw_positions_[i] = convertToRosPosition(positions[j]);
hw_velocities_[i] = (float)velocities[j];
break;
}
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type swerve_hardware::IsaacDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & period)
{
// Calculate Axle Velocities using motion magic
double dt = period.seconds();
for (auto i = 0u; i < joint_names_.size(); i++) {
if (joint_names_[i].find("axle") != std::string::npos) {
auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt);
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel);
hw_command_velocity_[i] = vel;
}
if (joint_names_[i] == "front_left_wheel_joint") {
auto& clk = *node_->get_clock();
RCLCPP_INFO_THROTTLE(rclcpp::get_logger("IsaacDriveHardware"), clk, 2000,
"Joint: %s Current Vel: %f Target Vel: %f Pos: %f", joint_names_[i].c_str(), hw_velocities_[i], hw_command_velocity_[i], hw_positions_[i]);
}
}
// Publish to Isaac
if (realtime_isaac_publisher_->trylock()) {
auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_;
realtime_isaac_command_.header.stamp = node_->get_clock()->now();
realtime_isaac_command_.name = joint_names_;
realtime_isaac_command_.velocity = hw_command_velocity_;
realtime_isaac_command_.position = empty_;
realtime_isaac_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
if (realtime_isaac_publisher_->trylock()) {
auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_;
realtime_isaac_command_.header.stamp = node_->get_clock()->now();
realtime_isaac_command_.name = joint_names_;
realtime_isaac_command_.velocity = empty_;
realtime_isaac_command_.position = hw_command_position_;
realtime_isaac_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::IsaacDriveHardware, hardware_interface::SystemInterface) | 11,781 | C++ | 37.006451 | 153 | 0.683643 |
RoboEagles4828/edna2023/src/swerve_hardware/src/test_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/test_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "rclcpp/rclcpp.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
hardware_interface::CallbackReturn TestDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// 8 positions states, 4 axle positions 4 wheel positions
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 8 velocity states, 4 axle velocity 4 wheel velocity
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 wheel velocity commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 axle position commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY));
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> TestDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> TestDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn TestDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn TestDriveHardware::on_deactivate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Deactivating ...please wait...");
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
hardware_interface::return_type TestDriveHardware::read(const rclcpp::Time & /*time*/, const rclcpp::Duration & period)
{
// Dumb Pass Through
// If you give the command for x velocity then the state is x velocity
// Loop through each joint name
// Check if joint name is in velocity command map
// If it is, use the index from the map to get the value in the velocity array
// If velocity not in map, set velocity value to 0
// Perform the same for position
double dt = period.seconds();
for (auto i = 0u; i < joint_names_.size(); i++)
{
if (joint_types_[i] == hardware_interface::HW_IF_VELOCITY)
{
hw_velocities_[i] = hw_command_velocity_[i];
hw_positions_[i] = hw_positions_[i] + dt * hw_velocities_[i];
}
else if (joint_types_[i] == hardware_interface::HW_IF_POSITION)
{
auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt);
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel);
hw_velocities_[i] = vel;
hw_positions_[i] = hw_positions_[i] + hw_velocities_[i] * dt;
// Test without any velocity smoothing
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Cmd: %f Name: %s", hw_command_position_[i], joint_names_[i].c_str());
// hw_velocities_[i] = 0.0;
// hw_positions_[i] = hw_command_position_[i];
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type TestDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/)
{
// Do Nothing
// Uncomment below if you want verbose messages for debugging.
// for (auto i = 0u; i < hw_command_velocity_.size(); i++)
// {
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Wheel %u Velocity: %f", i, hw_command_velocity_[i]);
// }
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "[%f] Joint 2 Position: %f", time.seconds(), hw_command_position_[2]);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::TestDriveHardware, hardware_interface::SystemInterface) | 9,533 | C++ | 37.59919 | 153 | 0.683625 |
RoboEagles4828/edna2023/src/swerve_hardware/src/motion_magic.cpp | #include "swerve_hardware/motion_magic.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include <ostream>
#include <iostream>
namespace swerve_hardware
{
MotionMagic::MotionMagic(double maxAcceleration, double maxVelocity)
{
this->MAX_ACCELERATION = maxAcceleration;
this->MAX_VELOCITY = maxVelocity;
}
double MotionMagic::getPositionDifference(double targetPosition, double sensorPosition) {
double copy_targetPosition = targetPosition;
double difference = copy_targetPosition - sensorPosition;
if (difference > M_PI) {
copy_targetPosition -= 2 * M_PI;
} else if (difference < -M_PI) {
copy_targetPosition += 2 * M_PI;
}
return std::fmod(copy_targetPosition - sensorPosition, M_PI);
}
// (maxV - curr)t1 + curr
// (curr - maxV)tf + b = 0
// 2 10
// 4(t1)
double MotionMagic::getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt) {
// method 0
double error = getPositionDifference(targetPosition, sensorPosition);
double absError = std::abs(error);
if (targetPosition != prevTargetPosition) {
totalDistance = absError;
prevTargetPosition = targetPosition;
}
if (absError < tolerance) {
return 0.0;
}
double dir = 1.0;
if (error < 0.0) {
dir = -1.0;
}
if (absError <= rampWindow1) {
return velocityInRampWindow1 * dir;
} else if (absError <= rampWindow2) {
return velocityInRampWindow2 * dir;
} else {
return velocityInCruiseWindow * dir;
}
//method 1
// double displacement = std::abs(getPositionDifference(targetPosition, sensorPosition));
// double dir = targetPosition - sensorPosition;
// double slow_down_dist = (MAX_JERK/6) * pow(2*sensorVelocity/MAX_JERK, 1.5);
// if(std::abs(displacement - 0.0) <= tolerance) return 0.0;
// if(dir > 0) {
// if(displacement <= slow_down_dist) return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY);
// // std::cout<<std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// else return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// } else {
// if(displacement <= slow_down_dist) return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// else return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY);
// }
}
} // namespace swerve_hardware
| 2,741 | C++ | 33.70886 | 145 | 0.594673 |
RoboEagles4828/edna2023/src/swerve_hardware/src/real_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/real_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
double RealDriveHardware::parse_double(const std::string & text)
{
return std::atof(text.c_str());
}
bool RealDriveHardware::parse_bool(const std::string & text)
{
if(strcmp(text.c_str(), "true") == 0) {
return true;
} else {
return false;
}
}
hardware_interface::CallbackReturn RealDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
node_ = rclcpp::Node::make_shared("isaac_hardware_interface");
// PUBLISHER SETUP
real_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_real_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
real_publisher_);
real_arm_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_arm_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_real_arm_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
real_arm_publisher_);
// SUBSCRIBER SETUP
const sensor_msgs::msg::JointState empty_joint_state;
auto qos = rclcpp::QoS(1);
qos.best_effort();
received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state));
real_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos,
[this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void
{
if (!subscriber_is_active_) {
RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive");
return;
}
received_joint_msg_ptr_.set(std::move(msg));
});
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// GLOBAL VECTOR SETUP
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
// JOINT GROUPS
for (auto i = 0u; i < info_.joints.size(); ++i)
{
const auto & joint = info_.joints.at(i);
bool use_percent = false;
double max = parse_double(joint.command_interfaces[0].max);
double min = parse_double(joint.command_interfaces[0].min);
auto param_percent_it = joint.parameters.find("percent");
if (param_percent_it != joint.parameters.end()) {
use_percent = parse_bool(joint.parameters.at("percent"));
}
// Mimics
if (joint.parameters.find("mimic") != joint.parameters.cend())
{
const auto mimicked_joint_it = std::find_if(
info_.joints.begin(), info_.joints.end(),
[&mimicked_joint =
joint.parameters.at("mimic")](const hardware_interface::ComponentInfo & joint_info)
{ return joint_info.name == mimicked_joint; });
if (mimicked_joint_it == info_.joints.cend())
{
throw std::runtime_error(
std::string("Mimicked joint '") + joint.parameters.at("mimic") + "' not found");
}
MimicJoint mimic_joint;
mimic_joint.joint_index = i;
mimic_joint.mimicked_joint_index = std::distance(info_.joints.begin(), mimicked_joint_it);
// Multiplier and offset
auto param_mult_it = joint.parameters.find("multiplier");
if (param_mult_it != joint.parameters.end()) {
mimic_joint.multiplier = parse_double(joint.parameters.at("multiplier"));
}
auto param_off_it = joint.parameters.find("offset");
if (param_off_it != joint.parameters.end()) {
mimic_joint.offset = parse_double(joint.parameters.at("offset"));
}
mimic_joints_.push_back(mimic_joint);
}
//
else if (joint.parameters.find("arm_group") != joint.parameters.cend())
{
JointGroupMember member;
member.joint_index = i;
member.joint_name = joint.name;
member.percent = use_percent;
member.max = max;
member.min = min;
arm_names_output_.push_back(joint.name);
arm_joints_.push_back(member);
} else {
JointGroupMember member;
member.joint_index = i;
member.joint_name = joint.name;
member.percent = use_percent;
member.max = max;
member.min = min;
drive_names_output_.push_back(joint.name);
drive_joints_.push_back(member);
}
}
hw_command_arm_velocity_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_arm_position_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_drive_velocity_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_drive_position_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN());
// Check that the info we were passed makes sense
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> RealDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> RealDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn RealDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
subscriber_is_active_ = true;
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn RealDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Deactivating ...please wait...");
subscriber_is_active_ = false;
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
double RealDriveHardware::convertToRosPosition(double real_position)
{
// Convert the rio integer that has been scaled
real_position /= RIO_CONVERSION_FACTOR;
// Just in case we get values we are not expecting
real_position = std::fmod(real_position, 2.0 * M_PI);
// Real goes from -2pi to 2pi, we want -pi to pi
if (real_position > M_PI)
{
real_position -= 2.0 * M_PI;
}
return real_position;
}
double RealDriveHardware::convertToRosVelocity(double real_velocity)
{
// Convert the rio integer that has been scaled
return real_velocity / RIO_CONVERSION_FACTOR;
}
hardware_interface::return_type RealDriveHardware::read(const rclcpp::Time &time, const rclcpp::Duration & /*period*/)
{
rclcpp::spin_some(node_);
std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg;
received_joint_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds());
return hardware_interface::return_type::ERROR;
}
auto names = last_command_msg->name;
auto positions = last_command_msg->position;
auto velocities = last_command_msg->velocity;
// Match Arm and Drive Joints
for (auto i = 0u; i < names.size(); i++) {
for (const auto & arm_joint : arm_joints_)
{
if (strcmp(names[i].c_str(), arm_joint.joint_name.c_str()) == 0) {
if (arm_joint.percent) {
double scale = arm_joint.max - arm_joint.min;
hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i] * scale + arm_joint.min);
hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i] * scale);
} else {
hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i]);
hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i]);
}
break;
}
}
for (const auto & drive_joint : drive_joints_)
{
if (strcmp(names[i].c_str(), drive_joint.joint_name.c_str()) == 0) {
hw_positions_[drive_joint.joint_index] = convertToRosPosition(positions[i]);
hw_velocities_[drive_joint.joint_index] = convertToRosVelocity((float)velocities[i]);
break;
}
}
}
// Apply Mimic Joints
for (const auto & mimic_joint : mimic_joints_)
{
hw_positions_[mimic_joint.joint_index] = hw_positions_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier + mimic_joint.offset;
hw_velocities_[mimic_joint.joint_index] = hw_velocities_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier;
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type swerve_hardware::RealDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/)
{
// convertToRealPositions(hw_command_position_);
// convertToRealElevatorPosition();
// Publish to Real
for (auto i = 0u; i < drive_joints_.size(); ++i)
{
auto joint = drive_joints_[i];
hw_command_drive_velocity_output_[i] = hw_command_velocity_[joint.joint_index];
hw_command_drive_position_output_[i] = hw_command_position_[joint.joint_index];
}
for (auto i = 0u; i < arm_joints_.size(); ++i)
{
auto joint = arm_joints_[i];
hw_command_arm_velocity_output_[i] = hw_command_velocity_[joint.joint_index];
hw_command_arm_position_output_[i] = hw_command_position_[joint.joint_index];
}
if (realtime_real_publisher_->trylock())
{
auto &realtime_real_command_ = realtime_real_publisher_->msg_;
realtime_real_command_.header.stamp = node_->get_clock()->now();
realtime_real_command_.name = drive_names_output_;
realtime_real_command_.velocity = hw_command_drive_velocity_output_;
realtime_real_command_.position = hw_command_drive_position_output_;
realtime_real_publisher_->unlockAndPublish();
}
if (realtime_real_arm_publisher_->trylock())
{
auto &realtime_real_arm_command_ = realtime_real_arm_publisher_->msg_;
realtime_real_arm_command_.header.stamp = node_->get_clock()->now();
realtime_real_arm_command_.name = arm_names_output_;
realtime_real_arm_command_.velocity = hw_command_arm_velocity_output_;
realtime_real_arm_command_.position = hw_command_arm_position_output_;
realtime_real_arm_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::RealDriveHardware, hardware_interface::SystemInterface) | 16,614 | C++ | 37.820093 | 155 | 0.648429 |
RoboEagles4828/edna2023/src/swerve_hardware/include/swerve_hardware/visibility_control.h | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef SWERVE_HARDWARE__VISIBILITY_CONTROL_H_
#define SWERVE_HARDWARE__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define SWERVE_HARDWARE_EXPORT __attribute__((dllexport))
#define SWERVE_HARDWARE_IMPORT __attribute__((dllimport))
#else
#define SWERVE_HARDWARE_EXPORT __declspec(dllexport)
#define SWERVE_HARDWARE_IMPORT __declspec(dllimport)
#endif
#ifdef SWERVE_HARDWARE_BUILDING_DLL
#define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_EXPORT
#else
#define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_IMPORT
#endif
#define SWERVE_HARDWARE_PUBLIC_TYPE SWERVE_HARDWARE_PUBLIC
#define SWERVE_HARDWARE_LOCAL
#else
#define SWERVE_HARDWARE_EXPORT __attribute__((visibility("default")))
#define SWERVE_HARDWARE_IMPORT
#if __GNUC__ >= 4
#define SWERVE_HARDWARE_PUBLIC __attribute__((visibility("default")))
#define SWERVE_HARDWARE_LOCAL __attribute__((visibility("hidden")))
#else
#define SWERVE_HARDWARE_PUBLIC
#define SWERVE_HARDWARE_LOCAL
#endif
#define SWERVE_HARDWARE_PUBLIC_TYPE
#endif
#endif // SWERVE_HARDWARE__VISIBILITY_CONTROL_H_ | 2,184 | C | 38.017856 | 79 | 0.763278 |
RoboEagles4828/edna2023/src/swerve_hardware/include/swerve_hardware/real_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__REAL_DRIVE_HPP_
#define SWERVE_HARDWARE__REAL_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/clock.hpp"
#include "rclcpp/duration.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include "swerve_hardware/visibility_control.h"
namespace swerve_hardware
{
class RealDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(RealDriveHardware)
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override;
private:
double RIO_CONVERSION_FACTOR = 10000.0;
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
// Output Topic Vectors
std::vector<std::string> arm_names_output_;
std::vector<double> hw_command_arm_velocity_output_;
std::vector<double> hw_command_arm_position_output_;
std::vector<std::string> drive_names_output_;
std::vector<double> hw_command_drive_velocity_output_;
std::vector<double> hw_command_drive_position_output_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
std::vector<double> hw_positions_input_;
std::vector<double> hw_velocities_input_;
// Mimic Joints for joints not controlled by the real robot
struct MimicJoint
{
std::size_t joint_index;
std::size_t mimicked_joint_index;
double multiplier = 1.0;
double offset = 0.0;
};
std::vector<MimicJoint> mimic_joints_;
double parse_double(const std::string & text);
bool parse_bool(const std::string & text);
// Keep Track of Arm vs Drive Joints
struct JointGroupMember
{
std::size_t joint_index;
std::string joint_name;
bool percent = false;
double min = -1.0;
double max = 1.0;
};
std::vector<JointGroupMember> drive_joints_;
std::vector<JointGroupMember> arm_joints_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
std::vector<std::string> joint_types_;
// Pub Sub to real
std::string joint_state_topic_ = "real_joint_states";
std::string joint_command_topic_ = "real_joint_commands";
std::string joint_arm_command_topic_ = "real_arm_commands";
rclcpp::Node::SharedPtr node_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_real_publisher_ = nullptr;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_arm_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_real_arm_publisher_ = nullptr;
bool subscriber_is_active_ = false;
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr real_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr};
// Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi
double convertToRosPosition(double real_position);
double convertToRosVelocity(double real_velocity);
// void convertToRealPositions(std::vector<double> ros_positions);
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_ | 5,378 | C++ | 37.148936 | 110 | 0.748605 |
RoboEagles4828/edna2023/src/swerve_hardware/include/swerve_hardware/test_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__TEST_DRIVE_HPP_
#define SWERVE_HARDWARE__TEST_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/clock.hpp"
#include "rclcpp/duration.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "swerve_hardware/visibility_control.h"
#include "swerve_hardware/motion_magic.hpp"
namespace swerve_hardware
{
class TestDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(TestDriveHardware)
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override;
private:
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
std::vector<std::string> joint_types_;
double MAX_VELOCITY = 20 * M_PI;
double MAX_ACCELERATION = 25 * M_PI;
std::vector<MotionMagic> motion_magic_;
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__TEST_DRIVE_HPP_ | 3,033 | C++ | 34.694117 | 109 | 0.765249 |
RoboEagles4828/edna2023/src/swerve_hardware/include/swerve_hardware/motion_magic.hpp | #ifndef SWERVE_HARDWARE__MOTION_MAGIC_HPP_
#define SWERVE_HARDWARE__MOTION_MAGIC_HPP_
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include <cmath>
#include "swerve_hardware/visibility_control.h"
namespace swerve_hardware
{
class MotionMagic
{
public:
SWERVE_HARDWARE_PUBLIC
MotionMagic(double maxAcceleration, double maxVelocity);
SWERVE_HARDWARE_PUBLIC
double getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt);
SWERVE_HARDWARE_PUBLIC
double getPositionDifference(double targetPosition, double sensorPosition);
SWERVE_HARDWARE_PUBLIC
double getTotalTime(double targetPosition);
private:
double MAX_ACCELERATION;
double MAX_VELOCITY;
double MAX_JERK = 6 * M_PI;
double prevVel = 0.0;
double prevAcceleration = 0.0;
double prevError = 0.0;
double prevTargetPosition = 0.0;
double totalDistance = 0.0;
double zeroTime = 0.0;
double tolerance = 0.15;
double rampWindow1 = 0.3;
double rampWindow2 = 0.8;
double velocityInRampWindow1 = 0.1;
double velocityInRampWindow2 = 2.0;
double velocityInCruiseWindow = 3.0;
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__MOTION_MAGIC_HPP_
| 1,307 | C++ | 24.153846 | 131 | 0.729151 |
RoboEagles4828/edna2023/src/swerve_hardware/include/swerve_hardware/isaac_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__ISAAC_DRIVE_HPP_
#define SWERVE_HARDWARE__ISAAC_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/clock.hpp"
#include "rclcpp/duration.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include "swerve_hardware/visibility_control.h"
#include "swerve_hardware/motion_magic.hpp"
namespace swerve_hardware
{
class IsaacDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(IsaacDriveHardware)
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override;
private:
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
std::vector<double> hw_command_velocity_converted_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
std::vector<std::string> joint_types_;
double MAX_VELOCITY = 2 * M_PI;
double MAX_ACCELERATION = 4 * M_PI;
double previous_velocity = 0.0;
std::vector<MotionMagic> motion_magic_;
// Pub Sub to isaac
std::string joint_state_topic_ = "isaac_joint_states";
std::string joint_command_topic_ = "isaac_joint_commands";
rclcpp::Node::SharedPtr node_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> isaac_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_isaac_publisher_ = nullptr;
bool subscriber_is_active_ = false;
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr isaac_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr};
std::vector<double> empty_;
// Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi
double convertToRosPosition(double isaac_position);
double convertToRosVelocity(double isaac_velocity);
void convertToIsaacVelocities(std::vector<double> ros_velocities);
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_ | 4,262 | C++ | 38.110091 | 110 | 0.762787 |
RoboEagles4828/edna2023/src/teleop_twist_joy/src/teleop_twist_joy.cpp | /**
Software License Agreement (BSD)
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cinttypes>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <geometry_msgs/msg/twist.hpp>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp_components/register_node_macro.hpp>
#include <rcutils/logging_macros.h>
#include <sensor_msgs/msg/joy.hpp>
#include "sensor_msgs/msg/imu.hpp"
#include "teleop_twist_joy/teleop_twist_joy.hpp"
#include "edna_interfaces/srv/set_bool.hpp"
#include <functional> // for bind()
using namespace std;
#define ROS_INFO_NAMED RCUTILS_LOG_INFO_NAMED
#define ROS_INFO_COND_NAMED RCUTILS_LOG_INFO_EXPRESSION_NAMED
namespace teleop_twist_joy
{
/**
* Internal members of class. This is the pimpl idiom, and allows more flexibility in adding
* parameters later without breaking ABI compatibility, for robots which link TeleopTwistJoy
* directly into base nodes.
*/
struct TeleopTwistJoy::Impl
{
void joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy);
void sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &, const std::string &which_map);
void imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg);
void timerCallback();
void resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response);
rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub;
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub;
rclcpp::Service<edna_interfaces::srv::SetBool>::SharedPtr reset_orientation_service;
rclcpp::TimerBase::SharedPtr timer_callback_;
rclcpp::Client<edna_interfaces::srv::SetBool>::SharedPtr start_writer_client_;
sensor_msgs::msg::Imu::SharedPtr last_msg;
bool require_enable_button;
int64_t enable_button;
int64_t enable_turbo_button;
int64_t enable_field_oriented_button;
int64_t start_writer_button;
int fieldOrientationButtonLastState = 0;
int turboButtonLastState = 0;
double last_offset = 0.0;
double rotation_offset = 0.0;
bool fieldOrientationEnabled = true;
bool turboEnabled = false;
int serviceButtonLastState = 0;
bool serviceEnabled = false;
std::map<std::string, int64_t> axis_linear_map;
std::map<std::string, std::map<std::string, double>> scale_linear_map;
std::map<std::string, int64_t> axis_angular_map;
std::map<std::string, std::map<std::string, double>> scale_angular_map;
bool sent_disable_msg;
};
/**
* Constructs TeleopTwistJoy.
*/
TeleopTwistJoy::TeleopTwistJoy(const rclcpp::NodeOptions &options) : Node("teleop_twist_joy_node", options)
{
pimpl_ = new Impl;
// rclcpp::Node node = Node("teleop_twist_joy_node", options); sensor_msgs/msg/Imu
pimpl_->cmd_vel_pub = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10);
pimpl_->imu_sub = this->create_subscription<sensor_msgs::msg::Imu>("zed/imu/data", rclcpp::QoS(10).best_effort(),
std::bind(&TeleopTwistJoy::Impl::imuCallback, this->pimpl_, std::placeholders::_1));
pimpl_->joy_sub = this->create_subscription<sensor_msgs::msg::Joy>("joy", rclcpp::QoS(10).best_effort(),
std::bind(&TeleopTwistJoy::Impl::joyCallback, this->pimpl_, std::placeholders::_1));
// pimpl_->client = this->create_client<writer_srv::srv::StartWriter>("start_writer");
// pimpl_->timer_callback_ = this->create_wall_timer(std::chrono::duration<double>(0.1), std::bind(&TeleopTwistJoy::Impl::timerCallback,this->pimpl_));
// pimpl_->client = create_client<writer_srv::srv::StartWriter>("start_writer",
// [this](std::shared_ptr<writer_srv::srv::StartWriter::Request> /*request*/, // NOLINT
// std::shared_ptr<writer_srv::srv::StartWriter::Response> response) { // NOLINT
// return startServiceCallback(std::move(response)); // NOLINT
pimpl_->reset_orientation_service = create_service<edna_interfaces::srv::SetBool>("reset_field_oriented", std::bind(&TeleopTwistJoy::Impl::resetOrientationCallback, this->pimpl_, std::placeholders::_1, std::placeholders::_2));
// });
pimpl_->start_writer_client_ = create_client<edna_interfaces::srv::SetBool>("set_bool");
pimpl_->require_enable_button = this->declare_parameter("require_enable_button", true);
pimpl_->enable_button = this->declare_parameter("enable_button", 5);
pimpl_->enable_turbo_button = this->declare_parameter("enable_turbo_button", -1);
pimpl_->enable_field_oriented_button = this->declare_parameter("enable_field_oriented_button", 8);
pimpl_->start_writer_button = this->declare_parameter("start_writer_button", 6);
this->declare_parameter("offset", 0.0);
pimpl_->last_offset = this->get_parameter("offset").as_double();
std::map<std::string, int64_t> default_linear_map{
{"x", 5L},
{"y", -1L},
{"z", -1L},
};
this->declare_parameters("axis_linear", default_linear_map);
this->get_parameters("axis_linear", pimpl_->axis_linear_map);
std::map<std::string, int64_t> default_angular_map{
{"yaw", 2L},
{"pitch", -1L},
{"roll", -1L},
};
this->declare_parameters("axis_angular", default_angular_map);
this->get_parameters("axis_angular", pimpl_->axis_angular_map);
std::map<std::string, double> default_scale_linear_normal_map{
{"x", 0.5},
{"y", 0.0},
{"z", 0.0},
};
this->declare_parameters("scale_linear", default_scale_linear_normal_map);
this->get_parameters("scale_linear", pimpl_->scale_linear_map["normal"]);
std::map<std::string, double> default_scale_linear_turbo_map{
{"x", 1.0},
{"y", 0.0},
{"z", 0.0},
};
this->declare_parameters("scale_linear_turbo", default_scale_linear_turbo_map);
this->get_parameters("scale_linear_turbo", pimpl_->scale_linear_map["turbo"]);
std::map<std::string, double> default_scale_angular_normal_map{
{"yaw", 0.5},
{"pitch", 0.0},
{"roll", 0.0},
};
this->declare_parameters("scale_angular", default_scale_angular_normal_map);
this->get_parameters("scale_angular", pimpl_->scale_angular_map["normal"]);
std::map<std::string, double> default_scale_angular_turbo_map{
{"yaw", 1.0},
{"pitch", 0.0},
{"roll", 0.0},
};
this->declare_parameters("scale_angular_turbo", default_scale_angular_turbo_map);
this->get_parameters("scale_angular_turbo", pimpl_->scale_angular_map["turbo"]);
ROS_INFO_COND_NAMED(pimpl_->require_enable_button, "TeleopTwistJoy",
"Teleop enable button %" PRId64 ".", pimpl_->enable_button);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
"Turbo on button %" PRId64 ".", pimpl_->enable_turbo_button);
for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_linear_map.begin();
it != pimpl_->axis_linear_map.end(); ++it)
{
ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Linear axis %s on %" PRId64 " at scale %f.",
it->first.c_str(), it->second, pimpl_->scale_linear_map["normal"][it->first]);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy",
"Turbo for linear axis %s is scale %f.", it->first.c_str(), pimpl_->scale_linear_map["turbo"][it->first]);
}
for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_angular_map.begin();
it != pimpl_->axis_angular_map.end(); ++it)
{
ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Angular axis %s on %" PRId64 " at scale %f.",
it->first.c_str(), it->second, pimpl_->scale_angular_map["normal"][it->first]);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy",
"Turbo for angular axis %s is scale %f.", it->first.c_str(), pimpl_->scale_angular_map["turbo"][it->first]);
}
pimpl_->sent_disable_msg = false;
auto param_callback =
[this](std::vector<rclcpp::Parameter> parameters)
{
static std::set<std::string> intparams = {"axis_linear.x", "axis_linear.y", "axis_linear.z",
"axis_angular.yaw", "axis_angular.pitch", "axis_angular.roll",
"enable_button", "enable_turbo_button", "enable_field_oriented_button", "start_writer_button", "offset"};
static std::set<std::string> doubleparams = {"scale_linear.x", "scale_linear.y", "scale_linear.z",
"scale_linear_turbo.x", "scale_linear_turbo.y", "scale_linear_turbo.z",
"scale_angular.yaw", "scale_angular.pitch", "scale_angular.roll",
"scale_angular_turbo.yaw", "scale_angular_turbo.pitch", "scale_angular_turbo.roll"};
static std::set<std::string> boolparams = {"require_enable_button"};
auto result = rcl_interfaces::msg::SetParametersResult();
result.successful = true;
// Loop to check if changed parameters are of expected data type
for (const auto ¶meter : parameters)
{
if (intparams.count(parameter.get_name()) == 1)
{
if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_INTEGER)
{
result.reason = "Only integer values can be set for '" + parameter.get_name() + "'.";
RCLCPP_WARN(this->get_logger(), result.reason.c_str());
result.successful = false;
return result;
}
}
else if (doubleparams.count(parameter.get_name()) == 1)
{
if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_DOUBLE)
{
result.reason = "Only double values can be set for '" + parameter.get_name() + "'.";
RCLCPP_WARN(this->get_logger(), result.reason.c_str());
result.successful = false;
return result;
}
}
else if (boolparams.count(parameter.get_name()) == 1)
{
if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_BOOL)
{
result.reason = "Only boolean values can be set for '" + parameter.get_name() + "'.";
RCLCPP_WARN(this->get_logger(), result.reason.c_str());
result.successful = false;
return result;
}
}
}
// Loop to assign changed parameters to the member variables
for (const auto ¶meter : parameters)
{
if (parameter.get_name() == "require_enable_button")
{
this->pimpl_->require_enable_button = parameter.get_value<rclcpp::PARAMETER_BOOL>();
}
if (parameter.get_name() == "enable_button")
{
this->pimpl_->enable_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "enable_turbo_button")
{
this->pimpl_->enable_turbo_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "enable_field_oriented_button")
{
this->pimpl_->enable_field_oriented_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "start_writer_button")
{
this->pimpl_->start_writer_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.x")
{
this->pimpl_->axis_linear_map["x"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.y")
{
this->pimpl_->axis_linear_map["y"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.z")
{
this->pimpl_->axis_linear_map["z"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.yaw")
{
this->pimpl_->axis_angular_map["yaw"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.pitch")
{
this->pimpl_->axis_angular_map["pitch"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.roll")
{
this->pimpl_->axis_angular_map["roll"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "scale_linear_turbo.x")
{
this->pimpl_->scale_linear_map["turbo"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear_turbo.y")
{
this->pimpl_->scale_linear_map["turbo"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear_turbo.z")
{
this->pimpl_->scale_linear_map["turbo"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.x")
{
this->pimpl_->scale_linear_map["normal"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.y")
{
this->pimpl_->scale_linear_map["normal"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.z")
{
this->pimpl_->scale_linear_map["normal"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.yaw")
{
this->pimpl_->scale_angular_map["turbo"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.pitch")
{
this->pimpl_->scale_angular_map["turbo"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.roll")
{
this->pimpl_->scale_angular_map["turbo"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.yaw")
{
this->pimpl_->scale_angular_map["normal"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.pitch")
{
this->pimpl_->scale_angular_map["normal"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.roll")
{
this->pimpl_->scale_angular_map["normal"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
}
return result;
};
callback_handle = this->add_on_set_parameters_callback(param_callback);
}
TeleopTwistJoy::~TeleopTwistJoy()
{
delete pimpl_;
}
double getVal(sensor_msgs::msg::Joy::SharedPtr joy_msg, const std::map<std::string, int64_t> &axis_map,
const std::map<std::string, double> &scale_map, const std::string &fieldname)
{
if (axis_map.find(fieldname) == axis_map.end() ||
axis_map.at(fieldname) == -1L ||
scale_map.find(fieldname) == scale_map.end() ||
static_cast<int>(joy_msg->axes.size()) <= axis_map.at(fieldname))
{
return 0.0;
}
return joy_msg->axes[axis_map.at(fieldname)] * scale_map.at(fieldname);
}
double get_scale_val(const std::map<std::string, int64_t> &axis_map,
const std::map<std::string, double> &scale_map, const std::string &fieldname)
{
if (axis_map.find(fieldname) == axis_map.end() ||
axis_map.at(fieldname) == -1L ||
scale_map.find(fieldname) == scale_map.end())
{
return 0.0;
}
return scale_map.at(fieldname);
}
double get_orientation_val(sensor_msgs::msg::Imu::SharedPtr imu_msg)
{
if (!imu_msg)
{
return 0.0;
}
double x = imu_msg->orientation.x;
double y = imu_msg->orientation.y;
double z = imu_msg->orientation.z;
double w = imu_msg->orientation.w;
double siny_cosp = 2 * (w * z + x * y);
double cosy_cosp = 1 - 2 * (y * y + z * z);
double angle = std::atan2(siny_cosp, cosy_cosp);
return angle;
}
double correct_joystick_pos(const std::map<std::string, double> &scale_map, const std::string &fieldname, double lin_x_vel, double lin_y_vel)
{
if (sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2)) > 1)
{
double scale = scale_map.at(fieldname);
if (scale < 0.001)
{
scale *= 10000;
}
if (fieldname == "x")
{
double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * scale;
return vel_to_correct;
}
else if (fieldname == "y")
{
double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * scale;
return vel_to_correct;
}
}
else
{
if (fieldname == "x")
{
double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2));
return vel_to_correct;
}
else if (fieldname == "y")
{
double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2));
return vel_to_correct;
}
}
return 0.0;
}
// void TeleopTwistJoy::startServiceCallBack(const std::shared_ptr<edna_interfaces::srv::SetBool::Response> response)
// {
// if(joy){
// }
// }
void TeleopTwistJoy::Impl::timerCallback()
{
// it's good to firstly check if the service server is even ready to be called
if (start_writer_client_->service_is_ready() && serviceEnabled && serviceButtonLastState == 1)
{
auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>();
request->data = true;
while (!start_writer_client_->wait_for_service(1s))
{
if (!rclcpp::ok())
{
RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting.");
break;
}
RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again...");
}
auto result = start_writer_client_->async_send_request(request);
}
else if (start_writer_client_->service_is_ready() && !serviceEnabled && serviceButtonLastState == 1)
{
auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>();
request->data = false;
while (!start_writer_client_->wait_for_service(1s))
{
if (!rclcpp::ok())
{
RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting.");
break;
}
RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again...");
}
auto result = start_writer_client_->async_send_request(request);
// RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Bag recording stopped: %d", !result.get()->recording);
// RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Path of Bag: %s", result.get()->path.c_str());
}
else if (!start_writer_client_->service_is_ready())
RCLCPP_WARN(rclcpp::get_logger("teleop_twist_joy"), "[ServiceClientExample]: not calling service using callback, service not ready!");
}
void TeleopTwistJoy::Impl::resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response)
{
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "received service call: %d", request->data);
if (request->data)
{
rotation_offset=3.1415;
}
response->message = "succeeded";
response->success = true;
}
void TeleopTwistJoy::Impl::sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &joy_msg,
const std::string &which_map)
{
// Initializes with zeros by default.
auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>();
double lin_x_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "x");
double lin_y_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "y");
double ang_z_vel = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw");
double temp = correct_joystick_pos(scale_linear_map[which_map], "x", lin_x_vel, lin_y_vel);
lin_y_vel = correct_joystick_pos(scale_linear_map[which_map], "y", lin_x_vel, lin_y_vel);
lin_x_vel = temp;
// RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%f",lin_x_vel);
// for( uint i =0u; i<joy_msg->buttons.size(); i++){
// RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%d:%d:%ld",joy_msg->buttons[i],i,enable_field_oriented_button);
// }
if (enable_field_oriented_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_field_oriented_button)
{
auto state = joy_msg->buttons[enable_field_oriented_button];
if (state == 1 && fieldOrientationButtonLastState == 0)
{
fieldOrientationEnabled = !fieldOrientationEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Field Oriented: %d", fieldOrientationEnabled);
}
fieldOrientationButtonLastState = state;
}
if (start_writer_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > start_writer_button)
{
auto state = joy_msg->buttons[start_writer_button];
if (state == 1 && serviceButtonLastState == 0)
{
serviceEnabled = !serviceEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Writer State: %d", serviceEnabled);
}
serviceButtonLastState = state;
}
// RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f",last_offset);
// Math for field oriented drive
if (fieldOrientationEnabled)
{
double robot_imu_orientation = (get_orientation_val(last_msg));
robot_imu_orientation += (ang_z_vel * last_offset) + rotation_offset;
// RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f", robot_imu_orientation);
double temp = lin_x_vel * cos(robot_imu_orientation) + lin_y_vel * sin(robot_imu_orientation);
lin_y_vel = -1 * lin_x_vel * sin(robot_imu_orientation) + lin_y_vel * cos(robot_imu_orientation);
lin_x_vel = temp;
}
// Set Velocities in twist msg and publish
cmd_vel_msg->linear.x = lin_x_vel;
cmd_vel_msg->linear.y = lin_y_vel;
cmd_vel_msg->linear.z = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "z");
cmd_vel_msg->angular.z = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw");
cmd_vel_msg->angular.y = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "pitch");
cmd_vel_msg->angular.x = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "roll");
cmd_vel_pub->publish(std::move(cmd_vel_msg));
sent_disable_msg = false;
}
void TeleopTwistJoy::Impl::joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy_msg)
{
if (enable_turbo_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_turbo_button)
{
auto state = joy_msg->buttons[enable_turbo_button];
if (state == 1 && turboButtonLastState == 0)
{
turboEnabled = !turboEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Turbo: %d", turboEnabled);
}
turboButtonLastState = state;
}
if (turboEnabled)
{
sendCmdVelMsg(joy_msg, "turbo");
}
else if (!require_enable_button ||
(static_cast<int>(joy_msg->buttons.size()) > enable_button &&
joy_msg->buttons[enable_button]))
{
sendCmdVelMsg(joy_msg, "normal");
}
else
{
// When enable button is released, immediately send a single no-motion command
// in order to stop the robot.
if (!sent_disable_msg)
{
// Initializes with zeros by default.
auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>();
cmd_vel_pub->publish(std::move(cmd_vel_msg));
sent_disable_msg = true;
}
}
}
void TeleopTwistJoy::Impl::imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg)
{
// Saves current message as global pointer
last_msg = imu_msg;
}
} // namespace teleop_twist_joy
RCLCPP_COMPONENTS_REGISTER_NODE(teleop_twist_joy::TeleopTwistJoy)
| 26,597 | C++ | 43.404007 | 230 | 0.615859 |
RoboEagles4828/edna2023/src/teleop_twist_joy/src/teleop_node.cpp | /**
Software License Agreement (BSD)
\file teleop_node.cpp
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "teleop_twist_joy/teleop_twist_joy.hpp"
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_unique<teleop_twist_joy::TeleopTwistJoy>(rclcpp::NodeOptions()));
rclcpp::shutdown();
return 0;
}
| 1,931 | C++ | 44.999999 | 110 | 0.785085 |
RoboEagles4828/edna2023/src/teleop_twist_joy/include/teleop_twist_joy/teleop_twist_joy.hpp | /**
Software License Agreement (BSD)
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
#define TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
#include <rclcpp/rclcpp.hpp>
#include "teleop_twist_joy/teleop_twist_joy_export.h"
namespace teleop_twist_joy
{
/**
* Class implementing a basic Joy -> Twist translation.
*/
class TELEOP_TWIST_JOY_EXPORT TeleopTwistJoy : public rclcpp::Node
{
public:
explicit TeleopTwistJoy(const rclcpp::NodeOptions& options);
virtual ~TeleopTwistJoy();
private:
struct Impl;
Impl* pimpl_;
OnSetParametersCallbackHandle::SharedPtr callback_handle;
};
} // namespace teleop_twist_joy
#endif // TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
| 2,237 | C++ | 41.226414 | 110 | 0.788556 |
RoboEagles4828/edna2023/src/frc_auton/setup.py | from setuptools import setup
package_name = 'frc_auton'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools','rosbags'],
zip_safe=True,
maintainer='admin',
maintainer_email='[email protected]',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'reader = frc_auton.reader:main',
'writer = frc_auton.writer:main',
],
},
)
| 721 | Python | 24.785713 | 53 | 0.590846 |
RoboEagles4828/edna2023/src/frc_auton/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
| 884 | Python | 33.03846 | 74 | 0.725113 |
RoboEagles4828/edna2023/src/frc_auton/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
| 803 | Python | 32.499999 | 74 | 0.743462 |
RoboEagles4828/edna2023/src/frc_auton/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_copyright.main import main
import pytest
# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
| 962 | Python | 36.03846 | 93 | 0.751559 |
RoboEagles4828/edna2023/src/frc_auton/frc_auton/test_frc_stage.py | import rclpy
from rclpy.node import Node
from std_msgs.msg import Bool, String
class StagePublisher(Node):
def __init__(self):
super().__init__('stage_publisher')
self.publisher_ = self.create_publisher(String, '/real/frc_stage', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = "AUTON|False|False"
self.publisher_.publish(msg)
self.get_logger().info('Publishing: %s' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = StagePublisher()
rclpy.spin(minimal_publisher)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 974 | Python | 23.999999 | 78 | 0.63347 |
RoboEagles4828/edna2023/src/frc_auton/frc_auton/writer.py | from std_msgs.msg import String
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from geometry_msgs.msg import Twist
import rclpy
from rclpy.node import Node
import os
import rclpy
from rclpy.node import Node
from rclpy.serialization import serialize_message
from std_msgs.msg import String
from edna_interfaces.srv import SetBool
import rosbag2_py
# create writer instance and open for writing
class StartWriting(Node):
def __init__(self):
super().__init__('start_writer')
self.subscription_stage =self.create_subscription(String, 'frc_stage', self.stage_callback, 10)
self.srv = self.create_service(SetBool, 'set_bool', self.service_callback)
self.stage = ""
self.fms = "False"
self.is_disabled = "True"
self.service_enabled = False
def service_callback(self, request, response):
self.bag_writer = BagWriter()
self.service_enabled = request.data
if(self.service_enabled):
self.start_bag_writer()
self.get_logger().info(f'Service Enabled: {self.service_enabled}')
response.sucess = True
response.message = self.bag_writer.path
return response
def start_bag_writer(self):
if (self.stage.lower() == "teleop" or self.stage.lower() == "auton") and (self.fms=='True' or self.service_enabled) and self.is_disabled=='False':
rclpy.spin(self.bag_writer)
self.bag_writer.destroy_node()
rclpy.shutdown()
def stage_callback(self, msg):
data = str(msg.data).split('|')
self.stage = (data[0])
self.fms = str(data[1])
self.is_disabled = str(data[2])
class BagWriter(Node):
def __init__(self):
super().__init__('bag_writer')
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.package_root = os.path.join(self.project_root_path, 'src/frc_auton')
self.subscription_arm = self.create_subscription(JointTrajectory,'joint_trajectory_controller/joint_trajectory',self.arm_callback,10)
self.subscription_swerve = self.create_subscription(Twist,'swerve_controller/cmd_vel_unstamped',self.swerve_callback,10)
file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag')))
self.path = f'{self.package_root}/frc_auton/Auto_ros_bag/bag_'+str(file_counter)
self.writer = rosbag2_py.SequentialWriter()
storage_options = rosbag2_py._storage.StorageOptions(uri=self.path,storage_id='sqlite3')
converter_options = rosbag2_py._storage.ConverterOptions('', '')
self.writer.open(storage_options, converter_options)
topic_info_arm = rosbag2_py._storage.TopicMetadata(name=self.subscription_arm.topic_name,type='trajectory_msgs/msg/JointTrajectory',serialization_format='cdr')
self.writer.create_topic(topic_info_arm)
topic_info_swerve = rosbag2_py._storage.TopicMetadata(name=self.subscription_swerve.topic_name,type='geometry_msgs/msg/Twist',serialization_format='cdr')
self.writer.create_topic(topic_info_swerve)
def swerve_callback(self, msg):
self.writer.write(
self.subscription_swerve.topic_name,
serialize_message(msg),
self.get_clock().now().nanoseconds)
def arm_callback(self, msg):
self.writer.write(
self.subscription_arm.topic_name,
serialize_message(msg),
self.get_clock().now().nanoseconds)
def main(args=None):
rclpy.init(args=args)
service_writer = StartWriting()
rclpy.spin(service_writer)
service_writer.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 3,865 | Python | 39.694736 | 167 | 0.649677 |
RoboEagles4828/edna2023/src/frc_auton/frc_auton/policy_runner.py | import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32
from nav_msgs.msg import Odometry
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
import numpy as np
import torch
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
class Reader(Node):
def __init__(self):
super().__init__("reinforcement_learning_runner")
# self.robot_ip = robot_ip
self.policy = torch.load("/workspaces/edna2023/isaac/Swervesim/swervesim/runs/SwerveCS/nn/SwerveCS.pth")
self.joint_action_pub = self.create_publisher(Twist, "cmd_vel", 10)
self.joint_trajectory_action_pub = self.create_publisher(Twist, "joint_trajectory_message", 10)
self.odom_sub = self.create_subscription(Float32, "odom", self.odom_callback, 10)
self.joint_state_sub = self.create_subscription(Float32, "joint_state", self.joint_state_callback, 10)
self.odom_msg = Odometry()
self.joint_state_msg = JointState()
self.twist_msg = Twist()
self.cmds = JointTrajectory()
self.position_cmds = JointTrajectoryPoint()
self.episode_reward = 0
self.step = 0
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
def get_action(self, msg):
obs = np.array([msg.data], dtype=np.float32)
action = self.policy(torch.tensor(obs).float())
self.twist_msg.linear.x = action[0].detach().numpy()
self.twist_msg.linear.y = action[1].detach().numpy()
self.twist_msg.angular.z = action[2].detach().numpy()
self.position_cmds.positions = [
action[3].detach().numpy(),
action[4].detach().numpy(),
action[5].detach().numpy(),
action[4].detach().numpy(),
action[6].detach().numpy(),
action[6].detach().numpy(),
action[7].detach().numpy(),
action[6].detach().numpy(),
action[8].detach().numpy(),
action[8].detach().numpy(),
]
self.cmds.joint_names = self.joints
self.cmds.points = [self.position_cmds]
self.publisher_.publish(self.cmds)
self.action_pub.publish(self.twist_msg)
self.step += 1
def joint_state_callback(self, msg):
if(msg != None):
self.joint_state_msg = msg
return
def odom_callback(self, msg):
if(msg != None):
self.odom_msg = msg
return
def get_reward():
return
def main(args=None):
# env = gym.create_env("RealRobot", ip=self.robot_ip)
rclpy.init(args=args)
reader = Reader()
rclpy.spin(reader)
# env.disconnect()
if __name__ == '__main__':
main() | 2,977 | Python | 35.765432 | 112 | 0.593215 |
RoboEagles4828/edna2023/src/frc_auton/frc_auton/reader.py | import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from std_msgs.msg import String
import rosbag2_py
from pathlib import Path
from rclpy.serialization import deserialize_message
import rosbag2_py
from std_msgs.msg import String
import os
from time import time
import yaml
import math
from edna_interfaces.srv import SetBool
class MinimalClientAsync(Node):
def __init__(self):
super().__init__('minimal_client_async')
self.client = self.create_client(SetBool, 'reset_field_oriented')
while not self.client.wait_for_service(timeout_sec=1.0):
self.get_logger().info('service not available, waiting again...')
self.request = SetBool.Request()
def send_request(self, request):
self.request.data = request
self.future = self.client.call_async(self.request)
rclpy.spin_until_future_complete(self, self.future)
return self.future.result()
class StageSubscriber(Node):
def __init__(self):
super().__init__('stage_subscriber')
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.package_root = os.path.join(self.project_root_path, 'src/frc_auton')
# minimal_client = MinimalClientAsync()
# response = minimal_client.send_request(True)
# minimal_client.get_logger().info(
# 'Result of add_two_ints: for %d + %d = %s' %
# (True, response.success, response.message))
# rclpy.spin_once(minimal_client)
# minimal_client.destroy_node()
file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag')))-1
# self.reader = rosbag2_py.SequentialReader()
# self.converter_options = rosbag2_py.ConverterOptions(input_serialization_format='cdr',output_serialization_format='cdr')
# self.reader.open(self.storage_options,self.converter_options)
if file_counter != -1:
self.subscription = self.create_subscription(String,'frc_stage',self.listener_callback,10)
self.publish_twist = self.create_publisher(Twist,'swerve_controller/cmd_vel_unstamped',10)
self.publish_trajectory = self.create_publisher(JointTrajectory,'joint_trajectory_controller/joint_trajectory',10)
self.changed_stage = False
self.stage= ""
self.fms = "False"
self.isdisabled = "True"
self.doAuton = False
self.cmd = Twist()
self.cmd.linear.x = 0.0
self.cmd.linear.y = 0.0
self.cmd.angular.z = 0.0
self.timeInSeconds = 2.0
self.taxiTimeDuration = 2.0
# joint trajectory msg stuff
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
self.cmds: JointTrajectory = JointTrajectory()
self.cmds.joint_names = self.joints
self.position_cmds = JointTrajectoryPoint()
self.cmds.points = [self.position_cmds]
self.cmds.points[0].positions = [0.0] * len(self.joints)
# yaml
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml')
with open(self.yaml_path, 'r') as f:
self.yaml = yaml.safe_load(f)
self.joint_map = self.yaml['joint_mapping']
self.joint_limits = self.yaml["joint_limits"]
# task times
self.tasks = [
{ 'dur': 0.25, 'task': self.gripperManager, 'arg': 0 },
{ 'dur': 0.5, 'task': self.armHeightManager, 'arg': 1 },
{ 'dur': 3.5, 'task': self.armExtensionManager, 'arg': 1 },
{ 'dur': 0.5, 'task': self.gripperManager, 'arg': 1 },
{ 'dur': 2.5, 'task': self.armExtensionManager, 'arg': 0 },
{ 'dur': 0.5, 'task': self.armHeightManager, 'arg': 0 },
{ 'dur': 3.0, 'task': self.goBackwards, 'arg': -1.5 },
{ 'dur': 0.1, 'task': self.stop, 'arg': 0 },
{ 'dur': 2.1, 'task': self.turnAround, 'arg': math.pi / 2 },
{ 'dur': 0.1, 'task': self.stop, 'arg': 0 },
]
self.conePlacementDuration = 0
for task in self.tasks:
self.conePlacementDuration += task['dur']
# TURN AROUND STUFF
self.turnCmd = Twist()
self.turnCmd.linear.x = 0.0
self.turnCmd.linear.y = 0.0
self.turnCmd.angular.z = 0.0
self.turnTimeDuration = 2.0
def flip_camera(self):
minimal_client = MinimalClientAsync()
response = minimal_client.send_request(True)
minimal_client.destroy_node()
def initAuton(self):
self.startTime = time()
self.turnStartTime = self.startTime + self.conePlacementDuration + 2
self.changed_stage = False
self.doAuton = True
self.flip_camera()
self.get_logger().info(f"STARTED AUTON AT {self.startTime}")
def loopAuton(self):
# self.taxiAuton()
self.coneAuton()
#self.turnAuton()
# CONE AUTOMATION STUFF
def publishCurrent(self):
self.cmds.points = [self.position_cmds]
self.publish_trajectory.publish(self.cmds)
def armExtensionManager(self, pos):
value = ''
if(pos == 0):
# RETRACT THE ARM
value = 'min'
self.get_logger().warn("ARM RETRACTED")
elif(pos == 1):
# EXTEND THE ARM
value = 'max'
self.get_logger().warn("ARM EXTENDED")
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"][value]
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"][value]
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"][value]
self.publishCurrent()
def armHeightManager(self, pos):
value = ''
if(pos == 0):
# LOWER THE ARM
value = "min"
self.get_logger().warn("ARM LOWERED")
elif(pos == 1):
# RAISE THE ARM
value = "max"
self.get_logger().warn("ARM RAISED")
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"][value]
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"][value]
self.publishCurrent()
def gripperManager(self, pos):
value = ''
if(pos == 1):
# OPEN THE GRIPPER
value = 'min'
self.get_logger().warn("GRIPPER OPENED")
elif(pos == 0):
# CLOSE THE GRIPPER
value = 'max'
self.get_logger().warn("GRIPPER CLOSED")
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value]
self.publishCurrent()
def coneAuton(self):
elapsedTime = time() - self.startTime
totalDur = 0.0
for task in self.tasks:
totalDur += task['dur']
if elapsedTime < totalDur:
task['task'](task['arg'])
return
def taxiAuton(self):
elapsedTime = time() - self.startTime
if elapsedTime < self.taxiTimeDuration:
self.cmd.linear.x = 0.5
self.publish_twist.publish(self.cmd)
else:
return
def stop(self, x):
self.cmd.linear.x = 0.0
self.cmd.linear.y = 0.0
self.cmd.angular.z = 0.0
self.publish_twist.publish(self.cmd)
def goBackwards(self, speed):
self.cmd.linear.x = speed
self.publish_twist.publish(self.cmd)
self.get_logger().warn("GOING BACKWARDS")
def turnAround(self, angVel):
self.turnCmd.angular.z = angVel
self.publish_twist.publish(self.turnCmd)
self.get_logger().warn("TURNING")
def stopAuton(self):
self.cmd.linear.x = 0.0
# Publish twice to just to be safe
self.publish_twist.publish(self.cmd)
self.publish_twist.publish(self.cmd)
self.get_logger().info(f"STOPPED AUTON AT {time()}"),
self.doAuton = False
def listener_callback(self, msg):
# Check when any state has changed, enabled, disabled, auton, teleop, etc.
stage = str(msg.data).split("|")[0]
isdisabled = str(msg.data).split("|")[2]
if stage != self.stage or isdisabled != self.isdisabled:
self.changed_stage = True
self.stage = stage
self.isdisabled = isdisabled
# fms = str(msg.data).split("|")[1]
# Execute auton actions
if(stage.lower() == 'auton' and self.isdisabled == "False"):# and fms == 'True' ):
if self.changed_stage:
self.initAuton()
if self.doAuton:
self.loopAuton()
# We have moved out of auton enabled mode so stop if we are still running
else:
if self.doAuton:
self.stopAuton()
def main(args=None):
rclpy.init(args=args)
# minimal_client = MinimalClientAsync()
# response = minimal_client.send_request(True)
# # minimal_client.get_logger().info(
# # 'Result of add_two_ints: for %d + %d = %s' %
# # (True, response.success, response.message))
# # minimal_client.destroy_node()
# minimal_client.destroy_node()
stage_subscriber = StageSubscriber()
# stage_subscriber.send_request()
rclpy.spin(stage_subscriber)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
stage_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
# create reader instance and open for reading
| 10,919 | Python | 34.454545 | 146 | 0.577617 |
RoboEagles4828/edna2023/src/frc_auton/frc_auton/Auto_ros_bag/bag_0/metadata.yaml | rosbag2_bagfile_information:
version: 5
storage_identifier: sqlite3
duration:
nanoseconds: 33616431360
starting_time:
nanoseconds_since_epoch: 1679698398612800019
message_count: 72
topics_with_message_count:
- topic_metadata:
name: /real/swerve_controller/cmd_vel_unstamped
type: geometry_msgs/msg/Twist
serialization_format: cdr
offered_qos_profiles: ""
message_count: 9
- topic_metadata:
name: /real/joint_trajectory_controller/joint_trajectory
type: trajectory_msgs/msg/JointTrajectory
serialization_format: cdr
offered_qos_profiles: ""
message_count: 63
compression_format: ""
compression_mode: ""
relative_file_paths:
- bag_0_0.db3
files:
- path: bag_0_0.db3
starting_time:
nanoseconds_since_epoch: 1679698398612800019
duration:
nanoseconds: 33616431360
message_count: 72 | 930 | YAML | 28.093749 | 64 | 0.672043 |
RoboEagles4828/edna2023/src/swerve_controller/swerve_plugin.xml | <library path="swerve_controller">
<class name="swerve_controller/SwerveController" type="swerve_controller::SwerveController" base_class_type="controller_interface::ControllerInterface">
<description>
The swerve controller transforms linear and angular velocity messages into signals for each wheel(s) and swerve modules.
</description>
</class>
</library>
| 370 | XML | 45.374994 | 154 | 0.783784 |
RoboEagles4828/edna2023/src/swerve_controller/src/speed_limiter.cpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Enrique Fernández
*/
#include <algorithm>
#include <stdexcept>
#include "swerve_controller/speed_limiter.hpp"
#include "rcppmath/clamp.hpp"
namespace swerve_controller
{
SpeedLimiter::SpeedLimiter(
bool has_velocity_limits, bool has_acceleration_limits, bool has_jerk_limits, double min_velocity,
double max_velocity, double min_acceleration, double max_acceleration, double min_jerk,
double max_jerk)
: has_velocity_limits_(has_velocity_limits),
has_acceleration_limits_(has_acceleration_limits),
has_jerk_limits_(has_jerk_limits),
min_velocity_(min_velocity),
max_velocity_(max_velocity),
min_acceleration_(min_acceleration),
max_acceleration_(max_acceleration),
min_jerk_(min_jerk),
max_jerk_(max_jerk)
{
// Check if limits are valid, max must be specified, min defaults to -max if unspecified
if (has_velocity_limits_)
{
if (std::isnan(max_velocity_))
{
throw std::runtime_error("Cannot apply velocity limits if max_velocity is not specified");
}
if (std::isnan(min_velocity_))
{
min_velocity_ = -max_velocity_;
}
}
if (has_acceleration_limits_)
{
if (std::isnan(max_acceleration_))
{
throw std::runtime_error(
"Cannot apply acceleration limits if max_acceleration is not specified");
}
if (std::isnan(min_acceleration_))
{
min_acceleration_ = -max_acceleration_;
}
}
if (has_jerk_limits_)
{
if (std::isnan(max_jerk_))
{
throw std::runtime_error("Cannot apply jerk limits if max_jerk is not specified");
}
if (std::isnan(min_jerk_))
{
min_jerk_ = -max_jerk_;
}
}
}
double SpeedLimiter::limit(double & v, double v0, double v1, double dt)
{
const double tmp = v;
limit_jerk(v, v0, v1, dt);
limit_acceleration(v, v0, dt);
limit_velocity(v);
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_velocity(double & v)
{
const double tmp = v;
if (has_velocity_limits_)
{
v = rcppmath::clamp(v, min_velocity_, max_velocity_);
}
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_acceleration(double & v, double v0, double dt)
{
const double tmp = v;
if (has_acceleration_limits_)
{
const double dv_min = min_acceleration_ * dt;
const double dv_max = max_acceleration_ * dt;
const double dv = rcppmath::clamp(v - v0, dv_min, dv_max);
v = v0 + dv;
}
return tmp != 0.0 ? v / tmp : 1.0;
}
double SpeedLimiter::limit_jerk(double & v, double v0, double v1, double dt)
{
const double tmp = v;
if (has_jerk_limits_)
{
const double dv = v - v0;
const double dv0 = v0 - v1;
const double dt2 = 2. * dt * dt;
const double da_min = min_jerk_ * dt2;
const double da_max = max_jerk_ * dt2;
const double da = rcppmath::clamp(dv - dv0, da_min, da_max);
v = v0 + dv0 + da;
}
return tmp != 0.0 ? v / tmp : 1.0;
}
} // namespace swerve_controller
| 3,526 | C++ | 24.014184 | 100 | 0.65485 |
RoboEagles4828/edna2023/src/swerve_controller/src/swerve_controller.cpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include <cmath>
#include "swerve_controller/swerve_controller.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "lifecycle_msgs/msg/state.hpp"
#include "rclcpp/logging.hpp"
namespace
{
constexpr auto DEFAULT_COMMAND_TOPIC = "~/cmd_vel";
constexpr auto DEFAULT_COMMAND_UNSTAMPED_TOPIC = "~/cmd_vel_unstamped";
constexpr auto DEFAULT_COMMAND_OUT_TOPIC = "~/cmd_vel_out";
} // namespace
namespace swerve_controller
{
using namespace std::chrono_literals;
using controller_interface::interface_configuration_type;
using controller_interface::InterfaceConfiguration;
using hardware_interface::HW_IF_POSITION;
using hardware_interface::HW_IF_VELOCITY;
using lifecycle_msgs::msg::State;
Wheel::Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name) : velocity_(velocity), name(std::move(name)) {}
void Wheel::set_velocity(double velocity)
{
velocity_.get().set_value(velocity);
}
Axle::Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> command_position, std::reference_wrapper<const hardware_interface::LoanedStateInterface> state_position, std::string name) : command_position_(command_position), state_position_(state_position), name(std::move(name)) {}
void Axle::set_position(double position)
{
command_position_.get().set_value(position);
}
double Axle::get_position(void)
{
// temporary
return state_position_.get().get_value();
}
void optimize(double& target, const double& current, double& wheel_velocity) {
double target_copy = target;
double diff = target_copy - current;
// Check one way
if (diff > M_PI) {
target_copy -= 2.0 * M_PI;
} else if (diff < -M_PI) {
target_copy += 2.0 * M_PI;
}
// Check other way
diff = target_copy - current;
if(std::abs(diff) > M_PI / 2.0) {
// Get better position 180 degrees away
if (target < 0.0) {
target += M_PI;
} else {
target -= M_PI;
}
// Reverse direction
wheel_velocity *= -1.0;
}
}
SwerveController::SwerveController() : controller_interface::ControllerInterface() {}
controller_interface::CallbackReturn SwerveController::on_init()
{
try
{
// with the lifecycle node being initialized, we can declare parameters
auto_declare<std::string>("front_left_wheel_joint", front_left_wheel_joint_name_);
auto_declare<std::string>("front_right_wheel_joint", front_right_wheel_joint_name_);
auto_declare<std::string>("rear_left_wheel_joint", rear_left_wheel_joint_name_);
auto_declare<std::string>("rear_right_wheel_joint", rear_right_wheel_joint_name_);
auto_declare<std::string>("front_left_axle_joint", front_left_axle_joint_name_);
auto_declare<std::string>("front_right_axle_joint", front_right_axle_joint_name_);
auto_declare<std::string>("rear_left_axle_joint", rear_left_axle_joint_name_);
auto_declare<std::string>("rear_right_axle_joint", rear_right_axle_joint_name_);
auto_declare<double>("chassis_length_meters", wheel_params_.x_offset);
auto_declare<double>("chassis_width_meters", wheel_params_.y_offset);
auto_declare<double>("wheel_radius_meters", wheel_params_.radius);
auto_declare<double>("max_wheel_angular_velocity", max_wheel_angular_velocity_);
auto_declare<double>("cmd_vel_timeout_seconds", cmd_vel_timeout_milliseconds_.count() / 1000.0);
auto_declare<bool>("use_stamped_vel", use_stamped_vel_);
// Limits
auto_declare<bool>("linear.x.has_velocity_limits", false);
auto_declare<bool>("linear.x.has_acceleration_limits", false);
auto_declare<bool>("linear.x.has_jerk_limits", false);
auto_declare<double>("linear.x.max_velocity", 0.0);
auto_declare<double>("linear.x.min_velocity", 0.0);
auto_declare<double>("linear.x.max_acceleration", 0.0);
auto_declare<double>("linear.x.min_acceleration", 0.0);
auto_declare<double>("linear.x.max_jerk", 0.0);
auto_declare<double>("linear.x.min_jerk", 0.0);
auto_declare<bool>("linear.y.has_velocity_limits", false);
auto_declare<bool>("linear.y.has_acceleration_limits", false);
auto_declare<bool>("linear.y.has_jerk_limits", false);
auto_declare<double>("linear.y.max_velocity", 0.0);
auto_declare<double>("linear.y.min_velocity", 0.0);
auto_declare<double>("linear.y.max_acceleration", 0.0);
auto_declare<double>("linear.y.min_acceleration", 0.0);
auto_declare<double>("linear.y.max_jerk", 0.0);
auto_declare<double>("linear.y.min_jerk", 0.0);
auto_declare<bool>("angular.z.has_velocity_limits", false);
auto_declare<bool>("angular.z.has_acceleration_limits", false);
auto_declare<bool>("angular.z.has_jerk_limits", false);
auto_declare<double>("angular.z.max_velocity", 0.0);
auto_declare<double>("angular.z.min_velocity", 0.0);
auto_declare<double>("angular.z.max_acceleration", 0.0);
auto_declare<double>("angular.z.min_acceleration", 0.0);
auto_declare<double>("angular.z.max_jerk", 0.0);
auto_declare<double>("angular.z.min_jerk", 0.0);
}
catch (const std::exception &e)
{
fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what());
return controller_interface::CallbackReturn::ERROR;
}
return controller_interface::CallbackReturn::SUCCESS;
}
InterfaceConfiguration SwerveController::command_interface_configuration() const
{
std::vector<std::string> conf_names;
conf_names.push_back(front_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(front_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(front_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(front_right_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_right_axle_joint_name_ + "/" + HW_IF_POSITION);
return {interface_configuration_type::INDIVIDUAL, conf_names};
}
InterfaceConfiguration SwerveController::state_interface_configuration() const
{
std::vector<std::string> conf_names;
conf_names.push_back(front_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(front_right_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_right_axle_joint_name_ + "/" + HW_IF_POSITION);
return {interface_configuration_type::INDIVIDUAL, conf_names};
}
controller_interface::return_type SwerveController::update(
const rclcpp::Time &time, const rclcpp::Duration & period)
{
auto logger = get_node()->get_logger();
auto clk = * get_node()->get_clock();
if (get_state().id() == State::PRIMARY_STATE_INACTIVE)
{
if (!is_halted)
{
halt();
is_halted = true;
}
return controller_interface::return_type::OK;
}
const auto current_time = time;
std::shared_ptr<Twist> last_command_msg;
received_velocity_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(logger, "Velocity message received was a nullptr.");
return controller_interface::return_type::ERROR;
}
// const auto age_of_last_command = current_time - last_command_msg->header.stamp;
// // Brake if cmd_vel has timeout, override the stored command
// if (age_of_last_command > cmd_vel_timeout_milliseconds_)
// {
// halt();
// }
// INPUTS
Twist command = *last_command_msg;
auto & last_command = previous_commands_.back().twist;
auto & second_to_last_command = previous_commands_.front().twist;
double &linear_x_velocity_comand = command.twist.linear.x;
double &linear_y_velocity_comand = command.twist.linear.y;
double &angular_velocity_comand = command.twist.angular.z;
double original_linear_x_velocity_comand = linear_x_velocity_comand;
double original_linear_y_velocity_comand = linear_y_velocity_comand;
double original_angular_velocity_comand = angular_velocity_comand;
// Limits
limiter_linear_X_.limit(linear_x_velocity_comand, last_command.linear.x, second_to_last_command.linear.x, period.seconds());
limiter_linear_Y_.limit(linear_y_velocity_comand, last_command.linear.y, second_to_last_command.linear.y, period.seconds());
limiter_angular_Z_.limit(angular_velocity_comand, last_command.angular.z, second_to_last_command.angular.z, period.seconds());
previous_commands_.pop();
previous_commands_.emplace(command);
if (linear_x_velocity_comand != original_linear_x_velocity_comand) {
RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Linear X %f -> %f", original_linear_x_velocity_comand, linear_x_velocity_comand);
}
if (linear_y_velocity_comand != original_linear_y_velocity_comand) {
RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Linear Y %f -> %f", original_linear_y_velocity_comand, linear_y_velocity_comand);
}
if (angular_velocity_comand != original_angular_velocity_comand) {
RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Angular Z %f -> %f", original_angular_velocity_comand, angular_velocity_comand);
}
double x_offset = wheel_params_.x_offset;
double radius = wheel_params_.radius;
// get current wheel positions
const double front_left_current_pos = front_left_axle_command_handle_->get_position();
const double front_right_current_pos = front_right_axle_command_handle_->get_position();
const double rear_left_current_pos = rear_left_axle_command_handle_->get_position();
const double rear_right_current_pos = rear_right_axle_command_handle_->get_position();
// Compute Wheel Velocities and Positions
const double a = (linear_y_velocity_comand * -1.0) - angular_velocity_comand * x_offset / 2.0;
const double b = (linear_y_velocity_comand * -1.0) + angular_velocity_comand * x_offset / 2.0;
const double c = linear_x_velocity_comand - angular_velocity_comand * x_offset / 2.0;
const double d = linear_x_velocity_comand + angular_velocity_comand * x_offset / 2.0;
double front_left_velocity = sqrt(pow(b, 2) + pow(d, 2)) / radius;
double front_right_velocity = sqrt(pow(b, 2) + pow(c, 2)) / radius;
double rear_left_velocity = sqrt(pow(a, 2) + pow(d, 2)) / radius;
double rear_right_velocity = sqrt(pow(a, 2) + pow(c, 2)) / radius;
// Normalize wheel velocities if any are greater than max
double velMax = std::max({front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity});
if (velMax > max_wheel_angular_velocity_)
{
front_left_velocity = front_left_velocity/velMax * max_wheel_angular_velocity_;
front_right_velocity = front_right_velocity/velMax * max_wheel_angular_velocity_;
rear_left_velocity = rear_left_velocity/velMax * max_wheel_angular_velocity_;
rear_right_velocity = rear_right_velocity/velMax * max_wheel_angular_velocity_;
}
double front_left_position;
double front_right_position ;
double rear_left_position;
double rear_right_position;
// Make position current if no movement is given
if (std::abs(linear_x_velocity_comand) <= 0.1 && std::abs(linear_y_velocity_comand) <= 0.1 && std::abs(angular_velocity_comand) <= 0.1)
{
front_left_position = front_left_current_pos;
front_right_position = front_right_current_pos;
rear_left_position = rear_left_current_pos;
rear_right_position = rear_right_current_pos;
} else {
front_left_position = atan2(b, d);
front_right_position = atan2(b, c);
rear_left_position = atan2(a, d);
rear_right_position = atan2(a, c);
// Optimization
optimize(front_left_position, front_left_current_pos, front_left_velocity);
optimize(front_right_position, front_right_current_pos, front_right_velocity);
optimize(rear_left_position, rear_left_current_pos, rear_left_velocity);
optimize(rear_right_position, rear_right_current_pos, rear_right_velocity);
}
// Old Limit Wheel Velocity
// front_left_velocity=limiter_wheel_.limit(front_left_velocity,last_wheel_commands[0], second_last_wheel_commands[0],0.1);
// front_right_velocity=limiter_wheel_.limit(front_right_velocity,last_wheel_commands[1], second_last_wheel_commands[1],0.1);
// rear_left_velocity=limiter_wheel_.limit(rear_left_velocity,last_wheel_commands[2], second_last_wheel_commands[2],0.1);
// rear_right_velocity=limiter_wheel_.limit(rear_right_velocity,last_wheel_commands[3], second_last_wheel_commands[3],0.1);
// second_last_wheel_commands= last_wheel_commands;
front_left_wheel_command_handle_->set_velocity(front_left_velocity);
front_right_wheel_command_handle_->set_velocity(front_right_velocity);
rear_left_wheel_command_handle_->set_velocity(rear_left_velocity);
rear_right_wheel_command_handle_->set_velocity(rear_right_velocity);
front_left_axle_command_handle_->set_position(front_left_position);
front_right_axle_command_handle_->set_position(front_right_position);
rear_left_axle_command_handle_->set_position(rear_left_position);
rear_right_axle_command_handle_->set_position(rear_right_position);
// Time update
const auto update_dt = current_time - previous_update_timestamp_;
previous_update_timestamp_ = current_time;
return controller_interface::return_type::OK;
}
controller_interface::CallbackReturn SwerveController::on_configure(const rclcpp_lifecycle::State &)
{
auto logger = get_node()->get_logger();
limiter_linear_X_ = SpeedLimiter(
get_node()->get_parameter("linear.x.has_velocity_limits").as_bool(),
get_node()->get_parameter("linear.x.has_acceleration_limits").as_bool(),
get_node()->get_parameter("linear.x.has_jerk_limits").as_bool(),
get_node()->get_parameter("linear.x.min_velocity").as_double(),
get_node()->get_parameter("linear.x.max_velocity").as_double(),
get_node()->get_parameter("linear.x.min_acceleration").as_double(),
get_node()->get_parameter("linear.x.max_acceleration").as_double(),
get_node()->get_parameter("linear.x.min_jerk").as_double(),
get_node()->get_parameter("linear.x.max_jerk").as_double());
RCLCPP_WARN(logger, "Linear X Limiter Velocity Limits: %f, %f", limiter_linear_X_.min_velocity_, limiter_linear_X_.max_velocity_);
RCLCPP_WARN(logger, "Linear X Limiter Acceleration Limits: %f, %f", limiter_linear_X_.min_acceleration_, limiter_linear_X_.max_acceleration_);
RCLCPP_WARN(logger, "Linear X Limiter Jert Limits: %f, %f", limiter_linear_X_.min_jerk_, limiter_linear_X_.max_jerk_);
limiter_linear_Y_ = SpeedLimiter(
get_node()->get_parameter("linear.y.has_velocity_limits").as_bool(),
get_node()->get_parameter("linear.y.has_acceleration_limits").as_bool(),
get_node()->get_parameter("linear.y.has_jerk_limits").as_bool(),
get_node()->get_parameter("linear.y.min_velocity").as_double(),
get_node()->get_parameter("linear.y.max_velocity").as_double(),
get_node()->get_parameter("linear.y.min_acceleration").as_double(),
get_node()->get_parameter("linear.y.max_acceleration").as_double(),
get_node()->get_parameter("linear.y.min_jerk").as_double(),
get_node()->get_parameter("linear.y.max_jerk").as_double());
RCLCPP_WARN(logger, "Linear Y Limiter Velocity Limits: %f, %f", limiter_linear_Y_.min_velocity_, limiter_linear_Y_.max_velocity_);
RCLCPP_WARN(logger, "Linear Y Limiter Acceleration Limits: %f, %f", limiter_linear_Y_.min_acceleration_, limiter_linear_Y_.max_acceleration_);
RCLCPP_WARN(logger, "Linear Y Limiter Jert Limits: %f, %f", limiter_linear_Y_.min_jerk_, limiter_linear_Y_.max_jerk_);
limiter_angular_Z_ = SpeedLimiter(
get_node()->get_parameter("angular.z.has_velocity_limits").as_bool(),
get_node()->get_parameter("angular.z.has_acceleration_limits").as_bool(),
get_node()->get_parameter("angular.z.has_jerk_limits").as_bool(),
get_node()->get_parameter("angular.z.min_velocity").as_double(),
get_node()->get_parameter("angular.z.max_velocity").as_double(),
get_node()->get_parameter("angular.z.min_acceleration").as_double(),
get_node()->get_parameter("angular.z.max_acceleration").as_double(),
get_node()->get_parameter("angular.z.min_jerk").as_double(),
get_node()->get_parameter("angular.z.max_jerk").as_double());
RCLCPP_WARN(logger, "Angular Z Limiter Velocity Limits: %f, %f", limiter_angular_Z_.min_velocity_, limiter_angular_Z_.max_velocity_);
RCLCPP_WARN(logger, "Angular Z Limiter Acceleration Limits: %f, %f", limiter_angular_Z_.min_acceleration_, limiter_angular_Z_.max_acceleration_);
RCLCPP_WARN(logger, "Angular Z Limiter Jert Limits: %f, %f", limiter_angular_Z_.min_jerk_, limiter_angular_Z_.max_jerk_);
// Get Parameters
front_left_wheel_joint_name_ = get_node()->get_parameter("front_left_wheel_joint").as_string();
front_right_wheel_joint_name_ = get_node()->get_parameter("front_right_wheel_joint").as_string();
rear_left_wheel_joint_name_ = get_node()->get_parameter("rear_left_wheel_joint").as_string();
rear_right_wheel_joint_name_ = get_node()->get_parameter("rear_right_wheel_joint").as_string();
front_left_axle_joint_name_ = get_node()->get_parameter("front_left_axle_joint").as_string();
front_right_axle_joint_name_ = get_node()->get_parameter("front_right_axle_joint").as_string();
rear_left_axle_joint_name_ = get_node()->get_parameter("rear_left_axle_joint").as_string();
rear_right_axle_joint_name_ = get_node()->get_parameter("rear_right_axle_joint").as_string();
if (front_left_wheel_joint_name_.empty())
{
RCLCPP_ERROR(logger, "front_left_wheel_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (front_right_wheel_joint_name_.empty())
{
RCLCPP_ERROR(logger, "front_right_wheel_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (rear_left_wheel_joint_name_.empty())
{
RCLCPP_ERROR(logger, "rear_left_wheel_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (rear_right_wheel_joint_name_.empty())
{
RCLCPP_ERROR(logger, "rear_right_wheel_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (front_left_axle_joint_name_.empty())
{
RCLCPP_ERROR(logger, "front_left_axle_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (front_right_axle_joint_name_.empty())
{
RCLCPP_ERROR(logger, "front_right_axle_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (rear_left_axle_joint_name_.empty())
{
RCLCPP_ERROR(logger, "rear_left_axle_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
if (rear_right_axle_joint_name_.empty())
{
RCLCPP_ERROR(logger, "rear_right_axle_joint_name is not set");
return controller_interface::CallbackReturn::ERROR;
}
wheel_params_.x_offset = get_node()->get_parameter("chassis_length_meters").as_double();
wheel_params_.y_offset = get_node()->get_parameter("chassis_width_meters").as_double();
wheel_params_.radius = get_node()->get_parameter("wheel_radius_meters").as_double();
max_wheel_angular_velocity_ = get_node()->get_parameter("max_wheel_angular_velocity").as_double();
cmd_vel_timeout_milliseconds_ = std::chrono::milliseconds{
static_cast<int>(get_node()->get_parameter("cmd_vel_timeout_seconds").as_double() * 1000.0)};
use_stamped_vel_ = get_node()->get_parameter("use_stamped_vel").as_bool();
// Run reset to make sure everything is initialized correctly
if (!reset())
{
return controller_interface::CallbackReturn::ERROR;
}
const Twist empty_twist;
received_velocity_msg_ptr_.set(std::make_shared<Twist>(empty_twist));
previous_commands_.emplace(empty_twist);
previous_commands_.emplace(empty_twist);
// initialize command subscriber
if (use_stamped_vel_)
{
velocity_command_subscriber_ = get_node()->create_subscription<Twist>(
DEFAULT_COMMAND_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<Twist> msg) -> void
{
if (!subscriber_is_active_)
{
RCLCPP_WARN(get_node()->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
if ((msg->header.stamp.sec == 0) && (msg->header.stamp.nanosec == 0))
{
RCLCPP_WARN_ONCE(
get_node()->get_logger(),
"Received TwistStamped with zero timestamp, setting it to current "
"time, this message will only be shown once");
msg->header.stamp = get_node()->get_clock()->now();
}
received_velocity_msg_ptr_.set(std::move(msg));
});
}
else
{
velocity_command_unstamped_subscriber_ = get_node()->create_subscription<geometry_msgs::msg::Twist>(
DEFAULT_COMMAND_UNSTAMPED_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<geometry_msgs::msg::Twist> msg) -> void
{
if (!subscriber_is_active_)
{
RCLCPP_WARN(get_node()->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
// Write fake header in the stored stamped command
std::shared_ptr<Twist> twist_stamped;
received_velocity_msg_ptr_.get(twist_stamped);
twist_stamped->twist = *msg;
twist_stamped->header.stamp = get_node()->get_clock()->now();
});
}
previous_update_timestamp_ = get_node()->get_clock()->now();
return controller_interface::CallbackReturn::SUCCESS;
}
controller_interface::CallbackReturn SwerveController::on_activate(const rclcpp_lifecycle::State &)
{
front_left_wheel_command_handle_ = get_wheel(front_left_wheel_joint_name_);
front_right_wheel_command_handle_ = get_wheel(front_right_wheel_joint_name_);
rear_left_wheel_command_handle_ = get_wheel(rear_left_wheel_joint_name_);
rear_right_wheel_command_handle_ = get_wheel(rear_right_wheel_joint_name_);
front_left_axle_command_handle_ = get_axle(front_left_axle_joint_name_);
front_right_axle_command_handle_ = get_axle(front_right_axle_joint_name_);
rear_left_axle_command_handle_ = get_axle(rear_left_axle_joint_name_);
rear_right_axle_command_handle_ = get_axle(rear_right_axle_joint_name_);
if (!front_left_wheel_command_handle_ || !front_right_wheel_command_handle_ || !rear_left_wheel_command_handle_ || !rear_right_wheel_command_handle_ || !front_left_axle_command_handle_ || !front_right_axle_command_handle_ || !rear_left_axle_command_handle_ || !rear_right_axle_command_handle_)
{
return controller_interface::CallbackReturn::ERROR;
}
is_halted = false;
subscriber_is_active_ = true;
RCLCPP_DEBUG(get_node()->get_logger(), "Subscriber and publisher are now active.");
return controller_interface::CallbackReturn::SUCCESS;
}
controller_interface::CallbackReturn SwerveController::on_deactivate(const rclcpp_lifecycle::State &)
{
subscriber_is_active_ = false;
return controller_interface::CallbackReturn::SUCCESS;
}
controller_interface::CallbackReturn SwerveController::on_cleanup(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return controller_interface::CallbackReturn::ERROR;
}
received_velocity_msg_ptr_.set(std::make_shared<Twist>());
return controller_interface::CallbackReturn::SUCCESS;
}
controller_interface::CallbackReturn SwerveController::on_error(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return controller_interface::CallbackReturn::ERROR;
}
return controller_interface::CallbackReturn::SUCCESS;
}
bool SwerveController::reset()
{
subscriber_is_active_ = false;
velocity_command_subscriber_.reset();
velocity_command_unstamped_subscriber_.reset();
std::queue<Twist> empty;
std::swap(previous_commands_, empty);
received_velocity_msg_ptr_.set(nullptr);
is_halted = false;
return true;
}
controller_interface::CallbackReturn SwerveController::on_shutdown(const rclcpp_lifecycle::State &)
{
return controller_interface::CallbackReturn::SUCCESS;
}
void SwerveController::halt()
{
front_left_wheel_command_handle_->set_velocity(0.0);
front_right_wheel_command_handle_->set_velocity(0.0);
rear_left_wheel_command_handle_->set_velocity(0.0);
rear_right_wheel_command_handle_->set_velocity(0.0);
auto logger = get_node()->get_logger();
RCLCPP_WARN(logger, "-----HALT CALLED : STOPPING ALL MOTORS-----");
}
std::shared_ptr<Wheel> SwerveController::get_wheel(const std::string &wheel_name)
{
auto logger = get_node()->get_logger();
if (wheel_name.empty())
{
RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified.");
return nullptr;
}
// Get Command Handle for joint
const auto command_handle = std::find_if(
command_interfaces_.begin(), command_interfaces_.end(),
[&wheel_name](const auto &interface)
{
return interface.get_name() == wheel_name + "/velocity" &&
interface.get_interface_name() == HW_IF_VELOCITY;
});
if (command_handle == command_interfaces_.end())
{
RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", wheel_name.c_str());
return nullptr;
}
auto cmd_interface_name = command_handle->get_name();
RCLCPP_INFO(logger, "FOUND! wheel cmd interface %s", cmd_interface_name.c_str());
return std::make_shared<Wheel>(std::ref(*command_handle), wheel_name);
}
std::shared_ptr<Axle> SwerveController::get_axle(const std::string &axle_name)
{
auto logger = get_node()->get_logger();
if (axle_name.empty())
{
RCLCPP_ERROR(logger, "Axle joint name not given. Make sure all joints are specified.");
return nullptr;
}
// Get Command Handle for joint
const auto command_handle_position = std::find_if(
command_interfaces_.begin(), command_interfaces_.end(),
[&axle_name](const auto &interface)
{
return interface.get_name() == axle_name + "/position" &&
interface.get_interface_name() == HW_IF_POSITION;
});
const auto state_handle = std::find_if(
state_interfaces_.cbegin(), state_interfaces_.cend(),
[&axle_name](const auto &interface)
{
return interface.get_name() == axle_name + "/position" &&
interface.get_interface_name() == HW_IF_POSITION;
});
if (command_handle_position == command_interfaces_.end())
{
RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", axle_name.c_str());
return nullptr;
}
if (state_handle == state_interfaces_.cend())
{
RCLCPP_ERROR(logger, "Unable to obtain joint state handle for %s", axle_name.c_str());
return nullptr;
}
auto cmd_interface_name = command_handle_position->get_name();
RCLCPP_INFO(logger, "FOUND! axle cmd interface %s", cmd_interface_name.c_str());
return std::make_shared<Axle>(std::ref(*command_handle_position), std::ref(*state_handle), axle_name);
}
} // namespace swerve_controller
#include "class_loader/register_macro.hpp"
CLASS_LOADER_REGISTER_CLASS(
swerve_controller::SwerveController, controller_interface::ControllerInterface)
| 28,957 | C++ | 43.896124 | 299 | 0.668267 |
RoboEagles4828/edna2023/src/swerve_controller/include/swerve_controller/swerve_controller.hpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#ifndef SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_
#define SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_
#include <chrono>
#include <cmath>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "controller_interface/controller_interface.hpp"
#include "swerve_controller/visibility_control.h"
#include "swerve_controller/speed_limiter.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "geometry_msgs/msg/twist_stamped.hpp"
#include "hardware_interface/handle.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include "hardware_interface/loaned_command_interface.hpp"
namespace swerve_controller
{
class Wheel {
public:
Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name);
void set_velocity(double velocity);
private:
std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity_;
std::string name;
};
class Axle {
public:
Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> command_position_,std::reference_wrapper< const hardware_interface::LoanedStateInterface> state_position_,
std::string name);
void set_position(double command_position_);
double get_position (void);
private:
std::reference_wrapper<hardware_interface::LoanedCommandInterface> command_position_;
std::reference_wrapper<const hardware_interface::LoanedStateInterface> state_position_;
std::string name;
};
class SwerveController : public controller_interface::ControllerInterface
{
using Twist = geometry_msgs::msg::TwistStamped;
public:
SWERVE_CONTROLLER_PUBLIC
SwerveController();
SWERVE_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration command_interface_configuration() const override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration state_interface_configuration() const override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::return_type update(
const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_init() override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_configure(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_cleanup(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_error(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::CallbackReturn on_shutdown(const rclcpp_lifecycle::State & previous_state) override;
protected:
std::shared_ptr<Wheel> get_wheel(const std::string & wheel_name);
std::shared_ptr<Axle> get_axle(const std::string & axle_name);
std::shared_ptr<Wheel> front_left_wheel_command_handle_;
std::shared_ptr<Wheel> front_right_wheel_command_handle_;
std::shared_ptr<Wheel> rear_left_wheel_command_handle_;
std::shared_ptr<Wheel> rear_right_wheel_command_handle_;
std::shared_ptr<Axle> front_left_axle_command_handle_;
std::shared_ptr<Axle> front_right_axle_command_handle_;
std::shared_ptr<Axle> rear_left_axle_command_handle_;
std::shared_ptr<Axle> rear_right_axle_command_handle_;
std::string front_left_wheel_joint_name_;
std::string front_right_wheel_joint_name_;
std::string rear_left_wheel_joint_name_;
std::string rear_right_wheel_joint_name_;
std::string front_left_axle_joint_name_;
std::string front_right_axle_joint_name_;
std::string rear_left_axle_joint_name_;
std::string rear_right_axle_joint_name_;
// std::vector<double> last_wheel_commands{0.0,0.0,0.0,0.0};
// std::vector<double> second_last_wheel_commands{0.0,0.0,0.0,0.0};
SpeedLimiter limiter_linear_X_;
SpeedLimiter limiter_linear_Y_;
SpeedLimiter limiter_angular_Z_;
std::queue<Twist> previous_commands_;
struct WheelParams
{
double x_offset = 0.0; // Chassis Center to Axle Center
double y_offset = 0.0; // Axle Center to Wheel Center
double radius = 0.0; // Assumed to be the same for all wheels
} wheel_params_;
// Timeout to consider cmd_vel commands old
std::chrono::milliseconds cmd_vel_timeout_milliseconds_{500};
rclcpp::Time previous_update_timestamp_{0};
// Topic Subscription
bool subscriber_is_active_ = false;
rclcpp::Subscription<Twist>::SharedPtr velocity_command_subscriber_ = nullptr;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr
velocity_command_unstamped_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<Twist>> received_velocity_msg_ptr_{nullptr};
double max_wheel_angular_velocity_ = 0.0;
bool is_halted = false;
bool use_stamped_vel_ = true;
bool reset();
void halt();
};
} // namespace swerve_controllerS
#endif // Swerve_CONTROLLER__SWERVE_CONTROLLER_HPP_
| 5,964 | C++ | 36.049689 | 182 | 0.753521 |
RoboEagles4828/edna2023/src/swerve_controller/include/swerve_controller/visibility_control.h | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
#define SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define SWERVE_CONTROLLER_EXPORT __attribute__((dllexport))
#define SWERVE_CONTROLLER_IMPORT __attribute__((dllimport))
#else
#define SWERVE_CONTROLLER_EXPORT __declspec(dllexport)
#define SWERVE_CONTROLLER_IMPORT __declspec(dllimport)
#endif
#ifdef SWERVE_CONTROLLER_BUILDING_DLL
#define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_EXPORT
#else
#define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_IMPORT
#endif
#define SWERVE_CONTROLLER_PUBLIC_TYPE SWERVE_CONTROLLER_PUBLIC
#define SWERVE_CONTROLLER_LOCAL
#else
#define SWERVE_CONTROLLER_EXPORT __attribute__((visibility("default")))
#define SWERVE_CONTROLLER_IMPORT
#if __GNUC__ >= 4
#define SWERVE_CONTROLLER_PUBLIC __attribute__((visibility("default")))
#define SWERVE_CONTROLLER_LOCAL __attribute__((visibility("hidden")))
#else
#define SWERVE_CONTROLLER_PUBLIC
#define SWERVE_CONTROLLER_LOCAL
#endif
#define SWERVE_CONTROLLER_PUBLIC_TYPE
#endif
#endif // SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
| 2,229 | C | 38.122806 | 79 | 0.767609 |
RoboEagles4828/edna2023/src/swerve_controller/include/swerve_controller/speed_limiter.hpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Enrique Fernández
*/
#ifndef SWERVE_CONTROLLER__SPEED_LIMITER_HPP_
#define SWERVE_CONTROLLER__SPEED_LIMITER_HPP_
#include <cmath>
namespace swerve_controller
{
class SpeedLimiter
{
public:
/**
* \brief Constructor
* \param [in] has_velocity_limits if true, applies velocity limits
* \param [in] has_acceleration_limits if true, applies acceleration limits
* \param [in] has_jerk_limits if true, applies jerk limits
* \param [in] min_velocity Minimum velocity [m/s], usually <= 0
* \param [in] max_velocity Maximum velocity [m/s], usually >= 0
* \param [in] min_acceleration Minimum acceleration [m/s^2], usually <= 0
* \param [in] max_acceleration Maximum acceleration [m/s^2], usually >= 0
* \param [in] min_jerk Minimum jerk [m/s^3], usually <= 0
* \param [in] max_jerk Maximum jerk [m/s^3], usually >= 0
*/
SpeedLimiter(
bool has_velocity_limits = false, bool has_acceleration_limits = false,
bool has_jerk_limits = false, double min_velocity = NAN, double max_velocity = NAN,
double min_acceleration = NAN, double max_acceleration = NAN, double min_jerk = NAN,
double max_jerk = NAN);
/**
* \brief Limit the velocity and acceleration
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity to v [m/s]
* \param [in] v1 Previous velocity to v0 [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
*/
double limit(double & v, double v0, double v1, double dt);
/**
* \brief Limit the velocity
* \param [in, out] v Velocity [m/s]
* \return Limiting factor (1.0 if none)
*/
double limit_velocity(double & v);
/**
* \brief Limit the acceleration
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
*/
double limit_acceleration(double & v, double v0, double dt);
/**
* \brief Limit the jerk
* \param [in, out] v Velocity [m/s]
* \param [in] v0 Previous velocity to v [m/s]
* \param [in] v1 Previous velocity to v0 [m/s]
* \param [in] dt Time step [s]
* \return Limiting factor (1.0 if none)
* \see http://en.wikipedia.org/wiki/Jerk_%28physics%29#Motion_control
*/
double limit_jerk(double & v, double v0, double v1, double dt);
// Enable/Disable velocity/acceleration/jerk limits:
bool has_velocity_limits_;
bool has_acceleration_limits_;
bool has_jerk_limits_;
// Velocity limits:
double min_velocity_;
double max_velocity_;
// Acceleration limits:
double min_acceleration_;
double max_acceleration_;
// Jerk limits:
double min_jerk_;
double max_jerk_;
};
} // namespace swerve_controller
#endif // SWERVE_CONTROLLER__SPEED_LIMITER_HPP_
| 3,423 | C++ | 31.609524 | 88 | 0.660532 |
RoboEagles4828/edna2023/src/edna_bringup/launch/teleopLayer.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import RegisterEventHandler, DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, Command, PythonExpression
from launch_ros.actions import Node
from launch.conditions import IfCondition
# Easy use of namespace since args are not strings
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
namespace = LaunchConfiguration('namespace')
joystick_file = LaunchConfiguration('joystick_file')
enable_joy = LaunchConfiguration('enable_joy')
frc_auton_reader = Node(
package = "frc_auton",
namespace=namespace,
executable= "reader",
name = "frc_auton_node",
parameters=[{
"auton_name": "24",
}]
)
frc_teleop_writer = Node(
package = "frc_auton",
namespace=namespace,
executable= "writer",
name = "frc_auton_node",
parameters=[{
"record_auton": False,
"record_without_fms": False,
}]
)
joy = Node(
package='joy',
namespace=namespace,
executable='joy_node',
name='joy_node',
condition=IfCondition(enable_joy),
parameters=[{
'use_sim_time': use_sim_time,
'deadzone': 0.15,
}])
controller_prefix = 'swerve_controller'
joy_teleop_twist = Node(
package='teleop_twist_joy',
namespace=namespace,
executable='teleop_node',
name='teleop_twist_joy_node',
parameters=[joystick_file, {'use_sim_time': use_sim_time}],
remappings={
("cmd_vel", f"{controller_prefix}/cmd_vel_unstamped"),
("odom", "zed/odom")
},
)
joint_trajectory_teleop = Node(
package='joint_trajectory_teleop',
namespace=namespace,
executable='joint_trajectory_teleop',
name='joint_trajectory_teleop',
parameters=[{'use_sim_time': use_sim_time}]
)
# Launch!
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
DeclareLaunchArgument(
'namespace',
default_value='default',
description='The namespace of nodes and links'),
DeclareLaunchArgument(
'joystick_file',
default_value='',
description='The file with joystick parameters'),
DeclareLaunchArgument(
'enable_joy',
default_value='true',
description='Enables joystick teleop'),
joy,
joy_teleop_twist,
joint_trajectory_teleop,
frc_auton_reader,
# frc_teleop_writer
]) | 3,004 | Python | 32.021978 | 93 | 0.58988 |
RoboEagles4828/edna2023/src/edna_bringup/launch/rviz.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'description.rviz')
common = { 'use_sim_time': 'false', 'namespace': NAMESPACE }
control_launch_args = common | {
'use_ros2_control': 'false',
'load_controllers': 'false'
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_joint_state_publisher': 'true',
'rviz_file': rviz_file
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
# Launch!
return LaunchDescription([
control_layer,
debug_layer,
]) | 1,469 | Python | 34.853658 | 91 | 0.647379 |
RoboEagles4828/edna2023/src/edna_bringup/launch/test_hw.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml')
rviz_file = os.path.join(bringup_path, 'config', 'view.rviz')
common = { 'use_sim_time': 'false', 'namespace': NAMESPACE }
control_launch_args = common | {
'use_ros2_control': 'true',
'hardware_plugin': 'swerve_hardware/TestDriveHardware',
}
teleoplaunch_args = common | {
'joystick_file': joystick_file,
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'true',
'rviz_file': rviz_file
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
teleop_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','teleopLayer.launch.py'
)]), launch_arguments=teleoplaunch_args.items())
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer])
# Launch!
return LaunchDescription([
control_layer,
teleop_layer,
delay_debug_layer,
])
| 1,956 | Python | 35.924528 | 91 | 0.643149 |
RoboEagles4828/edna2023/src/edna_bringup/launch/zed2i.launch.py | import os
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
from ament_index_python.packages import get_package_share_directory
from launch_ros.actions import Node
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
# Camera model (force value)
camera_model = 'zed2i'
config_common_path = os.path.join(
get_package_share_directory('zed_wrapper'),
'config',
'common.yaml'
)
config_camera_path = os.path.join(
get_package_share_directory('zed_wrapper'),
'config',
camera_model + '.yaml'
)
# ZED Wrapper node
zed_wrapper_node = Node(
package='zed_wrapper',
namespace=str(NAMESPACE),
executable='zed_wrapper',
name='zed',
output='screen',
#prefix=['xterm -e valgrind --tools=callgrind'],
#prefix=['xterm -e gdb -ex run --args'],
parameters=[
# YAML files
config_common_path, # Common parameters
config_camera_path, # Camera related parameters
# Overriding
{
'general.camera_name': f'{NAMESPACE}/{camera_model}',
'general.camera_model': camera_model,
'general.svo_file': 'live',
'pos_tracking.base_frame': f'{NAMESPACE}/base_link',
'pos_tracking.map_frame': f'{NAMESPACE}/map',
'pos_tracking.odometry_frame': f'{NAMESPACE}/odom',
'general.zed_id': 0,
'general.serial_number': 0,
'pos_tracking.publish_tf': True,
'pos_tracking.publish_map_tf': True,
'pos_tracking.publish_imu_tf': True
}
]
)
delay_zed_wrapper = TimerAction(period=5.0, actions=[zed_wrapper_node])
# Define LaunchDescription variable
ld = LaunchDescription()
# Add nodes to LaunchDescription
ld.add_action(delay_zed_wrapper)
return ld
| 2,150 | Python | 30.632352 | 91 | 0.597209 |
RoboEagles4828/edna2023/src/edna_bringup/launch/controlLayer.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import RegisterEventHandler, DeclareLaunchArgument, SetEnvironmentVariable, LogInfo, EmitEvent
from launch.substitutions import LaunchConfiguration, Command, PythonExpression, TextSubstitution
from launch.event_handlers import OnProcessExit
from launch_ros.actions import Node
from launch.conditions import IfCondition
from launch.events import Shutdown
# Easy use of namespace since args are not strings
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
use_ros2_control = LaunchConfiguration('use_ros2_control')
load_controllers = LaunchConfiguration('load_controllers')
forward_command_controllers = LaunchConfiguration('forward_command_controller')
namespace = LaunchConfiguration('namespace')
hardware_plugin = LaunchConfiguration('hardware_plugin')
# Process the URDF file
description_pkg_path = os.path.join(get_package_share_directory('edna_description'))
xacro_file = os.path.join(description_pkg_path,'urdf', 'robots','edna.urdf.xacro')
edna_description_xml = Command(['xacro ', xacro_file, ' hw_interface_plugin:=', hardware_plugin])
# Get paths to other config files
bringup_pkg_path = os.path.join(get_package_share_directory('edna_bringup'))
controllers_file = os.path.join(bringup_pkg_path, 'config', 'controllers.yaml')
# Create a robot_state_publisher node
node_robot_state_publisher = Node(
package='robot_state_publisher',
namespace=namespace,
executable='robot_state_publisher',
output='screen',
parameters=[{
'robot_description': edna_description_xml,
'use_sim_time': use_sim_time,
'publish_frequency': 50.0,
'frame_prefix': [namespace, '/']
}],
)
# Starts ROS2 Control
control_node = Node(
package="controller_manager",
namespace=namespace,
executable="ros2_control_node",
condition=IfCondition(use_ros2_control),
parameters=[{
"robot_description": edna_description_xml,
"use_sim_time": use_sim_time,
}, controllers_file],
output="both",
)
control_node_require = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=control_node,
on_exit=[
LogInfo(msg="Listener exited; tearing down entire system."),
EmitEvent(event=Shutdown())
],
)
)
# Starts ROS2 Control Joint State Broadcaster
joint_state_broadcaster_spawner = Node(
package="controller_manager",
namespace=namespace,
executable="spawner",
arguments=["joint_state_broadcaster", "-c", ['/', namespace, "/controller_manager"]],
condition=IfCondition(use_ros2_control),
)
joint_trajectory_controller_spawner = Node(
package="controller_manager",
namespace=namespace,
executable="spawner",
arguments=["joint_trajectory_controller", "-c", ['/', namespace, "/controller_manager"]],
parameters=[{
"robot_description": edna_description_xml,
"use_sim_time": use_sim_time,
}, controllers_file],
condition=IfCondition(use_ros2_control and load_controllers),
)
#Starts ROS2 Control Swerve Drive Controller
swerve_drive_controller_spawner = Node(
package="controller_manager",
namespace=namespace,
executable="spawner",
arguments=["swerve_controller", "-c", ['/', namespace, "/controller_manager"]],
condition=IfCondition(use_ros2_control and load_controllers),
)
swerve_drive_controller_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[swerve_drive_controller_spawner],
)
)
# Starts ROS2 Control Forward Controller
forward_position_controller_spawner = Node(
package="controller_manager",
namespace=namespace,
executable="spawner",
arguments=["forward_position_controller", "-c", ['/', namespace, "/controller_manager"]],
condition=IfCondition(use_ros2_control and forward_command_controllers),
)
forward_position_controller_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[forward_position_controller_spawner],
)
)
forward_velocity_controller_spawner = Node(
package="controller_manager",
namespace=namespace,
executable="spawner",
arguments=["forward_velocity_controller", "-c", ['/', namespace, "/controller_manager"]],
condition=IfCondition(use_ros2_control and forward_command_controllers),
)
forward_velocity_controller_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[forward_velocity_controller_spawner],
)
)
# Launch!
return LaunchDescription([
SetEnvironmentVariable('RCUTILS_COLORIZED_OUTPUT', '1'),
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
DeclareLaunchArgument(
'use_ros2_control',
default_value='true',
description='Use ros2_control if true'),
DeclareLaunchArgument(
'namespace',
default_value='default',
description='The namespace of nodes and links'),
DeclareLaunchArgument(
'hardware_plugin',
default_value='swerve_hardware/IsaacDriveHardware',
description='Which ros2 control hardware plugin to use'),
DeclareLaunchArgument(
'load_controllers',
default_value='true',
description='Enable or disable ros2 controllers but leave hardware interfaces'),
DeclareLaunchArgument(
'forward_command_controller',
default_value='false',
description='Forward commands for ros2 control'),
node_robot_state_publisher,
control_node,
joint_state_broadcaster_spawner,
joint_trajectory_controller_spawner,
swerve_drive_controller_delay,
forward_position_controller_delay,
forward_velocity_controller_delay,
control_node_require
]) | 6,682 | Python | 39.017964 | 114 | 0.652799 |
RoboEagles4828/edna2023/src/edna_bringup/launch/rtab.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
rtabmap_ros_path = get_package_share_directory("rtabmap_ros")
rtabmap_args = {
'rtabmap_args': '--delete_db_on_start',
'use_sim_time': use_sim_time,
'namespace': f'{NAMESPACE}_rtab',
# Frames
'frame_id': f'{NAMESPACE}/base_link',
'odom_frame_id': f'{NAMESPACE}/odom',
'map_frame_id': f'{NAMESPACE}/map',
# Topics
'rgb_topic': f'/{NAMESPACE}/left/rgb',
'camera_info_topic': f'/{NAMESPACE}/left/camera_info',
'depth_topic': f'/{NAMESPACE}/left/depth',
'imu_topic': f'/{NAMESPACE}/imu',
'odom_topic': f'/{NAMESPACE}/zed/odom',
'approx_sync': 'false',
'wait_imu_to_init': 'true',
'visual_odometry': 'false',
'publish_tf_odom': 'false',
'qos': '1',
'rviz': 'true',
}
rtab_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
rtabmap_ros_path,'launch','rtabmap.launch.py'
)]), launch_arguments=rtabmap_args.items())
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='true',
description='Use sim time if true'),
rtab_layer,
]) | 1,768 | Python | 34.379999 | 91 | 0.621041 |
RoboEagles4828/edna2023/src/edna_bringup/launch/isaac.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml')
rviz_file = os.path.join(bringup_path, 'config', 'view.rviz')
common = { 'use_sim_time': 'true', 'namespace': NAMESPACE }
control_launch_args = common | {
'use_ros2_control': 'true',
'hardware_plugin': 'swerve_hardware/IsaacDriveHardware',
}
teleoplaunch_args = common | {
'joystick_file': joystick_file,
}
debug_launch_args = common | {
'enable_rviz': 'false',
'enable_foxglove': 'false',
'rviz_file': rviz_file
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
teleop_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','teleopLayer.launch.py'
)]), launch_arguments=teleoplaunch_args.items())
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer])
# Launch!
return LaunchDescription([
control_layer,
teleop_layer,
delay_debug_layer,
])
| 1,958 | Python | 35.962263 | 91 | 0.643514 |
RoboEagles4828/edna2023/src/edna_bringup/launch/debugLayer.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch.substitutions import LaunchConfiguration, PythonExpression
from launch.event_handlers import OnProcessExit
from launch.actions import DeclareLaunchArgument, ExecuteProcess, RegisterEventHandler
from launch.conditions import IfCondition
import os
def generate_launch_description():
bringup_pkg_path = os.path.join(get_package_share_directory('edna_bringup'))
use_sim_time = LaunchConfiguration('use_sim_time')
namespace = LaunchConfiguration('namespace')
enable_rviz = LaunchConfiguration('enable_rviz')
enable_foxglove = LaunchConfiguration('enable_foxglove')
enable_debugger_gui = LaunchConfiguration('enable_debugger_gui')
enable_joint_state_publisher = LaunchConfiguration('enable_joint_state_publisher')
rviz_file = LaunchConfiguration('rviz_file')
foxglove = Node(
package='foxglove_bridge',
executable='foxglove_bridge',
namespace=namespace,
parameters=[{
'port': 8765,
'use_sim_time': use_sim_time
}],
condition=IfCondition(enable_foxglove)
)
parse_script = os.path.join(bringup_pkg_path, 'scripts', 'parseRviz.py')
parseRvizFile = ExecuteProcess(cmd=["python3", parse_script, rviz_file, namespace])
rviz2 = Node(
package='rviz2',
name='rviz2',
namespace=namespace,
executable='rviz2',
parameters=[{ 'use_sim_time': use_sim_time }],
output='screen',
arguments=[["-d"], [rviz_file]],
condition=IfCondition(enable_rviz)
)
rviz2_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=parseRvizFile,
on_exit=[rviz2],
)
)
debugger_gui = Node(
package='edna_debugger',
namespace=namespace,
executable='debugger',
name='debugger',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': 'true',
'source_list': ['joint_states']
}],
condition=IfCondition(enable_debugger_gui),
)
# Starts Joint State Publisher GUI for rviz (conflicts with edna_debugger)
joint_state_publisher_gui = Node (
package='joint_state_publisher_gui',
namespace=namespace,
executable='joint_state_publisher_gui',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': True,
}],
condition=IfCondition(enable_joint_state_publisher),
)
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use sim time if true'),
DeclareLaunchArgument(
'namespace',
default_value='default',
description='The namespace of nodes and links'),
DeclareLaunchArgument(
'enable_rviz',
default_value='true',
description='enables rviz'),
DeclareLaunchArgument(
'rviz_file',
default_value='',
description='The config file for rviz'),
DeclareLaunchArgument(
'enable_foxglove',
default_value='true',
description='enables foxglove bridge'),
DeclareLaunchArgument(
'enable_debugger_gui',
default_value='false',
description='enables the debugger gui tool'),
DeclareLaunchArgument(
'enable_joint_state_publisher',
default_value='false',
description='enables the joint state publisher tool'),
foxglove,
parseRvizFile,
rviz2_delay,
debugger_gui,
joint_state_publisher_gui,
]) | 3,908 | Python | 33.901785 | 87 | 0.620778 |
RoboEagles4828/edna2023/src/edna_bringup/launch/real-rviz.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'real.rviz')
common = {
'use_sim_time': 'false',
'namespace': 'real',
'forward_command_controller': 'false',
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_debugger_gui': 'true',
'rviz_file': rviz_file
}
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
# Launch!
return LaunchDescription([
debug_layer,
]) | 1,037 | Python | 31.437499 | 75 | 0.644166 |
RoboEagles4828/edna2023/src/edna_bringup/launch/real.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-real.yaml')
common = { 'use_sim_time': 'false', 'namespace': 'real' }
control_launch_args = common | {
'use_ros2_control': 'true',
'hardware_plugin': 'swerve_hardware/RealDriveHardware',
}
teleoplaunch_args = common | {
'joystick_file': joystick_file,
'enable_joy': 'false'
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
teleop_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','teleopLayer.launch.py'
)]), launch_arguments=teleoplaunch_args.items())
# Launch!
return LaunchDescription([
control_layer,
teleop_layer,
])
| 1,347 | Python | 34.473683 | 75 | 0.651819 |
RoboEagles4828/edna2023/src/edna_bringup/launch/rio-debug.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'riodebug.rviz')
common = { 'use_sim_time': 'false', 'namespace': 'real' }
control_launch_args = common | {
'use_ros2_control': 'true',
'load_controllers': 'false',
'forward_command_controller': 'true', # Change to false in order to disable publishing
'hardware_plugin': 'swerve_hardware/RealDriveHardware', # Use IsaacDriveHardware for isaac or RealDriveHardware for real.
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_debugger_gui': 'true',
'rviz_file': rviz_file
}
control_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','controlLayer.launch.py'
)]), launch_arguments=control_launch_args.items())
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer])
# Launch!
return LaunchDescription([
control_layer,
delay_debug_layer
])
| 1,762 | Python | 38.177777 | 129 | 0.662883 |
RoboEagles4828/edna2023/src/edna_bringup/scripts/parseRviz.py | import sys
import yaml
import os
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def processRvizFileForNamespace(rviz_file, NAMESPACE):
rviz_data = None
raw_rviz_data = None
with open(rviz_file, 'r') as stream:
raw_rviz_data = stream.read()
rviz_data = yaml.safe_load(raw_rviz_data)
# Get the namespace value from the rviz file
current_namespace = None
if rviz_data:
for display in rviz_data['Visualization Manager']['Displays']:
for k, v in display.items():
if 'Topic' in k and 'Value' in v:
segs = v['Value'].split('/')
if len(segs) > 1:
current_namespace = segs[1]
break
if current_namespace:
print('Found namespace: ', current_namespace)
print(f"mapping {current_namespace} -> {NAMESPACE}")
new_rviz_data = yaml.safe_load(raw_rviz_data.replace(current_namespace, NAMESPACE))
with open(rviz_file, 'w') as stream:
yaml.dump(new_rviz_data, stream)
else:
with open('err', 'w') as stream:
stream.write("Couldn't find namespace in rviz file")
if __name__ == "__main__":
processRvizFileForNamespace(sys.argv[1], sys.argv[2]) | 1,314 | Python | 33.605262 | 93 | 0.590563 |
RoboEagles4828/edna2023/src/edna_bringup/config/controllers.yaml | /*:
controller_manager:
ros__parameters:
update_rate: 20 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
swerve_controller:
type: swerve_controller/SwerveController
forward_position_controller:
type: position_controllers/JointGroupPositionController
forward_velocity_controller:
type: velocity_controllers/JointGroupVelocityController
joint_trajectory_controller:
type: joint_trajectory_controller/JointTrajectoryController
swerve_controller:
ros__parameters:
#Used to scale velocity
chassis_length_meters: 0.6032
chassis_width_meters: 0.6032
wheel_radius_meters: 0.0508
max_wheel_angular_velocity: 100.0
#If no new twist commands are created in 1 second the robot will halt
cmd_vel_timeout_seconds: 1.0
use_stamped_vel: false
front_left_wheel_joint: front_left_wheel_joint
front_right_wheel_joint: front_right_wheel_joint
rear_left_wheel_joint: rear_left_wheel_joint
rear_right_wheel_joint: rear_right_wheel_joint
front_left_axle_joint: front_left_axle_joint
front_right_axle_joint: front_right_axle_joint
rear_left_axle_joint: rear_left_axle_joint
rear_right_axle_joint: rear_right_axle_joint
linear.x.has_velocity_limits: false
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 3.0
linear.x.min_acceleration: -3.0
linear.x.max_jerk: 5.0
linear.x.min_jerk: -5.0
linear.y.has_velocity_limits: false
linear.y.has_acceleration_limits: true
linear.y.has_jerk_limits: false
linear.y.max_velocity: 2.0
linear.y.min_velocity: -2.0
linear.y.max_acceleration: 3.0
linear.y.min_acceleration: -3.0
linear.y.max_jerk: 5.0
linear.y.min_jerk: -5.0
angular.z.has_velocity_limits: false
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 3.0
angular.z.min_velocity: -3.0
angular.z.max_acceleration: 3.0
angular.z.min_acceleration: -3.0
angular.z.max_jerk: 5.0
angular.z.min_jerk: -5.0
forward_position_controller:
ros__parameters:
joints:
- 'front_left_axle_joint'
- 'front_right_axle_joint'
- 'rear_left_axle_joint'
- 'rear_right_axle_joint'
- 'arm_roller_bar_joint'
- 'elevator_outer_1_joint'
- 'elevator_center_joint'
- 'elevator_outer_2_joint'
- 'top_slider_joint'
- 'top_gripper_left_arm_joint'
- 'top_gripper_right_arm_joint'
- 'bottom_intake_joint'
forward_velocity_controller:
ros__parameters:
joints:
- 'front_left_wheel_joint'
- 'front_right_wheel_joint'
- 'rear_left_wheel_joint'
- 'rear_right_wheel_joint'
joint_trajectory_controller:
ros__parameters:
joints:
- 'arm_roller_bar_joint'
- 'elevator_center_joint'
- 'elevator_outer_1_joint'
- 'elevator_outer_2_joint'
- 'top_gripper_right_arm_joint'
- 'top_gripper_left_arm_joint'
- 'top_slider_joint'
- 'bottom_intake_joint'
command_interfaces:
- position
state_interfaces:
- position
- velocity
state_publish_rate: 50.0
action_monitor_rate: 20.0
allow_partial_joints_goal: false
open_loop_control: true
constraints:
stopped_velocity_tolerance: 0.01
goal_time: 0.0
| 3,706 | YAML | 28.188976 | 76 | 0.627361 |
RoboEagles4828/edna2023/src/edna_bringup/config/xbox-sim.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear:
x: 1.0
y: 1.0
scale_linear_turbo:
x: 2.5
y: 2.5
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular:
yaw: -1.0
scale_angular_turbo:
yaw: -2.2
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: 0.5
| 522 | YAML | 17.678571 | 51 | 0.5 |
RoboEagles4828/edna2023/src/edna_bringup/config/xbox-real.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear: #1/10000 to offset shifted 0 in /joystick-data
x: 0.0001
y: 0.0001
scale_linear_turbo:
x: 0.0004
y: 0.0004
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular: #negative to fix turning direction
yaw: -0.0001
scale_angular_turbo:
yaw: -0.0002
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: -0.25 | 610 | YAML | 24.458332 | 66 | 0.565574 |
RoboEagles4828/edna2023/src/edna_bringup/config/teleop-control.yaml | controller_mapping:
A: 0
B: 1
X: 2
Y: 3
LB: 4
RB: 5
squares: 6
menu: 7
xbox: 8
LSin: 9
RSin: 10
leftTriggerAxis: 2
rightTriggerAxis: 5
joint_limits:
arm_roller_bar_joint:
min: 0.0
max: 0.07
elevator_center_joint:
min: 0.0
max: 0.56
elevator_outer_1_joint:
min: 0.0
max: 0.2
elevator_outer_2_joint:
min: 0.0
max: 0.56
top_gripper_right_arm_joint:
min: -0.9
max: 0.0
top_gripper_left_arm_joint:
min: -0.9
max: 0.0
top_slider_joint:
min: 0.0
max: 0.30
bottom_intake_joint:
min: 0.0
max: 1.52
joint_mapping:
arm_roller_bar_joint: 0
elevator_center_joint: 1
elevator_outer_1_joint: 2
elevator_outer_2_joint: 3
top_gripper_right_arm_joint: 4
top_gripper_left_arm_joint: 5
top_slider_joint: 6
bottom_intake_joint: 7
function_mapping:
elevator_loading_station:
button: "RSin"
toggle: true
skis_up:
button: "leftTriggerAxis"
toggle: true
elevator_mid_level:
button: "LB"
toggle: true
elevator_high_level:
button: "X"
toggle: true
top_gripper_control:
button: "A"
toggle: true
elevator_pivot_control:
button: "Y"
toggle: true
top_slider_control:
button: "B"
toggle: true | 1,278 | YAML | 17.271428 | 32 | 0.606416 |
RoboEagles4828/edna2023/src/edna_debugger/setup.py | from setuptools import setup
package_name = 'edna_debugger'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='admin',
maintainer_email='[email protected]',
description='GUI Robot Control Debugger',
license='Apache License 2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'debugger = edna_debugger.debugger:main'
],
},
)
| 674 | Python | 23.999999 | 53 | 0.60089 |
RoboEagles4828/edna2023/src/edna_debugger/edna_debugger/flow_layout.py | # Implement a FlowLayout so sliders move around in a grid as the window is
# resized. Originally taken from:
# https://forum.qt.io/topic/109408/is-there-a-qt-layout-grid-that-can-dynamically-change-row-and-column-counts-to-best-fit-the-space/2
# with the license:
#
# This file taken from
# https://code.qt.io/cgit/qt/qtbase.git/tree/examples/widgets/layouts/flowlayout/flowlayout.cpp?h=5.13
# Modified/adapted by jon, 10/07/2019, to translate into Python/PyQt
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of the examples of the Qt Toolkit.
#
# $QT_BEGIN_LICENSE:BSD$
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# BSD License Usage
# Alternatively, you may use this file under the terms of the BSD license
# as follows:
#
# "Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of The Qt Company Ltd nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#
# $QT_END_LICENSE$
#
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import QPoint
from python_qt_binding.QtCore import QRect
from python_qt_binding.QtCore import QSize
from python_qt_binding.QtWidgets import QLayout
from python_qt_binding.QtWidgets import QSizePolicy
from python_qt_binding.QtWidgets import QStyle
class FlowLayout(QLayout):
def __init__(self, parent=None, margin=-1, hSpacing=-1, vSpacing=-1):
super().__init__(parent)
self.itemList = list()
self.m_hSpace = hSpacing
self.m_vSpace = vSpacing
self.setContentsMargins(margin, margin, margin, margin)
def __del__(self):
# copied for consistency, not sure this is needed or ever called
item = self.takeAt(0)
while item:
item = self.takeAt(0)
def addItem(self, item):
self.itemList.append(item)
def horizontalSpacing(self):
if self.m_hSpace >= 0:
return self.m_hSpace
else:
return self.smartSpacing(QStyle.PM_LayoutHorizontalSpacing)
def verticalSpacing(self):
if self.m_vSpace >= 0:
return self.m_vSpace
else:
return self.smartSpacing(QStyle.PM_LayoutVerticalSpacing)
def count(self):
return len(self.itemList)
def itemAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList[index]
return None
def takeAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList.pop(index)
return None
def expandingDirections(self):
return Qt.Orientations(Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
return self.doLayout(QRect(0, 0, width, 0), True)
def setGeometry(self, rect):
super().setGeometry(rect)
self.doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
def minimumSize(self):
size = QSize()
for item in self.itemList:
size = size.expandedTo(item.minimumSize())
margins = self.contentsMargins()
size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom())
return size
def smartSpacing(self, pm):
parent = self.parent()
if not parent:
return -1
elif parent.isWidgetType():
return parent.style().pixelMetric(pm, None, parent)
return parent.spacing()
def doLayout(self, rect, testOnly):
left, top, right, bottom = self.getContentsMargins()
effectiveRect = rect.adjusted(+left, +top, -right, -bottom)
x = effectiveRect.x()
y = effectiveRect.y()
lineHeight = 0
for item in self.itemList:
wid = item.widget()
spaceX = self.horizontalSpacing()
if spaceX == -1:
spaceX = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
spaceY = self.verticalSpacing()
if spaceY == -1:
spaceY = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > effectiveRect.right() and lineHeight > 0:
x = effectiveRect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0
if not testOnly:
item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y() + bottom | 6,445 | Python | 35.834286 | 134 | 0.672149 |
RoboEagles4828/edna2023/src/edna_debugger/edna_debugger/debugger.py |
import argparse
import random
import signal
import sys
import threading
import rclpy
from python_qt_binding.QtCore import pyqtSlot
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import Signal
from python_qt_binding.QtGui import QFont
from python_qt_binding.QtWidgets import QApplication
from python_qt_binding.QtWidgets import QFormLayout
from python_qt_binding.QtWidgets import QGridLayout
from python_qt_binding.QtWidgets import QHBoxLayout
from python_qt_binding.QtWidgets import QLabel
from python_qt_binding.QtWidgets import QLineEdit
from python_qt_binding.QtWidgets import QMainWindow
from python_qt_binding.QtWidgets import QPushButton
from python_qt_binding.QtWidgets import QSlider
from python_qt_binding.QtWidgets import QScrollArea
from python_qt_binding.QtWidgets import QVBoxLayout
from python_qt_binding.QtWidgets import QWidget
from edna_debugger.joint_state_publisher import JointStatePublisher
from edna_debugger.flow_layout import FlowLayout
RANGE = 10000
LINE_EDIT_WIDTH = 45
SLIDER_WIDTH = 200
INIT_NUM_SLIDERS = 7 # Initial number of sliders to show in window
# Defined by style - currently using the default style
DEFAULT_WINDOW_MARGIN = 11
DEFAULT_CHILD_MARGIN = 9
DEFAULT_BTN_HEIGHT = 25
DEFAULT_SLIDER_HEIGHT = 64 # Is the combination of default heights in Slider
# Calculate default minimums for window sizing
MIN_WIDTH = SLIDER_WIDTH + DEFAULT_CHILD_MARGIN * 4 + DEFAULT_WINDOW_MARGIN * 2
MIN_HEIGHT = DEFAULT_BTN_HEIGHT * 2 + DEFAULT_WINDOW_MARGIN * 2 + DEFAULT_CHILD_MARGIN * 2
PNEUMATICS_JOINTS = [
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'bottom_intake_joint'
]
class Button(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
self.row_layout = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout)
self.button = QPushButton('toggle', self)
self.button.setCheckable(True)
self.joint_layout.addWidget(self.button)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.remove_widget(self.button)
self.button.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class Slider(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
# top row
self.row_layout_top = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout_top.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout_top)
# subscribing row
self.row_layout_sub = QHBoxLayout()
self.display_sub = QLineEdit("0.00")
self.display_sub.setAlignment(Qt.AlignRight)
self.display_sub.setFont(font)
self.display_sub.setReadOnly(True)
self.display_sub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_sub.addWidget(self.display_sub)
self.slider_sub = QSlider(Qt.Horizontal)
self.slider_sub.setFont(font)
self.slider_sub.setRange(0, RANGE)
self.slider_sub.setValue(int(RANGE / 2))
self.slider_sub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_sub.addWidget(self.slider_sub)
self.joint_layout.addLayout(self.row_layout_sub)
# publishing row
self.row_layout_pub = QHBoxLayout()
self.display_pub = QLineEdit("0.00")
self.display_pub.setAlignment(Qt.AlignRight)
self.display_pub.setFont(font)
self.display_pub.setReadOnly(False)
self.display_pub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_pub.addWidget(self.display_pub)
self.slider_pub = QSlider(Qt.Horizontal)
self.slider_pub.setFont(font)
self.slider_pub.setRange(0, RANGE)
self.slider_pub.setValue(int(RANGE / 2))
self.slider_pub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_pub.addWidget(self.slider_pub)
self.joint_layout.addLayout(self.row_layout_pub)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.removeWidget(self.slider)
self.slider.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class JointStatePublisherGui(QMainWindow):
sliderUpdateTrigger = Signal()
initialize = Signal()
def __init__(self, title, jsp : JointStatePublisher):
super(JointStatePublisherGui, self).__init__()
self.joint_map = {}
self.setWindowTitle(title)
# Button for randomizing the sliders
self.rand_button = QPushButton('Randomize', self)
self.rand_button.clicked.connect(self.randomizeEvent)
# Button for centering the sliders
self.ctr_button = QPushButton('Center', self)
self.ctr_button.clicked.connect(self.centerEvent)
# Button for resetting the joint butttons
self.reset_button = QPushButton('Reset Pistons', self)
self.reset_button.clicked.connect(self.resetButtons)
# Scroll area widget contents - layout
self.scroll_layout = FlowLayout()
# Scroll area widget contents
self.scroll_widget = QWidget()
self.scroll_widget.setLayout(self.scroll_layout)
# Scroll area for sliders
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.scroll_widget)
# Main layout
self.main_layout = QVBoxLayout()
# Add buttons and scroll area to main layout
self.main_layout.addWidget(self.rand_button)
self.main_layout.addWidget(self.ctr_button)
self.main_layout.addWidget(self.reset_button)
self.main_layout.addWidget(self.scroll_area)
# central widget
self.central_widget = QWidget()
self.central_widget.setLayout(self.main_layout)
self.setCentralWidget(self.central_widget)
self.jsp = jsp
self.jsp.set_source_update_cb(self.sliderUpdateCb)
self.jsp.set_robot_description_update_cb(self.initializeCb)
self.running = True
self.sliders = {}
self.buttons = {}
# Setup signal for initializing the window
self.initialize.connect(self.initializeSliders)
# Set up a signal for updating the sliders based on external joint info
self.sliderUpdateTrigger.connect(self.updateSliders)
# Tell self to draw sliders in case the JointStatePublisher already has a robot_description
self.initialize.emit()
def initializeSliders(self):
self.joint_map = {}
for sl, _ in self.sliders.items():
self.scroll_layout.removeWidget(sl)
sl.remove()
### Generate sliders ###
for name in self.jsp.joint_list:
if name not in self.jsp.free_joints_sub:
continue
joint = self.jsp.free_joints_sub[name]
if joint['min'] == joint['max']:
continue
if (name in PNEUMATICS_JOINTS):
button = Button(name)
self.joint_map[name] = {'button': button.button, 'joint': joint}
self.scroll_layout.addWidget(button)
button.button.toggled.connect(lambda event,name=name: self.onInputValueChanged(name))
self.buttons[button] = button
else:
slider = Slider(name)
self.joint_map[name] = {'display_sub': slider.display_sub, 'slider_sub': slider.slider_sub, 'display_pub': slider.display_pub, 'slider_pub': slider.slider_pub, 'joint': joint}
self.scroll_layout.addWidget(slider)
slider.display_pub.textEdited.connect(lambda event,name=name: self.makeSliderEqualToText(name))
slider.slider_pub.valueChanged.connect(lambda event,name=name: self.makeTextEqualToSlider(name))
self.sliders[slider] = slider
# Set zero positions read from parameters
self.centerEvent(None)
# Set size of min size of window based on number of sliders.
if len(self.sliders) >= INIT_NUM_SLIDERS: # Limits min size to show INIT_NUM_SLIDERS
num_sliders = INIT_NUM_SLIDERS
else:
num_sliders = len(self.sliders)
scroll_layout_height = num_sliders * DEFAULT_SLIDER_HEIGHT
scroll_layout_height += (num_sliders + 1) * DEFAULT_CHILD_MARGIN
self.setMinimumSize(MIN_WIDTH, scroll_layout_height + MIN_HEIGHT)
self.sliderUpdateTrigger.emit()
def sliderUpdateCb(self):
self.sliderUpdateTrigger.emit()
def initializeCb(self):
self.initialize.emit()
# def onButtonClicked(self, name):
# # self.jsp.get_logger().info("button changed")
# joint_info = self.joint_map[name]
# buttonValue = 1 if joint_info['button'].isChecked() == True else 0
# joint_info['joint']['position'] = buttonValue
# joint_info['display'].setText(str(buttonValue))
# def onSliderTextEdited(self, slider, joint):
# self.jsp.get_logger().info(slider.display.text())
# slider.slider1.setSliderPosition(self.valueToSlider(float(slider.display.displayText()), joint))
def makeSliderEqualToText(self, name):
joint_info = self.joint_map[name]
textvalue = joint_info['display_pub'].text()
try:
joint_info['slider_pub'].setValue(self.valueToSlider(float(textvalue), joint_info['joint']))
self.onInputValueChanged(name)
except:
pass
def makeTextEqualToSlider(self, name):
joint_info = self.joint_map[name]
slidervalue = joint_info['slider_pub'].value()
joint_info['display_pub'].setText(str(round(self.sliderToValue(slidervalue, joint_info['joint']), 2)))
self.onInputValueChanged(name)
def onInputValueChanged(self, name):
# A slider value was changed, but we need to change the joint_info metadata.
joint_info = self.joint_map[name]
if ('slider_pub' in joint_info):
slidervalue = joint_info['slider_pub'].value()
joint = joint_info['joint']
if 'wheel' in name:
self.jsp.free_joints_pub[name]['velocity'] = self.sliderToValue(slidervalue, joint)
else:
self.jsp.free_joints_pub[name]['position'] = self.sliderToValue(slidervalue, joint)
elif ('button' in joint_info):
buttonValue = joint_info['joint']['max'] if joint_info['button'].isChecked() == True else joint_info['joint']['min']
self.jsp.free_joints_pub[name]['position'] = buttonValue
@pyqtSlot()
def updateSliders(self):
for name, joint_info in self.joint_map.items():
joint = joint_info['joint']
if ('slider_sub' in joint_info):
if 'wheel' in name:
slidervalue = self.valueToSlider(joint['velocity'], joint)
else:
slidervalue = self.valueToSlider(joint['position'], joint)
joint_info['slider_sub'].setValue(slidervalue)
joint_info['display_sub'].setText(str(round(self.sliderToValue(slidervalue, joint), 2)))
elif ('button' in joint_info):
buttonvalue = True if joint['position'] == joint['max'] else False
if (joint_info['button'].isChecked() == buttonvalue):
joint_info['button'].setStyleSheet('background-color: green')
else:
joint_info['button'].setStyleSheet('background-color: yellow')
def resetButtons(self, event):
self.jsp.get_logger().info("Toggling off")
for name, joint_info in self.joint_map.items():
if('button' in joint_info):
if(joint_info['button'].isChecked()):
joint_info['button'].setChecked(False)
def centerEvent(self, event):
self.jsp.get_logger().info("Centering")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(self.valueToSlider(joint['zero'], joint))
def randomizeEvent(self, event):
self.jsp.get_logger().info("Randomizing")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(
self.valueToSlider(random.uniform(joint['min'], joint['max']), joint))
def valueToSlider(self, value, joint):
# return int(value * 5000)
return int((value - joint['min']) * float(RANGE) / (joint['max'] - joint['min']))
def sliderToValue(self, slider, joint):
pctvalue = slider / float(RANGE)
return joint['min'] + (joint['max']-joint['min']) * pctvalue
def closeEvent(self, event):
self.running = False
def loop(self):
while self.running:
rclpy.spin_once(self.jsp, timeout_sec=0.1)
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
app = QApplication(sys.argv)
jsp_gui = JointStatePublisherGui('Debugger',
JointStatePublisher(parsed_args.urdf_file))
jsp_gui.show()
threading.Thread(target=jsp_gui.loop).start()
signal.signal(signal.SIGINT, signal.SIG_DFL)
sys.exit(app.exec_())
if __name__ == '__main__':
main() | 14,516 | Python | 35.2925 | 191 | 0.640052 |
RoboEagles4828/edna2023/src/edna_debugger/edna_debugger/joint_state_publisher.py | # Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Standard Python imports
import argparse
import math
import sys
import time
import xml.dom.minidom
# ROS 2 imports
import rclpy
import rclpy.node
from rcl_interfaces.msg import ParameterDescriptor, ParameterType
import sensor_msgs.msg
import std_msgs.msg
POSITION_JOINTS = {
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
'front_left_axle_joint',
'front_right_axle_joint',
'rear_left_axle_joint',
'rear_right_axle_joint',
}
VELOCITY_JOINTS = [
'front_left_wheel_joint',
'front_right_wheel_joint',
'rear_left_wheel_joint',
'rear_right_wheel_joint',
]
class JointStatePublisher(rclpy.node.Node):
def get_param(self, name):
return self.get_parameter(name).value
def _init_joint(self, minval, maxval, zeroval):
joint = {'min': minval, 'max': maxval, 'zero': zeroval}
if self.pub_def_positions:
joint['position'] = zeroval
if self.pub_def_vels:
joint['velocity'] = 0.0
if self.pub_def_efforts:
joint['effort'] = 0.0
return joint
def init_collada(self, robot):
robot = robot.getElementsByTagName('kinematics_model')[0].getElementsByTagName('technique_common')[0]
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
name = child.getAttribute('name')
if child.getElementsByTagName('revolute'):
joint = child.getElementsByTagName('revolute')[0]
else:
self.get_logger().warn('Unknown joint type %s', child)
continue
if joint:
limit = joint.getElementsByTagName('limits')[0]
minval = float(limit.getElementsByTagName('min')[0].childNodes[0].nodeValue)
maxval = float(limit.getElementsByTagName('max')[0].childNodes[0].nodeValue)
if minval == maxval: # this is a fixed joint
continue
self.joint_list.append(name)
minval *= math.pi/180.0
maxval *= math.pi/180.0
self.free_joints_sub[name] = self._init_joint(minval, maxval, 0.0)
self.free_joints_pub[name] = self.free_joints_sub[name]
def init_urdf(self, robot):
robot = robot.getElementsByTagName('robot')[0]
# Find all non-fixed joints
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
jtype = child.getAttribute('type')
if jtype in ['fixed', 'floating', 'planar']:
continue
name = child.getAttribute('name')
self.joint_list.append(name)
if jtype == 'continuous':
if name in VELOCITY_JOINTS:
minval = -39.4 # this is not a good number i pulled it out of thin air
maxval = 39.4 # please someone calculate the actual thing using the circumference of the wheels and that stuff
else:
minval = -math.pi
maxval = math.pi
else:
try:
limit = child.getElementsByTagName('limit')[0]
minval = float(limit.getAttribute('lower'))
maxval = float(limit.getAttribute('upper'))
except:
self.get_logger().warn('%s is not fixed, nor continuous, but limits are not specified!' % name)
continue
safety_tags = child.getElementsByTagName('safety_controller')
if self.use_small and len(safety_tags) == 1:
tag = safety_tags[0]
if tag.hasAttribute('soft_lower_limit'):
minval = max(minval, float(tag.getAttribute('soft_lower_limit')))
if tag.hasAttribute('soft_upper_limit'):
maxval = min(maxval, float(tag.getAttribute('soft_upper_limit')))
mimic_tags = child.getElementsByTagName('mimic')
if self.use_mimic and len(mimic_tags) == 1:
tag = mimic_tags[0]
entry = {'parent': tag.getAttribute('joint')}
if tag.hasAttribute('multiplier'):
entry['factor'] = float(tag.getAttribute('multiplier'))
if tag.hasAttribute('offset'):
entry['offset'] = float(tag.getAttribute('offset'))
self.dependent_joints[name] = entry
continue
if name in self.dependent_joints:
continue
if self.zeros and name in self.zeros:
zeroval = self.zeros[name]
elif minval > 0 or maxval < 0:
zeroval = (maxval + minval)/2
else:
zeroval = 0
joint = self._init_joint(minval, maxval, zeroval)
if jtype == 'continuous':
joint['continuous'] = True
self.free_joints_sub[name] = joint
self.free_joints_pub[name] = joint.copy()
def configure_robot(self, description):
self.get_logger().debug('Got description, configuring robot')
try:
robot = xml.dom.minidom.parseString(description)
except xml.parsers.expat.ExpatError:
# If the description fails to parse for some reason, print an error
# and get out of here without doing further work. If we were
# already running with a description, we'll continue running with
# that older one.
self.get_logger().warn('Invalid robot_description given, ignoring')
return
# Make sure to clear out the old joints so we don't get duplicate joints
# on a new robot description.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
if robot.getElementsByTagName('COLLADA'):
self.init_collada(robot)
else:
self.init_urdf(robot)
if self.robot_description_update_cb is not None:
self.robot_description_update_cb()
def parse_dependent_joints(self):
dj = {}
dependent_joints = self.get_parameters_by_prefix('dependent_joints')
# get_parameters_by_prefix returned a dictionary of keynames like
# 'head.parent', 'head.offset', etc. that map to rclpy Parameter values.
# The rest of the code assumes that the dependent_joints dictionary is
# a map of name -> dict['parent': parent, factor: factor, offset: offset],
# where both factor and offset are optional. Thus we parse the values we
# got into that structure.
for name, param in dependent_joints.items():
# First split on the dots; there should be one and exactly one dot
split = name.split('.')
if len(split) != 2:
raise Exception("Invalid dependent_joint name '%s'" % (name))
newkey = split[0]
newvalue = split[1]
if newvalue not in ['parent', 'factor', 'offset']:
raise Exception("Invalid dependent_joint name '%s' (allowed values are 'parent', 'factor', and 'offset')" % (newvalue))
if newkey in dj:
dj[newkey].update({newvalue: param.value})
else:
dj[newkey] = {newvalue: param.value}
# Now ensure that there is at least a 'parent' in all keys
for name,outdict in dj.items():
if outdict.get('parent', None) is None:
raise Exception('All dependent_joints must at least have a parent')
return dj
def declare_ros_parameter(self, name, default, descriptor):
# When the automatically_declare_parameters_from_overrides parameter to
# rclpy.create_node() is True, then any parameters passed in on the
# command-line are automatically declared. In that case, calling
# node.declare_parameter() will raise an exception. However, in the case
# where a parameter is *not* overridden, we still want to declare it
# (so it shows up in "ros2 param list", for instance). Thus we always do
# a declaration and just ignore ParameterAlreadyDeclaredException.
try:
self.declare_parameter(name, default, descriptor)
except rclpy.exceptions.ParameterAlreadyDeclaredException:
pass
def __init__(self, urdf_file):
super().__init__('joint_state_publisher', automatically_declare_parameters_from_overrides=True)
self.declare_ros_parameter('publish_default_efforts', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_positions', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_velocities', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('rate', 10, ParameterDescriptor(type=ParameterType.PARAMETER_INTEGER))
self.declare_ros_parameter('source_list', [], ParameterDescriptor(type=ParameterType.PARAMETER_STRING_ARRAY))
self.declare_ros_parameter('use_mimic_tags', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('use_smallest_joint_limits', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('delta', 0.0, ParameterDescriptor(type=ParameterType.PARAMETER_DOUBLE))
# In theory we would also declare 'dependent_joints' and 'zeros' here.
# Since rclpy doesn't support maps natively, though, we just end up
# letting 'automatically_declare_parameters_from_overrides' declare
# any parameters for us.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
self.dependent_joints = self.parse_dependent_joints()
self.use_mimic = self.get_param('use_mimic_tags')
self.use_small = self.get_param('use_smallest_joint_limits')
zeros = self.get_parameters_by_prefix('zeros')
# get_parameters_by_prefix() returns a map of name -> Parameter
# structures, but self.zeros is expected to be a list of name -> float;
# fix that here.
self.zeros = {k:v.value for (k, v) in zeros.items()}
self.pub_def_positions = self.get_param('publish_default_positions')
self.pub_def_vels = self.get_param('publish_default_velocities')
self.pub_def_efforts = self.get_param('publish_default_efforts')
self.robot_description_update_cb = None
if urdf_file is not None:
# If we were given a URDF file on the command-line, use that.
with open(urdf_file, 'r') as infp:
description = infp.read()
self.configure_robot(description)
else:
# Otherwise, subscribe to the '/robot_description' topic and wait
# for a callback there
self.get_logger().info('Waiting for robot_description to be published on the robot_description topic...')
self.create_subscription(std_msgs.msg.String, 'robot_description',
lambda msg: self.configure_robot(msg.data),
rclpy.qos.QoSProfile(depth=1, durability=rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL))
self.delta = self.get_param('delta')
source_list = self.get_param('source_list')
self.sources = []
# for source in source_list:
# self.sources.append(self.create_subscription(sensor_msgs.msg.JointState, source, self.source_cb, 10))
# The source_update_cb will be called at the end of self.source_cb.
# The main purpose is to allow external observers (such as the
# joint_state_publisher_gui) to be notified when things are updated.
self.source_update_cb = None
# Override topic name here
self.pub_pos = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_position_controller/commands', 10)
self.pub_vel = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_velocity_controller/commands', 10)
self.create_subscription(sensor_msgs.msg.JointState, 'joint_states', self.source_cb, 10)
self.timer = self.create_timer(1.0 / self.get_param('rate'), self.timer_callback)
def source_cb(self, msg):
# self.get_logger().info("ran source callback")
for i in range(len(msg.name)):
name = msg.name[i]
if name not in self.free_joints_sub:
continue
if msg.position:
position = msg.position[i]
else:
position = None
if msg.velocity:
velocity = msg.velocity[i]
else:
velocity = None
if msg.effort:
effort = msg.effort[i]
else:
effort = None
joint = self.free_joints_sub[name]
if position is not None:
joint['position'] = position
if velocity is not None:
joint['velocity'] = velocity
if effort is not None:
joint['effort'] = effort
if self.source_update_cb is not None:
self.source_update_cb()
def set_source_update_cb(self, user_cb):
self.source_update_cb = user_cb
def set_robot_description_update_cb(self, user_cb):
self.robot_description_update_cb = user_cb
def timer_callback(self):
# Publish Joint States
msg = sensor_msgs.msg.JointState()
msg.header.stamp = self.get_clock().now().to_msg()
if self.delta > 0:
self.update(self.delta)
# Initialize msg.position, msg.velocity, and msg.effort.
has_position = False
has_velocity = False
has_effort = False
for name, joint in self.free_joints_pub.items():
if not has_position and 'position' in joint:
has_position = True
if not has_velocity and 'velocity' in joint:
has_velocity = True
if not has_effort and 'effort' in joint:
has_effort = True
num_joints = (len(self.free_joints_pub.items()) +
len(self.dependent_joints.items()))
if has_position:
msg.position = []
if has_velocity:
msg.velocity = []
if has_effort:
msg.effort = num_joints * [0.0]
for i, name in enumerate(self.joint_list):
msg.name.append(str(name))
joint = None
# Add Free Joint
if name in self.free_joints_pub:
joint = self.free_joints_pub[name]
factor = 1
offset = 0
# Add Dependent Joint
elif name in self.dependent_joints:
param = self.dependent_joints[name]
parent = param['parent']
factor = param.get('factor', 1.0)
offset = param.get('offset', 0.0)
# Handle recursive mimic chain
recursive_mimic_chain_joints = [name]
while parent in self.dependent_joints:
if parent in recursive_mimic_chain_joints:
error_message = 'Found an infinite recursive mimic chain'
self.get_logger().error(f'{error_message}: {recursive_mimic_chain_joints + [parent]}')
sys.exit(1)
recursive_mimic_chain_joints.append(parent)
param = self.dependent_joints[parent]
parent = param['parent']
offset += factor * param.get('offset', 0)
factor *= param.get('factor', 1)
joint = self.free_joints_pub[parent]
# the issue here is that its setting [i] either to the joint, or its skipping i in the list when we need it to be the next value.
# For some reason, [list].append() ends up putting way too many empty values that come from nowhere into the list.
# The best thing to do here would be having two separate iterators which only increment if the variable has a position or a velocity.
if has_position and 'position' in joint and name in POSITION_JOINTS:
msg.position.append(float(joint['position']) * factor + offset)
if has_velocity and 'velocity' in joint and name in VELOCITY_JOINTS:
msg.velocity.append(float(joint['velocity']) * factor)
if has_effort and 'effort' in joint:
msg.effort[i] = float(joint['effort'])
# Only publish non-empty messages
if not (msg.name or msg.position or msg.velocity or msg.effort):
return
pos_msg = std_msgs.msg.Float64MultiArray()
vel_msg = std_msgs.msg.Float64MultiArray()
pos_msg.data = msg.position
vel_msg.data = msg.velocity
self.pub_pos.publish(pos_msg)
self.pub_vel.publish(vel_msg)
def update(self, delta):
for name, joint in self.free_joints_sub.items():
forward = joint.get('forward', True)
if forward:
joint['position'] += delta
if joint['position'] > joint['max']:
if joint.get('continuous', False):
joint['position'] = joint['min']
else:
joint['position'] = joint['max']
joint['forward'] = not forward
else:
joint['position'] -= delta
if joint['position'] < joint['min']:
joint['position'] = joint['min']
joint['forward'] = not forward
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
jsp = JointStatePublisher(parsed_args.urdf_file)
try:
rclpy.spin(jsp)
except KeyboardInterrupt:
pass
jsp.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 20,839 | Python | 42.873684 | 145 | 0.595038 |
RoboEagles4828/edna2023/isaac/README.md | # Isaac Sim Code and Assests | 28 | Markdown | 27.999972 | 28 | 0.785714 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
title = "edna"
description = "Extension for running edna in Isaac Sim"
authors = ["Gage Miller, Nitin C"]
repository = ""
keywords = ["isaac", "samples", "manipulation"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
writeTarget.kit = true
[dependencies]
"omni.kit.uiapp" = {}
"omni.physx" = {}
"omni.physx.vehicle" = {}
"omni.isaac.dynamic_control" = {}
"omni.isaac.motion_planning" = {}
"omni.isaac.synthetic_utils" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
"omni.isaac.franka" = {}
"omni.isaac.dofbot" = {}
"omni.isaac.universal_robots" = {}
"omni.isaac.motion_generation" = {}
"omni.isaac.demos" = {}
"omni.graph.action" = {}
"omni.graph.nodes" = {}
"omni.graph.core" = {}
"omni.isaac.quadruped" = {}
"omni.isaac.wheeled_robots" = {}
"omni.isaac.examples" = {}
[[python.module]]
name = "omni.isaac.edna.import_bot"
[[test]]
timeout = 960
| 1,012 | TOML | 21.021739 | 55 | 0.656126 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/base_sample/base_sample.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.core import World
from omni.isaac.core.scenes.scene import Scene
from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async
import gc
from abc import abstractmethod
class BaseSample(object):
def __init__(self) -> None:
self._world = None
self._current_tasks = None
self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0}
# self._logging_info = ""
return
def get_world(self):
return self._world
def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None):
if physics_dt is not None:
self._world_settings["physics_dt"] = physics_dt
if stage_units_in_meters is not None:
self._world_settings["stage_units_in_meters"] = stage_units_in_meters
if rendering_dt is not None:
self._world_settings["rendering_dt"] = rendering_dt
return
async def load_world_async(self):
"""Function called when clicking load buttton
"""
if World.instance() is None:
await create_new_stage_async()
self._world = World(**self._world_settings)
await self._world.initialize_simulation_context_async()
self.setup_scene()
else:
self._world = World.instance()
self._current_tasks = self._world.get_current_tasks()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_load()
if len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
async def reset_async(self):
"""Function called when clicking reset buttton
"""
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.remove_physics_callback("tasks_step")
await self._world.play_async()
await update_stage_async()
await self.setup_pre_reset()
await self._world.reset_async()
await self._world.pause_async()
await self.setup_post_reset()
if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0:
self._world.add_physics_callback("tasks_step", self._world.step_async)
return
@abstractmethod
def setup_scene(self, scene: Scene) -> None:
"""used to setup anything in the world, adding tasks happen here for instance.
Args:
scene (Scene): [description]
"""
return
@abstractmethod
async def setup_post_load(self):
"""called after first reset of the world when pressing load,
intializing provate variables happen here.
"""
return
@abstractmethod
async def setup_pre_reset(self):
""" called in reset button before resetting the world
to remove a physics callback for instance or a controller reset
"""
return
@abstractmethod
async def setup_post_reset(self):
""" called in reset button after resetting the world which includes one step with rendering
"""
return
@abstractmethod
async def setup_post_clear(self):
"""called after clicking clear button
or after creating a new stage and clearing the instance of the world with its callbacks
"""
return
# def log_info(self, info):
# self._logging_info += str(info) + "\n"
# return
def _world_cleanup(self):
self._world.stop()
self._world.clear_all_callbacks()
self._current_tasks = None
self.world_cleanup()
return
def world_cleanup(self):
"""Function called when extension shutdowns and starts again, (hot reloading feature)
"""
return
async def clear_async(self):
"""Function called when clicking clear buttton
"""
await create_new_stage_async()
if self._world is not None:
self._world_cleanup()
self._world.clear_instance()
self._world = None
gc.collect()
await self.setup_post_clear()
return
| 4,657 | Python | 34.287879 | 115 | 0.624222 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/base_sample/base_sample_extension.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from abc import abstractmethod
import omni.ext
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
import weakref
from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder
import asyncio
from omni.isaac.edna.base_sample import BaseSample
from omni.isaac.core import World
class BaseSampleExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
self._menu_items = None
self._buttons = None
self._ext_id = ext_id
self._sample = None
self._extra_frames = []
return
def start_extension(
self,
menu_name: str,
submenu_name: str,
name: str,
title: str,
doc_link: str,
overview: str,
file_path: str,
sample=None,
number_of_extra_frames=1,
window_width=350,
):
if sample is None:
self._sample = BaseSample()
else:
self._sample = sample
menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())]
if menu_name == "" or menu_name is None:
self._menu_items = menu_items
elif submenu_name == "" or submenu_name is None:
self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)]
else:
self._menu_items = [
MenuItemDescription(
name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)]
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._buttons = dict()
self._build_ui(
name=name,
title=title,
doc_link=doc_link,
overview=overview,
file_path=file_path,
number_of_extra_frames=number_of_extra_frames,
window_width=window_width,
)
if self.get_world() is not None:
self._on_load_world()
return
@property
def sample(self):
return self._sample
def get_frame(self, index):
if index >= len(self._extra_frames):
raise Exception("there were {} extra frames created only".format(len(self._extra_frames)))
return self._extra_frames[index]
def get_world(self):
return World.instance()
def get_buttons(self):
return self._buttons
def _build_ui(self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width):
self._window = omni.ui.Window(
name, width=window_width, height=0, visible=True, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
setup_ui_headers(self._ext_id, file_path, title, doc_link, overview)
self._controls_frame = ui.CollapsableFrame(
title="World Controls",
width=ui.Fraction(1),
height=0,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with ui.VStack(style=get_style(), spacing=5, height=0):
for i in range(number_of_extra_frames):
self._extra_frames.append(
ui.CollapsableFrame(
title="",
width=ui.Fraction(0.33),
height=0,
visible=False,
collapsed=False,
style=get_style(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
)
with self._controls_frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
dict = {
"label": "Load World",
"type": "button",
"text": "Load",
"tooltip": "Load World and Task",
"on_clicked_fn": self._on_load_world,
}
self._buttons["Load World"] = btn_builder(**dict)
self._buttons["Load World"].enabled = True
dict = {
"label": "Reset",
"type": "button",
"text": "Reset",
"tooltip": "Reset robot and environment",
"on_clicked_fn": self._on_reset,
}
self._buttons["Reset"] = btn_builder(**dict)
self._buttons["Reset"].enabled = False
dict = {
"label": "Clear",
"type": "button",
"text": "Clear",
"tooltip": "Clear the full environment",
"on_clicked_fn": self._on_clear,
}
self._buttons["Clear"] = btn_builder(**dict)
self._buttons["Clear"].enabled = True
return
def _set_button_tooltip(self, button_name, tool_tip):
self._buttons[button_name].set_tooltip(tool_tip)
return
def _on_load_world(self):
async def _on_load_world_async():
await self._sample.load_world_async()
await omni.kit.app.get_app().next_update_async()
self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event)
self._enable_all_buttons(True)
self._buttons["Load World"].enabled = False
self.post_load_button_event()
self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event)
asyncio.ensure_future(_on_load_world_async())
return
def _on_reset(self):
async def _on_reset_async():
await self._sample.reset_async()
await omni.kit.app.get_app().next_update_async()
self.post_reset_button_event()
asyncio.ensure_future(_on_reset_async())
return
def _on_clear(self):
async def _on_clear_async():
await self._sample.clear_async()
await omni.kit.app.get_app().next_update_async()
self.post_clear_button_event()
self._buttons["Load World"].enabled = True
asyncio.ensure_future(_on_clear_async())
return
@abstractmethod
def post_reset_button_event(self):
return
@abstractmethod
def post_load_button_event(self):
return
@abstractmethod
def post_clear_button_event(self):
return
def _enable_all_buttons(self, flag):
for btn_name, btn in self._buttons.items():
if isinstance(btn, omni.ui._ui.Button):
btn.enabled = flag
return
def _menu_callback(self):
self._window.visible = not self._window.visible
return
def _on_window(self, status):
# if status:
return
def on_shutdown(self):
self._extra_frames = []
if self._sample._world is not None:
self._sample._world_cleanup()
if self._menu_items is not None:
self._sample_window_cleanup()
if self._buttons is not None:
self._buttons["Load World"].enabled = True
self._enable_all_buttons(False)
self.shutdown_cleanup()
return
def shutdown_cleanup(self):
return
def _sample_window_cleanup(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
self._menu_items = None
self._buttons = None
return
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
if World.instance() is not None:
self.sample._world_cleanup()
self.sample._world.clear_instance()
if hasattr(self, "_buttons"):
if self._buttons is not None:
self._enable_all_buttons(False)
self._buttons["Load World"].enabled = True
return
def _reset_on_stop_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._buttons["Load World"].enabled = False
self._buttons["Reset"].enabled = True
self.post_clear_button_event()
return
| 9,389 | Python | 36.261905 | 114 | 0.530621 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/base_sample/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.isaac.edna.base_sample.base_sample import BaseSample
from omni.isaac.edna.base_sample.base_sample_extension import BaseSampleExtension
| 574 | Python | 46.916663 | 81 | 0.818815 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/__init__.py |
from omni.isaac.edna.import_bot.import_bot import ImportBot
from omni.isaac.edna.import_bot.import_bot_extension import ImportBotExtension
| 140 | Python | 34.249991 | 78 | 0.842857 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/import_bot_extension.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
from omni.isaac.edna.base_sample import BaseSampleExtension
from omni.isaac.edna.import_bot.import_bot import ImportBot
import omni.ui as ui
from omni.isaac.ui.ui_utils import state_btn_builder
class ImportBotExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Edna FRC",
submenu_name="",
name="Import URDF",
title="Load the URDF for Edna FRC 2023 Robot",
doc_link="",
overview="This loads the Edna robot into Isaac Sim.",
file_path=os.path.abspath(__file__),
sample=ImportBot(),
number_of_extra_frames=1
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_toggle_camera_button_event(self, val):
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Toggle Cameras",
"type": "button",
"a_text": "START",
"b_text": "STOP",
"tooltip": "Start the cameras",
"on_clicked_fn": self._on_toggle_camera_button_event,
}
self.task_ui_elements["Toggle Camera"] = state_btn_builder(**dict)
self.task_ui_elements["Toggle Camera"].enabled = False
| 2,080 | Python | 36.836363 | 82 | 0.597596 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/import_bot.py | from omni.isaac.core.utils.stage import add_reference_to_stage
import omni.graph.core as og
import omni.usd
from omni.isaac.edna.base_sample import BaseSample
from omni.isaac.urdf import _urdf
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils import prims
from omni.isaac.core.prims import GeometryPrim
from omni.isaac.core_nodes.scripts.utils import set_target_prims
# from omni.kit.viewport_legacy import get_default_viewport_window
# from omni.isaac.sensor import IMUSensor
from pxr import UsdPhysics, UsdShade, Sdf, Gf
import omni.kit.commands
import os
import numpy as np
import math
import carb
NAMESPACE = f"{os.environ.get('ROS_NAMESPACE')}" if 'ROS_NAMESPACE' in os.environ else 'default'
def set_drive_params(drive, stiffness, damping, max_force):
drive.GetStiffnessAttr().Set(stiffness)
drive.GetDampingAttr().Set(damping)
if(max_force != 0.0):
drive.GetMaxForceAttr().Set(max_force)
return
def add_physics_material_to_prim(prim, materialPath):
bindingAPI = UsdShade.MaterialBindingAPI.Apply(prim)
materialPrim = UsdShade.Material(materialPath)
bindingAPI.Bind(materialPrim, UsdShade.Tokens.weakerThanDescendants, "physics")
class ImportBot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def set_friction(self, robot_prim_path):
mtl_created_list = []
# Create a new material using OmniGlass.mdl
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniPBR.mdl",
mtl_name="Rubber",
mtl_created_list=mtl_created_list,
)
# Get reference to created material
stage = omni.usd.get_context().get_stage()
mtl_prim = stage.GetPrimAtPath(mtl_created_list[0])
friction_material = UsdPhysics.MaterialAPI.Apply(mtl_prim)
friction_material.CreateDynamicFrictionAttr(1.0)
friction_material.CreateStaticFrictionAttr(1.0)
front_left_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/front_left_wheel_link/collisions")
front_right_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/front_right_wheel_link/collisions")
rear_left_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/rear_left_wheel_link/collisions")
rear_right_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/rear_right_wheel_link/collisions")
add_physics_material_to_prim(front_left_wheel_prim, mtl_prim)
add_physics_material_to_prim(front_right_wheel_prim, mtl_prim)
add_physics_material_to_prim(rear_left_wheel_prim, mtl_prim)
add_physics_material_to_prim(rear_right_wheel_prim, mtl_prim)
def setup_scene(self):
world = self.get_world()
world.get_physics_context().enable_gpu_dynamics(False)
world.scene.add_default_ground_plane()
self.setup_field()
# self.setup_perspective_cam()
self.setup_world_action_graph()
return
def setup_field(self):
world = self.get_world()
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
field = os.path.join(self.project_root_path, "assets/2023_field_cpu/FE-2023.usd")
add_reference_to_stage(usd_path=field,prim_path="/World/Field")
cone = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23700_JFH.usd")
cube = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23701_JFL.usd")
chargestation = os.path.join(self.project_root_path, "assets/ChargeStation-Copy/Assembly-1.usd")
add_reference_to_stage(chargestation, "/World/ChargeStation_1")
add_reference_to_stage(chargestation, "/World/ChargeStation_2")
add_reference_to_stage(cone, "/World/Cone_1")
add_reference_to_stage(cone, "/World/Cone_2")
add_reference_to_stage(cone, "/World/Cone_3")
add_reference_to_stage(cone, "/World/Cone_4")
# add_reference_to_stage(cone, "/World/Cone_5")
# add_reference_to_stage(cone, "/World/Cone_6")
# add_reference_to_stage(cone, "/World/Cone_7")
# add_reference_to_stage(cone, "/World/Cone_8")
cone_1 = GeometryPrim("/World/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,0.0]))
cone_2 = GeometryPrim("/World/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0]))
cone_3 = GeometryPrim("/World/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0]))
cone_4 = GeometryPrim("/World/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0]))
chargestation_1 = GeometryPrim("/World/ChargeStation_1","cone_3_view",position=np.array([-4.20298,-0.56861,0.0]))
chargestation_2 = GeometryPrim("/World/ChargeStation_2","cone_4_view",position=np.array([4.20298,0.56861,0.0]))
add_reference_to_stage(cube, "/World/Cube_1")
add_reference_to_stage(cube, "/World/Cube_2")
add_reference_to_stage(cube, "/World/Cube_3")
add_reference_to_stage(cube, "/World/Cube_4")
# add_reference_to_stage(cube, "/World/Cube_5")
# add_reference_to_stage(cube, "/World/Cube_6")
# add_reference_to_stage(cube, "/World/Cube_7")
# add_reference_to_stage(cube, "/World/Cube_8")
cube_1 = GeometryPrim("/World/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121]))
cube_2 = GeometryPrim("/World/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121]))
cube_3 = GeometryPrim("/World/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121]))
cube_4 = GeometryPrim("/World/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121]))
async def setup_post_load(self):
self._world = self.get_world()
# self._world.get_physics_context().enable_gpu_dynamics(True)
self.robot_name = "edna"
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
self.path_to_urdf = os.path.join(self.extension_path, "../../../../../../../..", "src/edna_description/urdf/edna.urdf")
carb.log_info(self.path_to_urdf)
self._robot_prim_path = self.import_robot(self.path_to_urdf)
if self._robot_prim_path is None:
print("Error: failed to import robot")
return
self._robot_prim = self._world.scene.add(
Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.3]), orientation=np.array([0.0, 0.0, 0.0, 1.0]))
)
self.configure_robot(self._robot_prim_path)
return
def import_robot(self, urdf_path):
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = False
import_config.import_inertia_tensor = True
import_config.default_drive_strength = 1047.19751
import_config.default_position_drive_damping = 52.35988
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.distance_scale = 1.0
import_config.density = 0.0
result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config)
if result:
return prim_path
return None
def configure_robot(self, robot_prim_path):
w_sides = ['left', 'right']
l_sides = ['front', 'back']
stage = self._world.stage
chassis_name = f"swerve_chassis_link"
front_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_left_axle_joint"), "angular")
front_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_right_axle_joint"), "angular")
rear_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_left_axle_joint"), "angular")
rear_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_right_axle_joint"), "angular")
front_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_left_axle_link/front_left_wheel_joint"), "angular")
front_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_right_axle_link/front_right_wheel_joint"), "angular")
rear_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_left_axle_link/rear_left_wheel_joint"), "angular")
rear_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_right_axle_link/rear_right_wheel_joint"), "angular")
arm_roller_bar_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_elevator_leg_link/arm_roller_bar_joint"), "linear")
elevator_center_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_1_link/elevator_center_joint"), "linear")
elevator_outer_2_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_center_link/elevator_outer_2_joint"), "linear")
elevator_outer_1_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_back_leg_link/elevator_outer_1_joint"), "angular")
top_gripper_left_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_left_arm_joint"), "angular")
top_gripper_right_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_right_arm_joint"), "angular")
top_slider_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_2_link/top_slider_joint"), "linear")
bottom_intake_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_elevator_leg_link/bottom_intake_joint"), "angular")
set_drive_params(front_left_axle, 1, 1000, 98.0)
set_drive_params(front_right_axle, 1, 1000, 98.0)
set_drive_params(rear_left_axle, 1, 1000, 98.0)
set_drive_params(rear_right_axle, 1, 1000, 98.0)
set_drive_params(front_left_wheel, 1, 1000, 98.0)
set_drive_params(front_right_wheel, 1, 1000, 98.0)
set_drive_params(rear_left_wheel, 1, 1000, 98.0)
set_drive_params(rear_right_wheel, 1, 1000, 98.0)
set_drive_params(arm_roller_bar_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_center_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_outer_1_joint, 10000000, 100000, 2000.0)
set_drive_params(elevator_outer_2_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_left_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_right_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_slider_joint, 10000000, 100000, 98.0)
set_drive_params(bottom_intake_joint, 10000000, 100000, 98.0)
# self.create_lidar(robot_prim_path)
self.create_imu(robot_prim_path)
self.create_depth_camera(robot_prim_path)
self.setup_camera_action_graph(robot_prim_path)
self.setup_imu_action_graph(robot_prim_path)
self.setup_robot_action_graph(robot_prim_path)
self.set_friction(robot_prim_path)
return
def create_lidar(self, robot_prim_path):
lidar_parent = f"{robot_prim_path}/lidar_link"
lidar_path = "/lidar"
self.lidar_prim_path = lidar_parent + lidar_path
result, prim = omni.kit.commands.execute(
"RangeSensorCreateLidar",
path=lidar_path,
parent=lidar_parent,
min_range=0.4,
max_range=25.0,
draw_points=False,
draw_lines=True,
horizontal_fov=360.0,
vertical_fov=30.0,
horizontal_resolution=0.4,
vertical_resolution=4.0,
rotation_rate=0.0,
high_lod=False,
yaw_offset=0.0,
enable_semantics=False
)
return
def create_imu(self, robot_prim_path):
imu_parent = f"{robot_prim_path}/zed2i_imu_link"
imu_path = "/imu"
self.imu_prim_path = imu_parent + imu_path
result, prim = omni.kit.commands.execute(
"IsaacSensorCreateImuSensor",
path=imu_path,
parent=imu_parent,
translation=Gf.Vec3d(0, 0, 0),
orientation=Gf.Quatd(1, 0, 0, 0),
visualize=False,
)
return
def create_depth_camera(self, robot_prim_path):
self.depth_left_camera_path = f"{robot_prim_path}/zed2i_right_camera_isaac_frame/left_cam"
self.depth_right_camera_path = f"{robot_prim_path}/zed2i_right_camera_isaac_frame/right_cam"
self.left_camera = prims.create_prim(
prim_path=self.depth_left_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
self.right_camera = prims.create_prim(
prim_path=self.depth_right_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
return
def setup_world_action_graph(self):
og.Controller.edit(
{"graph_path": "/globalclock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"),
("Context.outputs:context", "PublishClock.inputs:context"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
],
}
)
return
def setup_camera_action_graph(self, robot_prim_path):
camera_graph = "{}/camera_sensor_graph".format(robot_prim_path)
enable_left_cam = False
enable_right_cam = False
rgbType = "RgbType"
infoType = "InfoType"
depthType = "DepthType"
depthPclType = "DepthPclType"
def createCamType(side, name, typeNode, topic):
return {
"create": [
(f"{side}CamHelper{name}", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
],
"connect": [
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamHelper{name}.inputs:renderProductPath"),
(f"{side}CamSet.outputs:execOut", f"{side}CamHelper{name}.inputs:execIn"),
(f"{typeNode}.inputs:value", f"{side}CamHelper{name}.inputs:type"),
],
"setvalues": [
(f"{side}CamHelper{name}.inputs:topicName", f"{side.lower()}/{topic}"),
(f"{side}CamHelper{name}.inputs:frameId", f"{NAMESPACE}/zed2i_{side.lower()}_camera_frame"),
(f"{side}CamHelper{name}.inputs:nodeNamespace", f"/{NAMESPACE}"),
]
}
def getCamNodes(side, enable):
camNodes = {
"create": [
(f"{side}CamBranch", "omni.graph.action.Branch"),
(f"{side}CamCreateViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(f"{side}CamViewportResolution", "omni.isaac.core_nodes.IsaacSetViewportResolution"),
(f"{side}CamViewProduct", "omni.isaac.core_nodes.IsaacGetViewportRenderProduct"),
(f"{side}CamSet", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"),
],
"connect": [
("OnPlaybackTick.outputs:tick", f"{side}CamBranch.inputs:execIn"),
(f"{side}CamBranch.outputs:execTrue", f"{side}CamCreateViewport.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:execOut", f"{side}CamViewportResolution.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewportResolution.inputs:viewport"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewProduct.inputs:viewport"),
(f"{side}CamViewportResolution.outputs:execOut", f"{side}CamViewProduct.inputs:execIn"),
(f"{side}CamViewProduct.outputs:execOut", f"{side}CamSet.inputs:execIn"),
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamSet.inputs:renderProductPath"),
],
"setvalues": [
(f"{side}CamBranch.inputs:condition", enable),
(f"{side}CamCreateViewport.inputs:name", f"{side}Cam"),
(f"{side}CamViewportResolution.inputs:width", 640),
(f"{side}CamViewportResolution.inputs:height", 360),
]
}
rgbNodes = createCamType(side, "RGB", rgbType, "rgb")
infoNodes = createCamType(side, "Info", infoType, "camera_info")
depthNodes = createCamType(side, "Depth", depthType, "depth")
depthPClNodes = createCamType(side, "DepthPcl", depthPclType, "depth_pcl")
camNodes["create"] += rgbNodes["create"] + infoNodes["create"] + depthNodes["create"] + depthPClNodes["create"]
camNodes["connect"] += rgbNodes["connect"] + infoNodes["connect"] + depthNodes["connect"] + depthPClNodes["connect"]
camNodes["setvalues"] += rgbNodes["setvalues"] + infoNodes["setvalues"] + depthNodes["setvalues"] + depthPClNodes["setvalues"]
return camNodes
leftCamNodes = getCamNodes("Left", enable_left_cam)
rightCamNodes = getCamNodes("Right", enable_right_cam)
og.Controller.edit(
{"graph_path": camera_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
(rgbType, "omni.graph.nodes.ConstantToken"),
(infoType, "omni.graph.nodes.ConstantToken"),
(depthType, "omni.graph.nodes.ConstantToken"),
(depthPclType, "omni.graph.nodes.ConstantToken"),
] + leftCamNodes["create"] + rightCamNodes["create"],
og.Controller.Keys.CONNECT: leftCamNodes["connect"] + rightCamNodes["connect"],
og.Controller.Keys.SET_VALUES: [
(f"{rgbType}.inputs:value", "rgb"),
(f"{infoType}.inputs:value", "camera_info"),
(f"{depthType}.inputs:value", "depth"),
(f"{depthPclType}.inputs:value", "depth_pcl"),
] + leftCamNodes["setvalues"] + rightCamNodes["setvalues"],
}
)
set_target_prims(primPath=f"{camera_graph}/RightCamSet", targetPrimPaths=[self.depth_right_camera_path], inputName="inputs:cameraPrim")
set_target_prims(primPath=f"{camera_graph}/LeftCamSet", targetPrimPaths=[self.depth_left_camera_path], inputName="inputs:cameraPrim")
return
def setup_imu_action_graph(self, robot_prim_path):
sensor_graph = "{}/imu_sensor_graph".format(robot_prim_path)
swerve_link = "{}/swerve_chassis_link".format(robot_prim_path)
lidar_link = "{}/lidar_link/lidar".format(robot_prim_path)
og.Controller.edit(
{"graph_path": sensor_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
# General Nodes
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("SimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
# Odometry Nodes
("ComputeOdometry", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("PublishOdometry", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("RawOdomTransform", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
# LiDAR Nodes
# ("ReadLidar", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
# ("PublishLidar", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
# IMU Nodes
("IsaacReadImu", "omni.isaac.sensor.IsaacReadIMU"),
("PublishImu", "omni.isaac.ros2_bridge.ROS2PublishImu"),
],
og.Controller.Keys.SET_VALUES: [
("PublishOdometry.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishImu.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:frameId", f"{NAMESPACE}/lidar_link"),
("RawOdomTransform.inputs:childFrameId", f"{NAMESPACE}/base_link"),
("RawOdomTransform.inputs:parentFrameId", f"{NAMESPACE}/zed/odom"),
("PublishOdometry.inputs:chassisFrameId", f"{NAMESPACE}/base_link"),
("PublishOdometry.inputs:odomFrameId", f"{NAMESPACE}/odom"),
("PublishImu.inputs:frameId", f"{NAMESPACE}/zed2i_imu_link"),
("PublishOdometry.inputs:topicName", "zed/odom")
],
og.Controller.Keys.CONNECT: [
# Odometry Connections
("OnPlaybackTick.outputs:tick", "ComputeOdometry.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "RawOdomTransform.inputs:execIn"),
("ComputeOdometry.outputs:execOut", "PublishOdometry.inputs:execIn"),
("ComputeOdometry.outputs:angularVelocity", "PublishOdometry.inputs:angularVelocity"),
("ComputeOdometry.outputs:linearVelocity", "PublishOdometry.inputs:linearVelocity"),
("ComputeOdometry.outputs:orientation", "PublishOdometry.inputs:orientation"),
("ComputeOdometry.outputs:orientation", "RawOdomTransform.inputs:rotation"),
("ComputeOdometry.outputs:position", "PublishOdometry.inputs:position"),
("ComputeOdometry.outputs:position", "RawOdomTransform.inputs:translation"),
("Context.outputs:context", "PublishOdometry.inputs:context"),
("Context.outputs:context", "RawOdomTransform.inputs:context"),
("SimTime.outputs:simulationTime", "PublishOdometry.inputs:timeStamp"),
("SimTime.outputs:simulationTime", "RawOdomTransform.inputs:timeStamp"),
# LiDAR Connections
# ("OnPlaybackTick.outputs:tick", "ReadLidar.inputs:execIn"),
# ("ReadLidar.outputs:execOut", "PublishLidar.inputs:execIn"),
# ("Context.outputs:context", "PublishLidar.inputs:context"),
# ("SimTime.outputs:simulationTime", "PublishLidar.inputs:timeStamp"),
# ("ReadLidar.outputs:azimuthRange", "PublishLidar.inputs:azimuthRange"),
# ("ReadLidar.outputs:depthRange", "PublishLidar.inputs:depthRange"),
# ("ReadLidar.outputs:horizontalFov", "PublishLidar.inputs:horizontalFov"),
# ("ReadLidar.outputs:horizontalResolution", "PublishLidar.inputs:horizontalResolution"),
# ("ReadLidar.outputs:intensitiesData", "PublishLidar.inputs:intensitiesData"),
# ("ReadLidar.outputs:linearDepthData", "PublishLidar.inputs:linearDepthData"),
# ("ReadLidar.outputs:numCols", "PublishLidar.inputs:numCols"),
# ("ReadLidar.outputs:numRows", "PublishLidar.inputs:numRows"),
# ("ReadLidar.outputs:rotationRate", "PublishLidar.inputs:rotationRate"),
# IMU Connections
("OnPlaybackTick.outputs:tick", "IsaacReadImu.inputs:execIn"),
("IsaacReadImu.outputs:execOut", "PublishImu.inputs:execIn"),
("Context.outputs:context", "PublishImu.inputs:context"),
("SimTime.outputs:simulationTime", "PublishImu.inputs:timeStamp"),
("IsaacReadImu.outputs:angVel", "PublishImu.inputs:angularVelocity"),
("IsaacReadImu.outputs:linAcc", "PublishImu.inputs:linearAcceleration"),
("IsaacReadImu.outputs:orientation", "PublishImu.inputs:orientation"),
],
}
)
# Setup target prims for the Odometry and the Lidar
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/IsaacReadImu", targetPrimPaths=[self.imu_prim_path], inputName="inputs:imuPrim")
return
def setup_robot_action_graph(self, robot_prim_path):
robot_controller_path = f"{robot_prim_path}/ros_interface_controller"
og.Controller.edit(
{"graph_path": robot_controller_path, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeJointState.inputs:topicName", "isaac_joint_commands"),
("articulation_controller.inputs:usePath", False),
("SubscribeJointState.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishJointState.inputs:nodeNamespace", f"/{NAMESPACE}"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "articulation_controller.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeJointState.inputs:context"),
("SubscribeJointState.outputs:jointNames", "articulation_controller.inputs:jointNames"),
("SubscribeJointState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"),
("SubscribeJointState.outputs:positionCommand", "articulation_controller.inputs:positionCommand"),
],
}
)
set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path])
return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
async def setup_post_clear(self):
return
def world_cleanup(self):
carb.log_info(f"Removing {self.robot_name}")
if self._world is not None:
self._world.scene.remove_object(self.robot_name)
return
| 29,278 | Python | 54.663498 | 164 | 0.609092 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/docs/CHANGELOG.md | **********
CHANGELOG
**********
[0.1.0] - 2022-6-26
[0.1.1] - 2022-10-15
========================
Added
-------
- Initial version of Swerve Bot Extension
- Enhanced physX
| 175 | Markdown | 10.733333 | 41 | 0.468571 |
RoboEagles4828/edna2023/isaac/exts/omni.isaac.edna/docs/README.md | # Usage
To enable this extension, go to the Extension Manager menu and enable omni.isaac.swerve_bot extension.
| 113 | Markdown | 21.799996 | 102 | 0.787611 |
RoboEagles4828/edna2023/isaac/Swervesim/rlgpu_conda_env.yml | name: rlgpu
channels:
- pytorch
- conda-forge
- defaults
dependencies:
- python=3.8
- pytorch=1.8.1
- torchvision=0.9.1
- cudatoolkit=11.1
- pyyaml>=5.3.1
- scipy>=1.5.0
- tensorboard==2.9.0
- tensorboard-plugin-wit==1.8.1
- protobuf==3.9.2
| 268 | YAML | 14.823529 | 34 | 0.615672 |
RoboEagles4828/edna2023/isaac/Swervesim/setup.py | """Installation script for the 'isaacgymenvs' python package."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from setuptools import setup, find_packages
import os
import compileall
compileall.compile_dir('swervesim')
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
"protobuf==3.20.1",
"omegaconf==2.1.1",
"hydra-core==1.1.1",
"redis==3.5.3", # needed by Ray on Windows
"rl-games==1.5.2",
"shapely"
]
# Installation operation
setup(
name="swervesim",
author="NVIDIA",
version="1.1.0",
description="RL environments for robot learning in NVIDIA Isaac Sim.",
keywords=["robotics", "rl"],
include_package_data=True,
install_requires=INSTALL_REQUIRES,
packages=find_packages("."),
classifiers=["Natural Language :: English", "Programming Language :: Python :: 3.7, 3.8"],
zip_safe=False,
)
# EOF
| 952 | Python | 24.078947 | 94 | 0.681723 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/envs/vec_env_rlgames_mt.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from omni.isaac.gym.vec_env import VecEnvMT
from omni.isaac.gym.vec_env import TaskStopException
from .vec_env_rlgames import VecEnvRLGames
import torch
import numpy as np
# VecEnv Wrapper for RL training
class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT):
def _parse_data(self, data):
self._obs = data["obs"].clone()
self._rew = data["rew"].to(self._task.rl_device).clone()
self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = data["reset"].to(self._task.rl_device).clone()
self._extras = data["extras"].copy()
def step(self, actions):
if self._stop:
raise TaskStopException()
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(actions=actions, reset_buf=self._task.reset_buf)
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone()
self.send_actions(actions)
data = self.get_data()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(observations=self._obs.to(self._task.rl_device), reset_buf=self._task.reset_buf)
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device)
obs_dict = {}
obs_dict["obs"] = self._obs
obs_dict["states"] = self._states
return obs_dict, self._rew, self._resets, self._extras
| 3,148 | Python | 43.352112 | 163 | 0.715057 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/envs/vec_env_rlgames.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from omni.isaac.gym.vec_env import VecEnvBase
import torch
import numpy as np
from datetime import datetime
# VecEnv Wrapper for RL training
class VecEnvRLGames(VecEnvBase):
def _process_data(self):
self._obs = torch.clamp(self._obs, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._rew = self._rew.to(self._task.rl_device).clone()
self._states = torch.clamp(self._states, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()
self._resets = self._resets.to(self._task.rl_device).clone()
self._extras = self._extras.copy()
def set_task(
self, task, backend="numpy", sim_params=None, init_sim=True
) -> None:
super().set_task(task, backend, sim_params, init_sim)
self.num_states = self._task.num_states
self.state_space = self._task.state_space
def step(self, actions):
if self._task.randomize_actions:
actions = self._task._dr_randomizer.apply_actions_randomization(actions=actions, reset_buf=self._task.reset_buf)
actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone()
self._task.pre_physics_step(actions)
for _ in range(self._task.control_frequency_inv):
self._world.step(render=self._render)
self.sim_frame_count += 1
self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step()
if self._task.randomize_observations:
self._obs = self._task._dr_randomizer.apply_observations_randomization(
observations=self._obs.to(device=self._task.rl_device), reset_buf=self._task.reset_buf)
self._states = self._task.get_states()
self._process_data()
obs_dict = {"obs": self._obs, "states": self._states}
return obs_dict, self._rew, self._resets, self._extras
def reset(self):
""" Resets the task and applies default zero actions to recompute observations and states. """
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{now}] Running RL reset")
self._task.reset()
actions = torch.zeros((self.num_envs, self._task.num_actions), device=self._task.rl_device)
obs_dict, _, _, _ = self.step(actions)
return obs_dict
| 3,933 | Python | 42.230769 | 124 | 0.690567 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/swerve_field.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from swervesim.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView, GeometryPrim
from omni.isaac.core.utils.stage import add_reference_to_stage
import numpy as np
import torch
import math
class Swerve_Field_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 29
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._ball_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_target()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
# Allows for position tracking of targets
# self._balls = RigidPrimView(
# prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
# scene.add(self._balls)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
# def get_target(self):
# # Adds a red ball as target
# radius = 0.1 # meters
# color = torch.tensor([0, 0, 1])
# ball = DynamicSphere(
# prim_path=self.default_zero_env_path + "/ball",
# translation=self._ball_position,
# name="target_0",
# radius=radius,
# color=color,
# )
# self._sim_config.apply_articulation_settings("ball", get_prim_at_path(
# ball.prim_path), self._sim_config.parse_actor_config("ball"))
# ball.set_collision_enabled(False)
def get_target(self):
# world = self.get_world()
self.task_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.task_path, "../../../../../../../.."))
field = os.path.join(self.project_root_path, "isaac/assets/2023_field/FE-2023.usd")
add_reference_to_stage(usd_path=field,prim_path=self.default_zero_env_path+"/Field")
cone = os.path.join(self.project_root_path, "isaac/assets/2023_field/parts/cone_without_deformable_body.usd")
cube = os.path.join(self.project_root_path, "isaac/assets/2023_field/parts/cube_without_deformable_body.usd")
chargestation = os.path.join(self.project_root_path, "isaac/assets/Charge Station/Assembly-1.usd")
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation_1")
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation_2")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_1")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_2")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_3")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_4")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_5")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_6")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_7")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_8")
self.cone_1 = GeometryPrim(self.default_zero_env_path+"/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,0.0]))
self.cone_2 = GeometryPrim(self.default_zero_env_path+"/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0]))
self.cone_3 = GeometryPrim(self.default_zero_env_path+"/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0]))
self.cone_4 = GeometryPrim(self.default_zero_env_path+"/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0]))
chargestation_1 = GeometryPrim(self.default_zero_env_path+"/ChargeStation_1","cone_3_view",position=np.array([-4.20298,-0.56861,0.0]))
chargestation_2 = GeometryPrim(self.default_zero_env_path+"/ChargeStation_2","cone_4_view",position=np.array([4.20298,0.56861,0.0]))
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_1")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_2")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_3")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_4")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_5")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_6")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_7")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_8")
self.cube_1 = GeometryPrim(self.default_zero_env_path+"/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121]))
self.cube_2 = GeometryPrim(self.default_zero_env_path+"/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121]))
self.cube_3 = GeometryPrim(self.default_zero_env_path+"/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121]))
self.cube_4 = GeometryPrim(self.default_zero_env_path+"/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121]))
return
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(
clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
# root_linvels = self.root_velocities[:, :3]
# root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:6] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 6:9] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 9:13] = root_quats
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
if (i == 1):
print(f"front_left_position:{front_left_position}")
print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
# self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
# self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-20, 20)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 20 - 1
self.target_positions[envs_long, 2] = 0.1
# print(self.target_positions)
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
self._balls.set_world_poses(
ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = self.rew_buf
# rewards for moving away form starting point
for i in range(len(self.root_position_reward)):
self.root_position_reward[i] = sum(root_positions[i][0:3])
self.rew_buf[:] = self.root_position_reward*pos_reward
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
| 20,572 | Python | 46.18578 | 142 | 0.615545 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/swerve_multi_action_auton.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from swervesim.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView
import numpy as np
import torch
import math
class Swerve_Multi_Action_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 29
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._ball_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_target()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
# Allows for position tracking of targets
self._balls = RigidPrimView(
prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
scene.add(self._balls)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
def get_target(self):
# Adds a red ball as target
radius = 0.1 # meters
color = torch.tensor([0, 0, 1])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(
ball.prim_path), self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(
clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
if (i == 1):
print(f"front_left_position:{front_left_position}")
print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-20, 20)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 20 - 1
self.target_positions[envs_long, 2] = 0.1
# print(self.target_positions)
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
self._balls.set_world_poses(
ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = self.rew_buf
# rewards for moving away form starting point
for i in range(len(self.root_position_reward)):
self.root_position_reward[i] = sum(root_positions[i][0:3])
self.rew_buf[:] = self.root_position_reward*pos_reward
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
| 17,197 | Python | 42.319899 | 141 | 0.605338 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/swerve_with_kinematics.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from swervesim.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView
import numpy as np
import torch
import math
class Swerve_Kinematics_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 29
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._ball_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_target()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
# Allows for position tracking of targets
self._balls = RigidPrimView(
prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
scene.add(self._balls)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
def get_target(self):
# Adds a red ball as target
radius = 0.1 # meters
color = torch.tensor([0, 0, 1])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(
ball.prim_path), self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(
clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
if (i == 1):
print(f"front_left_position:{front_left_position}")
print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-20, 20)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 20 - 1
self.target_positions[envs_long, 2] = 0.1
# print(self.target_positions)
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
self._balls.set_world_poses(
ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = self.rew_buf
# rewards for moving away form starting point
for i in range(len(self.root_position_reward)):
self.root_position_reward[i] = sum(root_positions[i][0:3])
self.rew_buf[:] = self.root_position_reward*pos_reward
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
| 16,912 | Python | 42.035623 | 141 | 0.605251 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/swerve.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from swervesim.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView
import numpy as np
import torch
import math
class Swerve_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 29
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._ball_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_target()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
# Allows for position tracking of targets
self._balls = RigidPrimView(
prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
scene.add(self._balls)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
def get_target(self):
# Adds a red ball as target
radius = 0.1 # meters
color = torch.tensor([0, 0, 1])
ball = DynamicSphere(
prim_path=self.default_zero_env_path + "/ball",
translation=self._ball_position,
name="target_0",
radius=radius,
color=color,
)
self._sim_config.apply_articulation_settings("ball", get_prim_at_path(
ball.prim_path), self._sim_config.parse_actor_config("ball"))
ball.set_collision_enabled(False)
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(
clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
if (i == 1):
print(f"front_left_position:{front_left_position}")
print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-20, 20)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 20 - 1
self.target_positions[envs_long, 2] = 0.1
# print(self.target_positions)
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
self._balls.set_world_poses(
ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = self.rew_buf
# rewards for moving away form starting point
for i in range(len(self.root_position_reward)):
self.root_position_reward[i] = sum(root_positions[i][0:3])
self.rew_buf[:] = self.root_position_reward*pos_reward
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
| 16,901 | Python | 42.007633 | 141 | 0.605053 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/swerve_charge_station.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from swervesim.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.robots.articulations.views.charge_station_view import ChargeStationView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.stage import add_reference_to_stage
import numpy as np
import torch
import math
from shapely.geometry import Polygon
class Swerve_Charge_Station_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10*math.pi
self.dt = 1 / 10
self.dt_total = 0.0
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 37
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._chargestation_part_1_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_rotation = torch.zeros(
(self._num_envs, 4), device=self._device, dtype=torch.float32) #ypr
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_charge_station()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
self._charge_station= ChargeStationView(prim_paths_expr="/World/envs/.*/ChargeStation", name="ChargeStation_1_view")
# Allows for position tracking of targets
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
scene.add(self._charge_station)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
def get_charge_station(self):
chargestation = "/root/edna/isaac/assets/ChargeStation-Copy/Assembly-1.usd"
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation")
charge_station_1 = Articulation(prim_path=self.default_zero_env_path+"/ChargeStation",name="ChargeStation")
self._sim_config.apply_articulation_settings("ChargeStation", get_prim_at_path(
charge_station_1.prim_path), self._sim_config.parse_actor_config("ChargeStation"))
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.charge_station_pos, self.charge_station_rot = self._charge_station.get_world_poses(clone=False)
self.chargestation_vertices = torch.zeros(
(self._num_envs, 8), device=self._device, dtype=torch.float32) #ypr
charge_station_pos = self.charge_station_pos - self._env_pos
for i in range(len(self.charge_station_pos)):
w=self.charge_station_rot[i][0]
x=self.charge_station_rot[i][1]
y=self.charge_station_rot[i][2]
z=self.charge_station_rot[i][3]
# print(f"x:{x} y:{y} z:{z} w:{w}")
siny_cosp = 2 * (w * z + x * y)
cosy_cosp = 1 - 2 * (y * y + z * z)
angle = math.atan2(siny_cosp, cosy_cosp)
self.chargestation_vertices[i][0] , self.chargestation_vertices[i][1] = findB(charge_station_pos[i][0],charge_station_pos[i][1],math.pi-angle)
self.chargestation_vertices[i][2] , self.chargestation_vertices[i][3] = findB(charge_station_pos[i][0],charge_station_pos[i][1],angle)
self.chargestation_vertices[i][4] , self.chargestation_vertices[i][5] = findB(charge_station_pos[i][0],charge_station_pos[i][1],(2*math.pi)-angle)
self.chargestation_vertices[i][6] , self.chargestation_vertices[i][7] = findB(charge_station_pos[i][0],charge_station_pos[i][1],angle+math.pi)
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
self.obs_buf[..., 29:37] = self.chargestation_vertices
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
# if (i == 1):
# print(f"front_left_position:{front_left_position}")
# print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
self.dt_total = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
self.initial_charge_station_pos, self.initial_charge_station_rot = self._charge_station.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-8, 8)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 8 - 1
self.target_rotation[envs_long, 0]= 0
self.target_rotation[envs_long, 1]= torch.rand((num_sets), device=self._device)
# self.target_rotation = self.target_rotation[envs_long]+self.initial_charge_station_rot[envs_long]
self.target_rotation[envs_long, 2]= 1
self.target_rotation[envs_long, 3] = 0#
self.target_positions[envs_long,2] = 0
# print(self.target_positions)
# shift the target up so it visually aligns better
charge_station_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
# print(self.initial_charge_station_rot)
# print(self.target_rotation)
self._charge_station.set_world_poses(
charge_station_pos[:, 0:3], self.target_rotation[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
self.dt_total += self.dt
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
charge_station_score = in_charge_station(self.chargestation_vertices,self._swerve.get_axle_positions(), self._device)
balance_reward = torch.mul(self._charge_station.if_balanced(self._device)[0],charge_station_score[:])*100
# print(f"shape_balance:{balance_reward.shape}")
# print(charge_station_score.tolist())
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = torch.zeros_like(self.rew_buf)
# rewards for moving away form starting point
# for i in range(len(self.root_position_reward)):
# self.root_position_reward[i] = sum(root_positions[i][0:3])
self.root_position_reward = torch.tensor([sum(i[0:3]) for i in root_positions], device=self._device)
# print(f"shape_numerator:{numerator.shape}")
numerator = self.root_position_reward*pos_reward+balance_reward
self.rew_buf[:] = torch.div(numerator,1+self.dt_total)
print('REWARDS: ', torch.div(numerator,1+self.dt_total))
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# die = torch.where(abs(math.atan2(2*self.root_rot[..., 2]*self.root_rot[..., 0] - 2*self.root_rot[1]*self.root_rot[..., 3], 1 - 2*self.root_rot[..., 2]*self.root_rot[..., 2] - 2*self.root_rot[..., 3]*self.root_rot[..., 3])) > math.pi/2, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
def findB(Cx,Cy, angle_change,angle_init=0.463647609,r=1.363107039084):
L= angle_init*r
if(angle_change < 0):
angle_init -= angle_change
else:
angle_init += angle_change
Bx = Cx + r*math.cos(angle_init)
By = Cy + r*math.sin(angle_init)
return Bx, By
def in_charge_station(charge_station_verticies,axle_position, device):
if_in_chargestation = torch.tensor([check_point_2(i, j) for i, j in zip(charge_station_verticies, axle_position)], device=device)
return if_in_chargestation
def check_point(r,m):
def dot(a, b):
return a[0]*b[0] + a[1]*b[1]
# print(len(m))
for i in range(4):
AB = [r[3]-r[1],r[2]-r[0]]
AM = [m[3*i]-r[1],m[3*i + 1]-r[0]]
BC = [r[5]-r[3],r[4]-r[2]]
BM = [m[3*i]-r[3],m[3*i + 1]-r[2]]
dotABAM = dot(AB, AM)
dotABAB = dot(AB, AB)
dotBCBC = dot(BC, BC)
dotBCBM = dot(BC, BM)
out = 0 <= dotABAM and dotABAM <= dotABAB and 0 <= dotBCBM and dotBCBM <= dotBCBC
if out == False:
return 0.0
return 1.0
def check_point_2(r, m):
charge_station = Polygon([(r[0], r[1]), (r[2], r[3]), (r[4], r[5]), (r[6], r[7])])
swerve = Polygon([(m[0], m[1]), (m[4], m[5]), (m[7], m[8]), (m[10], m[11])])
if charge_station.contains(swerve):
return 1.0
return 0.0
| 21,513 | Python | 44.484144 | 256 | 0.611119 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/base/rl_task.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from abc import abstractmethod
import numpy as np
import torch
from gym import spaces
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.prims import define_prim
from omni.isaac.cloner import GridCloner
from swervesim.tasks.utils.usd_utils import create_distant_light
from swervesim.utils.domain_randomization.randomize import Randomizer
import omni.kit
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Gf
class RLTask(BaseTask):
""" This class provides a PyTorch RL-specific interface for setting up RL tasks.
It includes utilities for setting up RL task related parameters,
cloning environments, and data collection for RL algorithms.
"""
def __init__(self, name, env, offset=None) -> None:
""" Initializes RL parameters, cloner object, and buffers.
Args:
name (str): name of the task.
env (VecEnvBase): an instance of the environment wrapper class to register task.
offset (Optional[np.ndarray], optional): offset applied to all assets of the task. Defaults to None.
"""
super().__init__(name=name, offset=offset)
self.test = self._cfg["test"]
self._device = self._cfg["sim_device"]
self._dr_randomizer = Randomizer(self._sim_config)
print("Task Device:", self._device)
self.randomize_actions = False
self.randomize_observations = False
self.clip_obs = self._cfg["task"]["env"].get("clipObservations", np.Inf)
self.clip_actions = self._cfg["task"]["env"].get("clipActions", np.Inf)
self.rl_device = self._cfg.get("rl_device", "cuda:0")
self.control_frequency_inv = self._cfg["task"]["env"].get("controlFrequencyInv", 1)
print("RL device: ", self.rl_device)
self._env = env
if not hasattr(self, "_num_agents"):
self._num_agents = 1 # used for multi-agent environments
if not hasattr(self, "_num_states"):
self._num_states = 0
# initialize data spaces (defaults to gym.Box)
if not hasattr(self, "action_space"):
self.action_space = spaces.Box(np.ones(self.num_actions) * -1.0, np.ones(self.num_actions) * 1.0)
if not hasattr(self, "observation_space"):
self.observation_space = spaces.Box(np.ones(self.num_observations) * -np.Inf, np.ones(self.num_observations) * np.Inf)
if not hasattr(self, "state_space"):
self.state_space = spaces.Box(np.ones(self.num_states) * -np.Inf, np.ones(self.num_states) * np.Inf)
self._cloner = GridCloner(spacing=self._env_spacing)
self._cloner.define_base_env(self.default_base_env_path)
define_prim(self.default_zero_env_path)
self.cleanup()
def cleanup(self) -> None:
""" Prepares torch buffers for RL data collection."""
# prepare tensors
self.obs_buf = torch.zeros((self._num_envs, self.num_observations), device=self._device, dtype=torch.float)
self.states_buf = torch.zeros((self._num_envs, self.num_states), device=self._device, dtype=torch.float)
self.rew_buf = torch.zeros(self._num_envs, device=self._device, dtype=torch.float)
self.reset_buf = torch.ones(self._num_envs, device=self._device, dtype=torch.long)
self.progress_buf = torch.zeros(self._num_envs, device=self._device, dtype=torch.long)
self.extras = {}
def set_up_scene(self, scene, replicate_physics=True) -> None:
""" Clones environments based on value provided in task config and applies collision filters to mask
collisions across environments.
Args:
scene (Scene): Scene to add objects to.
replicate_physics (bool): Clone physics using PhysX API for better performance
"""
super().set_up_scene(scene)
collision_filter_global_paths = list()
if self._sim_config.task_config["sim"].get("add_ground_plane", True):
self._ground_plane_path = "/World/defaultGroundPlane"
collision_filter_global_paths.append(self._ground_plane_path)
scene.add_default_ground_plane(prim_path=self._ground_plane_path)
prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs)
self._env_pos = self._cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=prim_paths, replicate_physics=replicate_physics)
self._env_pos = torch.tensor(np.array(self._env_pos), device=self._device, dtype=torch.float)
self._cloner.filter_collisions(
self._env._world.get_physics_context().prim_path, "/World/collisions", prim_paths, collision_filter_global_paths)
self.set_initial_camera_params(camera_position=[10, 10, 3], camera_target=[0, 0, 0])
if self._sim_config.task_config["sim"].get("add_distant_light", True):
create_distant_light()
def set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]):
if self._env._render:
viewport_api_2 = get_viewport_from_window_name("Viewport")
viewport_api_2.set_active_camera("/OmniverseKit_Persp")
camera_state = ViewportCameraState("/OmniverseKit_Persp", viewport_api_2)
camera_state.set_position_world(Gf.Vec3d(camera_position[0], camera_position[1], camera_position[2]), True)
camera_state.set_target_world(Gf.Vec3d(camera_target[0], camera_target[1], camera_target[2]), True)
@property
def default_base_env_path(self):
""" Retrieves default path to the parent of all env prims.
Returns:
default_base_env_path(str): Defaults to "/World/envs".
"""
return "/World/envs"
@property
def default_zero_env_path(self):
""" Retrieves default path to the first env prim (index 0).
Returns:
default_zero_env_path(str): Defaults to "/World/envs/env_0".
"""
return f"{self.default_base_env_path}/env_0"
@property
def num_envs(self):
""" Retrieves number of environments for task.
Returns:
num_envs(int): Number of environments.
"""
return self._num_envs
@property
def num_actions(self):
""" Retrieves dimension of actions.
Returns:
num_actions(int): Dimension of actions.
"""
return self._num_actions
@property
def num_observations(self):
""" Retrieves dimension of observations.
Returns:
num_observations(int): Dimension of observations.
"""
return self._num_observations
@property
def num_states(self):
""" Retrieves dimesion of states.
Returns:
num_states(int): Dimension of states.
"""
return self._num_states
@property
def num_agents(self):
""" Retrieves number of agents for multi-agent environments.
Returns:
num_agents(int): Dimension of states.
"""
return self._num_agents
def get_states(self):
""" API for retrieving states buffer, used for asymmetric AC training.
Returns:
states_buf(torch.Tensor): States buffer.
"""
return self.states_buf
def get_extras(self):
""" API for retrieving extras data for RL.
Returns:
extras(dict): Dictionary containing extras data.
"""
return self.extras
def reset(self):
""" Flags all environments for reset.
"""
self.reset_buf = torch.ones_like(self.reset_buf)
def pre_physics_step(self, actions):
""" Optionally implemented by individual task classes to process actions.
Args:
actions (torch.Tensor): Actions generated by RL policy.
"""
pass
def post_physics_step(self):
""" Processes RL required computations for observations, states, rewards, resets, and extras.
Also maintains progress buffer for tracking step count per environment.
Returns:
obs_buf(torch.Tensor): Tensor of observation data.
rew_buf(torch.Tensor): Tensor of rewards data.
reset_buf(torch.Tensor): Tensor of resets/dones data.
extras(dict): Dictionary of extras data.
"""
self.progress_buf[:] += 1
if self._env._world.is_playing():
self.get_observations()
self.get_states()
self.calculate_metrics()
self.is_done()
self.get_extras()
return self.obs_buf, self.rew_buf, self.reset_buf, self.extras
| 10,338 | Python | 39.073643 | 140 | 0.653705 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/utils/anymal_terrain_generator.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
import torch
import math
from swervesim.utils.terrain_utils.terrain_utils import *
# terrain generator
class Terrain:
def __init__(self, cfg, num_robots) -> None:
self.horizontal_scale = 0.1
self.vertical_scale = 0.005
self.border_size = 20
self.num_per_env = 2
self.env_length = cfg["mapLength"]
self.env_width = cfg["mapWidth"]
self.proportions = [np.sum(cfg["terrainProportions"][:i+1]) for i in range(len(cfg["terrainProportions"]))]
self.env_rows = cfg["numLevels"]
self.env_cols = cfg["numTerrains"]
self.num_maps = self.env_rows * self.env_cols
self.num_per_env = int(num_robots / self.num_maps)
self.env_origins = np.zeros((self.env_rows, self.env_cols, 3))
self.width_per_env_pixels = int(self.env_width / self.horizontal_scale)
self.length_per_env_pixels = int(self.env_length / self.horizontal_scale)
self.border = int(self.border_size/self.horizontal_scale)
self.tot_cols = int(self.env_cols * self.width_per_env_pixels) + 2 * self.border
self.tot_rows = int(self.env_rows * self.length_per_env_pixels) + 2 * self.border
self.height_field_raw = np.zeros((self.tot_rows , self.tot_cols), dtype=np.int16)
if cfg["curriculum"]:
self.curiculum(num_robots, num_terrains=self.env_cols, num_levels=self.env_rows)
else:
self.randomized_terrain()
self.heightsamples = self.height_field_raw
self.vertices, self.triangles = convert_heightfield_to_trimesh(self.height_field_raw, self.horizontal_scale, self.vertical_scale, cfg["slopeTreshold"])
def randomized_terrain(self):
for k in range(self.num_maps):
# Env coordinates in the world
(i, j) = np.unravel_index(k, (self.env_rows, self.env_cols))
# Heightfield coordinate system from now on
start_x = self.border + i * self.length_per_env_pixels
end_x = self.border + (i + 1) * self.length_per_env_pixels
start_y = self.border + j * self.width_per_env_pixels
end_y = self.border + (j + 1) * self.width_per_env_pixels
terrain = SubTerrain("terrain",
width=self.width_per_env_pixels,
length=self.width_per_env_pixels,
vertical_scale=self.vertical_scale,
horizontal_scale=self.horizontal_scale)
choice = np.random.uniform(0, 1)
if choice < 0.1:
if np.random.choice([0, 1]):
pyramid_sloped_terrain(terrain, np.random.choice([-0.3, -0.2, 0, 0.2, 0.3]))
random_uniform_terrain(terrain, min_height=-0.1, max_height=0.1, step=0.05, downsampled_scale=0.2)
else:
pyramid_sloped_terrain(terrain, np.random.choice([-0.3, -0.2, 0, 0.2, 0.3]))
elif choice < 0.6:
# step_height = np.random.choice([-0.18, -0.15, -0.1, -0.05, 0.05, 0.1, 0.15, 0.18])
step_height = np.random.choice([-0.15, 0.15])
pyramid_stairs_terrain(terrain, step_width=0.31, step_height=step_height, platform_size=3.)
elif choice < 1.:
discrete_obstacles_terrain(terrain, 0.15, 1., 2., 40, platform_size=3.)
self.height_field_raw[start_x: end_x, start_y:end_y] = terrain.height_field_raw
env_origin_x = (i + 0.5) * self.env_length
env_origin_y = (j + 0.5) * self.env_width
x1 = int((self.env_length/2. - 1) / self.horizontal_scale)
x2 = int((self.env_length/2. + 1) / self.horizontal_scale)
y1 = int((self.env_width/2. - 1) / self.horizontal_scale)
y2 = int((self.env_width/2. + 1) / self.horizontal_scale)
env_origin_z = np.max(terrain.height_field_raw[x1:x2, y1:y2])*self.vertical_scale
self.env_origins[i, j] = [env_origin_x, env_origin_y, env_origin_z]
def curiculum(self, num_robots, num_terrains, num_levels):
num_robots_per_map = int(num_robots / num_terrains)
left_over = num_robots % num_terrains
idx = 0
for j in range(num_terrains):
for i in range(num_levels):
terrain = SubTerrain("terrain",
width=self.width_per_env_pixels,
length=self.width_per_env_pixels,
vertical_scale=self.vertical_scale,
horizontal_scale=self.horizontal_scale)
difficulty = i / num_levels
choice = j / num_terrains
slope = difficulty * 0.4
step_height = 0.05 + 0.175 * difficulty
discrete_obstacles_height = 0.025 + difficulty * 0.15
stepping_stones_size = 2 - 1.8 * difficulty
if choice < self.proportions[0]:
if choice < 0.05:
slope *= -1
pyramid_sloped_terrain(terrain, slope=slope, platform_size=3.)
elif choice < self.proportions[1]:
if choice < 0.15:
slope *= -1
pyramid_sloped_terrain(terrain, slope=slope, platform_size=3.)
random_uniform_terrain(terrain, min_height=-0.1, max_height=0.1, step=0.025, downsampled_scale=0.2)
elif choice < self.proportions[3]:
if choice<self.proportions[2]:
step_height *= -1
pyramid_stairs_terrain(terrain, step_width=0.31, step_height=step_height, platform_size=3.)
elif choice < self.proportions[4]:
discrete_obstacles_terrain(terrain, discrete_obstacles_height, 1., 2., 40, platform_size=3.)
else:
stepping_stones_terrain(terrain, stone_size=stepping_stones_size, stone_distance=0.1, max_height=0., platform_size=3.)
# Heightfield coordinate system
start_x = self.border + i * self.length_per_env_pixels
end_x = self.border + (i + 1) * self.length_per_env_pixels
start_y = self.border + j * self.width_per_env_pixels
end_y = self.border + (j + 1) * self.width_per_env_pixels
self.height_field_raw[start_x: end_x, start_y:end_y] = terrain.height_field_raw
robots_in_map = num_robots_per_map
if j < left_over:
robots_in_map +=1
env_origin_x = (i + 0.5) * self.env_length
env_origin_y = (j + 0.5) * self.env_width
x1 = int((self.env_length/2. - 1) / self.horizontal_scale)
x2 = int((self.env_length/2. + 1) / self.horizontal_scale)
y1 = int((self.env_width/2. - 1) / self.horizontal_scale)
y2 = int((self.env_width/2. + 1) / self.horizontal_scale)
env_origin_z = np.max(terrain.height_field_raw[x1:x2, y1:y2])*self.vertical_scale
self.env_origins[i, j] = [env_origin_x, env_origin_y, env_origin_z]
| 8,788 | Python | 52.591463 | 159 | 0.59274 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/utils/usd_utils.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage
from pxr import UsdPhysics, UsdLux
def set_drive_type(prim_path, drive_type):
joint_prim = get_prim_at_path(prim_path)
# set drive type ("angular" or "linear")
drive = UsdPhysics.DriveAPI.Apply(joint_prim, drive_type)
return drive
def set_drive_target_position(drive, target_value):
if not drive.GetTargetPositionAttr():
drive.CreateTargetPositionAttr(target_value)
else:
drive.GetTargetPositionAttr().Set(target_value)
def set_drive_target_velocity(drive, target_value):
if not drive.GetTargetVelocityAttr():
drive.CreateTargetVelocityAttr(target_value)
else:
drive.GetTargetVelocityAttr().Set(target_value)
def set_drive_stiffness(drive, stiffness):
if not drive.GetStiffnessAttr():
drive.CreateStiffnessAttr(stiffness)
else:
drive.GetStiffnessAttr().Set(stiffness)
def set_drive_damping(drive, damping):
if not drive.GetDampingAttr():
drive.CreateDampingAttr(damping)
else:
drive.GetDampingAttr().Set(damping)
def set_drive_max_force(drive, max_force):
if not drive.GetMaxForceAttr():
drive.CreateMaxForceAttr(max_force)
else:
drive.GetMaxForceAttr().Set(max_force)
def set_drive(prim_path, drive_type, target_type, target_value, stiffness, damping, max_force) -> None:
drive = set_drive_type(prim_path, drive_type)
# set target type ("position" or "velocity")
if target_type == "position":
set_drive_target_position(drive, target_value)
elif target_type == "velocity":
set_drive_target_velocity(drive, target_value)
set_drive_stiffness(drive, stiffness)
set_drive_damping(drive, damping)
set_drive_max_force(drive, max_force)
def create_distant_light(prim_path="/World/defaultDistantLight", intensity=5000):
stage = get_current_stage()
light = UsdLux.DistantLight.Define(stage, prim_path)
light.GetPrim().GetAttribute("intensity").Set(intensity)
| 3,628 | Python | 40.238636 | 103 | 0.742007 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/shared/in_hand_manipulation.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from abc import abstractmethod
from swervesim.tasks.base.rl_task import RLTask
from omni.isaac.core.prims import RigidPrimView, XFormPrim
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.stage import get_current_stage, add_reference_to_stage
from omni.isaac.core.utils.torch import *
import numpy as np
import torch
import math
import omni.replicator.isaac as dr
class InHandManipulationTask(RLTask):
def __init__(
self,
name,
env,
offset=None
) -> None:
"""[summary]
"""
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self.dist_reward_scale = self._task_cfg["env"]["distRewardScale"]
self.rot_reward_scale = self._task_cfg["env"]["rotRewardScale"]
self.action_penalty_scale = self._task_cfg["env"]["actionPenaltyScale"]
self.success_tolerance = self._task_cfg["env"]["successTolerance"]
self.reach_goal_bonus = self._task_cfg["env"]["reachGoalBonus"]
self.fall_dist = self._task_cfg["env"]["fallDistance"]
self.fall_penalty = self._task_cfg["env"]["fallPenalty"]
self.rot_eps = self._task_cfg["env"]["rotEps"]
self.vel_obs_scale = self._task_cfg["env"]["velObsScale"]
self.reset_position_noise = self._task_cfg["env"]["resetPositionNoise"]
self.reset_rotation_noise = self._task_cfg["env"]["resetRotationNoise"]
self.reset_dof_pos_noise = self._task_cfg["env"]["resetDofPosRandomInterval"]
self.reset_dof_vel_noise = self._task_cfg["env"]["resetDofVelRandomInterval"]
self.hand_dof_speed_scale = self._task_cfg["env"]["dofSpeedScale"]
self.use_relative_control = self._task_cfg["env"]["useRelativeControl"]
self.act_moving_average = self._task_cfg["env"]["actionsMovingAverage"]
self.max_episode_length = self._task_cfg["env"]["episodeLength"]
self.reset_time = self._task_cfg["env"].get("resetTime", -1.0)
self.print_success_stat = self._task_cfg["env"]["printNumSuccesses"]
self.max_consecutive_successes = self._task_cfg["env"]["maxConsecutiveSuccesses"]
self.av_factor = self._task_cfg["env"].get("averFactor", 0.1)
self.dt = 1.0 / 60
control_freq_inv = self._task_cfg["env"].get("controlFrequencyInv", 1)
if self.reset_time > 0.0:
self.max_episode_length = int(round(self.reset_time/(control_freq_inv * self.dt)))
print("Reset time: ", self.reset_time)
print("New episode length: ", self.max_episode_length)
RLTask.__init__(self, name, env)
self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.y_unit_tensor = torch.tensor([0, 1, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.z_unit_tensor = torch.tensor([0, 0, 1], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.reset_goal_buf = self.reset_buf.clone()
self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device)
self.randomization_buf = torch.zeros(self.num_envs, dtype=torch.long, device=self.device)
self.av_factor = torch.tensor(self.av_factor, dtype=torch.float, device=self.device)
self.total_successes = 0
self.total_resets = 0
return
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
self._assets_root_path = get_assets_root_path()
hand_start_translation, pose_dy, pose_dz = self.get_hand()
self.get_object(hand_start_translation, pose_dy, pose_dz)
self.get_goal()
replicate_physics = False if self._dr_randomizer.randomize else True
super().set_up_scene(scene, replicate_physics)
self._hands = self.get_hand_view(scene)
scene.add(self._hands)
self._objects = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/object/object",
name="object_view",
reset_xform_properties=False,
masses=torch.tensor([0.07087]*self._num_envs, device=self.device),
)
scene.add(self._objects)
self._goals = RigidPrimView(
prim_paths_expr="/World/envs/env_.*/goal/object",
name="goal_view",
reset_xform_properties=False
)
scene.add(self._goals)
if self._dr_randomizer.randomize:
self._dr_randomizer.apply_on_startup_domain_randomization(self)
@abstractmethod
def get_hand(self):
pass
@abstractmethod
def get_hand_view(self):
pass
@abstractmethod
def get_observations(self):
pass
def get_object(self, hand_start_translation, pose_dy, pose_dz):
self.object_start_translation = hand_start_translation.clone()
self.object_start_translation[1] += pose_dy
self.object_start_translation[2] += pose_dz
self.object_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
self.object_usd_path = f"{self._assets_root_path}/Isaac/Props/Blocks/block_instanceable.usd"
add_reference_to_stage(self.object_usd_path, self.default_zero_env_path + "/object")
obj = XFormPrim(
prim_path=self.default_zero_env_path + "/object/object",
name="object",
translation=self.object_start_translation,
orientation=self.object_start_orientation,
scale=self.object_scale,
)
self._sim_config.apply_articulation_settings("object", get_prim_at_path(obj.prim_path), self._sim_config.parse_actor_config("object"))
def get_goal(self):
self.goal_displacement_tensor = torch.tensor([-0.2, -0.06, 0.12], device=self.device)
self.goal_start_translation = self.object_start_translation + self.goal_displacement_tensor
self.goal_start_translation[2] -= 0.04
self.goal_start_orientation = torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.device)
add_reference_to_stage(self.object_usd_path, self.default_zero_env_path + "/goal")
goal = XFormPrim(
prim_path=self.default_zero_env_path + "/goal",
name="goal",
translation=self.goal_start_translation,
orientation=self.goal_start_orientation,
scale=self.object_scale
)
self._sim_config.apply_articulation_settings("goal", get_prim_at_path(goal.prim_path), self._sim_config.parse_actor_config("goal_object"))
def post_reset(self):
self.num_hand_dofs = self._hands.num_dof
self.actuated_dof_indices = self._hands.actuated_dof_indices
self.hand_dof_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.prev_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.cur_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
dof_limits = self._hands.get_dof_limits()
self.hand_dof_lower_limits, self.hand_dof_upper_limits = torch.t(dof_limits[0].to(self.device))
self.hand_dof_default_pos = torch.zeros(self.num_hand_dofs, dtype=torch.float, device=self.device)
self.hand_dof_default_vel = torch.zeros(self.num_hand_dofs, dtype=torch.float, device=self.device)
self.object_init_pos, self.object_init_rot = self._objects.get_world_poses()
self.object_init_pos -= self._env_pos
self.object_init_velocities = torch.zeros_like(self._objects.get_velocities(), dtype=torch.float, device=self.device)
self.goal_pos = self.object_init_pos.clone()
self.goal_pos[:, 2] -= 0.04
self.goal_rot = self.object_init_rot.clone()
self.goal_init_pos = self.goal_pos.clone()
self.goal_init_rot = self.goal_rot.clone()
# randomize all envs
indices = torch.arange(self._num_envs, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
if self._dr_randomizer.randomize:
self._dr_randomizer.set_up_domain_randomization(self)
def get_object_goal_observations(self):
self.object_pos, self.object_rot = self._objects.get_world_poses(clone=False)
self.object_pos -= self._env_pos
self.object_velocities = self._objects.get_velocities(clone=False)
self.object_linvel = self.object_velocities[:, 0:3]
self.object_angvel = self.object_velocities[:, 3:6]
def calculate_metrics(self):
self.rew_buf[:], self.reset_buf[:], self.reset_goal_buf[:], self.progress_buf[:], self.successes[:], self.consecutive_successes[:] = compute_hand_reward(
self.rew_buf, self.reset_buf, self.reset_goal_buf, self.progress_buf, self.successes, self.consecutive_successes,
self.max_episode_length, self.object_pos, self.object_rot, self.goal_pos, self.goal_rot,
self.dist_reward_scale, self.rot_reward_scale, self.rot_eps, self.actions, self.action_penalty_scale,
self.success_tolerance, self.reach_goal_bonus, self.fall_dist, self.fall_penalty,
self.max_consecutive_successes, self.av_factor,
)
self.extras['consecutive_successes'] = self.consecutive_successes.mean()
self.randomization_buf += 1
if self.print_success_stat:
self.total_resets = self.total_resets + self.reset_buf.sum()
direct_average_successes = self.total_successes + self.successes.sum()
self.total_successes = self.total_successes + (self.successes * self.reset_buf).sum()
# The direct average shows the overall result more quickly, but slightly undershoots long term policy performance.
print("Direct average consecutive successes = {:.1f}".format(direct_average_successes/(self.total_resets + self.num_envs)))
if self.total_resets > 0:
print("Post-Reset average consecutive successes = {:.1f}".format(self.total_successes/self.total_resets))
def pre_physics_step(self, actions):
if not self._env._world.is_playing():
return
env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
goal_env_ids = self.reset_goal_buf.nonzero(as_tuple=False).squeeze(-1)
reset_buf = self.reset_buf.clone()
# if only goals need reset, then call set API
if len(goal_env_ids) > 0 and len(env_ids) == 0:
self.reset_target_pose(goal_env_ids)
elif len(goal_env_ids) > 0:
self.reset_target_pose(goal_env_ids)
if len(env_ids) > 0:
self.reset_idx(env_ids)
self.actions = actions.clone().to(self.device)
if self.use_relative_control:
targets = self.prev_targets[:, self.actuated_dof_indices] + self.hand_dof_speed_scale * self.dt * self.actions
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(targets,
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
else:
self.cur_targets[:, self.actuated_dof_indices] = scale(self.actions,
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
self.cur_targets[:, self.actuated_dof_indices] = self.act_moving_average * self.cur_targets[:, self.actuated_dof_indices] + \
(1.0 - self.act_moving_average) * self.prev_targets[:, self.actuated_dof_indices]
self.cur_targets[:, self.actuated_dof_indices] = tensor_clamp(self.cur_targets[:, self.actuated_dof_indices],
self.hand_dof_lower_limits[self.actuated_dof_indices], self.hand_dof_upper_limits[self.actuated_dof_indices])
self.prev_targets[:, self.actuated_dof_indices] = self.cur_targets[:, self.actuated_dof_indices]
self._hands.set_joint_position_targets(
self.cur_targets[:, self.actuated_dof_indices], indices=None, joint_indices=self.actuated_dof_indices
)
if self._dr_randomizer.randomize:
rand_envs = torch.where(self.randomization_buf >= self._dr_randomizer.min_frequency, torch.ones_like(self.randomization_buf), torch.zeros_like(self.randomization_buf))
rand_env_ids = torch.nonzero(torch.logical_and(rand_envs, reset_buf))
dr.physics_view.step_randomization(rand_env_ids)
self.randomization_buf[rand_env_ids] = 0
def is_done(self):
pass
def reset_target_pose(self, env_ids):
# reset goal
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), 4), device=self.device)
new_rot = randomize_rotation(rand_floats[:, 0], rand_floats[:, 1], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids])
self.goal_pos[env_ids] = self.goal_init_pos[env_ids, 0:3]
self.goal_rot[env_ids] = new_rot
goal_pos, goal_rot = self.goal_pos.clone(), self.goal_rot.clone()
goal_pos[env_ids] = self.goal_pos[env_ids] + self.goal_displacement_tensor + self._env_pos[env_ids] # add world env pos
self._goals.set_world_poses(goal_pos[env_ids], goal_rot[env_ids], indices)
self.reset_goal_buf[env_ids] = 0
def reset_idx(self, env_ids):
indices = env_ids.to(dtype=torch.int32)
rand_floats = torch_rand_float(-1.0, 1.0, (len(env_ids), self.num_hand_dofs * 2 + 5), device=self.device)
self.reset_target_pose(env_ids)
# reset object
new_object_pos = self.object_init_pos[env_ids] + \
self.reset_position_noise * rand_floats[:, 0:3] + self._env_pos[env_ids] # add world env pos
new_object_rot = randomize_rotation(rand_floats[:, 3], rand_floats[:, 4], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids])
object_velocities = torch.zeros_like(self.object_init_velocities, dtype=torch.float, device=self.device)
self._objects.set_velocities(object_velocities[env_ids], indices)
self._objects.set_world_poses(new_object_pos, new_object_rot, indices)
# reset hand
delta_max = self.hand_dof_upper_limits - self.hand_dof_default_pos
delta_min = self.hand_dof_lower_limits - self.hand_dof_default_pos
rand_delta = delta_min + (delta_max - delta_min) * 0.5 * (rand_floats[:, 5:5+self.num_hand_dofs] + 1.0)
pos = self.hand_dof_default_pos + self.reset_dof_pos_noise * rand_delta
dof_pos = torch.zeros((self.num_envs, self.num_hand_dofs), device=self.device)
dof_pos[env_ids, :] = pos
dof_vel = torch.zeros((self.num_envs, self.num_hand_dofs), device=self.device)
dof_vel[env_ids, :] = self.hand_dof_default_vel + \
self.reset_dof_vel_noise * rand_floats[:, 5+self.num_hand_dofs:5+self.num_hand_dofs*2]
self.prev_targets[env_ids, :self.num_hand_dofs] = pos
self.cur_targets[env_ids, :self.num_hand_dofs] = pos
self.hand_dof_targets[env_ids, :] = pos
self._hands.set_joint_position_targets(self.hand_dof_targets[env_ids], indices)
self._hands.set_joint_positions(dof_pos[env_ids], indices)
self._hands.set_joint_velocities(dof_vel[env_ids], indices)
self.progress_buf[env_ids] = 0
self.reset_buf[env_ids] = 0
self.successes[env_ids] = 0
#####################################################################
###=========================jit functions=========================###
#####################################################################
@torch.jit.script
def randomize_rotation(rand0, rand1, x_unit_tensor, y_unit_tensor):
return quat_mul(quat_from_angle_axis(rand0 * np.pi, x_unit_tensor), quat_from_angle_axis(rand1 * np.pi, y_unit_tensor))
@torch.jit.script
def compute_hand_reward(
rew_buf, reset_buf, reset_goal_buf, progress_buf, successes, consecutive_successes,
max_episode_length: float, object_pos, object_rot, target_pos, target_rot,
dist_reward_scale: float, rot_reward_scale: float, rot_eps: float,
actions, action_penalty_scale: float,
success_tolerance: float, reach_goal_bonus: float, fall_dist: float,
fall_penalty: float, max_consecutive_successes: int, av_factor: float
):
goal_dist = torch.norm(object_pos - target_pos, p=2, dim=-1)
# Orientation alignment for the cube in hand and goal cube
quat_diff = quat_mul(object_rot, quat_conjugate(target_rot))
rot_dist = 2.0 * torch.asin(torch.clamp(torch.norm(quat_diff[:, 1:4], p=2, dim=-1), max=1.0)) # changed quat convention
dist_rew = goal_dist * dist_reward_scale
rot_rew = 1.0/(torch.abs(rot_dist) + rot_eps) * rot_reward_scale
action_penalty = torch.sum(actions ** 2, dim=-1)
# Total reward is: position distance + orientation alignment + action regularization + success bonus + fall penalty
reward = dist_rew + rot_rew + action_penalty * action_penalty_scale
# Find out which envs hit the goal and update successes count
goal_resets = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.ones_like(reset_goal_buf), reset_goal_buf)
successes = successes + goal_resets
# Success bonus: orientation is within `success_tolerance` of goal orientation
reward = torch.where(goal_resets == 1, reward + reach_goal_bonus, reward)
# Fall penalty: distance to the goal is larger than a threashold
reward = torch.where(goal_dist >= fall_dist, reward + fall_penalty, reward)
# Check env termination conditions, including maximum success number
resets = torch.where(goal_dist >= fall_dist, torch.ones_like(reset_buf), reset_buf)
if max_consecutive_successes > 0:
# Reset progress buffer on goal envs if max_consecutive_successes > 0
progress_buf = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.zeros_like(progress_buf), progress_buf)
resets = torch.where(successes >= max_consecutive_successes, torch.ones_like(resets), resets)
resets = torch.where(progress_buf >= max_episode_length - 1, torch.ones_like(resets), resets)
# Apply penalty for not reaching the goal
if max_consecutive_successes > 0:
reward = torch.where(progress_buf >= max_episode_length - 1, reward + 0.5 * fall_penalty, reward)
num_resets = torch.sum(resets)
finished_cons_successes = torch.sum(successes * resets.float())
cons_successes = torch.where(num_resets > 0, av_factor*finished_cons_successes/num_resets + (1.0 - av_factor)*consecutive_successes, consecutive_successes)
return reward, resets, goal_resets, progress_buf, successes, cons_successes
| 20,471 | Python | 48.931707 | 179 | 0.656734 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/tasks/shared/locomotion.py | # Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from abc import abstractmethod
from swervesim.tasks.base.rl_task import RLTask
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
from omni.isaac.core.utils.torch.maths import torch_rand_float, tensor_clamp, unscale
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.utils.prims import get_prim_at_path
import numpy as np
import torch
import math
class LocomotionTask(RLTask):
def __init__(
self,
name,
env,
offset=None
) -> None:
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._env_spacing = self._task_cfg["env"]["envSpacing"]
self._max_episode_length = self._task_cfg["env"]["episodeLength"]
self.dof_vel_scale = self._task_cfg["env"]["dofVelocityScale"]
self.angular_velocity_scale = self._task_cfg["env"]["angularVelocityScale"]
self.contact_force_scale = self._task_cfg["env"]["contactForceScale"]
self.power_scale = self._task_cfg["env"]["powerScale"]
self.heading_weight = self._task_cfg["env"]["headingWeight"]
self.up_weight = self._task_cfg["env"]["upWeight"]
self.actions_cost_scale = self._task_cfg["env"]["actionsCost"]
self.energy_cost_scale = self._task_cfg["env"]["energyCost"]
self.joints_at_limit_cost_scale = self._task_cfg["env"]["jointsAtLimitCost"]
self.death_cost = self._task_cfg["env"]["deathCost"]
self.termination_height = self._task_cfg["env"]["terminationHeight"]
self.alive_reward_scale = self._task_cfg["env"]["alive_reward_scale"]
RLTask.__init__(self, name, env)
return
@abstractmethod
def set_up_scene(self, scene) -> None:
pass
@abstractmethod
def get_robot(self):
pass
def get_observations(self) -> dict:
torso_position, torso_rotation = self._robots.get_world_poses(clone=False)
velocities = self._robots.get_velocities(clone=False)
velocity = velocities[:, 0:3]
ang_velocity = velocities[:, 3:6]
dof_pos = self._robots.get_joint_positions(clone=False)
dof_vel = self._robots.get_joint_velocities(clone=False)
# force sensors attached to the feet
sensor_force_torques = self._robots._physics_view.get_force_sensor_forces() # (num_envs, num_sensors, 6)
self.obs_buf[:], self.potentials[:], self.prev_potentials[:], self.up_vec[:], self.heading_vec[:] = get_observations(
torso_position, torso_rotation, velocity, ang_velocity, dof_pos, dof_vel, self.targets, self.potentials, self.dt,
self.inv_start_rot, self.basis_vec0, self.basis_vec1, self.dof_limits_lower, self.dof_limits_upper, self.dof_vel_scale,
sensor_force_torques, self._num_envs, self.contact_force_scale, self.actions, self.angular_velocity_scale
)
observations = {
self._robots.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
if not self._env._world.is_playing():
return
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
self.actions = actions.clone().to(self._device)
forces = self.actions * self.joint_gears * self.power_scale
indices = torch.arange(self._robots.count, dtype=torch.int32, device=self._device)
# applies joint torques
self._robots.set_joint_efforts(forces, indices=indices)
def reset_idx(self, env_ids):
num_resets = len(env_ids)
# randomize DOF positions and velocities
dof_pos = torch_rand_float(-0.2, 0.2, (num_resets, self._robots.num_dof), device=self._device)
dof_pos[:] = tensor_clamp(
self.initial_dof_pos[env_ids] + dof_pos, self.dof_limits_lower, self.dof_limits_upper
)
dof_vel = torch_rand_float(-0.1, 0.1, (num_resets, self._robots.num_dof), device=self._device)
root_pos, root_rot = self.initial_root_pos[env_ids], self.initial_root_rot[env_ids]
root_vel = torch.zeros((num_resets, 6), device=self._device)
# apply resets
self._robots.set_joint_positions(dof_pos, indices=env_ids)
self._robots.set_joint_velocities(dof_vel, indices=env_ids)
self._robots.set_world_poses(root_pos, root_rot, indices=env_ids)
self._robots.set_velocities(root_vel, indices=env_ids)
to_target = self.targets[env_ids] - self.initial_root_pos[env_ids]
to_target[:, 2] = 0.0
self.prev_potentials[env_ids] = -torch.norm(to_target, p=2, dim=-1) / self.dt
self.potentials[env_ids] = self.prev_potentials[env_ids].clone()
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
num_resets = len(env_ids)
def post_reset(self):
self._robots = self.get_robot()
self.initial_root_pos, self.initial_root_rot = self._robots.get_world_poses()
self.initial_dof_pos = self._robots.get_joint_positions()
# initialize some data used later on
self.start_rotation = torch.tensor([1, 0, 0, 0], device=self._device, dtype=torch.float32)
self.up_vec = torch.tensor([0, 0, 1], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.heading_vec = torch.tensor([1, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.inv_start_rot = quat_conjugate(self.start_rotation).repeat((self.num_envs, 1))
self.basis_vec0 = self.heading_vec.clone()
self.basis_vec1 = self.up_vec.clone()
self.targets = torch.tensor([1000, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.target_dirs = torch.tensor([1, 0, 0], dtype=torch.float32, device=self._device).repeat((self.num_envs, 1))
self.dt = 1.0 / 60.0
self.potentials = torch.tensor([-1000.0 / self.dt], dtype=torch.float32, device=self._device).repeat(self.num_envs)
self.prev_potentials = self.potentials.clone()
self.actions = torch.zeros((self.num_envs, self.num_actions), device=self._device)
# randomize all envs
indices = torch.arange(self._robots.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def calculate_metrics(self) -> None:
self.rew_buf[:] = calculate_metrics(
self.obs_buf, self.actions, self.up_weight, self.heading_weight, self.potentials, self.prev_potentials,
self.actions_cost_scale, self.energy_cost_scale, self.termination_height,
self.death_cost, self._robots.num_dof, self.get_dof_at_limit_cost(), self.alive_reward_scale, self.motor_effort_ratio
)
def is_done(self) -> None:
self.reset_buf[:] = is_done(
self.obs_buf, self.termination_height, self.reset_buf, self.progress_buf, self._max_episode_length
)
#####################################################################
###=========================jit functions=========================###
#####################################################################
@torch.jit.script
def normalize_angle(x):
return torch.atan2(torch.sin(x), torch.cos(x))
@torch.jit.script
def get_observations(
torso_position,
torso_rotation,
velocity,
ang_velocity,
dof_pos,
dof_vel,
targets,
potentials,
dt,
inv_start_rot,
basis_vec0,
basis_vec1,
dof_limits_lower,
dof_limits_upper,
dof_vel_scale,
sensor_force_torques,
num_envs,
contact_force_scale,
actions,
angular_velocity_scale
):
# type: (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, float, Tensor, Tensor, Tensor, Tensor, Tensor, float, Tensor, int, float, Tensor, float) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]
to_target = targets - torso_position
to_target[:, 2] = 0.0
prev_potentials = potentials.clone()
potentials = -torch.norm(to_target, p=2, dim=-1) / dt
torso_quat, up_proj, heading_proj, up_vec, heading_vec = compute_heading_and_up(
torso_rotation, inv_start_rot, to_target, basis_vec0, basis_vec1, 2
)
vel_loc, angvel_loc, roll, pitch, yaw, angle_to_target = compute_rot(
torso_quat, velocity, ang_velocity, targets, torso_position
)
dof_pos_scaled = unscale(dof_pos, dof_limits_lower, dof_limits_upper)
# obs_buf shapes: 1, 3, 3, 1, 1, 1, 1, 1, num_dofs, num_dofs, num_sensors * 6, num_dofs
obs = torch.cat(
(
torso_position[:, 2].view(-1, 1),
vel_loc,
angvel_loc * angular_velocity_scale,
normalize_angle(yaw).unsqueeze(-1),
normalize_angle(roll).unsqueeze(-1),
normalize_angle(angle_to_target).unsqueeze(-1),
up_proj.unsqueeze(-1),
heading_proj.unsqueeze(-1),
dof_pos_scaled,
dof_vel * dof_vel_scale,
sensor_force_torques.reshape(num_envs, -1) * contact_force_scale,
actions,
),
dim=-1,
)
return obs, potentials, prev_potentials, up_vec, heading_vec
@torch.jit.script
def is_done(
obs_buf,
termination_height,
reset_buf,
progress_buf,
max_episode_length
):
# type: (Tensor, float, Tensor, Tensor, float) -> Tensor
reset = torch.where(obs_buf[:, 0] < termination_height, torch.ones_like(reset_buf), reset_buf)
reset = torch.where(progress_buf >= max_episode_length - 1, torch.ones_like(reset_buf), reset)
return reset
@torch.jit.script
def calculate_metrics(
obs_buf,
actions,
up_weight,
heading_weight,
potentials,
prev_potentials,
actions_cost_scale,
energy_cost_scale,
termination_height,
death_cost,
num_dof,
dof_at_limit_cost,
alive_reward_scale,
motor_effort_ratio
):
# type: (Tensor, Tensor, float, float, Tensor, Tensor, float, float, float, float, int, Tensor, float, Tensor) -> Tensor
heading_weight_tensor = torch.ones_like(obs_buf[:, 11]) * heading_weight
heading_reward = torch.where(
obs_buf[:, 11] > 0.8, heading_weight_tensor, heading_weight * obs_buf[:, 11] / 0.8
)
# aligning up axis of robot and environment
up_reward = torch.zeros_like(heading_reward)
up_reward = torch.where(obs_buf[:, 10] > 0.93, up_reward + up_weight, up_reward)
# energy penalty for movement
actions_cost = torch.sum(actions ** 2, dim=-1)
electricity_cost = torch.sum(torch.abs(actions * obs_buf[:, 12+num_dof:12+num_dof*2])* motor_effort_ratio.unsqueeze(0), dim=-1)
# reward for duration of staying alive
alive_reward = torch.ones_like(potentials) * alive_reward_scale
progress_reward = potentials - prev_potentials
total_reward = (
progress_reward
+ alive_reward
+ up_reward
+ heading_reward
- actions_cost_scale * actions_cost
- energy_cost_scale * electricity_cost
- dof_at_limit_cost
)
# adjust reward for fallen agents
total_reward = torch.where(
obs_buf[:, 0] < termination_height, torch.ones_like(total_reward) * death_cost, total_reward
)
return total_reward | 12,868 | Python | 38.719136 | 214 | 0.642913 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/config.yaml |
# Task name - used to pick the class to load
task_name: ${task.name}
# experiment name. defaults to name of training config
experiment: ''
# if set to positive integer, overrides the default number of environments
num_envs: ''
# seed - set to -1 to choose random seed
seed: 42
# set to True for deterministic performance
torch_deterministic: False
# set the maximum number of learning iterations to train for. overrides default per-environment setting
max_iterations: ''
## Device config
physics_engine: 'physx'
# whether to use cpu or gpu pipeline
pipeline: 'gpu'
# whether to use cpu or gpu physx
sim_device: 'gpu'
# used for gpu simulation only - device id for running sim and task if pipeline=gpu
device_id: 0
# device to run RL
rl_device: 'cuda:0'
## PhysX arguments
num_threads: 4 # Number of worker threads per scene used by PhysX - for CPU PhysX only.
solver_type: 1 # 0: pgs, 1: tgs
# RLGames Arguments
# test - if set, run policy in inference mode (requires setting checkpoint to load)
test: False
# used to set checkpoint path
checkpoint: ''
# disables rendering
headless: False
wandb_activate: False
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: 'swervesim'
# set default task and default training config based on task
defaults:
- task: Swerve
- train: ${task}PPO
- hydra/job_logging: disabled
# set the directory where the output files get saved
hydra:
output_subdir: null
run:
dir: .
| 1,466 | YAML | 23.45 | 103 | 0.736698 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/task/SwerveK.yaml | # used to create the object
name: SwerveK
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: 36
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12 # 10 Hz?
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
# episode length in seconds
episodeLength_s: 50
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 4
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 1024
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1024
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
SwerveK:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,367 | YAML | 26.858823 | 71 | 0.657795 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/task/SwerveF.yaml | # used to create the object
name: SwerveF
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: 36
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12 # 10 Hz?
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
# episode length in seconds
episodeLength_s: 50
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 4
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 1024
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1024
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
SwerveF:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,367 | YAML | 26.858823 | 71 | 0.657795 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/task/SwerveMAA.yaml | # used to create the object
name: SwerveMAA
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: 36
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12 # 10 Hz?
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
# episode length in seconds
episodeLength_s: 50
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 4
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 1024
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1024
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
SwerveMAA:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,371 | YAML | 26.905882 | 71 | 0.658372 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/task/Swerve.yaml | # used to create the object
name: Swerve
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: 324
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12 # 10 Hz?
baseInitState:
pos: [0.0, 0.0, 0.62] # x,y,z [m]
rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
# episode length in seconds
episodeLength_s: 50
sim:
dt: 0.0083 # 1/120 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 4
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 81920
gpu_found_lost_pairs_capacity: 1024
gpu_found_lost_aggregate_pairs_capacity: 262144
gpu_total_aggregate_pairs_capacity: 1024
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 67108864
gpu_temp_buffer_capacity: 16777216
gpu_max_num_partitions: 8
Swerve:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,366 | YAML | 26.847059 | 71 | 0.65765 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/task/SwerveCS.yaml | # used to create the object
name: SwerveCS
physics_engine: ${..physics_engine}
# if given, will override the device setting in gym.
env:
numEnvs: 36
envSpacing: 20
resetDist: 3.0
clipObservations: 1.0
clipActions: 1.0
controlFrequencyInv: 12 # 10 Hz?
# baseInitState:
# pos: [0.0, 0.0, 0.62] # x,y,z [m]
# rot: [0.0, 0.0, 0.0, 1.0] # x,y,z,w [quat]
# vLinear: [0.0, 0.0, 0.0] # x,y,z [m/s]
# vAngular: [0.0, 0.0, 0.0] # x,y,z [rad/s]
control:
# PD Drive parameters:
stiffness: 85.0 # [N*m/rad]
damping: 2.0 # [N*m*s/rad]
actionScale: 13.5
# episode length in seconds
episodeLength_s: 15
sim:
dt: 0.01 # 1/10 s
use_gpu_pipeline: ${eq:${...pipeline},"gpu"}
gravity: [0.0, 0.0, -9.81]
add_ground_plane: True
add_distant_light: True
use_flatcache: True
enable_scene_query_support: False
# set to True if you use camera sensors in the environment
default_physics_material:
static_friction: 1.0
dynamic_friction: 1.0
restitution: 0.0
physx:
worker_thread_count: ${....num_threads}
solver_type: ${....solver_type}
use_gpu: ${eq:${....sim_device},"gpu"} # set to False to run on CPU
solver_position_iteration_count: 4
solver_velocity_iteration_count: 4
contact_offset: 0.02
rest_offset: 0.001
bounce_threshold_velocity: 0.2
friction_offset_threshold: 0.04
friction_correlation_distance: 0.025
enable_sleeping: True
enable_stabilization: True
max_depenetration_velocity: 100.0
# GPU buffers
gpu_max_rigid_contact_count: 524288
gpu_max_rigid_patch_count: 163840
gpu_found_lost_pairs_capacity: 4194304
gpu_found_lost_aggregate_pairs_capacity: 33554432
gpu_total_aggregate_pairs_capacity: 4194304
gpu_max_soft_body_contacts: 1048576
gpu_max_particle_contacts: 1048576
gpu_heap_capacity: 134217728
gpu_temp_buffer_capacity: 33554432
gpu_max_num_partitions: 8
SwerveCS:
# -1 to use default values
override_usd_defaults: False
fixed_base: False
enable_self_collisions: False
enable_gyroscopic_forces: True
# also in stage params
# per-actor
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
# per-body
density: -1
max_depenetration_velocity: 100.0
# per-shape
contact_offset: 0.02
rest_offset: 0.001 | 2,383 | YAML | 27.380952 | 71 | 0.656735 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/train/SwerveKPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:SwerveK,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 10000
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 10
minibatch_size: 360
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001 | 1,527 | YAML | 20.828571 | 101 | 0.59332 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/train/SwerveCSPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:SwerveCS,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 10000
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 10
minibatch_size: 360
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001 | 1,528 | YAML | 20.842857 | 101 | 0.593586 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/train/SwervePPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:Swerve,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 10000
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 10
minibatch_size: 360
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001 | 1,526 | YAML | 20.814285 | 101 | 0.593054 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/train/SwerveMAAPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:SwerveK,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 10000
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 10
minibatch_size: 360
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001 | 1,527 | YAML | 20.828571 | 101 | 0.59332 |
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/cfg/train/SwerveFPPO.yaml | params:
seed: ${...seed}
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: ${if:${...checkpoint},True,False} # flag which sets whether to load the checkpoint
load_path: ${...checkpoint} # path to the checkpoint to load
config:
name: ${resolve_default:SwerveF,${....experiment}}
full_experiment_name: ${.name}
device: ${....rl_device}
device_name: ${....rl_device}
env_name: rlgpu
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: ${....task.env.numEnvs}
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 10000
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 10
minibatch_size: 360
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_len: 4
bounds_loss_coef: 0.0001 | 1,527 | YAML | 20.828571 | 101 | 0.59332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.