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/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/isaac/README.md | # Isaac Sim Code and Assests | 28 | Markdown | 27.999972 | 28 | 0.785714 |
RoboEagles4828/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/scripts/rlgames_demo.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.utils.hydra_cfg.hydra_utils import *
from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from swervesim.utils.demo_util import initialize_demo
from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path
from swervesim.envs.vec_env_rlgames import VecEnvRLGames
from swervesim.scripts.rlgames_train import RLGTrainer
import hydra
from omegaconf import DictConfig
import datetime
import os
import torch
class RLGDemo(RLGTrainer):
def __init__(self, cfg, cfg_dict):
RLGTrainer.__init__(self, cfg, cfg_dict)
self.cfg.test = True
@hydra.main(config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
headless = cfg.headless
env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id)
# ensure checkpoints can be specified as relative paths
if cfg.checkpoint:
cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint)
if cfg.checkpoint is None:
quit()
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict['seed'] = cfg.seed
task = initialize_demo(cfg_dict, env)
if cfg.wandb_activate:
# Make sure to install WandB if you actually use this.
import wandb
run_name = f"{cfg.wandb_name}_{time_str}"
wandb.init(
project=cfg.wandb_project,
group=cfg.wandb_group,
entity=cfg.wandb_entity,
config=cfg_dict,
sync_tensorboard=True,
id=run_name,
resume="allow",
monitor_gym=True,
)
rlg_trainer = RLGDemo(cfg, cfg_dict)
rlg_trainer.launch_rlg_hydra(env)
rlg_trainer.run()
env.close()
if cfg.wandb_activate:
wandb.finish()
if __name__ == '__main__':
parse_hydra_configs()
| 3,647 | Python | 35.118812 | 80 | 0.713737 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/scripts/rlgames_train.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.utils.hydra_cfg.hydra_utils import *
from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from swervesim.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv
from swervesim.utils.task_util import initialize_task
from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path
from swervesim.envs.vec_env_rlgames import VecEnvRLGames
import hydra
from omegaconf import DictConfig
from rl_games.common import env_configurations, vecenv
from rl_games.torch_runner import Runner
import datetime
import os
import torch
class RLGTrainer():
def __init__(self, cfg, cfg_dict):
self.cfg = cfg
self.cfg_dict = cfg_dict
def launch_rlg_hydra(self, env):
# `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally.
# We use the helper function here to specify the environment config.
self.cfg_dict["task"]["test"] = self.cfg.test
# register the rl-games adapter to use inside the runner
vecenv.register('RLGPU',
lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register('rlgpu', {
'vecenv_type': 'RLGPU',
'env_creator': lambda **kwargs: env
})
self.rlg_config_dict = omegaconf_to_dict(self.cfg.train)
def run(self):
# create runner and set the settings
runner = Runner(RLGPUAlgoObserver())
runner.load(self.rlg_config_dict)
runner.reset()
# dump config dict
experiment_dir = os.path.join('runs', self.cfg.train.params.config.name)
os.makedirs(experiment_dir, exist_ok=True)
with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f:
f.write(OmegaConf.to_yaml(self.cfg))
runner.run({
'train': not self.cfg.test,
'play': self.cfg.test,
'checkpoint': self.cfg.checkpoint,
'sigma': None
})
@hydra.main(config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
headless = cfg.headless
env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id)
# ensure checkpoints can be specified as relative paths
if cfg.checkpoint:
cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint)
if cfg.checkpoint is None:
quit()
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict['seed'] = cfg.seed
task = initialize_task(cfg_dict, env)
if cfg.wandb_activate:
# Make sure to install WandB if you actually use this.
import wandb
run_name = f"{cfg.wandb_name}_{time_str}"
wandb.init(
project=cfg.wandb_project,
group=cfg.wandb_group,
entity=cfg.wandb_entity,
config=cfg_dict,
sync_tensorboard=True,
id=run_name,
resume="allow",
monitor_gym=True,
)
rlg_trainer = RLGTrainer(cfg, cfg_dict)
rlg_trainer.launch_rlg_hydra(env)
rlg_trainer.run()
env.close()
if cfg.wandb_activate:
wandb.finish()
if __name__ == '__main__':
parse_hydra_configs()
| 5,082 | Python | 35.307143 | 116 | 0.685557 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/scripts/random_policy.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 hydra
from omegaconf import DictConfig
from swervesim.utils.hydra_cfg.hydra_utils import *
from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from swervesim.utils.task_util import initialize_task
from swervesim.envs.vec_env_rlgames import VecEnvRLGames
@hydra.main(config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
headless = cfg.headless
render = not headless
env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict['seed'] = cfg.seed
task = initialize_task(cfg_dict, env)
while env._simulation_app.is_running():
if env._world.is_playing():
if env._world.current_time_step_index == 0:
env._world.reset(soft=True)
actions = torch.tensor(np.array([env.action_space.sample() for _ in range(env.num_envs)]), device=task.rl_device)
env._task.pre_physics_step(actions)
env._world.step(render=render)
env.sim_frame_count += 1
env._task.post_physics_step()
else:
env._world.step(render=render)
env._simulation_app.close()
if __name__ == '__main__':
parse_hydra_configs()
| 3,055 | Python | 40.863013 | 125 | 0.728642 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/scripts/rlgames_train_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 swervesim.utils.hydra_cfg.hydra_utils import *
from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict
from swervesim.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv
from swervesim.utils.task_util import initialize_task
from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path
from swervesim.envs.vec_env_rlgames_mt import VecEnvRLGamesMT
import hydra
from omegaconf import DictConfig
from rl_games.common import env_configurations, vecenv
from rl_games.torch_runner import Runner
import copy
import datetime
import os
import threading
import queue
from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT
class RLGTrainer():
def __init__(self, cfg, cfg_dict):
self.cfg = cfg
self.cfg_dict = cfg_dict
def launch_rlg_hydra(self, env):
# `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally.
# We use the helper function here to specify the environment config.
self.cfg_dict["task"]["test"] = self.cfg.test
# register the rl-games adapter to use inside the runner
vecenv.register('RLGPU',
lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register('rlgpu', {
'vecenv_type': 'RLGPU',
'env_creator': lambda **kwargs: env
})
self.rlg_config_dict = omegaconf_to_dict(self.cfg.train)
def run(self):
# create runner and set the settings
runner = Runner(RLGPUAlgoObserver())
runner.load(copy.deepcopy(self.rlg_config_dict))
runner.reset()
# dump config dict
experiment_dir = os.path.join('runs', self.cfg.train.params.config.name)
os.makedirs(experiment_dir, exist_ok=True)
with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f:
f.write(OmegaConf.to_yaml(self.cfg))
time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if self.cfg.wandb_activate:
# Make sure to install WandB if you actually use this.
import wandb
run_name = f"{self.cfg.wandb_name}_{time_str}"
wandb.init(
project=self.cfg.wandb_project,
group=self.cfg.wandb_group,
entity=self.cfg.wandb_entity,
config=self.cfg_dict,
sync_tensorboard=True,
id=run_name,
resume="allow",
monitor_gym=True,
)
runner.run({
'train': not self.cfg.test,
'play': self.cfg.test,
'checkpoint': self.cfg.checkpoint,
'sigma': None
})
if self.cfg.wandb_activate:
wandb.finish()
class Trainer(TrainerMT):
def __init__(self, trainer, env):
self.ppo_thread = None
self.action_queue = None
self.data_queue = None
self.trainer = trainer
self.is_running = False
self.env = env
self.create_task()
self.run()
def create_task(self):
self.trainer.launch_rlg_hydra(self.env)
task = initialize_task(self.trainer.cfg_dict, self.env, init_sim=False)
self.task = task
def run(self):
self.is_running = True
self.action_queue = queue.Queue(1)
self.data_queue = queue.Queue(1)
if "mt_timeout" in self.trainer.cfg_dict:
self.env.initialize(self.action_queue, self.data_queue, self.trainer.cfg_dict["mt_timeout"])
else:
self.env.initialize(self.action_queue, self.data_queue)
self.ppo_thread = PPOTrainer(self.env, self.task, self.trainer)
self.ppo_thread.daemon = True
self.ppo_thread.start()
def stop(self):
self.env.stop = True
self.env.clear_queues()
if self.action_queue:
self.action_queue.join()
if self.data_queue:
self.data_queue.join()
if self.ppo_thread:
self.ppo_thread.join()
self.action_queue = None
self.data_queue = None
self.ppo_thread = None
self.is_running = False
class PPOTrainer(threading.Thread):
def __init__(self, env, task, trainer):
super().__init__()
self.env = env
self.task = task
self.trainer = trainer
def run(self):
from omni.isaac.gym.vec_env import TaskStopException
print("starting ppo...")
try:
self.trainer.run()
# trainer finished - send stop signal to main thread
self.env.send_actions(None)
self.env.stop = True
except TaskStopException:
print("Task Stopped!")
@hydra.main(config_name="config", config_path="../cfg")
def parse_hydra_configs(cfg: DictConfig):
headless = cfg.headless
env = VecEnvRLGamesMT(headless=headless, sim_device=cfg.device_id)
# ensure checkpoints can be specified as relative paths
if cfg.checkpoint:
cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint)
if cfg.checkpoint is None:
quit()
cfg_dict = omegaconf_to_dict(cfg)
print_dict(cfg_dict)
# sets seed. if seed is -1 will pick a random one
from omni.isaac.core.utils.torch.maths import set_seed
cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic)
cfg_dict['seed'] = cfg.seed
rlg_trainer = RLGTrainer(cfg, cfg_dict)
trainer = Trainer(rlg_trainer, env)
trainer.env.run(trainer)
if __name__ == '__main__':
parse_hydra_configs()
| 7,192 | Python | 33.416268 | 116 | 0.652392 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/demo_util.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.
def initialize_demo(config, env, init_sim=True):
from swervesim.demos.anymal_terrain import AnymalTerrainDemo
# Mappings from strings to environments
task_map = {
"AnymalTerrain": AnymalTerrainDemo,
}
from swervesim.utils.config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
cfg = sim_config.config
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim)
return task | 2,153 | Python | 43.874999 | 107 | 0.75569 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/task_util.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.
def initialize_task(config, env, init_sim=True):
from swervesim.tasks.swerve import Swerve_Task
from swervesim.tasks.swerve_with_kinematics import Swerve_Kinematics_Task
from swervesim.tasks.swerve_field import Swerve_Field_Task
from swervesim.tasks.swerve_multi_action_auton import Swerve_Multi_Action_Task
from swervesim.tasks.swerve_charge_station import Swerve_Charge_Station_Task
# Mappings from strings to environments
task_map = {
"Swerve": Swerve_Task,
"SwerveK": Swerve_Kinematics_Task,
"SwerveF": Swerve_Field_Task,
"SwerveMAA": Swerve_Multi_Action_Task,
"SwerveCS": Swerve_Charge_Station_Task,
}
from .config_utils.sim_config import SimConfig
sim_config = SimConfig(config)
cfg = sim_config.config
task = task_map[cfg["task_name"]](
name=cfg["task_name"], sim_config=sim_config, env=env
)
env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim)
return task | 2,593 | Python | 44.508771 | 107 | 0.748939 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/domain_randomization/randomize.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 copy
import omni
import omni.replicator.core as rep
import omni.replicator.isaac as dr
import numpy as np
import torch
from omni.isaac.core.prims import RigidPrimView
class Randomizer():
def __init__(self, sim_config):
self._cfg = sim_config.task_config
self._config = sim_config.config
self.randomize = False
dr_config = self._cfg.get("domain_randomization", None)
self.distributions = dict()
self.active_domain_randomizations = dict()
self._observations_dr_params = None
self._actions_dr_params = None
if dr_config is not None:
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize and randomization_params is not None:
self.randomize = True
self.min_frequency = dr_config.get("min_frequency", 1)
def apply_on_startup_domain_randomization(self, task):
if self.randomize:
torch.manual_seed(self._config["seed"])
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
for opt in randomization_params.keys():
if opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
for attribute, params in randomization_params["rigid_prim_views"][view_name].items():
params = randomization_params["rigid_prim_views"][view_name][attribute]
if attribute in ["scale", "mass", "density"] and params is not None:
if "on_startup" in params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \
"on_startup are provided: operation, distribution, distribution_parameters.")
view = task._env._world.scene._scene_registry.rigid_prim_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"]["distribution_parameters"],
operation=params["on_startup"]["operation"],
sync_dim_noise=True,
)
elif attribute == "mass":
self.randomize_mass_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"]["distribution_parameters"],
operation=params["on_startup"]["operation"],
)
elif attribute == "density":
self.randomize_density_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"]["distribution_parameters"],
operation=params["on_startup"]["operation"],
)
if opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
for attribute, params in randomization_params["articulation_views"][view_name].items():
params = randomization_params["articulation_views"][view_name][attribute]
if attribute in ["scale"] and params is not None:
if "on_startup" in params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \
"on_startup are provided: operation, distribution, distribution_parameters.")
view = task._env._world.scene._scene_registry.articulated_views[view_name]
if attribute == "scale":
self.randomize_scale_on_startup(
view=view,
distribution=params["on_startup"]["distribution"],
distribution_parameters=params["on_startup"]["distribution_parameters"],
operation=params["on_startup"]["operation"],
sync_dim_noise=True
)
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("On Startup Domain randomization will not be applied.")
def set_up_domain_randomization(self, task):
if self.randomize:
randomization_params = self._cfg["domain_randomization"]["randomization_params"]
rep.set_global_seed(self._config["seed"])
with dr.trigger.on_rl_frame(num_envs=self._cfg["env"]["numEnvs"]):
for opt in randomization_params.keys():
if opt == "observations":
self._set_up_observations_randomization(task)
elif opt == "actions":
self._set_up_actions_randomization(task)
elif opt == "simulation":
if randomization_params["simulation"] is not None:
self.distributions["simulation"] = dict()
dr.physics_view.register_simulation_context(task._env._world)
for attribute, params in randomization_params["simulation"].items():
self._set_up_simulation_randomization(attribute, params)
elif opt == "rigid_prim_views":
if randomization_params["rigid_prim_views"] is not None:
self.distributions["rigid_prim_views"] = dict()
for view_name in randomization_params["rigid_prim_views"].keys():
if randomization_params["rigid_prim_views"][view_name] is not None:
self.distributions["rigid_prim_views"][view_name] = dict()
dr.physics_view.register_rigid_prim_view(
rigid_prim_view=task._env._world.scene._scene_registry.rigid_prim_views[view_name],
)
for attribute, params in randomization_params["rigid_prim_views"][view_name].items():
if attribute not in ["scale", "density"]:
self._set_up_rigid_prim_view_randomization(view_name, attribute, params)
elif opt == "articulation_views":
if randomization_params["articulation_views"] is not None:
self.distributions["articulation_views"] = dict()
for view_name in randomization_params["articulation_views"].keys():
if randomization_params["articulation_views"][view_name] is not None:
self.distributions["articulation_views"][view_name] = dict()
dr.physics_view.register_articulation_view(
articulation_view=task._env._world.scene._scene_registry.articulated_views[view_name],
)
for attribute, params in randomization_params["articulation_views"][view_name].items():
if attribute not in ["scale"]:
self._set_up_articulation_view_randomization(view_name, attribute, params)
rep.orchestrator.run()
else:
dr_config = self._cfg.get("domain_randomization", None)
if dr_config is None:
raise ValueError("No domain randomization parameters are specified in the task yaml config file")
randomize = dr_config.get("randomize", False)
randomization_params = dr_config.get("randomization_params", None)
if randomize == False or randomization_params is None:
print("Domain randomization will not be applied.")
def _set_up_observations_randomization(self, task):
task.randomize_observations = True
self._observations_dr_params = self._cfg["domain_randomization"]["randomization_params"]["observations"]
if self._observations_dr_params is None:
raise ValueError(f"Observations randomization parameters are not provided.")
if "on_reset" in self._observations_dr_params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_reset"].keys()):
raise ValueError(f"Please ensure the following observations on_reset randomization parameters are provided: " + \
"operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("observations", "on_reset")] = np.array(self._observations_dr_params["on_reset"]["distribution_parameters"])
if "on_interval" in self._observations_dr_params.keys():
if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_interval"].keys()):
raise ValueError(f"Please ensure the following observations on_interval randomization parameters are provided: " + \
"frequency_interval, operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("observations", "on_interval")] = np.array(self._observations_dr_params["on_interval"]["distribution_parameters"])
self._observations_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"])
self._observations_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_observations), device=self._config["rl_device"])
def _set_up_actions_randomization(self, task):
task.randomize_actions = True
self._actions_dr_params = self._cfg["domain_randomization"]["randomization_params"]["actions"]
if self._actions_dr_params is None:
raise ValueError(f"Actions randomization parameters are not provided.")
if "on_reset" in self._actions_dr_params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_reset"].keys()):
raise ValueError(f"Please ensure the following actions on_reset randomization parameters are provided: " + \
"operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("actions", "on_reset")] = np.array(self._actions_dr_params["on_reset"]["distribution_parameters"])
if "on_interval" in self._actions_dr_params.keys():
if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_interval"].keys()):
raise ValueError(f"Please ensure the following actions on_interval randomization parameters are provided: " + \
"frequency_interval, operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("actions", "on_interval")] = np.array(self._actions_dr_params["on_interval"]["distribution_parameters"])
self._actions_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"])
self._actions_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_actions), device=self._config["rl_device"])
def apply_observations_randomization(self, observations, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._observations_counter_buffer[env_ids] = 0
self._observations_counter_buffer += 1
if "on_reset" in self._observations_dr_params.keys():
observations[:] = self._apply_correlated_noise(
buffer_type="observations",
buffer=observations,
reset_ids=env_ids,
operation=self._observations_dr_params["on_reset"]["operation"],
distribution=self._observations_dr_params["on_reset"]["distribution"],
distribution_parameters=self._observations_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._observations_dr_params.keys():
randomize_ids = (self._observations_counter_buffer >= self._observations_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1)
self._observations_counter_buffer[randomize_ids] = 0
observations[:] = self._apply_uncorrelated_noise(
buffer=observations,
randomize_ids=randomize_ids,
operation=self._observations_dr_params["on_interval"]["operation"],
distribution=self._observations_dr_params["on_interval"]["distribution"],
distribution_parameters=self._observations_dr_params["on_interval"]["distribution_parameters"],
)
return observations
def apply_actions_randomization(self, actions, reset_buf):
env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1)
self._actions_counter_buffer[env_ids] = 0
self._actions_counter_buffer += 1
if "on_reset" in self._actions_dr_params.keys():
actions[:] = self._apply_correlated_noise(
buffer_type="actions",
buffer=actions,
reset_ids=env_ids,
operation=self._actions_dr_params["on_reset"]["operation"],
distribution=self._actions_dr_params["on_reset"]["distribution"],
distribution_parameters=self._actions_dr_params["on_reset"]["distribution_parameters"],
)
if "on_interval" in self._actions_dr_params.keys():
randomize_ids = (self._actions_counter_buffer >= self._actions_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1)
self._actions_counter_buffer[randomize_ids] = 0
actions[:] = self._apply_uncorrelated_noise(
buffer=actions,
randomize_ids=randomize_ids,
operation=self._actions_dr_params["on_interval"]["operation"],
distribution=self._actions_dr_params["on_interval"]["distribution"],
distribution_parameters=self._actions_dr_params["on_interval"]["distribution_parameters"],
)
return actions
def _apply_uncorrelated_noise(self, buffer, randomize_ids, operation, distribution, distribution_parameters):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"])
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]) + np.log(distribution_parameters[0]))
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer[randomize_ids] += noise
elif operation == "scaling":
buffer[randomize_ids] *= noise
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _apply_correlated_noise(self, buffer_type, buffer, reset_ids, operation, distribution, distribution_parameters):
if buffer_type == "observations":
correlated_noise_buffer = self._observations_correlated_noise
elif buffer_type == "actions":
correlated_noise_buffer = self._actions_correlated_noise
if len(reset_ids) > 0:
if distribution == "gaussian" or distribution == "normal":
correlated_noise_buffer[reset_ids] = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(reset_ids), buffer.shape[1]), device=self._config["rl_device"])
elif distribution == "uniform":
correlated_noise_buffer[reset_ids] = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
correlated_noise_buffer[reset_ids] = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]) + np.log(distribution_parameters[0]))
else:
print(f"The specified {distribution} distribution is not supported.")
if operation == "additive":
buffer += correlated_noise_buffer
elif operation == "scaling":
buffer *= correlated_noise_buffer
else:
print(f"The specified {operation} operation type is not supported.")
return buffer
def _set_up_simulation_randomization(self, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for simulation {attribute} is not provided.")
if attribute in dr.SIMULATION_CONTEXT_ATTRIBUTES:
self.distributions["simulation"][attribute] = dict()
if "on_reset" in params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]):
raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_reset are provided: " + \
"operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("simulation", attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"])
kwargs = {"operation": params["on_reset"]["operation"]}
self.distributions["simulation"][attribute]["on_reset"] = self._generate_distribution(
dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_reset"]
with dr.gate.on_env_reset():
dr.physics_view.randomize_simulation_context(**kwargs)
if "on_interval" in params.keys():
if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]):
raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_interval are provided: " + \
"frequency_interval, operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("simulation", attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"])
kwargs = {"operation": params["on_interval"]["operation"]}
self.distributions["simulation"][attribute]["on_interval"] = self._generate_distribution(
dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0],
view_name="simulation",
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["simulation"][attribute]["on_interval"]
with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
dr.physics_view.randomize_simulation_context(**kwargs)
def _set_up_rigid_prim_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for rigid prim view {view_name} {attribute} is not provided.")
if attribute in dr.RIGID_PRIM_ATTRIBUTES:
self.distributions["rigid_prim_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \
"operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] = self._generate_distribution(
dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"]
with dr.gate.on_env_reset():
dr.physics_view.randomize_rigid_prim_view(**kwargs)
if "on_interval" in params.keys():
if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \
"frequency_interval, operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"] = self._generate_distribution(
dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"]
with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
dr.physics_view.randomize_rigid_prim_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _set_up_articulation_view_randomization(self, view_name, attribute, params):
if params is None:
raise ValueError(f"Randomization parameters for articulation view {view_name} {attribute} is not provided.")
if attribute in dr.ARTICULATION_ATTRIBUTES:
self.distributions["articulation_views"][view_name][attribute] = dict()
if "on_reset" in params.keys():
if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \
"operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys():
kwargs["num_buckets"] = params["on_reset"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute]["on_reset"] = self._generate_distribution(
dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_reset"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_reset"]
with dr.gate.on_env_reset():
dr.physics_view.randomize_articulation_view(**kwargs)
if "on_interval" in params.keys():
if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]):
raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \
"frequency_interval, operation, distribution, distribution_parameters.")
self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"])
kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]}
if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys():
kwargs["num_buckets"] = params["on_interval"]["num_buckets"]
self.distributions["articulation_views"][view_name][attribute]["on_interval"] = self._generate_distribution(
dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1],
view_name=view_name,
attribute=attribute,
params=params["on_interval"],
)
kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_interval"]
with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]):
dr.physics_view.randomize_articulation_view(**kwargs)
else:
raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.")
def _generate_distribution(self, view_name, attribute, dimension, params):
dist_params = self._sanitize_distribution_parameters(attribute, dimension, params["distribution_parameters"])
if params["distribution"] == "uniform":
return rep.distribution.uniform(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "gaussian" or params["distribution"] == "normal":
return rep.distribution.normal(tuple(dist_params[0]), tuple(dist_params[1]))
elif params["distribution"] == "loguniform" or params["distribution"] == "log_uniform":
return rep.distribution.log_uniform(tuple(dist_params[0]), tuple(dist_params[1]))
else:
raise ValueError(f"The provided distribution for {view_name} {attribute} is not supported. "
+ "Options: uniform, gaussian/normal, loguniform/log_uniform"
)
def _sanitize_distribution_parameters(self, attribute, dimension, params):
distribution_parameters = np.array(params)
if distribution_parameters.shape == (2,):
# if the user does not provide a set of parameters for each dimension
dist_params = [[distribution_parameters[0]]*dimension, [distribution_parameters[1]]*dimension]
elif distribution_parameters.shape == (2, dimension):
# if the user provides a set of parameters for each dimension in the format [[...], [...]]
dist_params = distribution_parameters.tolist()
elif attribute in ["material_properties", "body_inertias"] and distribution_parameters.shape == (2, 3):
# if the user only provides the parameters for one body in the articulation, assume the same parameters for all other links
dist_params = [[distribution_parameters[0]] * (dimension // 3), [distribution_parameters[1]] * (dimension // 3)]
else:
raise ValueError(f"The provided distribution_parameters for {view_name} {attribute} is invalid due to incorrect dimensions.")
return dist_params
def set_dr_distribution_parameters(self, distribution_parameters, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.")
if distribution_path[0] == "observations":
if len(distribution_parameters) == 2:
self._observations_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(f"Please provide distribution_parameters for observations {distribution_path[1]} " +
"in the form of [dist_param_1, dist_param_2]")
elif distribution_path[0] == "actions":
if len(distribution_parameters) == 2:
self._actions_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters
else:
raise ValueError(f"Please provide distribution_parameters for actions {distribution_path[1]} " +
"in the form of [dist_param_1, dist_param_2]")
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \
or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform":
dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["lower"])[0])
dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters)
dr.utils.set_distribution_params(replicator_distribution, {"lower": dist_params[0], "upper": dist_params[1]})
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["mean"])[0])
dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters)
dr.utils.set_distribution_params(replicator_distribution, {"mean": dist_params[0], "std": dist_params[1]})
def get_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.")
if distribution_path[0] == "observations":
return self._observations_dr_params[distribution_path[1]]["distribution_parameters"]
elif distribution_path[0] == "actions":
return self._actions_dr_params[distribution_path[1]]["distribution_parameters"]
else:
replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]]
if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views":
replicator_distribution = replicator_distribution[distribution_path[3]]
if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \
or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform":
return dr.utils.get_distribution_params(replicator_distribution, ["lower", "upper"])
elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal":
return dr.utils.get_distribution_params(replicator_distribution, ["mean", "std"])
def get_initial_dr_distribution_parameters(self, *distribution_path):
if distribution_path not in self.active_domain_randomizations.keys():
raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.")
return self.active_domain_randomizations[distribution_path].copy()
def _generate_noise(self, distribution, distribution_parameters, size, device):
if distribution == "gaussian" or distribution == "normal":
noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=size, device=device)
elif distribution == "uniform":
noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(size, device=device) + distribution_parameters[0]
elif distribution == "loguniform" or distribution == "log_uniform":
noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand(size, device=device) + np.log(distribution_parameters[0]))
else:
print(f"The specified {distribution} distribution is not supported.")
return noise
def randomize_scale_on_startup(self, view, distribution, distribution_parameters, operation, sync_dim_noise=True):
scales = view.get_local_scales()
if sync_dim_noise:
dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=1, params=distribution_parameters))
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device).repeat(3,1).T
else:
dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=3, params=distribution_parameters))
noise = torch.zeros((view.count, 3), device=view._device)
for i in range(3):
noise[:, i] = self._generate_noise(distribution, dist_params[:, i], (view.count,), view._device)
if operation == "additive":
scales += noise
elif operation == "scaling":
scales *= noise
elif operation == "direct":
scales = noise
else:
print(f"The specified {operation} operation type is not supported.")
view.set_local_scales(scales=scales)
def randomize_mass_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
masses = view.get_masses()
dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} mass", dimension=1, params=distribution_parameters))
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_masses = view.set_masses
if operation == "additive":
masses += noise
elif operation == "scaling":
masses *= noise
elif operation == "direct":
masses = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_masses(masses)
def randomize_density_on_startup(self, view, distribution, distribution_parameters, operation):
if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView):
densities = view.get_densities()
dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} density", dimension=1, params=distribution_parameters))
noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device)
set_densities = view.set_densities
if operation == "additive":
densities += noise
elif operation == "scaling":
densities *= noise
elif operation == "direct":
densities = noise
else:
print(f"The specified {operation} operation type is not supported.")
set_densities(densities)
| 41,564 | Python | 70.787565 | 256 | 0.602877 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/rlgames/rlgames_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 rl_games.common import env_configurations, vecenv
from rl_games.common.algo_observer import AlgoObserver
from rl_games.algos_torch import torch_ext
import torch
import numpy as np
from typing import Callable
class RLGPUAlgoObserver(AlgoObserver):
"""Allows us to log stats from the env along with the algorithm running stats. """
def __init__(self):
pass
def after_init(self, algo):
self.algo = algo
self.mean_scores = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device)
self.ep_infos = []
self.direct_info = {}
self.writer = self.algo.writer
def process_infos(self, infos, done_indices):
assert isinstance(infos, dict), "RLGPUAlgoObserver expects dict info"
if isinstance(infos, dict):
if 'episode' in infos:
self.ep_infos.append(infos['episode'])
if len(infos) > 0 and isinstance(infos, dict): # allow direct logging from env
self.direct_info = {}
for k, v in infos.items():
# only log scalars
if isinstance(v, float) or isinstance(v, int) or (isinstance(v, torch.Tensor) and len(v.shape) == 0):
self.direct_info[k] = v
def after_clear_stats(self):
self.mean_scores.clear()
def after_print_stats(self, frame, epoch_num, total_time):
if self.ep_infos:
for key in self.ep_infos[0]:
infotensor = torch.tensor([], device=self.algo.device)
for ep_info in self.ep_infos:
# handle scalar and zero dimensional tensor infos
if not isinstance(ep_info[key], torch.Tensor):
ep_info[key] = torch.Tensor([ep_info[key]])
if len(ep_info[key].shape) == 0:
ep_info[key] = ep_info[key].unsqueeze(0)
infotensor = torch.cat((infotensor, ep_info[key].to(self.algo.device)))
value = torch.mean(infotensor)
self.writer.add_scalar('Episode/' + key, value, epoch_num)
self.ep_infos.clear()
for k, v in self.direct_info.items():
self.writer.add_scalar(f'{k}/frame', v, frame)
self.writer.add_scalar(f'{k}/iter', v, epoch_num)
self.writer.add_scalar(f'{k}/time', v, total_time)
if self.mean_scores.current_size > 0:
mean_scores = self.mean_scores.get_mean()
self.writer.add_scalar('scores/mean', mean_scores, frame)
self.writer.add_scalar('scores/iter', mean_scores, epoch_num)
self.writer.add_scalar('scores/time', mean_scores, total_time)
class RLGPUEnv(vecenv.IVecEnv):
def __init__(self, config_name, num_actors, **kwargs):
self.env = env_configurations.configurations[config_name]['env_creator'](**kwargs)
def step(self, action):
return self.env.step(action)
def reset(self):
return self.env.reset()
def get_number_of_agents(self):
return self.env.get_number_of_agents()
def get_env_info(self):
info = {}
info['action_space'] = self.env.action_space
info['observation_space'] = self.env.observation_space
if self.env.num_states > 0:
info['state_space'] = self.env.state_space
print(info['action_space'], info['observation_space'], info['state_space'])
else:
print(info['action_space'], info['observation_space'])
return info
| 5,154 | Python | 42.319327 | 121 | 0.642608 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/config_utils/sim_config.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.utils.config_utils.default_scene_params import *
import copy
import omni.usd
import numpy as np
import torch
import carb
class SimConfig():
def __init__(self, config: dict = None):
if config is None:
config = dict()
self._config = config
self._cfg = config.get("task", dict())
self._parse_config()
if self._config["test"] == True:
self._sim_params["enable_scene_query_support"] = True
if self._config["headless"] == True and not self._sim_params["enable_cameras"]:
self._sim_params["use_flatcache"] = False
self._sim_params["enable_viewport"] = False
if self._sim_params["disable_contact_processing"]:
carb.settings.get_settings().set_bool("/physics/disableContactProcessing", True)
def _parse_config(self):
# general sim parameter
self._sim_params = copy.deepcopy(default_sim_params)
self._default_physics_material = copy.deepcopy(default_physics_material)
sim_cfg = self._cfg.get("sim", None)
if sim_cfg is not None:
for opt in sim_cfg.keys():
if opt in self._sim_params:
if opt == "default_physics_material":
for material_opt in sim_cfg[opt]:
self._default_physics_material[material_opt] = sim_cfg[opt][material_opt]
else:
self._sim_params[opt] = sim_cfg[opt]
else:
print("Sim params does not have attribute: ", opt)
self._sim_params["default_physics_material"] = self._default_physics_material
# physx parameters
self._physx_params = copy.deepcopy(default_physx_params)
if sim_cfg is not None and "physx" in sim_cfg:
for opt in sim_cfg["physx"].keys():
if opt in self._physx_params:
self._physx_params[opt] = sim_cfg["physx"][opt]
else:
print("Physx sim params does not have attribute: ", opt)
self._sanitize_device()
def _sanitize_device(self):
if self._sim_params["use_gpu_pipeline"]:
self._physx_params["use_gpu"] = True
# device should be in sync with pipeline
if self._sim_params["use_gpu_pipeline"]:
self._config["sim_device"] = f"cuda:{self._config['device_id']}"
else:
self._config["sim_device"] = "cpu"
# also write to physics params for setting sim device
self._physx_params["sim_device"] = self._config["sim_device"]
print("Pipeline: ", "GPU" if self._sim_params["use_gpu_pipeline"] else "CPU")
print("Pipeline Device: ", self._config["sim_device"])
print("Sim Device: ", "GPU" if self._physx_params["use_gpu"] else "CPU")
def parse_actor_config(self, actor_name):
actor_params = copy.deepcopy(default_actor_options)
if "sim" in self._cfg and actor_name in self._cfg["sim"]:
actor_cfg = self._cfg["sim"][actor_name]
for opt in actor_cfg.keys():
if actor_cfg[opt] != -1 and opt in actor_params:
actor_params[opt] = actor_cfg[opt]
elif opt not in actor_params:
print("Actor params does not have attribute: ", opt)
return actor_params
def _get_actor_config_value(self, actor_name, attribute_name, attribute=None):
actor_params = self.parse_actor_config(actor_name)
if attribute is not None:
if attribute_name not in actor_params:
return attribute.Get()
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
elif actor_params["override_usd_defaults"] and not attribute.IsAuthored():
return self._physx_params[attribute_name]
else:
if actor_params[attribute_name] != -1:
return actor_params[attribute_name]
@property
def sim_params(self):
return self._sim_params
@property
def config(self):
return self._config
@property
def task_config(self):
return self._cfg
@property
def physx_params(self):
return self._physx_params
def get_physics_params(self):
return {**self.sim_params, **self.physx_params}
def _get_physx_collision_api(self, prim):
from pxr import UsdPhysics, PhysxSchema
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
return physx_collision_api
def _get_physx_rigid_body_api(self, prim):
from pxr import UsdPhysics, PhysxSchema
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI(prim)
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
return physx_rb_api
def _get_physx_articulation_api(self, prim):
from pxr import UsdPhysics, PhysxSchema
arti_api = PhysxSchema.PhysxArticulationAPI(prim)
if not arti_api:
arti_api = PhysxSchema.PhysxArticulationAPI.Apply(prim)
return arti_api
def set_contact_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
contact_offset = physx_collision_api.GetContactOffsetAttr()
# if not contact_offset:
# contact_offset = physx_collision_api.CreateContactOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "contact_offset", contact_offset)
if value != -1:
contact_offset.Set(value)
def set_rest_offset(self, name, prim, value=None):
physx_collision_api = self._get_physx_collision_api(prim)
rest_offset = physx_collision_api.GetRestOffsetAttr()
# if not rest_offset:
# rest_offset = physx_collision_api.CreateRestOffsetAttr()
if value is None:
value = self._get_actor_config_value(name, "rest_offset", rest_offset)
if value != -1:
rest_offset.Set(value)
def set_position_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_position_iteration_count = physx_rb_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count)
if value != -1:
solver_position_iteration_count.Set(value)
def set_velocity_iteration(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
solver_velocity_iteration_count = physx_rb_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_max_depenetration_velocity(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
max_depenetration_velocity = physx_rb_api.GetMaxDepenetrationVelocityAttr()
if value is None:
value = self._get_actor_config_value(name, "max_depenetration_velocity", max_depenetration_velocity)
if value != -1:
max_depenetration_velocity.Set(value)
def set_sleep_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
sleep_threshold = physx_rb_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_stabilization_threshold(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
stabilization_threshold = physx_rb_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def set_gyroscopic_forces(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
enable_gyroscopic_forces = physx_rb_api.GetEnableGyroscopicForcesAttr()
if value is None:
value = self._get_actor_config_value(name, "enable_gyroscopic_forces", enable_gyroscopic_forces)
if value != -1:
enable_gyroscopic_forces.Set(value)
def set_density(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
density = physx_rb_api.GetDensityAttr()
if value is None:
value = self._get_actor_config_value(name, "density", density)
if value != -1:
density.Set(value)
# auto-compute mass
self.set_mass(prim, 0.0)
def set_mass(self, name, prim, value=None):
physx_rb_api = self._get_physx_rigid_body_api(prim)
mass = physx_rb_api.GetMassAttr()
if value is None:
value = self._get_actor_config_value(name, "mass", mass)
if value != -1:
mass.Set(value)
def retain_acceleration(self, prim):
# retain accelerations if running with more than one substep
physx_rb_api = self._get_physx_rigid_body_api(prim)
if self._sim_params["substeps"] > 1:
physx_rb_api.GetRetainAccelerationsAttr().Set(True)
def add_fixed_base(self, name, prim, cfg, value=None):
# add fixed root joint for rigid body
from pxr import UsdPhysics, PhysxSchema
stage = omni.usd.get_context().get_stage()
if value is None:
value = self._get_actor_config_value(name, "fixed_base")
if value:
root_joint_path = f"{prim.GetPath()}_fixedBaseRootJoint"
joint = UsdPhysics.Joint.Define(stage, root_joint_path)
joint.CreateBody1Rel().SetTargets([prim.GetPath()])
self.apply_articulation_settings(name, joint.GetPrim(), cfg, force_articulation=True)
def set_articulation_position_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_position_iteration_count = arti_api.GetSolverPositionIterationCountAttr()
if value is None:
value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count)
if value != -1:
solver_position_iteration_count.Set(value)
def set_articulation_velocity_iteration(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
solver_velocity_iteration_count = arti_api.GetSolverVelocityIterationCountAttr()
if value is None:
value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count)
if value != -1:
solver_velocity_iteration_count.Set(value)
def set_articulation_sleep_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
sleep_threshold = arti_api.GetSleepThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold)
if value != -1:
sleep_threshold.Set(value)
def set_articulation_stabilization_threshold(self, name, prim, value=None):
arti_api = self._get_physx_articulation_api(prim)
stabilization_threshold = arti_api.GetStabilizationThresholdAttr()
if value is None:
value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold)
if value != -1:
stabilization_threshold.Set(value)
def apply_rigid_body_settings(self, name, prim, cfg, is_articulation):
from pxr import UsdPhysics, PhysxSchema
stage = omni.usd.get_context().get_stage()
rb_api = UsdPhysics.RigidBodyAPI.Get(stage, prim.GetPath())
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPath())
if not physx_rb_api:
physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim)
# if it's a body in an articulation, it's handled at articulation root
if not is_articulation:
self.add_fixed_base(name, prim, cfg, cfg["fixed_base"])
self.set_position_iteration(name, prim, cfg["solver_position_iteration_count"])
self.set_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"])
self.set_max_depenetration_velocity(name, prim, cfg["max_depenetration_velocity"])
self.set_sleep_threshold(name, prim, cfg["sleep_threshold"])
self.set_stabilization_threshold(name, prim, cfg["stabilization_threshold"])
self.set_gyroscopic_forces(name, prim, cfg["enable_gyroscopic_forces"])
# density and mass
mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath())
if mass_api is None:
mass_api = UsdPhysics.MassAPI.Apply(prim)
mass_attr = mass_api.GetMassAttr()
density_attr = mass_api.GetDensityAttr()
if not mass_attr:
mass_attr = mass_api.CreateMassAttr()
if not density_attr:
density_attr = mass_api.CreateDensityAttr()
if cfg["density"] != -1:
density_attr.Set(cfg["density"])
mass_attr.Set(0.0) # mass is to be computed
elif cfg["override_usd_defaults"] and not density_attr.IsAuthored() and not mass_attr.IsAuthored():
density_attr.Set(self._physx_params["density"])
self.retain_acceleration(prim)
def apply_rigid_shape_settings(self, name, prim, cfg):
from pxr import UsdPhysics, PhysxSchema
stage = omni.usd.get_context().get_stage()
# collision APIs
collision_api = UsdPhysics.CollisionAPI(prim)
if not collision_api:
collision_api = UsdPhysics.CollisionAPI.Apply(prim)
physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
self.set_contact_offset(name, prim, cfg["contact_offset"])
self.set_rest_offset(name, prim, cfg["rest_offset"])
def apply_articulation_settings(self, name, prim, cfg, force_articulation=False):
from pxr import UsdPhysics, PhysxSchema
stage = omni.usd.get_context().get_stage()
is_articulation = False
# check if is articulation
prims = [prim]
while len(prims) > 0:
prim_tmp = prims.pop(0)
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim_tmp.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim_tmp.GetPath())
if articulation_api or physx_articulation_api:
is_articulation = True
children_prims = prim_tmp.GetPrim().GetChildren()
prims = prims + children_prims
if not is_articulation and force_articulation:
articulation_api = UsdPhysics.ArticulationRootAPI.Apply(prim)
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Apply(prim)
# parse through all children prims
prims = [prim]
while len(prims) > 0:
cur_prim = prims.pop(0)
rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath())
collision_body = UsdPhysics.CollisionAPI.Get(stage, cur_prim.GetPath())
articulation = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
if rb:
self.apply_rigid_body_settings(name, cur_prim, cfg, is_articulation)
if collision_body:
self.apply_rigid_shape_settings(name, cur_prim, cfg)
if articulation:
articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath())
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, cur_prim.GetPath())
# enable self collisions
enable_self_collisions = physx_articulation_api.GetEnabledSelfCollisionsAttr()
if cfg["enable_self_collisions"] != -1:
enable_self_collisions.Set(cfg["enable_self_collisions"])
self.set_articulation_position_iteration(name, cur_prim, cfg["solver_position_iteration_count"])
self.set_articulation_velocity_iteration(name, cur_prim, cfg["solver_velocity_iteration_count"])
self.set_articulation_sleep_threshold(name, cur_prim, cfg["sleep_threshold"])
self.set_articulation_stabilization_threshold(name, cur_prim, cfg["stabilization_threshold"])
children_prims = cur_prim.GetPrim().GetChildren()
prims = prims + children_prims
| 18,615 | Python | 44.627451 | 122 | 0.641257 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/config_utils/default_scene_params.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.
default_physx_params = {
### Per-scene settings
"use_gpu": False,
"worker_thread_count": 4,
"solver_type": 1, # 0: PGS, 1:TGS
"bounce_threshold_velocity": 0.2,
"friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact
# point will experience friction forces.
"friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the
# distance between the contacts is smaller than correlation distance.
# disabling these can be useful for debugging
"enable_sleeping": True,
"enable_stabilization": True,
# GPU buffers
"gpu_max_rigid_contact_count": 512 * 1024,
"gpu_max_rigid_patch_count": 80 * 1024,
"gpu_found_lost_pairs_capacity": 1024,
"gpu_found_lost_aggregate_pairs_capacity": 1024,
"gpu_total_aggregate_pairs_capacity": 1024,
"gpu_max_soft_body_contacts": 1024 * 1024,
"gpu_max_particle_contacts": 1024 * 1024,
"gpu_heap_capacity": 64 * 1024 * 1024,
"gpu_temp_buffer_capacity": 16 * 1024 * 1024,
"gpu_max_num_partitions": 8,
### Per-actor settings ( can override in actor_options )
"solver_position_iteration_count": 4,
"solver_velocity_iteration_count": 1,
"sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep.
# Allowed range [0, max_float).
"stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may
# participate in stabilization. Allowed range [0, max_float).
### Per-body settings ( can override in actor_options )
"enable_gyroscopic_forces": False,
"density": 1000.0, # density to be used for bodies that do not specify mass or density
"max_depenetration_velocity": 100.0,
### Per-shape settings ( can override in actor_options )
"contact_offset": 0.02,
"rest_offset": 0.001
}
default_physics_material = {
"static_friction": 1.0,
"dynamic_friction": 1.0,
"restitution": 0.0
}
default_sim_params = {
"gravity": [0.0, 0.0, -9.81],
"dt": 1.0 / 60.0,
"substeps": 1,
"use_gpu_pipeline": True,
"add_ground_plane": True,
"add_distant_light": True,
"use_flatcache": True,
"enable_scene_query_support": False,
"enable_cameras": False,
"disable_contact_processing": False,
"default_physics_material": default_physics_material
}
default_actor_options = {
# -1 means use authored value from USD or default values from default_sim_params if not explicitly authored in USD.
# If an attribute value is not explicitly authored in USD, add one with the value given here,
# which overrides the USD default.
"override_usd_defaults": False,
"fixed_base": -1,
"enable_self_collisions": -1,
"enable_gyroscopic_forces": -1,
"solver_position_iteration_count": -1,
"solver_velocity_iteration_count": -1,
"sleep_threshold": -1,
"stabilization_threshold": -1,
"max_depenetration_velocity": -1,
"density": -1,
"mass": -1,
"contact_offset": -1,
"rest_offset": -1
}
| 4,799 | Python | 41.105263 | 119 | 0.684101 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/config_utils/path_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.
import carb
from hydra.utils import to_absolute_path
import os
def is_valid_local_file(path):
return os.path.isfile(path)
def is_valid_ov_file(path):
import omni.client
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
def download_ov_file(source_path, target_path):
import omni.client
result = omni.client.copy(source_path, target_path)
if result == omni.client.Result.OK:
return True
return False
def break_ov_path(path):
import omni.client
return omni.client.break_url(path)
def retrieve_checkpoint_path(path):
print(to_absolute_path(path))
# check if it's a local path
if is_valid_local_file(path):
return to_absolute_path(path)
# check if it's an OV path
elif is_valid_ov_file(path):
ov_path = break_ov_path(path)
file_name = os.path.basename(ov_path.path)
target_path = f"checkpoints/{file_name}"
copy_to_local = download_ov_file(path, target_path)
return to_absolute_path(target_path)
else:
carb.log_error(f"Invalid checkpoint path: {path}")
return None | 2,690 | Python | 38.573529 | 80 | 0.734944 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/hydra_cfg/hydra_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.
import hydra
from omegaconf import DictConfig, OmegaConf
## OmegaConf & Hydra Config
# Resolvers used in hydra configs (see https://omegaconf.readthedocs.io/en/2.1_branch/usage.html#resolvers)
OmegaConf.register_new_resolver('eq', lambda x, y: x.lower()==y.lower())
OmegaConf.register_new_resolver('contains', lambda x, y: x.lower() in y.lower())
OmegaConf.register_new_resolver('if', lambda pred, a, b: a if pred else b)
# allows us to resolve default arguments which are copied in multiple places in the config. used primarily for
# num_ensv
OmegaConf.register_new_resolver('resolve_default', lambda default, arg: default if arg=='' else arg)
| 2,207 | Python | 51.571427 | 110 | 0.775714 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/hydra_cfg/reformat.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 omegaconf import DictConfig, OmegaConf
from typing import Dict
def omegaconf_to_dict(d: DictConfig)->Dict:
"""Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation."""
ret = {}
for k, v in d.items():
if isinstance(v, DictConfig):
ret[k] = omegaconf_to_dict(v)
else:
ret[k] = v
return ret
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionory."""
if type(val) == dict:
if not start:
print('')
nesting += 4
for k in val:
print(nesting * ' ', end='')
print(k, end=': ')
print_dict(val[k], nesting, start=False)
else:
print(val) | 2,307 | Python | 41.74074 | 95 | 0.70958 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/terrain_utils/terrain_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.
import numpy as np
from numpy.random import choice
from scipy import interpolate
from math import sqrt
from omni.isaac.core.prims import XFormPrim
from pxr import UsdPhysics, Sdf, Gf, PhysxSchema
def random_uniform_terrain(terrain, min_height, max_height, step=1, downsampled_scale=None,):
"""
Generate a uniform noise terrain
Parameters
terrain (SubTerrain): the terrain
min_height (float): the minimum height of the terrain [meters]
max_height (float): the maximum height of the terrain [meters]
step (float): minimum height change between two points [meters]
downsampled_scale (float): distance between two randomly sampled points ( musty be larger or equal to terrain.horizontal_scale)
"""
if downsampled_scale is None:
downsampled_scale = terrain.horizontal_scale
# switch parameters to discrete units
min_height = int(min_height / terrain.vertical_scale)
max_height = int(max_height / terrain.vertical_scale)
step = int(step / terrain.vertical_scale)
heights_range = np.arange(min_height, max_height + step, step)
height_field_downsampled = np.random.choice(heights_range, (int(terrain.width * terrain.horizontal_scale / downsampled_scale), int(
terrain.length * terrain.horizontal_scale / downsampled_scale)))
x = np.linspace(0, terrain.width * terrain.horizontal_scale, height_field_downsampled.shape[0])
y = np.linspace(0, terrain.length * terrain.horizontal_scale, height_field_downsampled.shape[1])
f = interpolate.interp2d(y, x, height_field_downsampled, kind='linear')
x_upsampled = np.linspace(0, terrain.width * terrain.horizontal_scale, terrain.width)
y_upsampled = np.linspace(0, terrain.length * terrain.horizontal_scale, terrain.length)
z_upsampled = np.rint(f(y_upsampled, x_upsampled))
terrain.height_field_raw += z_upsampled.astype(np.int16)
return terrain
def sloped_terrain(terrain, slope=1):
"""
Generate a sloped terrain
Parameters:
terrain (SubTerrain): the terrain
slope (int): positive or negative slope
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * terrain.width)
terrain.height_field_raw[:, np.arange(terrain.length)] += (max_height * xx / terrain.width).astype(terrain.height_field_raw.dtype)
return terrain
def pyramid_sloped_terrain(terrain, slope=1, platform_size=1.):
"""
Generate a sloped terrain
Parameters:
terrain (terrain): the terrain
slope (int): positive or negative slope
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
center_x = int(terrain.width / 2)
center_y = int(terrain.length / 2)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = (center_x - np.abs(center_x-xx)) / center_x
yy = (center_y - np.abs(center_y-yy)) / center_y
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * (terrain.width / 2))
terrain.height_field_raw += (max_height * xx * yy).astype(terrain.height_field_raw.dtype)
platform_size = int(platform_size / terrain.horizontal_scale / 2)
x1 = terrain.width // 2 - platform_size
x2 = terrain.width // 2 + platform_size
y1 = terrain.length // 2 - platform_size
y2 = terrain.length // 2 + platform_size
min_h = min(terrain.height_field_raw[x1, y1], 0)
max_h = max(terrain.height_field_raw[x1, y1], 0)
terrain.height_field_raw = np.clip(terrain.height_field_raw, min_h, max_h)
return terrain
def discrete_obstacles_terrain(terrain, max_height, min_size, max_size, num_rects, platform_size=1.):
"""
Generate a terrain with gaps
Parameters:
terrain (terrain): the terrain
max_height (float): maximum height of the obstacles (range=[-max, -max/2, max/2, max]) [meters]
min_size (float): minimum size of a rectangle obstacle [meters]
max_size (float): maximum size of a rectangle obstacle [meters]
num_rects (int): number of randomly generated obstacles
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
max_height = int(max_height / terrain.vertical_scale)
min_size = int(min_size / terrain.horizontal_scale)
max_size = int(max_size / terrain.horizontal_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
(i, j) = terrain.height_field_raw.shape
height_range = [-max_height, -max_height // 2, max_height // 2, max_height]
width_range = range(min_size, max_size, 4)
length_range = range(min_size, max_size, 4)
for _ in range(num_rects):
width = np.random.choice(width_range)
length = np.random.choice(length_range)
start_i = np.random.choice(range(0, i-width, 4))
start_j = np.random.choice(range(0, j-length, 4))
terrain.height_field_raw[start_i:start_i+width, start_j:start_j+length] = np.random.choice(height_range)
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def wave_terrain(terrain, num_waves=1, amplitude=1.):
"""
Generate a wavy terrain
Parameters:
terrain (terrain): the terrain
num_waves (int): number of sine waves across the terrain length
Returns:
terrain (SubTerrain): update terrain
"""
amplitude = int(0.5*amplitude / terrain.vertical_scale)
if num_waves > 0:
div = terrain.length / (num_waves * np.pi * 2)
x = np.arange(0, terrain.width)
y = np.arange(0, terrain.length)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(terrain.width, 1)
yy = yy.reshape(1, terrain.length)
terrain.height_field_raw += (amplitude*np.cos(yy / div) + amplitude*np.sin(xx / div)).astype(
terrain.height_field_raw.dtype)
return terrain
def stairs_terrain(terrain, step_width, step_height):
"""
Generate a stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the height of the step [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
num_steps = terrain.width // step_width
height = step_height
for i in range(num_steps):
terrain.height_field_raw[i * step_width: (i + 1) * step_width, :] += height
height += step_height
return terrain
def pyramid_stairs_terrain(terrain, step_width, step_height, platform_size=1.):
"""
Generate stairs
Parameters:
terrain (terrain): the terrain
step_width (float): the width of the step [meters]
step_height (float): the step_height [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
step_width = int(step_width / terrain.horizontal_scale)
step_height = int(step_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height = 0
start_x = 0
stop_x = terrain.width
start_y = 0
stop_y = terrain.length
while (stop_x - start_x) > platform_size and (stop_y - start_y) > platform_size:
start_x += step_width
stop_x -= step_width
start_y += step_width
stop_y -= step_width
height += step_height
terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = height
return terrain
def stepping_stones_terrain(terrain, stone_size, stone_distance, max_height, platform_size=1., depth=-10):
"""
Generate a stepping stones terrain
Parameters:
terrain (terrain): the terrain
stone_size (float): horizontal size of the stepping stones [meters]
stone_distance (float): distance between stones (i.e size of the holes) [meters]
max_height (float): maximum height of the stones (positive and negative) [meters]
platform_size (float): size of the flat platform at the center of the terrain [meters]
depth (float): depth of the holes (default=-10.) [meters]
Returns:
terrain (SubTerrain): update terrain
"""
# switch parameters to discrete units
stone_size = int(stone_size / terrain.horizontal_scale)
stone_distance = int(stone_distance / terrain.horizontal_scale)
max_height = int(max_height / terrain.vertical_scale)
platform_size = int(platform_size / terrain.horizontal_scale)
height_range = np.arange(-max_height-1, max_height, step=1)
start_x = 0
start_y = 0
terrain.height_field_raw[:, :] = int(depth / terrain.vertical_scale)
if terrain.length >= terrain.width:
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
start_x = np.random.randint(0, stone_size)
# fill first hole
stop_x = max(0, start_x - stone_distance)
terrain.height_field_raw[0: stop_x, start_y: stop_y] = np.random.choice(height_range)
# fill row
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range)
start_x += stone_size + stone_distance
start_y += stone_size + stone_distance
elif terrain.width > terrain.length:
while start_x < terrain.width:
stop_x = min(terrain.width, start_x + stone_size)
start_y = np.random.randint(0, stone_size)
# fill first hole
stop_y = max(0, start_y - stone_distance)
terrain.height_field_raw[start_x: stop_x, 0: stop_y] = np.random.choice(height_range)
# fill column
while start_y < terrain.length:
stop_y = min(terrain.length, start_y + stone_size)
terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range)
start_y += stone_size + stone_distance
start_x += stone_size + stone_distance
x1 = (terrain.width - platform_size) // 2
x2 = (terrain.width + platform_size) // 2
y1 = (terrain.length - platform_size) // 2
y2 = (terrain.length + platform_size) // 2
terrain.height_field_raw[x1:x2, y1:y2] = 0
return terrain
def convert_heightfield_to_trimesh(height_field_raw, horizontal_scale, vertical_scale, slope_threshold=None):
"""
Convert a heightfield array to a triangle mesh represented by vertices and triangles.
Optionally, corrects vertical surfaces above the provide slope threshold:
If (y2-y1)/(x2-x1) > slope_threshold -> Move A to A' (set x1 = x2). Do this for all directions.
B(x2,y2)
/|
/ |
/ |
(x1,y1)A---A'(x2',y1)
Parameters:
height_field_raw (np.array): input heightfield
horizontal_scale (float): horizontal scale of the heightfield [meters]
vertical_scale (float): vertical scale of the heightfield [meters]
slope_threshold (float): the slope threshold above which surfaces are made vertical. If None no correction is applied (default: None)
Returns:
vertices (np.array(float)): array of shape (num_vertices, 3). Each row represents the location of each vertex [meters]
triangles (np.array(int)): array of shape (num_triangles, 3). Each row represents the indices of the 3 vertices connected by this triangle.
"""
hf = height_field_raw
num_rows = hf.shape[0]
num_cols = hf.shape[1]
y = np.linspace(0, (num_cols-1)*horizontal_scale, num_cols)
x = np.linspace(0, (num_rows-1)*horizontal_scale, num_rows)
yy, xx = np.meshgrid(y, x)
if slope_threshold is not None:
slope_threshold *= horizontal_scale / vertical_scale
move_x = np.zeros((num_rows, num_cols))
move_y = np.zeros((num_rows, num_cols))
move_corners = np.zeros((num_rows, num_cols))
move_x[:num_rows-1, :] += (hf[1:num_rows, :] - hf[:num_rows-1, :] > slope_threshold)
move_x[1:num_rows, :] -= (hf[:num_rows-1, :] - hf[1:num_rows, :] > slope_threshold)
move_y[:, :num_cols-1] += (hf[:, 1:num_cols] - hf[:, :num_cols-1] > slope_threshold)
move_y[:, 1:num_cols] -= (hf[:, :num_cols-1] - hf[:, 1:num_cols] > slope_threshold)
move_corners[:num_rows-1, :num_cols-1] += (hf[1:num_rows, 1:num_cols] - hf[:num_rows-1, :num_cols-1] > slope_threshold)
move_corners[1:num_rows, 1:num_cols] -= (hf[:num_rows-1, :num_cols-1] - hf[1:num_rows, 1:num_cols] > slope_threshold)
xx += (move_x + move_corners*(move_x == 0)) * horizontal_scale
yy += (move_y + move_corners*(move_y == 0)) * horizontal_scale
# create triangle mesh vertices and triangles from the heightfield grid
vertices = np.zeros((num_rows*num_cols, 3), dtype=np.float32)
vertices[:, 0] = xx.flatten()
vertices[:, 1] = yy.flatten()
vertices[:, 2] = hf.flatten() * vertical_scale
triangles = -np.ones((2*(num_rows-1)*(num_cols-1), 3), dtype=np.uint32)
for i in range(num_rows - 1):
ind0 = np.arange(0, num_cols-1) + i*num_cols
ind1 = ind0 + 1
ind2 = ind0 + num_cols
ind3 = ind2 + 1
start = 2*i*(num_cols-1)
stop = start + 2*(num_cols-1)
triangles[start:stop:2, 0] = ind0
triangles[start:stop:2, 1] = ind3
triangles[start:stop:2, 2] = ind1
triangles[start+1:stop:2, 0] = ind0
triangles[start+1:stop:2, 1] = ind2
triangles[start+1:stop:2, 2] = ind3
return vertices, triangles
def add_terrain_to_stage(stage, vertices, triangles, position=None, orientation=None):
num_faces = triangles.shape[0]
terrain_mesh = stage.DefinePrim("/World/terrain", "Mesh")
terrain_mesh.GetAttribute("points").Set(vertices)
terrain_mesh.GetAttribute("faceVertexIndices").Set(triangles.flatten())
terrain_mesh.GetAttribute("faceVertexCounts").Set(np.asarray([3]*num_faces))
terrain = XFormPrim(prim_path="/World/terrain",
name="terrain",
position=position,
orientation=orientation)
UsdPhysics.CollisionAPI.Apply(terrain.prim)
# collision_api = UsdPhysics.MeshCollisionAPI.Apply(terrain.prim)
# collision_api.CreateApproximationAttr().Set("meshSimplification")
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(terrain.prim)
physx_collision_api.GetContactOffsetAttr().Set(0.02)
physx_collision_api.GetRestOffsetAttr().Set(0.00)
class SubTerrain:
def __init__(self, terrain_name="terrain", width=256, length=256, vertical_scale=1.0, horizontal_scale=1.0):
self.terrain_name = terrain_name
self.vertical_scale = vertical_scale
self.horizontal_scale = horizontal_scale
self.width = width
self.length = length
self.height_field_raw = np.zeros((self.width, self.length), dtype=np.int16)
| 17,478 | Python | 42.917085 | 147 | 0.655166 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/terrain_utils/create_terrain_demo.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 os, sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SCRIPT_DIR)
import omni
from omni.isaac.kit import SimulationApp
import numpy as np
import torch
simulation_app = SimulationApp({"headless": False})
from abc import abstractmethod
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.prims import RigidPrimView, RigidPrim, XFormPrim
from omni.isaac.core import World
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import define_prim, get_prim_at_path
from omni.isaac.core.utils.nucleus import find_nucleus_server
from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage
from omni.isaac.core.materials import PreviewSurface
from omni.isaac.cloner import GridCloner
from pxr import UsdPhysics, UsdLux, UsdShade, Sdf, Gf, UsdGeom, PhysxSchema
from terrain_utils import *
class TerrainCreation(BaseTask):
def __init__(self, name, num_envs, num_per_row, env_spacing, config=None, offset=None,) -> None:
BaseTask.__init__(self, name=name, offset=offset)
self._num_envs = num_envs
self._num_per_row = num_per_row
self._env_spacing = env_spacing
self._device = "cpu"
self._cloner = GridCloner(self._env_spacing, self._num_per_row)
self._cloner.define_base_env(self.default_base_env_path)
define_prim(self.default_zero_env_path)
@property
def default_base_env_path(self):
return "/World/envs"
@property
def default_zero_env_path(self):
return f"{self.default_base_env_path}/env_0"
def set_up_scene(self, scene) -> None:
self._stage = get_current_stage()
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight"))
distantLight.CreateIntensityAttr(2000)
self.get_terrain()
self.get_ball()
super().set_up_scene(scene)
prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs)
print(f"cloning {self._num_envs} environments...")
self._env_pos = self._cloner.clone(
source_prim_path="/World/envs/env_0",
prim_paths=prim_paths
)
return
def get_terrain(self):
# create all available terrain types
num_terains = 8
terrain_width = 12.
terrain_length = 12.
horizontal_scale = 0.25 # [m]
vertical_scale = 0.005 # [m]
num_rows = int(terrain_width/horizontal_scale)
num_cols = int(terrain_length/horizontal_scale)
heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16)
def new_sub_terrain():
return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale)
heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=-0.2, max_height=0.2, step=0.2, downsampled_scale=0.5).height_field_raw
heightfield[num_rows:2*num_rows, :] = sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[2*num_rows:3*num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw
heightfield[3*num_rows:4*num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=0.5, min_size=1., max_size=5., num_rects=20).height_field_raw
heightfield[4*num_rows:5*num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=2., amplitude=1.).height_field_raw
heightfield[5*num_rows:6*num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[6*num_rows:7*num_rows, :] = pyramid_stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw
heightfield[7*num_rows:8*num_rows, :] = stepping_stones_terrain(new_sub_terrain(), stone_size=1.,
stone_distance=1., max_height=0.5, platform_size=0.).height_field_raw
vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5)
position = np.array([-6.0, 48.0, 0])
orientation = np.array([0.70711, 0.0, 0.0, -0.70711])
add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation)
def get_ball(self):
ball = DynamicSphere(prim_path=self.default_zero_env_path + "/ball",
name="ball",
translation=np.array([0.0, 0.0, 1.0]),
mass=0.5,
radius=0.2,)
def post_reset(self):
for i in range(self._num_envs):
ball_prim = self._stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}/ball")
color = 0.5 + 0.5 * np.random.random(3)
visual_material = PreviewSurface(prim_path=f"{self.default_base_env_path}/env_{i}/ball/Looks/visual_material", color=color)
binding_api = UsdShade.MaterialBindingAPI(ball_prim)
binding_api.Bind(visual_material.material, bindingStrength=UsdShade.Tokens.strongerThanDescendants)
def get_observations(self):
pass
def calculate_metrics(self) -> None:
pass
def is_done(self) -> None:
pass
if __name__ == "__main__":
world = World(
stage_units_in_meters=1.0,
rendering_dt=1.0/60.0,
backend="torch",
device="cpu",
)
num_envs = 800
num_per_row = 80
env_spacing = 0.56*2
terrain_creation_task = TerrainCreation(name="TerrainCreation",
num_envs=num_envs,
num_per_row=num_per_row,
env_spacing=env_spacing,
)
world.add_task(terrain_creation_task)
world.reset()
while simulation_app.is_running():
if world.is_playing():
if world.current_time_step_index == 0:
world.reset(soft=True)
world.step(render=True)
else:
world.step(render=True)
simulation_app.close() | 7,869 | Python | 43.213483 | 166 | 0.650654 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/utils/usd_utils/create_instanceable_assets.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 omni.usd
import omni.client
from pxr import UsdGeom, Sdf
def update_reference(source_prim_path, source_reference_path, target_reference_path):
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
prim_spec = stage.GetRootLayer().GetPrimAtPath(prim.GetPath())
reference_list = prim_spec.referenceList
refs = reference_list.GetAddedOrExplicitItems()
if len(refs) > 0:
for ref in refs:
if ref.assetPath == source_reference_path:
prim.GetReferences().RemoveReference(ref)
prim.GetReferences().AddReference(assetPath=target_reference_path, primPath=prim.GetPath())
prims = prims + prim.GetChildren()
def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None):
""" Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path.
Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
"""
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
edits = Sdf.BatchNamespaceEdit()
while len(prims) > 0:
prim = prims.pop(0)
print(prim)
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform")
print(prim, new_xform)
edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0))
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
stage.GetRootLayer().Apply(edits)
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
def convert_asset_instanceable(asset_usd_path, source_prim_path, save_as_path=None, create_xforms=True):
""" Makes all mesh/geometry prims instanceable.
Can optionally add UsdGeom.Xform prim as parent for all mesh/geometry prims.
Makes a copy of the asset USD file, which will be used for referencing.
Updates asset file to convert all parent prims of mesh/geometry prims to reference cloned USD file.
Args:
asset_usd_path (str): USD file path for asset
source_prim_path (str): USD path of root prim
save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file.
create_xforms (bool): Whether to add new UsdGeom.Xform prims to mesh/geometry prims.
"""
if create_xforms:
create_parent_xforms(asset_usd_path, source_prim_path, save_as_path)
asset_usd_path = save_as_path
instance_usd_path = ".".join(asset_usd_path.split(".")[:-1]) + "_meshes.usd"
omni.client.copy(asset_usd_path, instance_usd_path)
omni.usd.get_context().open_stage(asset_usd_path)
stage = omni.usd.get_context().get_stage()
prims = [stage.GetPrimAtPath(source_prim_path)]
while len(prims) > 0:
prim = prims.pop(0)
if prim:
if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]:
parent_prim = prim.GetParent()
if parent_prim and not parent_prim.IsInstance():
parent_prim.GetReferences().AddReference(assetPath=instance_usd_path, primPath=str(parent_prim.GetPath()))
parent_prim.SetInstanceable(True)
continue
children_prims = prim.GetChildren()
prims = prims + children_prims
if save_as_path is None:
omni.usd.get_context().save_stage()
else:
omni.usd.get_context().save_as_stage(save_as_path)
| 5,639 | Python | 43.761904 | 126 | 0.675829 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/runs/SwerveCS/config.yaml | task:
name: SwerveCS
physics_engine: ${..physics_engine}
env:
numEnvs: 36
envSpacing: 20
resetDist: 3.0
clipObservations: 1.0
clipActions: 1.0
controlFrequencyInv: 12
control:
stiffness: 85.0
damping: 2.0
actionScale: 13.5
episodeLength_s: 15
sim:
dt: 0.01
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
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"}
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_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:
override_usd_defaults: false
fixed_base: false
enable_self_collisions: false
enable_gyroscopic_forces: true
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
density: -1
max_depenetration_velocity: 100.0
contact_offset: 0.02
rest_offset: 0.001
train:
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}
load_path: ${...checkpoint}
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: 0.0003
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
task_name: ${task.name}
experiment: ''
num_envs: ''
seed: 42
torch_deterministic: false
max_iterations: ''
physics_engine: physx
pipeline: gpu
sim_device: gpu
device_id: 0
rl_device: cuda:0
num_threads: 4
solver_type: 1
test: true
checkpoint: /root/edna/isaac/Swervesim/swervesim/runs/SwerveCS/nn/last_SwerveCS_ep_750_rew_166.53838.pth
headless: false
wandb_activate: false
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: swervesim
| 3,989 | YAML | 24.741935 | 104 | 0.61093 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/runs/Swerve/config.yaml | task:
name: Swerve
physics_engine: ${..physics_engine}
env:
numEnvs: 324
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12
baseInitState:
pos:
- 0.0
- 0.0
- 0.62
rot:
- 0.0
- 0.0
- 0.0
- 1.0
vLinear:
- 0.0
- 0.0
- 0.0
vAngular:
- 0.0
- 0.0
- 0.0
control:
stiffness: 85.0
damping: 2.0
actionScale: 13.5
episodeLength_s: 50
sim:
dt: 0.0083
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
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"}
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_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:
override_usd_defaults: false
fixed_base: false
enable_self_collisions: false
enable_gyroscopic_forces: true
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
density: -1
max_depenetration_velocity: 100.0
contact_offset: 0.02
rest_offset: 0.001
train:
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}
load_path: ${...checkpoint}
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: 0.0003
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
task_name: ${task.name}
experiment: ''
num_envs: ''
seed: 42
torch_deterministic: false
max_iterations: ''
physics_engine: physx
pipeline: gpu
sim_device: gpu
device_id: 0
rl_device: cuda:0
num_threads: 4
solver_type: 1
test: false
checkpoint: ''
headless: false
wandb_activate: false
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: omniisaacgymenv
| 4,124 | YAML | 22.843931 | 55 | 0.586081 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/runs/SwerveK/config.yaml | task:
name: SwerveK
physics_engine: ${..physics_engine}
env:
numEnvs: 36
envSpacing: 20.0
resetDist: 3.0
clipObservations: 5.0
clipActions: 1.0
controlFrequencyInv: 12
baseInitState:
pos:
- 0.0
- 0.0
- 0.62
rot:
- 0.0
- 0.0
- 0.0
- 1.0
vLinear:
- 0.0
- 0.0
- 0.0
vAngular:
- 0.0
- 0.0
- 0.0
control:
stiffness: 85.0
damping: 2.0
actionScale: 13.5
episodeLength_s: 50
sim:
dt: 0.0083
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
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"}
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_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:
override_usd_defaults: false
fixed_base: false
enable_self_collisions: false
enable_gyroscopic_forces: true
solver_velocity_iteration_count: 8
sleep_threshold: 0.005
stabilization_threshold: 0.001
density: -1
max_depenetration_velocity: 100.0
contact_offset: 0.02
rest_offset: 0.001
train:
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}
load_path: ${...checkpoint}
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: 0.0003
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
task_name: ${task.name}
experiment: ''
num_envs: ''
seed: 42
torch_deterministic: false
max_iterations: ''
physics_engine: physx
pipeline: gpu
sim_device: gpu
device_id: 0
rl_device: cuda:0
num_threads: 4
solver_type: 1
test: true
checkpoint: /home/nitin/Documents/2023RobotROS/Swervesim/swervesim/runs/SwerveK/nn/Best_SwerveK.pth
headless: false
wandb_activate: false
wandb_group: ''
wandb_name: ${train.params.config.name}
wandb_entity: ''
wandb_project: omniisaacgymenv
| 4,210 | YAML | 23.34104 | 99 | 0.592162 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/robots/articulations/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 typing import Optional
import numpy as np
import torch
import omni.kit.commands
from omni.isaac.urdf import _urdf
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.robots.robot import Robot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.utils.stage import get_current_stage
import numpy as np
import torch
import os
from pxr import PhysxSchema
class Swerve(Robot):
def __init__(self,prim_path,name,translation):
self._name = name
#self.prim_path = prim_path
file_path = os.path.abspath(__file__)
project_root_path = os.path.abspath(os.path.join(file_path, "../../../../../../"))
root_path= os.path.join(project_root_path, "isaac/assets/swerve/swerve.usd")
print(str(root_path))
print(prim_path)
self._usd_path = root_path
add_reference_to_stage(self._usd_path, prim_path)
print(str(get_current_stage() ))
super().__init__(
prim_path=prim_path,
name=name,
translation=translation,
orientation=None,
articulation_controller=None,
)
self._dof_names = ["front_left_axle_joint",
"front_right_axle_joint",
"rear_left_axle_joint",
"rear_right_axle_joint",
"front_left_wheel_joint",
"front_right_wheel_joint",
"rear_left_wheel_joint",
"rear_right_wheel_joint",
]
@property
def dof_names(self):
return self._dof_names
def set_swerve_properties(self, stage, prim):
for link_prim in prim.GetChildren():
if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI):
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath())
rb.GetDisableGravityAttr().Set(False)
rb.GetRetainAccelerationsAttr().Set(False)
rb.GetLinearDampingAttr().Set(0.0)
rb.GetMaxLinearVelocityAttr().Set(1000.0)
rb.GetAngularDampingAttr().Set(0.0)
rb.GetMaxAngularVelocityAttr().Set(64/np.pi*180)
| 3,885 | Python | 41.703296 | 90 | 0.665894 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/robots/articulations/views/charge_station_view.py |
from typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
import math
import torch
class ChargeStationView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "ChargeStationView",
) -> None:
"""[summary]
"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
reset_xform_properties=False
)
self.chargestation_base = RigidPrimView(prim_paths_expr="/World/envs/.*/ChargeStation", name="base_view", reset_xform_properties=False)
# self.top = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field", name="field_view", reset_xform_properties=False)
# self.red_ball_1 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_08", name="redball[1]", reset_xform_properties=False)
# self.red_ball_2 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_09", name="redball[2]", reset_xform_properties=False)
# self.red_ball_3 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_10", name="redball[3]", reset_xform_properties=False)
# self.red_ball_4 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_11", name="redball[4]", reset_xform_properties=False)
# self.red_ball_5 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_12", name="redball[5]", reset_xform_properties=False)
# self.red_ball_6 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_13", name="redball[6]", reset_xform_properties=False)
# self.red_ball_7 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_14", name="redball[7]", reset_xform_properties=False)
# self.red_ball_8 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_15", name="redball[8]", reset_xform_properties=False)
# self.blue_ball_1 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_08", name="blueball[1]", reset_xform_properties=False)
# self.blue_ball_2 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_09", name="blueball[2]", reset_xform_properties=False)
# self.blue_ball_3 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_10", name="blueball[3]", reset_xform_properties=False)
# self.blue_ball_4 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_11", name="blueball[4]", reset_xform_properties=False)
# self.blue_ball_5 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_12", name="blueball[5]", reset_xform_properties=False)
# self.blue_ball_6 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_13", name="blueball[6]", reset_xform_properties=False)
# self.blue_ball_7 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_14", name="blueball[7]", reset_xform_properties=False)
# self.blue_ball_8 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_15", name="blueball[8]", reset_xform_properties=False)
# self.goal = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/THE_HUB_GE_22300_01/GE_22434", name="goal[1]", reset_xform_properties=False)
def if_balanced(self, device):
self.base_pose, self.base_orientation = self.chargestation_base.get_world_poses()
tolerance = 0.03
output_roll = torch.tensor([1.0 if math.atan2(2*i[2]*i[0] - 2*i[1]*i[3], 1 - 2*i[2]*i[2] - 2*i[3]*i[3]) <= tolerance else 0.0 for i in self.base_orientation], device=device)
return output_roll
| 4,200 | Python | 84.734692 | 181 | 0.684286 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/robots/articulations/views/swerve_view.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 typing import Optional
from omni.isaac.core.articulations import ArticulationView
from omni.isaac.core.prims import RigidPrimView
import torch
class SwerveView(ArticulationView):
def __init__(
self,
prim_paths_expr: str,
name: Optional[str] = "SwerveView",
) -> None:
"""[summary]
"""
super().__init__(
prim_paths_expr=prim_paths_expr,
name=name,
reset_xform_properties=False
)
self._base = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link", name="base_view", reset_xform_properties=False)
# self._axle = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/.*_axle_link", name="axle_view", reset_xform_properties=False)
# self._wheel = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/.*_wheel_link", name="wheel_view", reset_xform_properties=False)
self._axle = [
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_axle_link", name="axle_view[0]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_axle_link", name="axle_view[1]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_axle_link", name="axle_view[2]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_axle_link", name="axle_view[3]", reset_xform_properties=False)
]
self._wheel = [
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_wheel_link", name="wheel_view[0]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_wheel_link", name="wheel_view[1]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_wheel_link", name="wheel_view[2]", reset_xform_properties=False),
RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_wheel_link", name="wheel_view[3]", reset_xform_properties=False)
]
# self._axle = [
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/front_left_axle_joint", name="axle_view[0]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/front_right_axle_joint", name="axle_view[1]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/rear_left_axle_joint", name="axle_view[2]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/rear_right_axle_joint", name="axle_view[3]", reset_xform_properties=False)
# ]
# self._wheel = [
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_axle_link/front_left_wheel_joint", name="wheel_view[0]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_axle_link/front_right_wheel_joint", name="wheel_view[1]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_axle_link/rear_left_wheel_joint", name="wheel_view[2]", reset_xform_properties=False),
# RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_axle_link/rear_right_wheel_joint", name="wheel_view[3]", reset_xform_properties=False)
# ]
def get_axle_positions(self):
axle_pose1, __ = self._axle[0].get_local_poses()
axle_pose2, __ = self._axle[1].get_local_poses()
axle_pose3, __ = self._axle[2].get_local_poses()
axle_pose4, __ = self._axle[3].get_local_poses()
tuple = (torch.transpose(axle_pose1, 0, 1),
torch.transpose(axle_pose2, 0, 1),
torch.transpose(axle_pose3, 0, 1),
torch.transpose(axle_pose4, 0, 1)
)
tuple_tensor = torch.cat(tuple)
return torch.transpose(tuple_tensor, 0, 1)
# def get_knee_transforms(self):
# return self._knees.get_world_poses()
# def is_knee_below_threshold(self, threshold, ground_heights=None):
# knee_pos, _ = self._knees.get_world_poses()
# knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2]
# if ground_heights is not None:
# knee_heights -= ground_heights
# return (knee_heights[:, 0] < threshold) | (knee_heights[:, 1] < threshold) | (knee_heights[:, 2] < threshold) | (knee_heights[:, 3] < threshold)
# def is_base_below_threshold(self, threshold, ground_heights):
# base_pos, _ = self.get_world_poses()
# base_heights = base_pos[:, 2]
# base_heights -= ground_heights
# return (base_heights[:] < threshold)
| 6,450 | Python | 59.289719 | 167 | 0.664341 |
RoboEagles4828/offseason2023/scripts/quickpub.py | #!/usr/bin/python3
import time
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
from threading import Thread
JOINT_NAMES = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'bottom_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
class ROSNode(Node):
def __init__(self):
super().__init__('quickpublisher')
self.publish_positions = [0.0]*6
self.publisher = self.create_publisher(JointState, "/real/real_arm_commands", 10)
self.publishTimer = self.create_timer(0.5, self.publish)
def publish(self):
msg = JointState()
msg.name = JOINT_NAMES
msg.position = self.publish_positions
self.publisher.publish(msg)
def main():
rclpy.init()
node = ROSNode()
Thread(target=rclpy.spin, args=(node,)).start()
while True:
try:
joint_index = int(input("Joint index: "))
position = float(input("Position: "))
node.publish_positions[joint_index] = position
except:
print("Invalid input")
continue
if __name__ == '__main__':
main() | 1,227 | Python | 25.127659 | 89 | 0.605542 |
RoboEagles4828/offseason2023/scripts/config/omniverse.toml |
[bookmarks]
IsaacAssets = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac"
Scenarios = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Samples/ROS2/Scenario"
edna = "/workspaces/edna2023"
localhost = "omniverse://localhost"
[cache]
data_dir = "/root/.cache/ov/Cache"
proxy_cache_enabled = false
proxy_cache_server = ""
[connection_library]
proxy_dict = "*#localhost:8891,f"
| 397 | TOML | 25.533332 | 92 | 0.743073 |
RoboEagles4828/offseason2023/docker/developer/README.md | # Docker for Development
This directory has the configuration for building the image used in the edna devcontainer.
It uses the osrf ros humble image as a base and installs edna related software on top.
When loading the devcontainer the common utils feature is used to update the user GID/UID to match local and setup zsh and other terminal nice to haves.
**Common Utils**: `devcontainers/features/common-utils` \
**URL**: https://github.com/devcontainers/features/tree/main/src/common-utils
# Build
1. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \
This will be used to push the image to the registry
2. Run `./build` to build the image. \
The script will prompt you if you would like to do a quick test or push to the registry. | 897 | Markdown | 48.888886 | 210 | 0.782609 |
RoboEagles4828/offseason2023/docker/jetson/README.md | # Jetson Docker Image | 21 | Markdown | 20.999979 | 21 | 0.809524 |
RoboEagles4828/offseason2023/docker/developer-isaac-ros/README.md | # Docker for isaac ros
This directory has the configuration for building the image used for isaac utilities that require l4t.
It uses the isaac ros common container as a base and installs edna related software on top.
# Build
1. Docker Login to the nvidia NGC registry. [Guide](https://docs.nvidia.com/ngc/ngc-catalog-user-guide/index.html)\
This will be used to download nvidia images.
2. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \
This will be used to push the image to the registry
3. Run `./build` to build the image. \
The script will prompt you if you would like to do a quick test or push to the registry. | 780 | Markdown | 59.076919 | 210 | 0.783333 |
RoboEagles4828/offseason2023/docker/jetson-isaac-ros/README.md | # Jetson Docker Image with Isaac ROS | 36 | Markdown | 35.999964 | 36 | 0.805556 |
RoboEagles4828/offseason2023/rio/robot.py | import logging
import wpilib
import threading
import traceback
import time
import os, inspect
from hardware_interface.drivetrain import DriveTrain
from hardware_interface.joystick import Joystick
from hardware_interface.armcontroller import ArmController
from dds.dds import DDS_Publisher, DDS_Subscriber
EMABLE_ENCODER = True
ENABLE_JOY = True
ENABLE_DRIVE = True
ENABLE_ARM = True
ENABLE_STAGE_BROADCASTER = True
# Global Variables
frc_stage = "DISABLED"
fms_attached = False
stop_threads = False
drive_train : DriveTrain = None
joystick : Joystick = None
arm_controller : ArmController = None
# Logging
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
# XML Path for DDS configuration
curr_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
xml_path = os.path.join(curr_path, "dds/xml/ROS_RTI.xml")
############################################
## Hardware
def initDriveTrain():
global drive_train
if drive_train == None:
drive_train = DriveTrain()
logging.info("Success: DriveTrain created")
return drive_train
def initJoystick():
global joystick
if joystick == None:
joystick = Joystick()
logging.info("Success: Joystick created")
return joystick
def initArmController():
global arm_controller
if arm_controller == None:
arm_controller = ArmController()
logging.info("Success: ArmController created")
return arm_controller
def initDDS(ddsAction, participantName, actionName):
dds = None
with rti_init_lock:
dds = ddsAction(xml_path, participantName, actionName)
return dds
############################################
############################################
## Threads
def threadLoop(name, dds, action):
logging.info(f"Starting {name} thread")
global stop_threads
global frc_stage
try:
while stop_threads == False:
if (frc_stage == 'AUTON' and name != "joystick") or (name in ["encoder", "stage-broadcaster"]) or (frc_stage == 'TELEOP'):
action(dds)
time.sleep(20/1000)
except Exception as e:
logging.error(f"An issue occured with the {name} thread")
logging.error(e)
logging.error(traceback.format_exc())
logging.info(f"Closing {name} thread")
dds.close()
# Generic Start Thread Function
def startThread(name) -> threading.Thread | None:
thread = None
if name == "encoder":
thread = threading.Thread(target=encoderThread, daemon=True)
elif name == "command":
thread = threading.Thread(target=commandThread, daemon=True)
elif name == "arm-command":
thread = threading.Thread(target=armThread, daemon=True)
elif name == "joystick":
thread = threading.Thread(target=joystickThread, daemon=True)
elif name == "stage-broadcaster":
thread = threading.Thread(target=stageBroadcasterThread, daemon=True)
thread.start()
return thread
# Locks
rti_init_lock = threading.Lock()
drive_train_lock = threading.Lock()
arm_controller_lock = threading.Lock()
############################################
################## ENCODER ##################
ENCODER_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::encoder_info"
ENCODER_WRITER_NAME = "encoder_info_publisher::encoder_info_writer"
def encoderThread():
encoder_publisher = initDDS(DDS_Publisher, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME)
threadLoop('encoder', encoder_publisher, encoderAction)
def encoderAction(publisher):
# TODO: Make these some sort of null value to identify lost data
data = {
'name': [],
'position': [],
'velocity': []
}
global drive_train
with drive_train_lock:
if ENABLE_DRIVE:
drive_data = drive_train.getEncoderData()
data['name'] += drive_data['name']
data['position'] += drive_data['position']
data['velocity'] += drive_data['velocity']
global arm_controller
with arm_controller_lock:
if ENABLE_ARM:
arm_data = arm_controller.getEncoderData()
data['name'] += arm_data['name']
data['position'] += arm_data['position']
data['velocity'] += arm_data['velocity']
publisher.write(data)
############################################
################## COMMAND ##################
COMMAND_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::joint_commands"
COMMAND_WRITER_NAME = "isaac_joint_commands_subscriber::joint_commands_reader"
def commandThread():
command_subscriber = initDDS(DDS_Subscriber, COMMAND_PARTICIPANT_NAME, COMMAND_WRITER_NAME)
threadLoop('command', command_subscriber, commandAction)
def commandAction(subscriber : DDS_Subscriber):
data = subscriber.read()
global drive_train
with drive_train_lock:
drive_train.sendCommands(data)
############################################
################## ARM ##################
ARM_COMMAND_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::arm_commands"
ARM_COMMAND_WRITER_NAME = "isaac_arm_commands_subscriber::arm_commands_reader"
def armThread():
arm_command_subscriber = initDDS(DDS_Subscriber, ARM_COMMAND_PARTICIPANT_NAME, ARM_COMMAND_WRITER_NAME)
threadLoop('arm', arm_command_subscriber, armAction)
def armAction(subscriber : DDS_Subscriber):
data = subscriber.read()
global arm_controller
with arm_controller_lock:
arm_controller.sendCommands(data)
############################################
################## JOYSTICK ##################
JOYSTICK_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::joystick"
JOYSTICK_WRITER_NAME = "joystick_data_publisher::joystick_data_writer"
def joystickThread():
joystick_publisher = initDDS(DDS_Publisher, JOYSTICK_PARTICIPANT_NAME, JOYSTICK_WRITER_NAME)
threadLoop('joystick', joystick_publisher, joystickAction)
def joystickAction(publisher : DDS_Publisher):
if frc_stage == "TELEOP":
global joystick
data = None
try:
data = joystick.getData()
except:
logging.warn("No joystick data could be fetched!")
initJoystick()
publisher.write(data)
############################################
################## STAGE ##################
STAGE_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::stage_broadcaster"
STAGE_WRITER_NAME = "stage_publisher::stage_writer"
def stageBroadcasterThread():
stage_publisher = initDDS(DDS_Publisher, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME)
threadLoop('stage-broadcaster', stage_publisher, stageBroadcasterAction)
def stageBroadcasterAction(publisher : DDS_Publisher):
global frc_stage
global fms_attached
is_disabled = wpilib.DriverStation.isDisabled()
publisher.write({ "data": f"{frc_stage}|{fms_attached}|{is_disabled}" })
############################################
######### Robot Class #########
class EdnaRobot(wpilib.TimedRobot):
def robotInit(self):
self.use_threading = True
wpilib.CameraServer.launch()
logging.warning("Running in simulation!") if wpilib.RobotBase.isSimulation() else logging.info("Running in real!")
self.drive_train = initDriveTrain()
self.joystick = initJoystick()
self.arm_controller = initArmController()
self.threads = []
if self.use_threading:
logging.info("Initializing Threads")
global stop_threads
stop_threads = False
if ENABLE_DRIVE: self.threads.append({"name": "command", "thread": startThread("command") })
if ENABLE_ARM: self.threads.append({"name": "arm-command", "thread": startThread("arm-command")})
if ENABLE_JOY: self.threads.append({"name": "joystick", "thread": startThread("joystick") })
if EMABLE_ENCODER: self.threads.append({"name": "encoder", "thread": startThread("encoder") })
if ENABLE_STAGE_BROADCASTER: self.threads.append({"name": "stage-broadcaster", "thread": startThread("stage-broadcaster") })
else:
self.encoder_publisher = DDS_Publisher(xml_path, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME)
self.joystick_publisher = DDS_Publisher(xml_path, JOYSTICK_PARTICIPANT_NAME, JOYSTICK_WRITER_NAME)
self.command_subscriber = DDS_Subscriber(xml_path, COMMAND_PARTICIPANT_NAME, COMMAND_WRITER_NAME)
self.arm_command_subscriber = DDS_Subscriber(xml_path, ARM_COMMAND_PARTICIPANT_NAME, ARM_COMMAND_WRITER_NAME)
self.stage_publisher = DDS_Publisher(xml_path, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME)
# Auton
def autonomousInit(self):
logging.info("Entering Auton")
global frc_stage
frc_stage = "AUTON"
def autonomousPeriodic(self):
global fms_attached
fms_attached = wpilib.DriverStation.isFMSAttached()
if self.use_threading:
self.manageThreads()
else:
self.doActions()
def autonomousExit(self):
logging.info("Exiting Auton")
global frc_stage
frc_stage = "AUTON"
# Teleop
def teleopInit(self):
logging.info("Entering Teleop")
global frc_stage
frc_stage = "TELEOP"
def teleopPeriodic(self):
global fms_attached
fms_attached = wpilib.DriverStation.isFMSAttached()
if self.use_threading:
self.manageThreads()
else:
self.doActions()
def teleopExit(self):
logging.info("Exiting Teleop")
global frc_stage
frc_stage = "DISABLED"
with drive_train_lock:
drive_train.stop()
with arm_controller_lock:
arm_controller.stop()
def manageThreads(self):
# Check all threads and make sure they are alive
for thread in self.threads:
if thread["thread"].is_alive() == False:
# If this is the command thread, we need to stop the robot
if thread["name"] == "command":
logging.warning(f"Stopping robot due to command thread failure")
with drive_train_lock:
drive_train.stop()
with arm_controller_lock:
arm_controller.stop()
logging.warning(f"Thread {thread['name']} is not alive, restarting...")
thread["thread"] = startThread(thread["name"])
def doActions(self):
encoderAction(self.encoder_publisher)
commandAction(self.command_subscriber)
armAction(self.arm_command_subscriber)
joystickAction(self.joystick_publisher)
stageBroadcasterAction(self.stage_publisher)
# Is this needed?
def stopThreads(self):
global stop_threads
stop_threads = True
for thread in self.threads:
thread.join()
logging.info('All Threads Stopped')
if __name__ == '__main__':
wpilib.run(EdnaRobot)
| 11,010 | Python | 31.967066 | 136 | 0.622797 |
RoboEagles4828/offseason2023/rio/physics.py |
import wpilib
import wpilib.simulation
import ctre
from pyfrc.physics import drivetrains
from pyfrc.physics.core import PhysicsInterface
from sim.talonFxSim import TalonFxSim
from sim.cancoderSim import CancoderSim
from hardware_interface.drivetrain import getAxleRadians, getWheelRadians, SwerveModule, AXLE_JOINT_GEAR_RATIO
from hardware_interface.armcontroller import PORTS, TOTAL_INTAKE_REVOLUTIONS
from hardware_interface.joystick import CONTROLLER_PORT
import math
import typing
if typing.TYPE_CHECKING:
from robot import EdnaRobot
# Calculations
axle_radius = 0.05
axle_mass = 0.23739
wheel_radius = 0.0508
wheel_length = 0.0381
wheel_mass = 0.2313
center_axle_moi = 0.5 * pow(axle_radius, 2) * axle_mass
center_side_wheel_moi = (0.25 * pow(wheel_radius, 2) * wheel_mass) + ((1/12) * pow(wheel_length, 2) * wheel_mass)
center_wheel_moi = 0.5 * pow(wheel_radius, 2) * wheel_mass
class PhysicsEngine:
def __init__(self, physics_controller: PhysicsInterface, robot: "EdnaRobot"):
self.physics_controller = physics_controller
self.xbox = wpilib.simulation.XboxControllerSim(CONTROLLER_PORT)
self.roborio = wpilib.simulation.RoboRioSim()
self.battery = wpilib.simulation.BatterySim()
self.roborio.setVInVoltage(self.battery.calculate([0.0]))
self.frontLeftModuleSim = SwerveModuleSim(robot.drive_train.front_left)
self.frontRightModuleSim = SwerveModuleSim(robot.drive_train.front_right)
self.rearLeftModuleSim = SwerveModuleSim(robot.drive_train.rear_left)
self.rearRightModuleSim = SwerveModuleSim(robot.drive_train.rear_right)
self.elevator = TalonFxSim(robot.arm_controller.elevator.motor, 0.0003, 1, False)
# self.intake = TalonFxSim(robot.arm_controller.bottom_gripper_lift.motor, 0.0004, 1, False)
# self.intake.addLimitSwitch("fwd", 0)
# self.intake.addLimitSwitch("rev", TOTAL_INTAKE_REVOLUTIONS * -2 * math.pi)
self.pneumaticHub = wpilib.simulation.REVPHSim(PORTS['HUB'])
self.armRollerBar = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['ARM_ROLLER_BAR'])
self.topGripperSlider = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['TOP_GRIPPER_SLIDER'])
self.topGripper = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['TOP_GRIPPER'])
def update_sim(self, now: float, tm_diff: float) -> None:
# Simulate Swerve Modules
self.frontLeftModuleSim.update(tm_diff)
self.frontRightModuleSim.update(tm_diff)
self.rearLeftModuleSim.update(tm_diff)
self.rearRightModuleSim.update(tm_diff)
# Simulate Arm
self.elevator.update(tm_diff)
# self.intake.update(tm_diff)
# Add Currents into Battery Simulation
self.roborio.setVInVoltage(self.battery.calculate([0.0]))
class SwerveModuleSim():
wheel : TalonFxSim = None
axle : TalonFxSim = None
encoder : CancoderSim = None
def __init__(self, module: "SwerveModule"):
wheelMOI = center_wheel_moi
axleMOI = center_axle_moi + center_side_wheel_moi
self.wheel = TalonFxSim(module.wheel_motor, wheelMOI, 1, False)
self.axle = TalonFxSim(module.axle_motor, axleMOI, AXLE_JOINT_GEAR_RATIO, False)
self.encoder = CancoderSim(module.encoder, module.encoder_offset, True)
# There is a bad feedback loop between controller and the rio code
# It will create oscillations in the simulation when the robot is not being commanded to move
# The issue is from the controller commanding the axle position to stay at the same position when idle
# but if the axle is moving during that time it will constantly overshoot the idle position
def update(self, tm_diff):
self.wheel.update(tm_diff)
self.axle.update(tm_diff)
self.encoder.update(tm_diff, self.axle.getVelocityRadians())
# Useful for debugging the simulation or code
def __str__(self) -> str:
wheelPos = getWheelRadians(self.wheel.talon.getSelectedSensorPosition(), "position")
wheelVel = getWheelRadians(self.wheel.talon.getSelectedSensorVelocity(), "velocity")
stateStr = f"Wheel POS: {wheelPos:5.2f} VEL: {wheelVel:5.2f} "
axlePos = getAxleRadians(self.axle.talon.getSelectedSensorPosition(), "position")
axleVel = getAxleRadians(self.axle.talon.getSelectedSensorVelocity(), "velocity")
stateStr += f"Axle POS: {axlePos:5.2f} VEL: {axleVel:5.2f} "
encoderPos = math.radians(self.encoder.cancoder.getAbsolutePosition())
encoderVel = math.radians(self.encoder.cancoder.getVelocity())
stateStr += f"Encoder POS: {encoderPos:5.2f} VEL: {encoderVel:5.2f}"
return stateStr | 4,791 | Python | 43.785046 | 116 | 0.707577 |
RoboEagles4828/offseason2023/rio/README.md | # RIO Code | 10 | Markdown | 9.99999 | 10 | 0.7 |
RoboEagles4828/offseason2023/rio/dds/dds.py | import rticonnextdds_connector as rti
import logging
# Subscribe to DDS topics
class DDS_Subscriber:
def __init__(self, xml_path, participant_name, reader_name):
# Connectors are not thread safe, so we need to create a new one for each thread
self.connector = rti.Connector(config_name=participant_name, url=xml_path)
self.input = self.connector.get_input(reader_name)
def read(self) -> dict:
# Take the input data off of queue and read it
try:
self.input.take()
except rti.Error as e:
logging.warn("RTI Read Error", e.args)
# Return the first valid data sample
data = None
for sample in self.input.samples.valid_data_iter:
data = sample.get_dictionary()
break
return data
def close(self):
self.connector.close()
# Publish to DDS topics
class DDS_Publisher:
def __init__(self, xml_path, participant_name, writer_name):
self.connector = rti.Connector(config_name=participant_name, url=xml_path)
self.output = self.connector.get_output(writer_name)
def write(self, data) -> None:
if data:
self.output.instance.set_dictionary(data)
try:
self.output.write()
except rti.Error as e:
logging.warn("RTI Write Error", e.args)
# else:
# logging.warn("No data to write")
def close(self):
self.connector.close() | 1,491 | Python | 31.434782 | 88 | 0.608987 |
RoboEagles4828/offseason2023/rio/sim/cancoderSim.py | from ctre.sensors import CANCoder, CANCoderSimCollection
import math
CANCODER_TICKS_PER_REV = 4096
class CancoderSim():
def __init__(self, cancoder : CANCoder, offsetDegress : float = 0.0, sensorPhase: bool = False):
self.cancoder : CANCoder = cancoder
self.cancoderSim : CANCoderSimCollection = self.cancoder.getSimCollection()
self.cancoderSim.setRawPosition(self.radiansToEncoderTicks(0, "position"))
self.offset = math.radians(offsetDegress)
self.sensorPhase = -1 if sensorPhase else 1
self.velocity = 0.0
self.position = 0.0
def update(self, period : float, velocityRadians : float):
self.position = velocityRadians * period * self.sensorPhase
self.velocity = velocityRadians * self.sensorPhase
# Update the encoder sensors on the motor
self.cancoderSim = self.cancoder.getSimCollection()
self.cancoderSim.addPosition(self.radiansToEncoderTicks(self.position, "position"))
self.cancoderSim.setVelocity(self.radiansToEncoderTicks(self.velocity, "velocity"))
def radiansToEncoderTicks(self, radians : float, displacementType : str) -> int:
ticks = radians * CANCODER_TICKS_PER_REV / (2 * math.pi)
if displacementType == "position":
return int(ticks)
else:
return int(ticks / 10) | 1,367 | Python | 43.129031 | 100 | 0.67959 |
RoboEagles4828/offseason2023/rio/sim/talonFxSim.py | from ctre import TalonFX, TalonFXSimCollection
from wpilib import RobotController
import random
import math
from pyfrc.physics.motor_cfgs import MOTOR_CFG_FALCON_500
import wpilib.simulation
import wpimath.system.plant
FALCON_SENSOR_TICKS_PER_REV = 2048
class TalonFxSim:
def __init__(self, talonFx : TalonFX, moi : float, gearRatio : float, sensorPhase : bool ) -> None:
self.talon : TalonFX = talonFx
self.talonSim : TalonFXSimCollection = None
self.moi = moi
self.gearRatio = gearRatio
self.sensorPhase = -1 if sensorPhase else 1
self.gearbox = wpimath.system.plant.DCMotor.falcon500(1)
self.motor = wpilib.simulation.DCMotorSim(self.gearbox, self.gearRatio, self.moi, [0.0, 0.0])
self.velocity = 0.0
self.position = 0.0
self.fwdLimitEnabled = False
self.fwdLimit = 0.0
self.revLimitEnabled = False
self.revLimit = 0.0
# Simulates the movement of falcon 500 motors by getting the voltages from the
# the motor model that is being controlled by the robot code.
def update(self, period : float):
self.talonSim = self.talon.getSimCollection()
# Update the motor model
voltage = self.talonSim.getMotorOutputLeadVoltage() * self.sensorPhase
self.motor.setInputVoltage(voltage)
self.motor.update(period)
newPosition = self.motor.getAngularPosition()
self.deltaPosition = newPosition - self.position
self.position = newPosition
self.velocity = self.motor.getAngularVelocity()
if self.fwdLimitEnabled and self.position >= self.fwdLimit:
self.talonSim.setLimitFwd(True)
self.position = self.fwdLimit
else:
self.talonSim.setLimitFwd(False)
if self.revLimitEnabled and self.position <= self.revLimit:
self.talonSim.setLimitRev(True)
self.position = self.revLimit
else:
self.talonSim.setLimitRev(False)
# Update the encoder sensors on the motor
positionShaftTicks = int(self.radiansToSensorTicks(self.position * self.gearRatio, "position"))
velocityShaftTicks = int(self.radiansToSensorTicks(self.velocity * self.gearRatio, "velocity"))
self.talonSim.setIntegratedSensorRawPosition(positionShaftTicks)
self.talonSim.setIntegratedSensorVelocity(velocityShaftTicks)
# Update the current and voltage
self.talonSim.setSupplyCurrent(self.motor.getCurrentDraw())
self.talonSim.setBusVoltage(RobotController.getBatteryVoltage())
def radiansToSensorTicks(self, radians : float, displacementType : str) -> int:
ticks = radians * FALCON_SENSOR_TICKS_PER_REV / (2 * math.pi)
if displacementType == "position":
return ticks
else:
return ticks / 10
def getPositionRadians(self) -> float:
return self.position
def getVelocityRadians(self) -> float:
return self.velocity
def getSupplyCurrent(self) -> float:
return self.motor.getCurrentDraw()
def addLimitSwitch(self, limitType: str, positionRadians: float):
if limitType == "fwd":
self.fwdLimitEnabled = True
self.fwdLimit = positionRadians
elif limitType == "rev":
self.revLimitEnabled = True
self.revLimit = positionRadians
else:
print("Invalid limit type") | 3,473 | Python | 38.033707 | 103 | 0.663403 |
RoboEagles4828/offseason2023/rio/hardware_interface/armcontroller.py | import wpilib
import wpilib.simulation
import ctre
import ctre.sensors
import time
import logging
import math
NAMESPACE = 'real'
CMD_TIMEOUT_SECONDS = 1
MOTOR_TIMEOUT = 30 # 0 means do not use the timeout
TICKS_PER_REVOLUTION = 2048.0
TOTAL_ELEVATOR_REVOLUTIONS = 164
TOTAL_INTAKE_REVOLUTIONS = 6
SCALING_FACTOR_FIX = 10000
# Port Numbers for all of the Solenoids and other connected things
# The numbers below will **need** to be changed to fit the robot wiring
PORTS = {
# Modules
'HUB': 18,
# Pistons
'ARM_ROLLER_BAR': [14, 15],
'TOP_GRIPPER_SLIDER': [10, 11],
'TOP_GRIPPER': [12, 13],
# Wheels
'ELEVATOR': 13,
# 'BOTTOM_GRIPPER_LIFT': 14
}
MOTOR_PID_CONFIG = {
'SLOT': 2,
'MAX_SPEED': 18000, # Ticks/100ms
'TARGET_ACCELERATION': 14000, # Ticks/100ms
"kP": 0.2,
"kI": 0.0,
"kD": 0.1,
"kF": 0.2,
}
JOINT_LIST = [
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'elevator_center_joint',
]
def getJointList():
return JOINT_LIST
class ArmController():
def __init__(self):
self.last_cmds_time = time.time()
self.warn_timeout = True
self.hub = wpilib.PneumaticHub(PORTS['HUB'])
self.compressor = self.hub.makeCompressor()
self.arm_roller_bar = Piston(self.hub, PORTS['ARM_ROLLER_BAR'], max=0.07, name="Arm Roller Bar")
self.top_gripper_slider = Piston(self.hub, PORTS['TOP_GRIPPER_SLIDER'], max=0.30, name="Top Gripper Slider")
self.top_gripper = Piston(self.hub, PORTS['TOP_GRIPPER'], min=0.0, max=-0.9, name="Top Gripper", reverse=True)
self.elevator = Elevator(PORTS['ELEVATOR'], max=0.56)
self.JOINT_MAP = {
# Pneumatics
'arm_roller_bar_joint': self.arm_roller_bar,
'top_slider_joint': self.top_gripper_slider,
'top_gripper_left_arm_joint': self.top_gripper,
# Wheels
'elevator_center_joint': self.elevator,
}
def getEncoderData(self):
names = [""]*4
positions = [0]*4
velocities = [0]*4
# Iterate over the JOINT_MAP and run the get() function for each of them
for index, joint_name in enumerate(self.JOINT_MAP):
names[index] = joint_name
# Allow for joints to be removed quickly
positions[index] = int(self.JOINT_MAP[joint_name].getPosition() * SCALING_FACTOR_FIX)
velocities[index] = int(self.JOINT_MAP[joint_name].getVelocity() * SCALING_FACTOR_FIX)
return { "name" : names, "position": positions, "velocity": velocities}
def stop(self):
for joint in self.JOINT_MAP.values():
joint.stop()
def sendCommands(self, commands):
if commands:
self.last_cmds_time = time.time()
self.warn_timeout = True
for i in range(len(commands["name"])):
joint_name = commands["name"][i]
if joint_name in self.JOINT_MAP:
self.JOINT_MAP[joint_name].setPosition(commands['position'][i])
elif (time.time() - self.last_cmds_time > CMD_TIMEOUT_SECONDS):
self.stop()
if self.warn_timeout:
logging.warning(f"Didn't recieve any commands for {CMD_TIMEOUT_SECONDS} second(s). Halting...")
self.warn_timeout = False
class Piston():
def __init__(self, hub : wpilib.PneumaticHub, ports : list[int], min : float = 0.0, max : float = 1.0, reverse : bool = False, name : str = "Piston"):
self.solenoid = hub.makeDoubleSolenoid(ports[0], ports[1])
self.state = self.solenoid.get() != wpilib.DoubleSolenoid.Value.kForward
self.min = min
self.max = max
self.reverse = reverse
self.name = name
self.lastCommand = None
def getPosition(self):
return float(self.state) * (self.max - self.min) + self.min
# The Solenoids don't have a velocity value, so we set it to zero here
def getVelocity(self):
return 0.0
def stop(self):
self.solenoid.set(wpilib.DoubleSolenoid.Value.kOff)
def setPosition(self, position : float):
if position != self.lastCommand:
logging.info(f"{self.name} Position: {position}")
self.lastCommand = position
center = abs((self.max - self.min) / 2 + self.min)
forward = wpilib.DoubleSolenoid.Value.kForward
reverse = wpilib.DoubleSolenoid.Value.kReverse
if abs(position) >= center and self.state == 0:
logging.info(f"{self.name} first block")
self.solenoid.set(reverse if self.reverse else forward)
self.state = 1
elif abs(position) < center and self.state == 1:
logging.info(f"{self.name} first block")
self.solenoid.set(forward if self.reverse else reverse)
self.state = 0
def commonTalonSetup(talon : ctre.WPI_TalonFX):
talon.configFactoryDefault(MOTOR_TIMEOUT)
talon.configNeutralDeadband(0.01, MOTOR_TIMEOUT)
# Voltage
talon.configVoltageCompSaturation(12, MOTOR_TIMEOUT)
talon.enableVoltageCompensation(True)
# Sensor
talon.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, 0, MOTOR_TIMEOUT)
talon.configIntegratedSensorInitializationStrategy(ctre.sensors.SensorInitializationStrategy.BootToZero)
# PID
talon.selectProfileSlot(MOTOR_PID_CONFIG['SLOT'], 0)
talon.config_kP(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kP'], MOTOR_TIMEOUT)
talon.config_kI(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kI'], MOTOR_TIMEOUT)
talon.config_kD(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kD'], MOTOR_TIMEOUT)
talon.config_kD(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kF'], MOTOR_TIMEOUT)
# Nominal and Peak
talon.configNominalOutputForward(0, MOTOR_TIMEOUT)
talon.configNominalOutputReverse(0, MOTOR_TIMEOUT)
talon.configPeakOutputForward(1, MOTOR_TIMEOUT)
talon.configPeakOutputReverse(-1, MOTOR_TIMEOUT)
return
class Intake():
def __init__(self, port : int, min : float = 0.0, max : float = 1.0):
self.motor = ctre.WPI_TalonFX(port, "rio")
commonTalonSetup(self.motor)
self.state = 0
self.min = min
self.max = max
self.totalTicks = TICKS_PER_REVOLUTION * TOTAL_INTAKE_REVOLUTIONS
self.lastCommand = None
# Phase
self.motor.setSensorPhase(False)
self.motor.setInverted(False)
# Frames
self.motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, MOTOR_TIMEOUT)
# Brake
self.motor.setNeutralMode(ctre.NeutralMode.Brake)
def getPosition(self):
percent = self.motor.getSelectedSensorPosition() / self.totalTicks
return percent * (self.max - self.min) + self.min
def getVelocity(self):
percent = self.motor.getSelectedSensorVelocity() * 10 / self.totalTicks
return percent * (self.max - self.min) + self.min
def stop(self):
self.motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
def setPosition(self, position : float):
if position != self.lastCommand:
logging.info(f"Intake Position: {position}")
self.lastCommand = position
# Moves the intake
center = (self.max - self.min) / 2 + self.min
if position >= center and self.state == 0:
self.motor.set(ctre.TalonFXControlMode.Velocity, -TICKS_PER_REVOLUTION/2)
self.state = 1
elif position < center and self.state == 1:
self.motor.set(ctre.TalonFXControlMode.Velocity, TICKS_PER_REVOLUTION/2)
self.state = 0
if self.state == 0 and not self.motor.isFwdLimitSwitchClosed():
self.motor.set(ctre.TalonFXControlMode.Velocity, TICKS_PER_REVOLUTION/2)
elif self.state == 1 and not self.motor.isRevLimitSwitchClosed():
self.motor.set(ctre.TalonFXControlMode.Velocity, -TICKS_PER_REVOLUTION/2)
class Elevator():
def __init__(self, port : int, min : float = 0.0, max : float = 1.0):
self.motor = ctre.WPI_TalonFX(port, "rio")
commonTalonSetup(self.motor)
self.min = min
self.max = max
self.totalTicks = TICKS_PER_REVOLUTION * TOTAL_ELEVATOR_REVOLUTIONS
self.lastCommand = None
# Phase
self.motor.setSensorPhase(False)
self.motor.setInverted(False)
# Frames
self.motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, MOTOR_TIMEOUT)
# Motion Magic
self.motor.configMotionCruiseVelocity(MOTOR_PID_CONFIG['MAX_SPEED'], MOTOR_TIMEOUT) # Sets the maximum speed of motion magic (ticks/100ms)
self.motor.configMotionAcceleration(MOTOR_PID_CONFIG['TARGET_ACCELERATION'], MOTOR_TIMEOUT) # Sets the maximum acceleration of motion magic (ticks/100ms)
# self.motor.configClearPositionOnLimitR(True)
def getPosition(self) -> float:
percent = self.motor.getSelectedSensorPosition() / self.totalTicks
return percent * (self.max - self.min) + self.min
def getVelocity(self) -> float:
percent = (self.motor.getSelectedSensorVelocity() * 10) / self.totalTicks
return percent * (self.max - self.min) + self.min
def stop(self):
self.motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
def setPosition(self, position : float):
if position != self.lastCommand:
logging.info(f"Elevator Position: {position}")
self.lastCommand = position
percent = (position - self.min) / (self.max - self.min)
self.motor.set(ctre.TalonFXControlMode.MotionMagic, percent * self.totalTicks) | 9,753 | Python | 38.016 | 161 | 0.63724 |
RoboEagles4828/offseason2023/rio/hardware_interface/joystick.py | import wpilib
import logging
CONTROLLER_PORT = 0
SCALING_FACTOR_FIX = 10000
ENABLE_THROTTLE = True
pov_x_map = {
-1: 0.0,
0: 0.0,
45: -1.0,
90: -1.0,
135: -1.0,
180: 0.0,
225: 1.0,
270: 1.0,
315: 1.0,
}
pov_y_map = {
-1: 0.0,
0: 1.0,
45: 1.0,
90: 0.0,
135: -1.0,
180: -1.0,
225: -1.0,
270: 0.0,
315: 1.0,
}
class Joystick:
def __init__(self):
self.joystick = wpilib.XboxController(CONTROLLER_PORT)
self.deadzone = 0.15
self.last_joystick_data = self.getEmptyData()
self.count = 0
def scaleAxis(self, axis):
return int(axis * SCALING_FACTOR_FIX * -1)
def scaleTrigger(self, trigger):
return int(trigger * SCALING_FACTOR_FIX * -1)
def getEmptyData(self):
return {
"axes": [0.0] * 8,
"buttons": [0] * 11,
}
def getData(self):
pov = self.joystick.getPOV(0)
leftX = self.joystick.getLeftX()
leftY = self.joystick.getLeftY()
rightX = self.joystick.getRightX()
rightY = self.joystick.getRightY()
leftTrigger = self.joystick.getLeftTriggerAxis()
rightTrigger = self.joystick.getRightTriggerAxis()
axes = [
self.scaleAxis(leftX) if abs(leftX) > self.deadzone else 0.0,
self.scaleAxis(leftY) if abs(leftY) > self.deadzone else 0.0,
self.scaleTrigger(leftTrigger),
self.scaleAxis(rightX) if abs(rightX) > self.deadzone else 0.0,
self.scaleAxis(rightY) if abs(rightY) > self.deadzone else 0.0,
self.scaleTrigger(rightTrigger),
pov_x_map[pov], # left 1.0 right -1.0
pov_y_map[pov], # up 1.0 down -1.0
]
buttons = [
int(self.joystick.getAButton()),
int(self.joystick.getBButton()),
int(self.joystick.getXButton()),
int(self.joystick.getYButton()),
int(self.joystick.getLeftBumper()),
int(self.joystick.getRightBumper()),
int(self.joystick.getBackButton()),
int(self.joystick.getStartButton()),
0,
int(self.joystick.getLeftStickButton()),
int(self.joystick.getRightStickButton())
]
data = {"axes": axes, "buttons": buttons}
if ENABLE_THROTTLE:
if self.is_equal(data, self.last_joystick_data):
self.count += 1
if self.count >= 10:
return None
else:
self.count = 0
self.last_joystick_data = data
return data
else:
return data
def is_equal(self, d, d1):
res = all((d1.get(k) == v for k, v in d.items()))
return res
| 2,835 | Python | 25.504673 | 75 | 0.522751 |
RoboEagles4828/offseason2023/rio/hardware_interface/drivetrain.py | import wpilib
import ctre
import ctre.sensors
import math
import time
import logging
from wpimath.filter import SlewRateLimiter
NAMESPACE = 'real'
# Small Gear Should Face the back of the robot
# All wheel drive motors should not be inverted
# All axle turn motors should be inverted + sensor phase
# All Cancoders should be direction false
MODULE_CONFIG = {
"front_left": {
"wheel_joint_name": "front_left_wheel_joint",
"wheel_motor_port": 3, #9
"axle_joint_name": "front_left_axle_joint",
"axle_motor_port": 1, #7
"axle_encoder_port": 2, #8
"encoder_offset": 18.984 # 248.203,
},
"front_right": {
"wheel_joint_name": "front_right_wheel_joint",
"wheel_motor_port": 6, #12
"axle_joint_name": "front_right_axle_joint",
"axle_motor_port": 4, #10
"axle_encoder_port": 5, #11
"encoder_offset": 145.723 #15.908,
},
"rear_left": {
"wheel_joint_name": "rear_left_wheel_joint",
"wheel_motor_port": 12, #6
"axle_joint_name": "rear_left_axle_joint",
"axle_motor_port": 10, #4
"axle_encoder_port": 11, #5
"encoder_offset": 194.678 #327.393,
},
"rear_right": {
"wheel_joint_name": "rear_right_wheel_joint",
"wheel_motor_port": 9, #3
"axle_joint_name": "rear_right_axle_joint",
"axle_motor_port": 7, #1
"axle_encoder_port": 8, #2
"encoder_offset": 69.785 #201.094,
}
}
def getJointList():
joint_list = []
for module in MODULE_CONFIG.values():
joint_list.append(module['wheel_joint_name'])
joint_list.append(module['axle_joint_name'])
return joint_list
AXLE_DIRECTION = False
WHEEL_DIRECTION = False
ENCODER_DIRECTION = True
WHEEL_JOINT_GEAR_RATIO = 6.75 #8.14
AXLE_JOINT_GEAR_RATIO = 150.0/7.0
TICKS_PER_REV = 2048.0
CMD_TIMEOUT_SECONDS = 1
nominal_voltage = 9.0
steer_current_limit = 20.0
# This is needed to fix bad float values being published by RTI from the RIO.
# To fix this, we scale the float and convert to integers.
# Then we scale it back down inside the ROS2 hardware interface.
SCALING_FACTOR_FIX = 10000
# Encoder Constants
encoder_ticks_per_rev = 4096.0
encoder_reset_velocity = math.radians(0.5)
encoder_reset_iterations = 500
axle_pid_constants = {
"kP": 0.2,
"kI": 0.0,
"kD": 0.1,
"kF": 0.2,
"kIzone": 0,
"kPeakOutput": 1.0
}
wheel_pid_constants = {
"kF": 1023.0/20660.0,
"kP": 0.1,
"kI": 0.001,
"kD": 5
}
slot_idx = 0
pid_loop_idx = 0
timeout_ms = 30
velocityConstant = 0.5
accelerationConstant = 0.25
# Conversion Functions
positionCoefficient = 2.0 * math.pi / TICKS_PER_REV / AXLE_JOINT_GEAR_RATIO
velocityCoefficient = positionCoefficient * 10.0
# axle (radians) -> shaft (ticks)
def getShaftTicks(radians, displacementType) -> int:
if displacementType == "position":
return int(radians / positionCoefficient)
elif displacementType == "velocity":
return int(radians / velocityCoefficient)
else:
return 0
# shaft (ticks) -> axle (radians)
def getAxleRadians(ticks, displacementType):
if displacementType == "position":
return ticks * positionCoefficient
elif displacementType == "velocity":
return ticks * velocityCoefficient
else:
return 0
wheelPositionCoefficient = 2.0 * math.pi / TICKS_PER_REV / WHEEL_JOINT_GEAR_RATIO
wheelVelocityCoefficient = wheelPositionCoefficient * 10.0
# wheel (radians) -> shaft (ticks)
def getWheelShaftTicks(radians, displacementType) -> int:
if displacementType == "position":
return int(radians / wheelPositionCoefficient)
elif displacementType == "velocity":
return int(radians / wheelVelocityCoefficient)
else:
return 0
# shaft (ticks) -> wheel (radians)
def getWheelRadians(ticks, displacementType):
if displacementType == "position":
return ticks * wheelPositionCoefficient
elif displacementType == "velocity":
return ticks * wheelVelocityCoefficient
else:
return 0
class SwerveModule():
def __init__(self, module_config) -> None:
#IMPORTANT:
# The wheel joint is the motor that drives the wheel.
# The axle joint is the motor that steers the wheel.
self.wheel_joint_name = module_config["wheel_joint_name"]
self.axle_joint_name = module_config["axle_joint_name"]
self.wheel_joint_port = module_config["wheel_motor_port"]
self.axle_joint_port = module_config["axle_motor_port"]
self.axle_encoder_port = module_config["axle_encoder_port"]
self.encoder_offset = module_config["encoder_offset"]
self.wheel_motor = ctre.WPI_TalonFX(self.wheel_joint_port, "rio")
self.axle_motor = ctre.WPI_TalonFX(self.axle_joint_port, "rio")
self.encoder = ctre.sensors.WPI_CANCoder(self.axle_encoder_port, "rio")
self.last_wheel_vel_cmd = None
self.last_axle_vel_cmd = None
self.reset_iterations = 0
self.setupEncoder()
self.setupWheelMotor()
self.setupAxleMotor()
def setupEncoder(self):
self.encoderconfig = ctre.sensors.CANCoderConfiguration()
self.encoderconfig.absoluteSensorRange = ctre.sensors.AbsoluteSensorRange.Unsigned_0_to_360
self.encoderconfig.initializationStrategy = ctre.sensors.SensorInitializationStrategy.BootToAbsolutePosition
self.encoderconfig.sensorDirection = ENCODER_DIRECTION
self.encoder.configAllSettings(self.encoderconfig)
self.encoder.setPositionToAbsolute(timeout_ms)
self.encoder.setStatusFramePeriod(ctre.sensors.CANCoderStatusFrame.SensorData, 10, timeout_ms)
def getEncoderPosition(self):
return math.radians(self.encoder.getAbsolutePosition() - self.encoder_offset)
def getEncoderVelocity(self):
return math.radians(self.encoder.getVelocity())
def setupWheelMotor(self):
self.wheel_motor.configFactoryDefault()
self.wheel_motor.configNeutralDeadband(0.01, timeout_ms)
# Direction and Sensors
self.wheel_motor.setSensorPhase(WHEEL_DIRECTION)
self.wheel_motor.setInverted(WHEEL_DIRECTION)
self.wheel_motor.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, slot_idx, timeout_ms)
self.wheel_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_21_FeedbackIntegrated, 10, timeout_ms)
# Peak and Nominal Outputs
self.wheel_motor.configNominalOutputForward(0, timeout_ms)
self.wheel_motor.configNominalOutputReverse(0, timeout_ms)
self.wheel_motor.configPeakOutputForward(1, timeout_ms)
self.wheel_motor.configPeakOutputReverse(-1, timeout_ms)
# Voltage Comp
self.wheel_motor.configVoltageCompSaturation(nominal_voltage, timeout_ms)
self.axle_motor.enableVoltageCompensation(True)
# Tuning
self.wheel_motor.config_kF(0, wheel_pid_constants["kF"], timeout_ms)
self.wheel_motor.config_kP(0, wheel_pid_constants["kP"], timeout_ms)
self.wheel_motor.config_kI(0, wheel_pid_constants["kI"], timeout_ms)
self.wheel_motor.config_kD(0, wheel_pid_constants["kD"], timeout_ms)
# Brake
self.wheel_motor.setNeutralMode(ctre.NeutralMode.Brake)
# Velocity Ramp
# TODO: Tweak this value
self.wheel_motor.configClosedloopRamp(0.1)
# Current Limit
current_limit = 20
current_threshold = 40
current_threshold_time = 0.1
supply_current_limit_configs = ctre.SupplyCurrentLimitConfiguration(True, current_limit, current_threshold, current_threshold_time)
self.wheel_motor.configSupplyCurrentLimit(supply_current_limit_configs, timeout_ms)
def setupAxleMotor(self):
self.axle_motor.configFactoryDefault()
self.axle_motor.configNeutralDeadband(0.01, timeout_ms)
# Direction and Sensors
self.axle_motor.setSensorPhase(AXLE_DIRECTION)
self.axle_motor.setInverted(AXLE_DIRECTION)
self.axle_motor.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, slot_idx, timeout_ms)
# self.axle_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, timeout_ms)
self.axle_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, timeout_ms)
self.axle_motor.setSelectedSensorPosition(getShaftTicks(self.getEncoderPosition(), "position"), pid_loop_idx, timeout_ms)
# Peak and Nominal Outputs
self.axle_motor.configNominalOutputForward(0, timeout_ms)
self.axle_motor.configNominalOutputReverse(0, timeout_ms)
self.axle_motor.configPeakOutputForward(1, timeout_ms)
self.axle_motor.configPeakOutputReverse(-1, timeout_ms)
# Tuning
self.axle_motor.selectProfileSlot(slot_idx, pid_loop_idx)
self.axle_motor.config_kP(slot_idx, axle_pid_constants["kP"], timeout_ms)
self.axle_motor.config_kI(slot_idx, axle_pid_constants["kI"], timeout_ms)
self.axle_motor.config_kD(slot_idx, axle_pid_constants["kD"], timeout_ms)
self.axle_motor.config_kF(slot_idx, (1023.0 * velocityCoefficient / nominal_voltage) * velocityConstant, timeout_ms)
self.axle_motor.configMotionCruiseVelocity(2.0 / velocityConstant / velocityCoefficient, timeout_ms)
self.axle_motor.configMotionAcceleration((8.0 - 2.0) / accelerationConstant / velocityCoefficient, timeout_ms)
self.axle_motor.configMotionSCurveStrength(2)
# Voltage Comp
self.axle_motor.configVoltageCompSaturation(nominal_voltage, timeout_ms)
self.axle_motor.enableVoltageCompensation(True)
# Braking
self.axle_motor.setNeutralMode(ctre.NeutralMode.Brake)
def neutralize_module(self):
self.wheel_motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
self.axle_motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
def set(self, wheel_motor_vel, axle_position):
wheel_vel = getWheelShaftTicks(wheel_motor_vel, "velocity")
if abs(wheel_motor_vel) < 0.2:
self.neutralize_module()
return
else:
self.wheel_motor.set(ctre.TalonFXControlMode.Velocity, wheel_vel)
self.last_wheel_vel_cmd = wheel_vel
# MOTION MAGIC CONTROL FOR AXLE POSITION
axle_motorPosition = getAxleRadians(self.axle_motor.getSelectedSensorPosition(), "position")
axle_motorVelocity = getAxleRadians(self.axle_motor.getSelectedSensorVelocity(), "velocity")
axle_absolutePosition = self.getEncoderPosition()
# Reset
if axle_motorVelocity < encoder_reset_velocity:
self.reset_iterations += 1
if self.reset_iterations >= encoder_reset_iterations:
self.reset_iterations = 0
self.axle_motor.setSelectedSensorPosition(getShaftTicks(axle_absolutePosition, "position"))
axle_motorPosition = axle_absolutePosition
else:
self.reset_iterations = 0
# First let's assume that we will move directly to the target position.
newAxlePosition = axle_position
# The motor could get to the target position by moving clockwise or counterclockwise.
# The shortest path should be the direction that is less than pi radians away from the current motor position.
# The shortest path could loop around the circle and be less than 0 or greater than 2pi.
# We need to get the absolute current position to determine if we need to loop around the 0 - 2pi range.
# The current motor position does not stay inside the 0 - 2pi range.
# We need the absolute position to compare with the target position.
axle_absoluteMotorPosition = math.fmod(axle_motorPosition, 2.0 * math.pi)
if axle_absoluteMotorPosition < 0.0:
axle_absoluteMotorPosition += 2.0 * math.pi
# If the target position was in the first quadrant area
# and absolute motor position was in the last quadrant area
# then we need to move into the next loop around the circle.
if newAxlePosition - axle_absoluteMotorPosition < -math.pi:
newAxlePosition += 2.0 * math.pi
# If the target position was in the last quadrant area
# and absolute motor position was in the first quadrant area
# then we need to move into the previous loop around the circle.
elif newAxlePosition - axle_absoluteMotorPosition > math.pi:
newAxlePosition -= 2.0 * math.pi
# Last, add the current existing loops that the motor has gone through.
newAxlePosition += axle_motorPosition - axle_absoluteMotorPosition
self.axle_motor.set(ctre.TalonFXControlMode.MotionMagic, getShaftTicks(newAxlePosition, "position"))
# logging.info('AXLE MOTOR POS: ', newAxlePosition)
# logging.info('WHEEL MOTOR VEL: ', wheel_vel)
def stop(self):
self.wheel_motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
self.axle_motor.set(ctre.TalonFXControlMode.PercentOutput, 0)
def getEncoderData(self):
output = [
{
"name": self.wheel_joint_name,
"position": int(getWheelRadians(self.wheel_motor.getSelectedSensorPosition(), "position") * SCALING_FACTOR_FIX),
"velocity": int(getWheelRadians(self.wheel_motor.getSelectedSensorVelocity(), "velocity") * SCALING_FACTOR_FIX)
},
{
"name": self.axle_joint_name,
"position": int(self.getEncoderPosition() * SCALING_FACTOR_FIX),
"velocity": int(self.getEncoderVelocity() * SCALING_FACTOR_FIX)
}
]
return output
class DriveTrain():
def __init__(self):
self.last_cmds = { "name" : getJointList(), "position": [0.0]*len(getJointList()), "velocity": [0.0]*len(getJointList()) }
self.last_cmds_time = time.time()
self.warn_timeout = True
self.front_left = SwerveModule(MODULE_CONFIG["front_left"])
self.front_right = SwerveModule(MODULE_CONFIG["front_right"])
self.rear_left = SwerveModule(MODULE_CONFIG["rear_left"])
self.rear_right = SwerveModule(MODULE_CONFIG["rear_right"])
self.module_lookup = \
{
'front_left_axle_joint': self.front_left,
'front_right_axle_joint': self.front_right,
'rear_left_axle_joint': self.rear_left,
'rear_right_axle_joint': self.rear_right,
}
def getEncoderData(self):
names = [""]*8
positions = [0]*8
velocities = [0]*8
encoderInfo = []
encoderInfo += self.front_left.getEncoderData()
encoderInfo += self.front_right.getEncoderData()
encoderInfo += self.rear_left.getEncoderData()
encoderInfo += self.rear_right.getEncoderData()
assert len(encoderInfo) == 8
for index, encoder in enumerate(encoderInfo):
names[index] = encoder['name']
positions[index] = encoder['position']
velocities[index] = encoder['velocity']
return { "name": names, "position": positions, "velocity": velocities }
def stop(self):
self.front_left.stop()
self.front_right.stop()
self.rear_left.stop()
self.rear_right.stop()
def sendCommands(self, commands):
if commands:
self.last_cmds = commands
self.last_cmds_time = time.time()
self.warn_timeout = True
for i in range(len(commands['name'])):
if 'axle' in commands['name'][i]:
axle_name = commands['name'][i]
axle_position = commands['position'][i] if len(commands['position']) > i else 0.0
wheel_name = axle_name.replace('axle', 'wheel')
wheel_index = commands['name'].index(wheel_name)
wheel_velocity = commands['velocity'][wheel_index] if len(commands['velocity']) > wheel_index else 0.0
module = self.module_lookup[axle_name]
module.set(wheel_velocity, axle_position)
if axle_name == "front_left_axle_joint":
# logging.info(f"{wheel_name}: {wheel_velocity}\n{axle_name}: {axle_position}")
pass
else:
current_time = time.time()
if current_time - self.last_cmds_time > CMD_TIMEOUT_SECONDS:
self.stop()
# Display Warning Once
if self.warn_timeout:
logging.warning("CMD TIMEOUT: HALTING")
self.warn_timeout = False
| 16,813 | Python | 40.413793 | 139 | 0.650984 |
RoboEagles4828/offseason2023/rio/POC/pneumatics_test/robot.py | import wpilib
# does not work yet
class MyRobot(wpilib.TimedRobot):
def robotInit(self):
print("Initalizing")
# make rev hub object
self.hub = wpilib.PneumaticHub(1)
# make single solenoid objects (pass in channel as parameter)
self.solenoids = [self.hub.makeSolenoid(0), self.hub.makeSolenoid(1)]
# make double solenoid objects (pass in forward channel and reverse channel as parameters)
self.double_solenoids = [self.hub.makeDoubleSolenoid(2, 3), self.hub.makeDoubleSolenoid(4, 5)]
# make compressor
self.compressor = self.hub.makeCompressor(1)
self.timer = wpilib.Timer
self.input = wpilib.Joystick(0)
def teleopInit(self):
print("Starting Compressor")
self.compressor.enableDigital()
for solenoid in self.double_solenoids:
solenoid.set(wpilib.DoubleSolenoid.Value.kOff)
def teleopPeriodic(self):
if self.input.getRawButtonPressed(5): # LB (Xbox)
print("Toggling First...")
for solenoid in self.double_solenoids:
solenoid.toggle()
if self.input.getRawButtonPressed(6): # RB (Xbox)
print("Toggling Second...")
for solenoid in self.double_solenoids:
solenoid.toggle()
def teleopExit(self):
print("Turning off compressor...")
self.compressor.disable()
if __name__ == "__main__":
wpilib.run(MyRobot) | 1,469 | Python | 29.624999 | 102 | 0.628319 |
RoboEagles4828/offseason2023/rio/POC/motion_magic_poc/MotionProfile.py | import argparse
import logging
import math
from collections import deque
import copy
import matplotlib.pyplot as plt
logger = logging.getLogger(f"{__name__}")
#Constants
VPROG = 4.00
T1 = 400
T2 = 200
ITP = 10
if __name__ == '__main__':
# Instantiate the parser
parser = argparse.ArgumentParser(description='Talon SRX motion profiler')
# Required Positional Arguments
parser.add_argument('-d', '--distance', type=str, required=True,
help="Distance to move")
parser.add_argument('-l', "--loglevel", type=str,
default='INFO', help="logging level")
parser.add_argument('-v', '--max_vel', type=str, help="max velocity", default="4.0")
parser.add_argument('-a', '--max_accel', type=str, help="max_acclereation", default="10.0")
args = parser.parse_args()
# Setup logger
numeric_level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f"Invalid log level: {args.loglevel}")
logging.basicConfig(format='%(asctime)s-%(levelname)s-%(message)s',
datefmt='%H:%M:%S', level=numeric_level)
VPROG = float(args.max_vel)
max_accel = float(args.max_accel)
if max_accel != 0.0:
T1 = VPROG/max_accel * 1000
# Calculation constants
dist = float(args.distance)
t4 = (dist/VPROG) * 1000
fl1 = float(math.trunc(T1 / ITP))
fl2 = math.trunc(T2 / ITP)
N = float(t4 / ITP)
step = 1
time = 0.0
velocity = 0.0
input = False
runningSum = deque(fl2*[0.0], fl2)
trajectory = list()
trajectory.append({"step": step, "time": time, "velocity": velocity})
runningSum.append(0.0)
zeropt = list()
# Now we print out the trajectory
fs1 = 0.0
exit = False
while not exit:
step += 1
time = ((step - 1) * ITP)/1000
input = 1 if step < (N+2) else 0
addition = (1/fl1) if input==1 else (-1/fl1)
fs1 = max(0, min(1, fs1 + addition))
# logging.log(numeric_level, f"fs1 = {fs1}")
fs2 = sum(runningSum)
# logging.log(numeric_level, f"fs2 = {fs2}")
runningSum.append(fs1)
if fs1 == 0:
if fs2 == 0:
zeropt.append(1)
else:
zeropt.append(0)
else:
zeropt.append(0)
output_included = 1 if sum(zeropt[0:step]) <= 2 else 0
if output_included == 1:
velocity = ((fs1+fs2)/(1.0/fl2))*VPROG if fs2 != 0 else 0
trajectory.append({"step": step, "time": time, "velocity": velocity})
else:
exit = True
logging.log(numeric_level, "EXITTING")
print(trajectory)
x = list()
y = list()
for i in trajectory:
x.append(i["time"])
y.append(i["velocity"])
plt.plot(x, y)
plt.xlabel("TIME")
plt.ylabel("VELOCITY")
plt.show() | 2,915 | Python | 29.061855 | 95 | 0.568782 |
RoboEagles4828/offseason2023/rio/POC/motion_magic_poc/test.py | import math
# 90 degrees
testVal = math.pi / 4
# go down 180 degrees
modifyVal = math.pi
# Get remainder
result = math.fmod(testVal - modifyVal, 2 * math.pi)
print(result)
# theory
moveDown = modifyVal - testVal
result2 = (2 * math.pi) - moveDown
print(result2)
# Correction for negative values
result += (2 * math.pi)
print(result)
assert result == result2 | 364 | Python | 14.869565 | 52 | 0.708791 |
RoboEagles4828/offseason2023/rio/POC/motion_magic_poc/robot.py | import logging
import wpilib
import ctre
import math
# Ports
motorPort = 7
controllerPort = 0
encoderPort = 8
# PID Constants
pid_constants = {
"kP": 0.2,
"kI": 0.0,
"kD": 0.1,
"kF": 0.2,
"kIzone": 0,
"kPeakOutput": 1.0
}
slot_idx = 0
pid_loop_idx = 0
timeout_ms = 30
# Motor Constants
DRIVE_RATIO = 6.75
STEER_RATIO = 150.0/7.0
motor_ticks_per_rev = 2048.0
nominal_voltage = 12.0
steer_current_limit = 20.0
# Encoder Constants
encoder_ticks_per_rev = 4096.0
encoder_offset = 0
encoder_direction = False
encoder_reset_velocity = math.radians(0.5)
encoder_reset_iterations = 500
# Demo Behavior
# Range: 0 - 2pi
velocityConstant = 1.0
accelerationConstant = 0.5
increment = math.pi / 8
# Conversion Functions
# This is thought of as radians per shaft tick times the ratio to the axle (steer)
positionCoefficient = 2.0 * math.pi / motor_ticks_per_rev / STEER_RATIO
# This is the same conversion with time in mind.
velocityCoefficient = positionCoefficient * 10.0
# axle (radians) -> shaft (ticks)
def getShaftTicks(radians, type):
if type == "position":
return radians / positionCoefficient
elif type == "velocity":
return radians / velocityCoefficient
else:
return 0
# shaft (ticks) -> axle (radians)
def getAxleRadians(ticks, type):
if type == "position":
return ticks * positionCoefficient
elif type == "velocity":
return ticks * velocityCoefficient
else:
return 0
######### Robot Class #########
class motor_poc(wpilib.TimedRobot):
def robotInit(self) -> None:
logging.info("Entering Robot Init")
# Configure Joystick
self.joystick = wpilib.XboxController(controllerPort)
# Configure CANCoder
canCoderConfig = ctre.CANCoderConfiguration()
canCoderConfig.absoluteSensorRange = ctre.AbsoluteSensorRange.Unsigned_0_to_360
canCoderConfig.initializationStrategy = ctre.SensorInitializationStrategy.BootToAbsolutePosition
canCoderConfig.magnetOffsetDegrees = encoder_offset
canCoderConfig.sensorDirection = encoder_direction
# Setup encoder to be in radians
canCoderConfig.sensorCoefficient = 2 * math.pi / encoder_ticks_per_rev
canCoderConfig.unitString = "rad"
canCoderConfig.sensorTimeBase = ctre.SensorTimeBase.PerSecond
self.encoder = ctre.CANCoder(encoderPort)
self.encoder.configAllSettings(canCoderConfig, timeout_ms)
self.encoder.setPositionToAbsolute(timeout_ms)
self.encoder.setStatusFramePeriod(ctre.CANCoderStatusFrame.SensorData, 10, timeout_ms)
# Configure Talon
self.talon = ctre.TalonFX(motorPort)
self.talon.configFactoryDefault()
self.talon.configSelectedFeedbackSensor(ctre.TalonFXFeedbackDevice.IntegratedSensor, pid_loop_idx, timeout_ms)
self.talon.configNeutralDeadband(0.01, timeout_ms)
self.talon.setSensorPhase(True)
self.talon.setInverted(True)
self.talon.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, timeout_ms)
self.talon.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, timeout_ms)
self.talon.configNominalOutputForward(0, timeout_ms)
self.talon.configNominalOutputReverse(0, timeout_ms)
self.talon.configPeakOutputForward(1, timeout_ms)
self.talon.configPeakOutputReverse(-1, timeout_ms)
self.talon.selectProfileSlot(slot_idx, pid_loop_idx)
self.talon.config_kP(slot_idx, pid_constants["kP"], timeout_ms)
self.talon.config_kI(slot_idx, pid_constants["kI"], timeout_ms)
self.talon.config_kD(slot_idx, pid_constants["kD"], timeout_ms)
# TODO: Figure out Magic Numbers and Calculations Below
self.talon.config_kF(slot_idx, (1023.0 * velocityCoefficient / nominal_voltage) * velocityConstant, timeout_ms)
self.talon.configMotionCruiseVelocity(2.0 / velocityConstant / velocityCoefficient, timeout_ms)
self.talon.configMotionAcceleration((8.0 - 2.0) / accelerationConstant / velocityCoefficient, timeout_ms)
self.talon.configMotionSCurveStrength(1)
# Set Sensor Position to match Absolute Position of CANCoder
self.talon.setSelectedSensorPosition(getShaftTicks(self.encoder.getAbsolutePosition(), "position"), pid_loop_idx, timeout_ms)
self.talon.configVoltageCompSaturation(nominal_voltage, timeout_ms)
currentLimit = ctre.SupplyCurrentLimitConfiguration()
currentLimit.enable = True
currentLimit.currentLimit = steer_current_limit
self.talon.configSupplyCurrentLimit(currentLimit, timeout_ms)
self.talon.enableVoltageCompensation(True)
self.talon.setNeutralMode(ctre.NeutralMode.Brake)
# Keep track of position
self.targetPosition = 0
self.reset_iterations = 0
def teleopInit(self) -> None:
logging.info("Entering Teleop")
def teleopPeriodic(self) -> None:
# Get position and velocities of the motor
motorPosition = getAxleRadians(self.talon.getSelectedSensorPosition(), "position")
motorVelocity = getAxleRadians(self.talon.getSelectedSensorVelocity(), "velocity")
absolutePosition = self.encoder.getAbsolutePosition()
# Reset
if motorVelocity < encoder_reset_velocity:
self.reset_iterations += 1
if self.reset_iterations >= encoder_reset_iterations:
self.reset_iterations = 0
self.talon.setSelectedSensorPosition(getShaftTicks(absolutePosition, "position"))
motorPosition = absolutePosition
else:
self.reset_iterations = 0
# Increment Target Position
if self.joystick.getAButtonPressed():
self.targetPosition += increment
elif self.joystick.getBButtonPressed():
self.targetPosition -= increment
# Move back in 0 - 2pi range in case increment kicked us out
self.targetPosition = math.fmod(self.targetPosition, 2.0 * math.pi)
# This correction is needed in case we got a negative remainder
# A negative radian can be thought of as starting at 2pi and moving down abs(remainder)
if self.targetPosition < 0.0:
self.targetPosition += 2.0 * math.pi
# Now that we have a new target position, we need to figure out how to move the motor.
# First let's assume that we will move directly to the target position.
newMotorPosition = self.targetPosition
# The motor could get to the target position by moving clockwise or counterclockwise.
# The shortest path should be the direction that is less than pi radians away from the current motor position.
# The shortest path could loop around the circle and be less than 0 or greater than 2pi.
# We need to get the absolute current position to determine if we need to loop around the 0 - 2pi range.
# The current motor position does not stay inside the 0 - 2pi range.
# We need the absolute position to compare with the target position.
absoluteMotorPosition = math.fmod(motorPosition, 2.0 * math.pi)
if absoluteMotorPosition < 0.0:
absoluteMotorPosition += 2.0 * math.pi
# If the target position was in the first quadrant area
# and absolute motor position was in the last quadrant area
# then we need to move into the next loop around the circle.
if self.targetPosition - absoluteMotorPosition < -math.pi:
newMotorPosition += 2.0 * math.pi
# If the target position was in the last quadrant area
# and absolute motor position was in the first quadrant area
# then we need to move into the previous loop around the circle.
elif self.targetPosition - absoluteMotorPosition > math.pi:
newMotorPosition -= 2.0 * math.pi
# Last, add the current existing loops that the motor has gone through.
newMotorPosition += motorPosition - absoluteMotorPosition
print(f"ABS Target: {self.targetPosition} Motor Target: {newMotorPosition} Motor Current: {motorPosition} ABS Current: {absolutePosition}")
self.talon.set(ctre.TalonFXControlMode.MotionMagic, getShaftTicks(newMotorPosition, "position"))
def teleopExit(self) -> None:
logging.info("Exiting Teleop")
if __name__ == '__main__':
wpilib.run(motor_poc)
| 8,490 | Python | 41.243781 | 156 | 0.690813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.