repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -0,0 +1,537 @@ +#include <iostream> +#include <sstream> +#include <algorithm> +#include <regex> +#include <stack> +#include <queue> +#include <unordered_map> +#include <vector> +#include <boost/algorithm/string/join.hpp> + +#include "db/catalog/meta_types.hpp" +#include "logger/logger.hpp" +#include "utils/status.hpp" +#include "expr.hpp" + +namespace vectordb { +namespace query { +namespace expr { + +enum class State { + Start, + Number, + String, + Attribute, + Operator, +}; + +bool isArithChar(char c) { + return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; +}; + +bool isCompareChar(char c) { + return c == '>' || c == '<' || c == '='; +}; + +bool isArithStr(std::string str) { + return str == "+" || str == "-" || str == "*" || str == "/" || str == "%"; +}; + +bool isCompareStr(std::string str) { + return str == ">" || str == ">=" || str == "=" || str == "<=" || str == "<" || str == "<>"; +}; + +bool isLogicalStr(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "AND" || str == "OR" || str == "NOT"; +}; + +bool isUnsupportedLogicalOp(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "ALL" || str == "ANY" || str == "BETWEEN" || str == "EXISTS" || str == "IN" || + str == "LIKE" || str == "SOME"; +} + +bool isOperator(std::string str) { + return isArithStr(str) || isCompareStr(str) || isLogicalStr(str); +}; + +int getPrecedence(std::string& op) { + if (isLogicalStr(op)) + return 1; + else if (isCompareStr(op)) + return 2; + if (op == "+" || op == "-") + return 3; + else if (op == "*" || op == "/" || op == "%") + return 4; + return 0; +}; + +Status SplitTokens(std::string& expression, std::vector<std::string>& tokens) { + std::vector<std::string> token_list; + State state = State::Start; + std::string cur_token; + + size_t last_index = expression.length() - 1; + for (size_t i = 0; i < expression.length(); ) { + char c = expression[i]; + switch (state) { + case State::Start: + if (std::isspace(c)) { + i++; + continue; + } else if (std::isdigit(c)) { + state = State::Number; + } else if (std::isalpha(c) || c == '_') { + state = State::Attribute; + } else if (c == '(' || c == ')') { + token_list.push_back(std::string(1, c)); + i++; + } else if (isArithChar(c) || isCompareChar(c)) { + if (c == '-' && i != last_index && std::isdigit(expression[i + 1])) { + if (!token_list.empty()) { + std::string ele = token_list.back(); + if (!isOperator(ele) && ele != "(") { + state = State::Operator; + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + state = State::Operator; + } + } else if (c == '\'') { + state = State::String; + } else if (c == '&' || c == '|' || c == '^') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support bitwise operators yet."); + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::String: + if (c == '\'') { + i++; + cur_token += c; + if (cur_token == "''") { + return Status(INVALID_EXPR, "String constant cannot be empty."); + } + if (cur_token.size() > 2) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } + } else { + if (i == last_index) { + return Status(INVALID_EXPR, "Missing terminating '."); + } else { + cur_token += c; + i++; + } + } + break; + case State::Attribute: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } else if (std::isalnum(c) || c == '_') { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Invalid name: " + (cur_token += c)); + } + break; + case State::Number: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + if (std::count(cur_token.begin(), cur_token.end(), '.') > 1) { + return Status(INVALID_EXPR, cur_token + " is not a valid number."); + } else { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } + } else if (std::isdigit(c)) { + cur_token += c; + i++; + } else if (c == '.' && i != last_index && std::isdigit(expression[i + 1])) { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::Operator: + if (isArithChar(c)) { + if (i != last_index && expression[i + 1] == '=') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support compound operators yet."); + } + token_list.push_back(std::string(1, c)); + i++; + state = State::Start; + } else if (isCompareChar(c)) { + cur_token += c; + if (i != last_index && isCompareChar(expression[i + 1])) { + i++; + } else { + if (isCompareStr(cur_token)) { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } else { + return Status(INVALID_EXPR, "'" + cur_token + "' is an invalid operator."); + } + } + } + break; + } + } + if (!cur_token.empty()) { + token_list.push_back(cur_token); + cur_token.clear(); + } + + tokens = token_list; + return Status::OK(); +}; + +std::vector<std::string> ShuntingYard(const std::vector<std::string>& tokens) { + std::vector<std::string> res; + std::stack<std::string> operatorStack; + + for (std::string str : tokens) { + if (str == "(") { + operatorStack.push(str); + } else if (str == ")") { + while (!operatorStack.empty() && operatorStack.top() != "(") { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + operatorStack.pop(); // Pop the '(' + } else if (isOperator(str)) { + while (!operatorStack.empty() && getPrecedence(operatorStack.top()) >= getPrecedence(str)) { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + operatorStack.push(str); + } else { + res.push_back(str); + } + } + + while (!operatorStack.empty()) { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + + return res; +}; + +bool isBoolConstant(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "TRUE" || str == "FALSE"; +}; + +bool isIntConstant(const std::string& str) { + std::regex integerPattern("^[-+]?\\d+$"); + + return std::regex_match(str, integerPattern); +}; + +bool isDoubleConstant(const std::string& str) { + std::regex doublePattern("^[-+]?\\d+\\.\\d+(?:[eE][-+]?\\d+)?$"); + + return std::regex_match(str, doublePattern); +}; + +bool to_bool(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), ::tolower); + std::istringstream is(str); + bool b; + is >> std::boolalpha >> b; + return b; +}; + +bool isNotOperator(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "NOT"; +}; + +NodeType GetOperatorNodeType(std::string op) { + if (isLogicalStr(op)) { + std::transform(op.begin(), op.end(), op.begin(), [](unsigned char c) { + return std::toupper(c); + }); + } + + auto it = OperatorNodeTypeMap.find(op); + if (it != OperatorNodeTypeMap.end()) { + return it->second;
Wrong indentation
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -0,0 +1,537 @@ +#include <iostream> +#include <sstream> +#include <algorithm> +#include <regex> +#include <stack> +#include <queue> +#include <unordered_map> +#include <vector> +#include <boost/algorithm/string/join.hpp> + +#include "db/catalog/meta_types.hpp" +#include "logger/logger.hpp" +#include "utils/status.hpp" +#include "expr.hpp" + +namespace vectordb { +namespace query { +namespace expr { + +enum class State { + Start, + Number, + String, + Attribute, + Operator, +}; + +bool isArithChar(char c) { + return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; +}; + +bool isCompareChar(char c) { + return c == '>' || c == '<' || c == '='; +}; + +bool isArithStr(std::string str) { + return str == "+" || str == "-" || str == "*" || str == "/" || str == "%"; +}; + +bool isCompareStr(std::string str) { + return str == ">" || str == ">=" || str == "=" || str == "<=" || str == "<" || str == "<>"; +}; + +bool isLogicalStr(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "AND" || str == "OR" || str == "NOT"; +}; + +bool isUnsupportedLogicalOp(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "ALL" || str == "ANY" || str == "BETWEEN" || str == "EXISTS" || str == "IN" || + str == "LIKE" || str == "SOME"; +} + +bool isOperator(std::string str) { + return isArithStr(str) || isCompareStr(str) || isLogicalStr(str); +}; + +int getPrecedence(std::string& op) { + if (isLogicalStr(op)) + return 1; + else if (isCompareStr(op)) + return 2; + if (op == "+" || op == "-") + return 3; + else if (op == "*" || op == "/" || op == "%") + return 4; + return 0; +}; + +Status SplitTokens(std::string& expression, std::vector<std::string>& tokens) { + std::vector<std::string> token_list; + State state = State::Start; + std::string cur_token; + + size_t last_index = expression.length() - 1; + for (size_t i = 0; i < expression.length(); ) { + char c = expression[i]; + switch (state) { + case State::Start: + if (std::isspace(c)) { + i++; + continue; + } else if (std::isdigit(c)) { + state = State::Number; + } else if (std::isalpha(c) || c == '_') { + state = State::Attribute; + } else if (c == '(' || c == ')') { + token_list.push_back(std::string(1, c)); + i++; + } else if (isArithChar(c) || isCompareChar(c)) { + if (c == '-' && i != last_index && std::isdigit(expression[i + 1])) { + if (!token_list.empty()) { + std::string ele = token_list.back(); + if (!isOperator(ele) && ele != "(") { + state = State::Operator; + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + state = State::Operator; + } + } else if (c == '\'') { + state = State::String; + } else if (c == '&' || c == '|' || c == '^') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support bitwise operators yet."); + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::String: + if (c == '\'') { + i++; + cur_token += c; + if (cur_token == "''") { + return Status(INVALID_EXPR, "String constant cannot be empty."); + } + if (cur_token.size() > 2) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } + } else { + if (i == last_index) { + return Status(INVALID_EXPR, "Missing terminating '."); + } else { + cur_token += c; + i++; + } + } + break; + case State::Attribute: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } else if (std::isalnum(c) || c == '_') { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Invalid name: " + (cur_token += c)); + } + break; + case State::Number: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + if (std::count(cur_token.begin(), cur_token.end(), '.') > 1) { + return Status(INVALID_EXPR, cur_token + " is not a valid number."); + } else { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } + } else if (std::isdigit(c)) { + cur_token += c; + i++; + } else if (c == '.' && i != last_index && std::isdigit(expression[i + 1])) { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::Operator: + if (isArithChar(c)) { + if (i != last_index && expression[i + 1] == '=') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support compound operators yet."); + } + token_list.push_back(std::string(1, c)); + i++; + state = State::Start; + } else if (isCompareChar(c)) { + cur_token += c; + if (i != last_index && isCompareChar(expression[i + 1])) { + i++; + } else { + if (isCompareStr(cur_token)) { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } else { + return Status(INVALID_EXPR, "'" + cur_token + "' is an invalid operator."); + } + } + } + break; + } + } + if (!cur_token.empty()) { + token_list.push_back(cur_token); + cur_token.clear(); + } + + tokens = token_list; + return Status::OK(); +}; + +std::vector<std::string> ShuntingYard(const std::vector<std::string>& tokens) { + std::vector<std::string> res; + std::stack<std::string> operatorStack; + + for (std::string str : tokens) { + if (str == "(") { + operatorStack.push(str); + } else if (str == ")") { + while (!operatorStack.empty() && operatorStack.top() != "(") { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + operatorStack.pop(); // Pop the '(' + } else if (isOperator(str)) { + while (!operatorStack.empty() && getPrecedence(operatorStack.top()) >= getPrecedence(str)) { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + operatorStack.push(str); + } else { + res.push_back(str); + } + } + + while (!operatorStack.empty()) { + res.push_back(operatorStack.top()); + operatorStack.pop(); + } + + return res; +}; + +bool isBoolConstant(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "TRUE" || str == "FALSE"; +}; + +bool isIntConstant(const std::string& str) { + std::regex integerPattern("^[-+]?\\d+$"); + + return std::regex_match(str, integerPattern); +}; + +bool isDoubleConstant(const std::string& str) { + std::regex doublePattern("^[-+]?\\d+\\.\\d+(?:[eE][-+]?\\d+)?$"); + + return std::regex_match(str, doublePattern); +}; + +bool to_bool(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), ::tolower); + std::istringstream is(str); + bool b; + is >> std::boolalpha >> b; + return b; +}; + +bool isNotOperator(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "NOT"; +}; + +NodeType GetOperatorNodeType(std::string op) { + if (isLogicalStr(op)) { + std::transform(op.begin(), op.end(), op.begin(), [](unsigned char c) { + return std::toupper(c); + }); + } + + auto it = OperatorNodeTypeMap.find(op); + if (it != OperatorNodeTypeMap.end()) { + return it->second; + } + + return NodeType::Invalid; +}; + +Status CheckCompatible(std::string& op, ValueType& left, ValueType& right, ValueType& root) { + if (isLogicalStr(op)) { + if (left != ValueType::BOOL || right != ValueType::BOOL) { + return Status(INVALID_EXPR, op + " statement is invalid."); + } + + root = ValueType::BOOL; + } + if (isCompareStr(op)) { + if (op != "=" && op != "<>") { + if (left == ValueType::STRING || left == ValueType::BOOL || + right == ValueType::STRING || right == ValueType::BOOL + ) { + return Status(INVALID_EXPR, op + " statement is invalid."); + } + } else { + if (left != right) { + bool compatible = left == ValueType::INT && right == ValueType::DOUBLE || + left == ValueType::DOUBLE && right == ValueType::INT; + if (!compatible) { + return Status(INVALID_EXPR, op + " statement is invalid."); + } + } + } + + root = ValueType::BOOL; + } + if (isArithStr(op)) { + if (left == ValueType::BOOL || right == ValueType::BOOL) { + return Status(INVALID_EXPR, "Boolean value is not compatible with " + op + " operation."); + } + if (op != "+") { + if (left == ValueType::STRING || right == ValueType::STRING) { + return Status(INVALID_EXPR, "String value is not compatible with " + op + " operation."); + } else { + if (left == ValueType::DOUBLE || right == ValueType::DOUBLE) { + root = ValueType::DOUBLE; + } else { + root = ValueType::INT; + } + } + } else { + if (left == ValueType::STRING && right == ValueType::STRING) { + root = ValueType::STRING; + } else { + if (left == ValueType::STRING || right == ValueType::STRING) { + return Status(INVALID_EXPR, op + " statement is invalid."); + } + if (left == ValueType::DOUBLE || right == ValueType::DOUBLE) { + root = ValueType::DOUBLE; + } else { + root = ValueType::INT; + } + } + } + } + + return Status::OK(); +}; + +Status GenerateNodes( + std::vector<std::string>& tokens, + std::vector<ExprNodePtr>& nodes, + std::unordered_map<std::string, engine::meta::FieldType>& field_map +) { + std::stack<ExprNodePtr> nodeStack;
Rename to node_stack
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -0,0 +1,537 @@ +#include <iostream> +#include <sstream> +#include <algorithm> +#include <regex> +#include <stack> +#include <queue> +#include <unordered_map> +#include <vector> +#include <boost/algorithm/string/join.hpp> + +#include "db/catalog/meta_types.hpp" +#include "logger/logger.hpp" +#include "utils/status.hpp" +#include "expr.hpp" + +namespace vectordb { +namespace query { +namespace expr { + +enum class State { + Start, + Number, + String, + Attribute, + Operator, +}; + +bool isArithChar(char c) { + return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; +}; + +bool isCompareChar(char c) { + return c == '>' || c == '<' || c == '='; +}; + +bool isArithStr(std::string str) { + return str == "+" || str == "-" || str == "*" || str == "/" || str == "%"; +}; + +bool isCompareStr(std::string str) { + return str == ">" || str == ">=" || str == "=" || str == "<=" || str == "<" || str == "<>"; +}; + +bool isLogicalStr(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "AND" || str == "OR" || str == "NOT"; +}; + +bool isUnsupportedLogicalOp(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); + return str == "ALL" || str == "ANY" || str == "BETWEEN" || str == "EXISTS" || str == "IN" || + str == "LIKE" || str == "SOME"; +} + +bool isOperator(std::string str) { + return isArithStr(str) || isCompareStr(str) || isLogicalStr(str); +}; + +int getPrecedence(std::string& op) { + if (isLogicalStr(op)) + return 1; + else if (isCompareStr(op)) + return 2; + if (op == "+" || op == "-") + return 3; + else if (op == "*" || op == "/" || op == "%") + return 4; + return 0; +}; + +Status SplitTokens(std::string& expression, std::vector<std::string>& tokens) { + std::vector<std::string> token_list; + State state = State::Start; + std::string cur_token; + + size_t last_index = expression.length() - 1; + for (size_t i = 0; i < expression.length(); ) { + char c = expression[i]; + switch (state) { + case State::Start: + if (std::isspace(c)) { + i++; + continue; + } else if (std::isdigit(c)) { + state = State::Number; + } else if (std::isalpha(c) || c == '_') { + state = State::Attribute; + } else if (c == '(' || c == ')') { + token_list.push_back(std::string(1, c)); + i++; + } else if (isArithChar(c) || isCompareChar(c)) { + if (c == '-' && i != last_index && std::isdigit(expression[i + 1])) { + if (!token_list.empty()) { + std::string ele = token_list.back(); + if (!isOperator(ele) && ele != "(") { + state = State::Operator; + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + cur_token += c; + i++; + state = State::Number; + } + } else { + state = State::Operator; + } + } else if (c == '\'') { + state = State::String; + } else if (c == '&' || c == '|' || c == '^') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support bitwise operators yet."); + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::String: + if (c == '\'') { + i++; + cur_token += c; + if (cur_token == "''") { + return Status(INVALID_EXPR, "String constant cannot be empty."); + } + if (cur_token.size() > 2) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } + } else { + if (i == last_index) { + return Status(INVALID_EXPR, "Missing terminating '."); + } else { + cur_token += c; + i++; + } + } + break; + case State::Attribute: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + token_list.push_back(cur_token); + cur_token.clear(); + state = State::Start; + } else if (std::isalnum(c) || c == '_') { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Invalid name: " + (cur_token += c)); + } + break; + case State::Number: + if (std::isspace(c) || c == ')' || isArithChar(c) || isCompareChar(c)) { + if (std::count(cur_token.begin(), cur_token.end(), '.') > 1) { + return Status(INVALID_EXPR, cur_token + " is not a valid number."); + } else { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } + } else if (std::isdigit(c)) { + cur_token += c; + i++; + } else if (c == '.' && i != last_index && std::isdigit(expression[i + 1])) { + cur_token += c; + i++; + } else { + return Status(INVALID_EXPR, "Filter expression is not valid."); + } + break; + case State::Operator: + if (isArithChar(c)) { + if (i != last_index && expression[i + 1] == '=') { + return Status(NOT_IMPLEMENTED_ERROR, "Epsilla does not support compound operators yet."); + } + token_list.push_back(std::string(1, c)); + i++; + state = State::Start; + } else if (isCompareChar(c)) { + cur_token += c; + if (i != last_index && isCompareChar(expression[i + 1])) { + i++; + } else { + if (isCompareStr(cur_token)) { + token_list.push_back(cur_token); + cur_token.clear(); + i++; + state = State::Start; + } else { + return Status(INVALID_EXPR, "'" + cur_token + "' is an invalid operator."); + } + } + } + break; + } + } + if (!cur_token.empty()) { + token_list.push_back(cur_token); + cur_token.clear(); + } + + tokens = token_list; + return Status::OK(); +}; + +std::vector<std::string> ShuntingYard(const std::vector<std::string>& tokens) { + std::vector<std::string> res; + std::stack<std::string> operatorStack;
rename to operator_stack
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -1,12 +1,14 @@ -#pragma once
Why removed this line? It is important to avoid duplicated include causing compiler issues
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -718,15 +726,30 @@ bool VecSearchExecutor::BruteForceSearch(const float *query_data, const int64_t return true; } -Status VecSearchExecutor::Search(const float *query_data, const ConcurrentBitset &deleted, const size_t limit, const int64_t total_vector, int64_t &result_size) { +Status VecSearchExecutor::Search( + const float *query_data, + vectordb::engine::TableSegmentMVP *table_segment, + const size_t limit, + std::vector<vectordb::query::expr::ExprNodePtr> &filter_nodes, + int64_t &result_size) { + int64_t total_vector = table_segment->record_number_; + ConcurrentBitset &deleted = *(table_segment->deleted_); + vectordb::query::expr::ExprEvaluator expr_evaluator( + filter_nodes, + table_segment->field_name_mem_offset_map_, + table_segment->primitive_offset_, + table_segment->string_num_, + table_segment->attribute_table_, + table_segment->string_table_); + int filter_root_index = filter_nodes.size() - 1; // currently the max returned result is L_local_ // TODO: support larger search results std::cout << "search with limit: " << limit << " brute force: " << brute_force_search_
Forgot to tell TopKeyboard to remove this comment, let's comment it out or change it into debug log
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -0,0 +1,44 @@ +#include <any> +#include <unordered_map> +#include <vector> + +#include "expr_types.hpp" + +namespace vectordb { +namespace query { +namespace expr { + +class ExprEvaluator { + public: + explicit ExprEvaluator( + std::vector<ExprNodePtr>& nodes, + std::unordered_map<std::string, size_t>& field_name_mem_offset_map, + int64_t& primitive_offset_, + int64_t& string_num_, + char* attribute_table_, + std::string* string_table_); + + ~ExprEvaluator(); + + bool LogicalEvaluate(const int& node_index, const int64_t& cand_ind); + + private: + std::string GetStrFieldValue(const std::string& field_name, const int64_t& cand_ind); + bool GetBoolFieldValue(const std::string& field_name, const int64_t& cand_ind); + int64_t GetIntFieldValue(const std::string& field_name, const int64_t& cand_ind, NodeType& node_type); + double GetDoubleFieldValue(const std::string& field_name, const int64_t& cand_ind, NodeType& node_type); + std::string StrEvaluate(const int& node_index, const int64_t& cand_ind); + double NumEvaluate(const int& node_index, const int64_t& cand_ind); + + public: + std::vector<ExprNodePtr>& nodes_; + std::unordered_map<std::string, size_t>& field_name_mem_offset_map_; + int64_t& primitive_offset_;
No need to use & here for a primitive type field, as the copy is very cheap
vectordb
github_2023
cpp
52
epsilla-cloud
richard-epsilla
@@ -0,0 +1,193 @@ +#include "expr_evaluator.hpp" + +#include <cmath> +#include <iostream> + +namespace vectordb { +namespace query { +namespace expr { + +ExprEvaluator::ExprEvaluator( + std::vector<ExprNodePtr>& nodes, + std::unordered_map<std::string, size_t>& field_name_mem_offset_map, + int64_t& primitive_offset, + int64_t& string_num, + char* attribute_table, + std::string* string_table) + : nodes_(nodes), + field_name_mem_offset_map_(field_name_mem_offset_map), + primitive_offset_(primitive_offset), + string_num_(string_num), + attribute_table_(attribute_table), + string_table_(string_table) { +} + +std::string ExprEvaluator::GetStrFieldValue(const std::string& field_name, const int64_t& cand_ind) { + auto offset = field_name_mem_offset_map_[field_name] + cand_ind * string_num_; + return string_table_[offset]; +} + +bool ExprEvaluator::GetBoolFieldValue(const std::string& field_name, const int64_t& cand_ind) { + auto offset = field_name_mem_offset_map_[field_name] + cand_ind * primitive_offset_; + return reinterpret_cast<bool*>(attribute_table_[offset]); +} + +int64_t ExprEvaluator::GetIntFieldValue(const std::string& field_name, const int64_t& cand_ind, NodeType& node_type) { + auto offset = field_name_mem_offset_map_[field_name] + cand_ind * primitive_offset_; + int64_t result; + switch (node_type) { + case NodeType::Int1Attr: { + int8_t* ptr = reinterpret_cast<int8_t*>(&attribute_table_[offset]); + result = (int64_t)(*ptr); + break; + } + case NodeType::Int2Attr: { + int16_t* ptr = reinterpret_cast<int16_t*>(&attribute_table_[offset]); + result = (int64_t)(*ptr); + break; + } + case NodeType::Int4Attr: { + int32_t* ptr = reinterpret_cast<int32_t*>(&attribute_table_[offset]); + result = (int64_t)(*ptr); + break; + } + case NodeType::Int8Attr: { + int64_t* ptr = reinterpret_cast<int64_t*>(&attribute_table_[offset]); + result = (int64_t)(*ptr); + break; + } + default: + result = 0; + } + std::cout << result << std::endl; + return result; +} + +double ExprEvaluator::GetDoubleFieldValue(const std::string& field_name, const int64_t& cand_ind, NodeType& node_type) {
Can make the function name GetRealNumberFieldValue to cover double and float
vectordb
github_2023
python
50
epsilla-cloud
richard-epsilla
@@ -34,6 +34,22 @@ limit=2, with_distance=True ) + +print(code, response) + +pk_to_delete = [1, 2, 3, 4] +print("deleting pk ", pk_to_delete) +code = epsilla.delete_by_pk(table_name="MyTable", primary_keys=pk_to_delete)
Can we call this just delete? And use primary_keys and future filter condition as positional parameters to distinguish which underneath function to call?
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -334,6 +334,39 @@ class WebController : public oatpp::web::server::api::ApiController { return createDtoResponse(Status::CODE_200, status_dto); } + ADD_CORS(DeleteRecordsByPK) + + ENDPOINT("POST", "/api/{db_name}/data/delete/pk", DeleteRecordsByPK,
Can we just use ""/api/{db_name}/data/delete"? Later we can use whether primaryKeys exist and whether filter condition exists to distinguish which underneath function to call
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -189,6 +195,11 @@ TableSegmentMVP::TableSegmentMVP(meta::TableSchema& table_schema, const std::str // Read the string table for (auto i = 0; i < record_number_; ++i) { + // skip deleted entry + if (deleted_->test(i)) {
Can we skip? If we skip reading the file, the file cursor will messed up?
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -133,6 +134,57 @@ Status DBServer::Insert(const std::string& db_name, return table->Insert(records); } +Status DBServer::DeleteByPK(const std::string& db_name, const std::string& table_name, vectordb::Json& pkList) { + auto db = GetDB(db_name); + if (db == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "DB not found: " + db_name); + } + auto table = db->GetTable(table_name); + if (table == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "Table not found: " + table_name); + } + int pkIdx = 0; + for (; pkIdx < table->table_schema_.fields_.size(); pkIdx++) { + if (table->table_schema_.fields_[pkIdx].is_primary_key_) { + break; + } + } + if (pkIdx == table->table_schema_.fields_.size()) { + return Status(DB_UNEXPECTED_ERROR, "PK not found: " + table_name);
"Primary key not found"
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -133,6 +134,57 @@ Status DBServer::Insert(const std::string& db_name, return table->Insert(records); } +Status DBServer::DeleteByPK(const std::string& db_name, const std::string& table_name, vectordb::Json& pkList) { + auto db = GetDB(db_name); + if (db == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "DB not found: " + db_name); + } + auto table = db->GetTable(table_name); + if (table == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "Table not found: " + table_name); + } + int pkIdx = 0; + for (; pkIdx < table->table_schema_.fields_.size(); pkIdx++) { + if (table->table_schema_.fields_[pkIdx].is_primary_key_) { + break; + } + } + if (pkIdx == table->table_schema_.fields_.size()) { + return Status(DB_UNEXPECTED_ERROR, "PK not found: " + table_name); + } + + // simple sanity check + auto pkField = table->table_schema_.fields_[pkIdx]; + size_t pkListSize = pkList.GetSize(); + if (pkListSize == 0) { + std::cout << "No pk to delete." << std::endl; + return Status::OK(); + } + switch (pkField.field_type_) { + case meta::FieldType::INT1: // fall through + case meta::FieldType::INT2: // fall through + case meta::FieldType::INT4: // fall through + case meta::FieldType::INT8: + for (int i = 0; i < pkListSize; i++) { + if (!pkList.GetArrayElement(i).IsNumber()) { + return Status(DB_UNEXPECTED_ERROR, "PK type mismatch at pos " + std::to_string(i));
PK -> Primary key pos -> field position
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -133,6 +134,57 @@ Status DBServer::Insert(const std::string& db_name, return table->Insert(records); } +Status DBServer::DeleteByPK(const std::string& db_name, const std::string& table_name, vectordb::Json& pkList) { + auto db = GetDB(db_name); + if (db == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "DB not found: " + db_name); + } + auto table = db->GetTable(table_name); + if (table == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "Table not found: " + table_name); + } + int pkIdx = 0; + for (; pkIdx < table->table_schema_.fields_.size(); pkIdx++) { + if (table->table_schema_.fields_[pkIdx].is_primary_key_) { + break; + } + } + if (pkIdx == table->table_schema_.fields_.size()) { + return Status(DB_UNEXPECTED_ERROR, "PK not found: " + table_name); + } + + // simple sanity check + auto pkField = table->table_schema_.fields_[pkIdx]; + size_t pkListSize = pkList.GetSize(); + if (pkListSize == 0) { + std::cout << "No pk to delete." << std::endl; + return Status::OK(); + } + switch (pkField.field_type_) { + case meta::FieldType::INT1: // fall through + case meta::FieldType::INT2: // fall through + case meta::FieldType::INT4: // fall through + case meta::FieldType::INT8: + for (int i = 0; i < pkListSize; i++) { + if (!pkList.GetArrayElement(i).IsNumber()) { + return Status(DB_UNEXPECTED_ERROR, "PK type mismatch at pos " + std::to_string(i)); + } + } + break; + case meta::FieldType::STRING: + for (int i = 0; i < pkListSize; i++) { + if (!pkList.GetArrayElement(i).IsString()) { + return Status(DB_UNEXPECTED_ERROR, "PK type mismatch at pos " + std::to_string(i));
Same here
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -133,6 +134,57 @@ Status DBServer::Insert(const std::string& db_name, return table->Insert(records); } +Status DBServer::DeleteByPK(const std::string& db_name, const std::string& table_name, vectordb::Json& pkList) { + auto db = GetDB(db_name); + if (db == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "DB not found: " + db_name); + } + auto table = db->GetTable(table_name); + if (table == nullptr) { + return Status(DB_UNEXPECTED_ERROR, "Table not found: " + table_name); + } + int pkIdx = 0; + for (; pkIdx < table->table_schema_.fields_.size(); pkIdx++) { + if (table->table_schema_.fields_[pkIdx].is_primary_key_) { + break; + } + } + if (pkIdx == table->table_schema_.fields_.size()) { + return Status(DB_UNEXPECTED_ERROR, "PK not found: " + table_name); + } + + // simple sanity check + auto pkField = table->table_schema_.fields_[pkIdx]; + size_t pkListSize = pkList.GetSize(); + if (pkListSize == 0) { + std::cout << "No pk to delete." << std::endl; + return Status::OK(); + } + switch (pkField.field_type_) { + case meta::FieldType::INT1: // fall through + case meta::FieldType::INT2: // fall through + case meta::FieldType::INT4: // fall through + case meta::FieldType::INT8: + for (int i = 0; i < pkListSize; i++) { + if (!pkList.GetArrayElement(i).IsNumber()) { + return Status(DB_UNEXPECTED_ERROR, "PK type mismatch at pos " + std::to_string(i)); + } + } + break; + case meta::FieldType::STRING: + for (int i = 0; i < pkListSize; i++) { + if (!pkList.GetArrayElement(i).IsString()) { + return Status(DB_UNEXPECTED_ERROR, "PK type mismatch at pos " + std::to_string(i)); + } + } + break; + default: + return Status(DB_UNEXPECTED_ERROR, "unexpected PK type.");
Unexpected primary key type
vectordb
github_2023
cpp
50
epsilla-cloud
richard-epsilla
@@ -694,32 +695,43 @@ bool VecSearchExecutor::BruteForceSearch(const float *query_data, const int64_t float dist = fstdistfunc_(vector_table_ + dimension_ * v_id, query_data, dist_func_param_); brute_force_queue_[v_id - start] = Candidate(v_id, dist, false); } + + // compacting the result with 2 pointers by removing the deleted entries + // iter: the iterator to loop through the brute force queue + // num_result: the pointer to the current right-most slot in the new result + int64_t iter = 0, + num_result = 0; + // remove the invalid entries + for (; iter < end - start; ++iter) { + if (!deleted.test(iter)) { + if (iter != num_result) { + brute_force_queue_[num_result] = brute_force_queue_[iter]; + } + num_result++; + } + } + brute_force_queue_.resize(num_result);
Does frequent resize have performance problem?
vectordb
github_2023
cpp
50
epsilla-cloud
ricki-epsilla
@@ -334,38 +334,38 @@ class WebController : public oatpp::web::server::api::ApiController { return createDtoResponse(Status::CODE_200, status_dto); } - // TODO: implement with corresponding function later. - ADD_CORS(DeleteRecordsByID) + ADD_CORS(DeleteRecordsByPK) - ENDPOINT("POST", "/api/{db_name}/data/delete", DeleteRecordsByID, + ENDPOINT("POST", "/api/{db_name}/data/delete", DeleteRecordsByPK, PATH(String, db_name, "db_name"), - BODY_DTO(Object<DeleteRecordsReqDto>, body)) { + BODY_STRING(String, body)) { auto dto = StatusDto::createShared(); - - if (!body->table) { + vectordb::Json requestBody; + requestBody.LoadFromString(body);
add payload validation check. ```suggestion auto valid = requestBody.LoadFromString(body); if (!valid) { status_dto->statusCode = Status::CODE_400.code; status_dto->message = "Invalid payload."; return createDtoResponse(Status::CODE_400, status_dto); } ```
vectordb
github_2023
cpp
42
epsilla-cloud
richard-epsilla
@@ -52,6 +52,10 @@ Status TableSegmentMVP::Init(meta::TableSchema& table_schema, int64_t size_limit if (field_schema.field_type_ == meta::FieldType::STRING) { field_id_mem_offset_map_[field_schema.id_] = string_num_; field_name_mem_offset_map_[field_schema.name_] = string_num_; + if (field_schema.is_primary_key_) { + assert(!primitive_pk_field_id_); // only one pk allowed
Assert will crash the engine. Can we use semantic check during schema creation to avoid it?
vectordb
github_2023
cpp
42
epsilla-cloud
richard-epsilla
@@ -306,9 +393,17 @@ Status TableSegmentMVP::Insert(meta::TableSchema& table_schema, Json& records, i } } ++cursor; + + LOOP_END : {} + // nothing should be done at the end of block } record_number_.store(cursor); - return Status::OK(); + auto msg = std::string("loading done. added entries: " +
auto msg = "Successfully inserted " + std::to_string(new_record_size - skipped_entry) + records." if (skipped_entry > 0) { msg += "Skipped " + std::to_string(skipped_entry) + " records with primary key values that already exist." }
vectordb
github_2023
cpp
28
epsilla-cloud
richard-epsilla
@@ -58,7 +58,7 @@ class WriteAheadLog { RotateFile(); } int64_t next = global_counter_.IncrementAndGet(); - fprintf(file_, "%lld %d %s\n", next, type, entry.c_str()); + fprintf(file_, "%ld %d %s\n", next, type, entry.c_str());
This part is interesting. lld will not warning on macos. ld will not warning on linux. Cannot satisfy both
vectordb
github_2023
cpp
28
epsilla-cloud
richard-epsilla
@@ -0,0 +1,34 @@ +#define PY_SSIZE_T_CLEAN +#include <Python.h> +#include <string> +#include <memory> +#include "db/db_server.hpp" +static PyObject *EpsillaError; + +static PyObject *spam_system(PyObject *self, PyObject *args); +static PyObject *load_db(PyObject *self, PyObject *args); +static PyObject *use_db(PyObject *self, PyObject *args); +static PyObject *create_table(PyObject *self, PyObject *args); +static PyObject *insert(PyObject *self, PyObject *args); +static PyObject *query(PyObject *self, PyObject *args);
There is also drop_table and unload_db
vectordb
github_2023
cpp
28
epsilla-cloud
richard-epsilla
@@ -0,0 +1,34 @@ +#define PY_SSIZE_T_CLEAN +#include <Python.h> +#include <string> +#include <memory> +#include "db/db_server.hpp" +static PyObject *EpsillaError; + +static PyObject *spam_system(PyObject *self, PyObject *args); +static PyObject *load_db(PyObject *self, PyObject *args); +static PyObject *use_db(PyObject *self, PyObject *args); +static PyObject *create_table(PyObject *self, PyObject *args); +static PyObject *insert(PyObject *self, PyObject *args); +static PyObject *query(PyObject *self, PyObject *args); + +static std::string db_name; +static vectordb::engine::DBServer *db; + +static PyMethodDef EpsillaMethods[] = { + {"system", spam_system, METH_VARARGS, "Execute a shell command."}, + {"load_db", load_db, METH_VARARGS, "Load the database"}, + {"use_db", use_db, METH_VARARGS, "Use the database"},
Why not all functions above exposed here?
vectordb
github_2023
cpp
28
epsilla-cloud
richard-epsilla
@@ -68,6 +55,101 @@ static PyObject *use_db(PyObject *self, PyObject *args) db_name = namePtr; return PyLong_FromLong(0); } -static PyObject *create_table(PyObject *self, PyObject *args) {} +static PyObject *create_table(PyObject *self, PyObject *args)
does this mean we will need reimplement the interface and keep the native C++ and python binding implementation in sync from now on?
vectordb
github_2023
cpp
23
epsilla-cloud
richard-epsilla
@@ -183,6 +184,10 @@ Status BasicMetaImpl::LoadDatabase(std::string& db_catalog_path, const std::stri if (databases_.find(db_name) != databases_.end()) { return Status(DB_UNEXPECTED_ERROR, "DB already exists: " + db_name); } + std::regex pattern("[A-Za-z_][A-Za-z_0-9]*");
Can we have a validator function like isValidName for all name checks?
vectordb
github_2023
cpp
23
epsilla-cloud
richard-epsilla
@@ -259,6 +264,77 @@ Status BasicMetaImpl::DropDatabase(const std::string& db_name) { return Status::OK(); } +Status ValidateSchema(TableSchema& table_schema) { + // 1. Check table name + std::regex pattern("[A-Za-z_][A-Za-z_0-9]*");
Same here
vectordb
github_2023
cpp
23
epsilla-cloud
richard-epsilla
@@ -259,6 +264,77 @@ Status BasicMetaImpl::DropDatabase(const std::string& db_name) { return Status::OK(); } +Status ValidateSchema(TableSchema& table_schema) { + // 1. Check table name + std::regex pattern("[A-Za-z_][A-Za-z_0-9]*"); + if (!std::regex_match(table_schema.name_, pattern)) { + return Status(DB_UNEXPECTED_ERROR, "Table name should start with a letter or '_' and can contain only letters, digits, and underscores."); + } + + size_t size = table_schema.fields_.size(); + + // 2. Check table fields duplication + std::unordered_set<std::string> seen_fields; + bool duplicate = false; + + // 3. At least one vector field + bool has_vector_field = false; + + // 4. Only 1 primary key field should apply + bool has_primary_key = false; + + for (size_t i = 0; i < size; i++) { + auto field = table_schema.fields_[i]; + auto name = field.name_; + if (!std::regex_match(name, pattern)) { + return Status(DB_UNEXPECTED_ERROR, name + ": Field name should start with a letter or '_' and can contain only letters, digits, and underscores."); + } + + if (seen_fields.find(name) != seen_fields.end()) { + duplicate = true; + break; + } else { + seen_fields.insert(name); + } + + // 5. Field type validation + if (field.field_type_ == FieldType::UNKNOWN) { + return Status(DB_UNEXPECTED_ERROR, "Type of " + field.name_ + " is not valid."); + } + + if (field.field_type_ == FieldType::VECTOR_DOUBLE || field.field_type_ == FieldType::VECTOR_FLOAT) { + has_vector_field = true; + // 6. Vector fields must have dimension and metric + // 7. Dimension must be positive + if (field.vector_dimension_ <= 0) { + return Status(DB_UNEXPECTED_ERROR, "Vector dimension must be positive."); + } + if (field.metric_type_ == MetricType::UNKNOWN) { + return Status(DB_UNEXPECTED_ERROR, "Metric type of " + field.name_ + " is not valid."); + } + } + + if (has_primary_key && field.is_primary_key_) { + return Status(DB_UNEXPECTED_ERROR, "Cannot have more than 1 primary key field."); + } + if (!has_primary_key && field.is_primary_key_) has_primary_key = true; + } + + std::cout << duplicate << std::endl; + std::cout << has_vector_field << std::endl; + std::cout << has_primary_key << std::endl; + + if (duplicate) { + return Status(DB_UNEXPECTED_ERROR, "Field names can not be deplicated.");
Typo: duplicated
vectordb
github_2023
cpp
23
epsilla-cloud
richard-epsilla
@@ -259,6 +264,77 @@ Status BasicMetaImpl::DropDatabase(const std::string& db_name) { return Status::OK(); } +Status ValidateSchema(TableSchema& table_schema) { + // 1. Check table name + std::regex pattern("[A-Za-z_][A-Za-z_0-9]*"); + if (!std::regex_match(table_schema.name_, pattern)) { + return Status(DB_UNEXPECTED_ERROR, "Table name should start with a letter or '_' and can contain only letters, digits, and underscores."); + } + + size_t size = table_schema.fields_.size(); + + // 2. Check table fields duplication + std::unordered_set<std::string> seen_fields; + bool duplicate = false; + + // 3. At least one vector field + bool has_vector_field = false; + + // 4. Only 1 primary key field should apply + bool has_primary_key = false; + + for (size_t i = 0; i < size; i++) { + auto field = table_schema.fields_[i]; + auto name = field.name_; + if (!std::regex_match(name, pattern)) { + return Status(DB_UNEXPECTED_ERROR, name + ": Field name should start with a letter or '_' and can contain only letters, digits, and underscores."); + } + + if (seen_fields.find(name) != seen_fields.end()) { + duplicate = true; + break; + } else { + seen_fields.insert(name); + } + + // 5. Field type validation + if (field.field_type_ == FieldType::UNKNOWN) { + return Status(DB_UNEXPECTED_ERROR, "Type of " + field.name_ + " is not valid."); + } + + if (field.field_type_ == FieldType::VECTOR_DOUBLE || field.field_type_ == FieldType::VECTOR_FLOAT) { + has_vector_field = true; + // 6. Vector fields must have dimension and metric + // 7. Dimension must be positive + if (field.vector_dimension_ <= 0) { + return Status(DB_UNEXPECTED_ERROR, "Vector dimension must be positive."); + } + if (field.metric_type_ == MetricType::UNKNOWN) { + return Status(DB_UNEXPECTED_ERROR, "Metric type of " + field.name_ + " is not valid."); + } + } + + if (has_primary_key && field.is_primary_key_) { + return Status(DB_UNEXPECTED_ERROR, "Cannot have more than 1 primary key field.");
field -> fields
vectordb
github_2023
cpp
23
epsilla-cloud
richard-epsilla
@@ -259,6 +264,77 @@ Status BasicMetaImpl::DropDatabase(const std::string& db_name) { return Status::OK(); } +Status ValidateSchema(TableSchema& table_schema) { + // 1. Check table name + std::regex pattern("[A-Za-z_][A-Za-z_0-9]*"); + if (!std::regex_match(table_schema.name_, pattern)) { + return Status(DB_UNEXPECTED_ERROR, "Table name should start with a letter or '_' and can contain only letters, digits, and underscores."); + } + + size_t size = table_schema.fields_.size(); + + // 2. Check table fields duplication + std::unordered_set<std::string> seen_fields; + bool duplicate = false; + + // 3. At least one vector field + bool has_vector_field = false; + + // 4. Only 1 primary key field should apply + bool has_primary_key = false; + + for (size_t i = 0; i < size; i++) { + auto field = table_schema.fields_[i]; + auto name = field.name_; + if (!std::regex_match(name, pattern)) {
Same here
NetAdmin
github_2023
csharp
177
nsnail
nsnail
@@ -0,0 +1,32 @@ +namespace NetAdmin.Domain.DbMaps.Adm; + +/// <summary> +/// 女朋友表 +/// </summary> +[Table(Name = Chars.FLG_DB_TABLE_NAME_PREFIX + nameof(Adm_GirlFriends))] +public record Adm_GirlFriends : VersionEntity +{ + /// <summary> + /// 姓名 + /// </summary> + [Column(DbType = Chars.FLG_DB_FIELD_TYPE_VARCHAR_255)] + public virtual string RealName { get; init; }
很好,有个小细节 ; 每个字段上请打上这两个特性, 因为dto都是继承于table entity类, 未避免字段暴露到客户端, 默认启用json忽略,csv导出忽略。 [CsvIgnore] [JsonIgnore] #################################### 如需要输出到客户端,或接收客户端输入,才在Rsp或者Req 对象override时,取消忽略 [JsonIgnore(Condition = JsonIgnoreCondition.Never)] 或 [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
quic
github_2023
c
18
lxin
lxin
@@ -5,26 +5,63 @@ #include <stdlib.h> #include <stdio.h> #include <errno.h> - +#include <netdb.h> #include <netinet/quic.h> +static const char *parse_address( + char const *address, char const *port, struct sockaddr_storage *sas) +{ + struct addrinfo hints = {0}; + struct addrinfo *res; + int rc; + + hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + + rc = getaddrinfo(address, port, &hints, &res); + if (rc != 0) + return gai_strerror(rc); + memcpy(sas, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); + return NULL; +} +static unsigned short get_port(struct sockaddr_storage *sas) +{ + if (sas->ss_family == AF_INET) + return ntohs(((struct sockaddr_in *)sas)->sin_port); + return ntohs(((struct sockaddr_in6 *)sas)->sin6_port); +} +static void set_port(struct sockaddr_storage *sas, unsigned short port) +{ + if (sas->ss_family == AF_INET) + ((struct sockaddr_in *)sas)->sin_port = htons(port); + else + ((struct sockaddr_in6 *)sas)->sin6_port = htons(port); +}
You can simplify: get_port() -> return ntohs(((struct sockaddr_in *)sas)->sin_port) set_port() -> ((struct sockaddr_in *)sas)->sin_port = htons(port); as sin_port in struct sockaddr_in and sin6_port in struct sockaddr_in6 are located at the same offset. also, please add a blank line between functions. same things at func_test.c
quic
github_2023
c
18
lxin
lxin
@@ -227,10 +268,10 @@ static int do_server(int argc, char *argv[]) printf("socket getsockname error %d\n", errno); return -1; } - printf("LOCAL PORT %d\n", ntohs(sa.sin_port)); - if (preferred_port != ntohs(sa.sin_port)) { + printf("LOCAL PORT %d\n", get_port(&sa)); + if (preferred_port != get_port(&sa)) { printf("preferred port: %d\n", preferred_port); - return -1; + //return -1;
any reason why this line is commented out?
quic
github_2023
c
18
lxin
lxin
@@ -5,15 +5,34 @@ #include <stdlib.h> #include <stdio.h> #include <errno.h> - +#include <netdb.h> #include <netinet/quic.h> +static const char *parse_address( + char const *address, char const *port, struct sockaddr_storage *sas) +{ + struct addrinfo hints = {0}; + struct addrinfo *res; + int rc; + + hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + + rc = getaddrinfo(address, port, &hints, &res); + if (rc != 0) + return gai_strerror(rc); + memcpy(sas, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); + return NULL; +}
same here, please add a blank line.
quic
github_2023
c
5
lxin
lxin
@@ -380,12 +381,12 @@ void quic_outq_retransmit(struct sock *sk) } next: - skb = outq->retransmit_skb ?: skb_peek(head); + skb = outq->retransmit_skb ?: __skb_dequeue(head); if (!skb) return quic_outq_flush(sk); - __skb_unlink(skb, head);
nice change
quic
github_2023
c
5
lxin
lxin
@@ -499,6 +502,9 @@ int quic_crypto_decrypt(struct quic_crypto *crypto, struct sk_buff *skb, u8 *key, *iv, *hp_key; int err; + if (!crypto->recv_ready) + return -EINVAL; + hp_key = crypto->rx_hp_key;
the packets shouldn't arrive here if crypto->recv_ready is false, as in quic_packet_process()/quic_packet_handshake_process(), it will be put into a backlog_list: APP DATA: ``` if (!quic_crypto(sk, QUIC_CRYPTO_APP)->recv_ready) { __skb_queue_tail(&quic_inq(sk)->backlog_list, skb); return 0; } ``` 0-RTT DATA: ``` } else if (type == QUIC_PACKET_0RTT) { level = QUIC_CRYPTO_EARLY; if (!quic_crypto(sk, QUIC_CRYPTO_APP)->recv_ready) { __skb_queue_tail(&quic_inq(sk)->backlog_list, skb); return 0; } ``` and the backlog_list is processed when setting secrets/keys in quic_sock_set_crypto_secret() by userspace: ``` if (!secret->send) { /* recv key is ready */ __skb_queue_head_init(&tmpq); skb_queue_splice_init(&quic_inq(sk)->backlog_list, &tmpq); skb = __skb_dequeue(&tmpq); while (skb) { skb_orphan(skb); if (!quic_hdr(skb)->form) { QUIC_RCV_CB(skb)->number_offset = quic_source(sk)->active->id.len + sizeof(struct quichdr); } QUIC_RCV_CB(skb)->saddr = quic_path_addr(quic_dst(sk)); quic_packet_process(sk, skb); skb = __skb_dequeue(&tmpq); } ``` Note that when processing the backlog_list, if crypto->recv_ready for the corresponding level is still not set, it will be put back into the backlog_list again until the crypto->recv_ready is set for its level. So there's no need to do the crypto->recv_ready check in quic_crypto_decrypt().
quic
github_2023
c
5
lxin
lxin
@@ -474,6 +474,9 @@ int quic_crypto_encrypt(struct quic_crypto *crypto, struct sk_buff *skb, u8 *key, *iv, *hp_key; int err; + if (!crypto->send_ready) + return -EINVAL; +
the design is to dequeue and transmit packets only when crypto->send_ready is set, and the packet shouldn't arrive here if it's not set. The check is in quic_outq_transmit_data(): ``` if (!quic_crypto(sk, level)->send_ready) return; ``` so for APP DATA, it will stay in the sk_write_queue until its crypto send_ready is set. there's no such check in quic_outq_retransmit(), as retransmission happens only after transmission. So there's no need to do the crypto->send_ready check in quic_crypto_encrypt(). 0-RTT triggered this issue in retransmission due to its special handling, see comment in quic_outq_retransmit() below
quic
github_2023
c
5
lxin
lxin
@@ -395,9 +396,11 @@ void quic_outq_retransmit(struct sock *sk) goto next; } - quic_packet_config(sk, snd_cb->level); - quic_packet_tail(sk, skb); - quic_packet_flush(sk); + if (quic_crypto(sk, level)->send_ready) { + quic_packet_config(sk, level); + quic_packet_tail(sk, skb); + quic_packet_flush(sk); + }
0-RTT DATA is special. According to rfc9000: 1. Packets that a client sends with 0-RTT packet protection MUST be acknowledged by the server in packets protected by 1-RTT keys. 2. All 0-RTT and 1-RTT (APP) packets are sharing Application data space (quic_pnmap(sk, QUIC_CRYPTO_APP) in this repo), but they're using different crypto quic_crypto(sk, QUIC_CRYPTO_EARLY) and quic_crypto(sk, QUIC_CRYPTO_APP). To handle this, 0-RTT and 1-RTT DATA are treated the same way when enqueued into sk_write_queue with level QUIC_CRYPTO_APP(its value is 0) in QUIC_SND_CB(skb)->level. But when dequeuing in quic_outq_transmit_data(), it will use the level from `quic_outq(sk)->level` where it's set to QUIC_CRYPTO_EARLY when send_ready of 0-rrt crypto is set, and changed to QUIC_CRYPTO_APP when send_ready of 1-rrt/app crypto is set in quic_sock_set_crypto_secret(): ``` /* send key is ready */ if (secret->level) { /* 0rtt send key is ready */ if (secret->level == QUIC_CRYPTO_EARLY) quic_outq(sk)->level = QUIC_CRYPTO_EARLY; return 0; } /* app send key is ready */ quic_outq(sk)->level = QUIC_CRYPTO_APP; ``` and this 'level' will be used in packet->level to create the QUIC packet in quic_packet_create() as well as quic_packet_handshake_create() where it however uses quic_pnmap(sk, QUIC_CRYPTO_APP) to get packet number for 0-RTT data. Now when retransmitting the 0-RTT DATA, it used the level from QUIC_SND_CB(skb)->level, which is always QUIC_CRYPTO_APP and caused the crash, as crypto send_ready for 1-RTT/QUIC_CRYPTO_APP might not be set yet. The proper fix should be to get the level from `quic_outq(sk)->level` for 0-RTT/APP DATA, the same way as in quic_outq_transmit_data() for 0-RTT DATA: ``` - quic_packet_config(sk, snd_cb->level); + quic_packet_config(sk, (snd_cb->level ?: outq->level)); ``` Can you give it a try? Also, probably worth adding an annotation for the level in quic_outqueue. Thanks.
quic
github_2023
c
5
lxin
lxin
@@ -509,6 +510,7 @@ static struct sk_buff *quic_packet_create(struct sock *sk, struct quic_packet_in continue; } quic_outq_rtx_tail(sk, fskb); + QUIC_SND_CB(fskb)->level = packet->level;
Never change QUIC_SND_CB(fskb)->level once fskb was created. For 0-RTT DATA, it will be ACKed by 1-RTT packet, for which it needs to match both QUIC_SND_CB(fskb)->level and packet_number in quic_outq_retransmit_check(). In fact, here in quic_packet_create() `packet->level` is always QUIC_CRYPTO_APP, in quic_packet_handshake_create(), `level` is always QUIC_CRYPTO_APP, the same as QUIC_SND_CB(fskb)->level for 0-RTT DATA.
quic
github_2023
c
4
lxin
lxin
@@ -1639,18 +1637,18 @@ static void quic_shutdown(struct sock *sk, int how) inet_sk_set_state(sk, QUIC_SS_CLOSED); } -static int quic_ioctl(struct sock *sk, int cmd, int *karg) +static int quic_ioctl(struct sock *sk, int cmd, unsigned long arg) {
I was using the latest upstream kernel, it has been changed to "int (*ioctl)(struct sock *sk, int cmd, int *karg)" in kernel 6.4 in this commit: https://lore.kernel.org/lkml/20230609200010.27991-1-kuniyu@amazon.com/T/ This quic implementation is not in the upstream kernel yet and for now we expect this to be used in old kernels, and also it's difficult to detect ioctl format only by `#if KERNEL_VERSION()` as some release might backport it to their old version kernels. Can you completely revert/delete this ioctl support feature in QUIC in this patch for now? Thanks.
serl_franka_controllers
github_2023
others
1
rail-berkeley
youliangtan
@@ -0,0 +1,115 @@ +cmake_minimum_required(VERSION 3.4) +project(serl_franka_controllers) + +set(CMAKE_BUILD_TYPE Release) +set(CMAKE_CXX_STANDARD 14)
does this work with higher CXXX version (e.g. 17 or 20), for forward compatibility
serl_franka_controllers
github_2023
others
1
rail-berkeley
youliangtan
@@ -0,0 +1,44 @@ +<?xml version="1.0"?> +<package format="2"> + <name>serl_franka_controllers</name> + <version>0.8.0</version> + <description>serl_franka_controllers provides example code for controlling Franka Emika research robots with ros_control</description> + <maintainer email="support@franka.de">Franka Emika GmbH</maintainer> + <license>Apache 2.0</license> + + <url type="website">http://wiki.ros.org/franka_example_controllers</url> + <url type="repository">https://github.com/frankaemika/franka_ros</url> + <url type="bugtracker">https://github.com/frankaemika/franka_ros/issues</url> + <author>Franka Emika GmbH</author>
Clean this, remove unessasary lines. and maybe add the license to this repo too
serl
github_2023
python
65
rail-berkeley
jianlanluo
@@ -223,10 +226,15 @@ def compute_reward(self, obs) -> bool: current_pose = np.hstack([current_pose[:3], euler_angles]) delta = np.abs(current_pose - self._TARGET_POSE) if np.all(delta < self._REWARD_THRESHOLD): - return True + reward = 1 else: # print(f'Goal not reached, the difference is {delta}, the desired threshold is {_REWARD_THRESHOLD}') - return False + reward = 0 + + if gripper_action_effective:
we should make a flag if enabling this reward or not, otherwise it'll apply this thing across the board even you don't need a gripper
serl
github_2023
python
38
rail-berkeley
jianlanluo
@@ -94,3 +94,12 @@ def transform_action(self, action: np.ndarray): action = np.array(action) # in case action is a jax read-only array action[:6] = self.adjoint_matrix @ action[:6] return action + + def transform_action_inv(self, action: np.ndarray): + """
can you add description that this assumes last dimension is gripper open/close?
serl
github_2023
python
38
rail-berkeley
jianlanluo
@@ -49,8 +49,10 @@ raise PermissionError(f"No permission to write to {file_dir}") while success_count < success_needed: - next_obs, rew, done, truncated, info = env.step(action=np.zeros((6,))) - actions = info["intervene_action"] + actions = np.zeros((6,)) + next_obs, rew, done, truncated, info = env.step(action=actions) + if "intervene_action" in info: + actions = info["intervene_action"]
how does this code run correctly without issues previously? if "intervene_action" is None, the previous code always assumes `actions = info["intervene_action"]` and this doesn't throw out errors?
serl
github_2023
python
38
rail-berkeley
jianlanluo
@@ -44,7 +44,7 @@ def step(self, action: np.ndarray): # this is to convert the spacemouse intervention action if "intervene_action" in info: - info["intervene_action"] = self.transform_action(info["intervene_action"]) + info["intervene_action"] = self.transform_action_inv(info["intervene_action"])
same for other function in this class, please indicate in function docstring the leading six dimension are [\delta x, \delta y, ...] last one is gripper open/close (discrete?)
serl
github_2023
python
38
rail-berkeley
jianlanluo
@@ -202,14 +202,17 @@ def action(self, action: np.ndarray) -> np.ndarray: expert_a = np.concatenate((expert_a, gripper_action), axis=0) if time.time() - self.last_intervene < 0.5: - return expert_a + return expert_a, True - return action + return action, False def step(self, action): - new_action = self.action(action) + + new_action, replaced = self.action(action)
`replaced` is always False?
serl
github_2023
python
32
rail-berkeley
youliangtan
@@ -88,13 +91,43 @@ def print_green(x): return print("\033[92m {}\033[00m".format(x)) +SHOULD_PAUSE = False # flag to pause actor/learner agents
For proper impl of this, I would use: ``` from threading import Lock mutex = Lock() ```
serl
github_2023
python
32
rail-berkeley
youliangtan
@@ -88,13 +91,43 @@ def print_green(x): return print("\033[92m {}\033[00m".format(x)) +SHOULD_PAUSE = False # flag to pause actor/learner agents + + +def pause_client(a, b): + """Set flag to pause actor/learner agents at next iteration""" + global SHOULD_PAUSE + SHOULD_PAUSE = True + print("Requested pause training") + + +def on_press(key): + """Callback for when a key is pressed""" + try: + # print(f'{key.char} pressed') + + # chosen a rarely used key to avoid conflicts. this listener is always on, even when the program is not in focus + if key == pynput.keyboard.Key.pause: + print("Pause pressed") + pause_client(None, None) + except AttributeError: + # print(f'{key} pressed') + pass + + +signal.signal(signal.SIGUSR1, pause_client) # enable interrupt signal to pause training +listener = pynput.keyboard.Listener(on_press=on_press) # to enable keyboard based pause
I didnt try it on my pc. can we just have a single keyboard listener for this. It seems that we can simplify the code without having both `pause_client` and `on_press` fn. It would be good to just have a single `on_press_pause` function. Also, what is the exact keyboard key to pause this operation?
serl
github_2023
python
32
rail-berkeley
youliangtan
@@ -92,31 +92,26 @@ def print_green(x): SHOULD_PAUSE = False # flag to pause actor/learner agents +PAUSE_LOCK = threading.Lock()
Oh srry, i meant using [`threading Event`](https://docs.python.org/3/library/threading.html#event-objects), which is easier than having 2 variables. Also, can rename it to `PAUSE_EVENT_FLAG`. Personally i dont like using global, but i think this should be okay since it mainly serves as an example. Thanks
serl
github_2023
python
28
rail-berkeley
youliangtan
@@ -53,13 +54,28 @@ obs = next_obs if done: - print(rew) success_count += rew + total_count += 1 + print( + f"{rew}\tGot {success_count} successes of {total_count} trials. {success_needed} successes needed." + ) pbar.update(rew) obs, _ = env.reset() uuid = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") - file_name = f"./bc_demos/pcb_insert_{success_needed}_demos_{uuid}.pkl" - with open(file_name, "wb") as f: - pkl.dump(transitions, f) - print(f"saved {success_needed} demos to {file_name}") + file_name = f"./pcb_insert_{success_needed}_demos_{uuid}.pkl"
Is it easier if we check the dir exists beforehand? else create the dir if it doesnt exist. something like ```py if os.path.exists(DATA_DIRECTORY): shutil.rmtree(DATA_DIRECTORY) os.makedirs(DATA_DIRECTORY) ```
serl
github_2023
python
23
rail-berkeley
jianlanluo
@@ -0,0 +1,21 @@ +""" Test the spacemouse output. """ + +import time +import numpy as np +from serl_robot_infra.franka_env.spacemouse.spacemouse_expert import SpaceMouseExpert +np.set_printoptions(precision=3, suppress=True)
can you move this to test_spacemouse() ? this should be only locally valid
serl
github_2023
python
23
rail-berkeley
jianlanluo
@@ -0,0 +1,21 @@ +""" Test the spacemouse output. """ + +import time +import numpy as np +from serl_robot_infra.franka_env.spacemouse.spacemouse_expert import SpaceMouseExpert +np.set_printoptions(precision=3, suppress=True) + +def test_spacemouse(): + """ Test the SpaceMouseExpert class. """
can you add detailed descriptions?
serl
github_2023
python
23
rail-berkeley
jianlanluo
@@ -0,0 +1,33 @@ +""" Test the spacemouse output. """ + + +def test_spacemouse(): + """Test the SpaceMouseExpert class. + + This interactive test prints the action and buttons of the spacemouse at a rate of 10Hz. + The user is expected to move the spacemouse and press its buttons while the test is running. + It keeps running until the user stops it. + + """ + import time + import numpy as np
import should be on top of the file
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100:
this is assume 10HZ, so 10s ? probably don't use this hardcoding
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100: + break + + # Stop joint controller + print("RESET DONE") + self.j.terminate() + time.sleep(1) + self.clear() + print("KILLED JOINT RESET", self.pos) + + # Restart impedece controller + self.start_impedence() + print("IMPEDENCE STARTED") + + def move(self, pose): + msg = geom_msg.PoseStamped() + msg.header.frame_id = "0" + msg.header.stamp = rospy.Time.now() + msg.pose.position = geom_msg.Point(pose[0], pose[1], pose[2]) + msg.pose.orientation = geom_msg.Quaternion(pose[3], pose[4], pose[5], pose[6]) + self.eepub.publish(msg) + + def open(self): + pass + + def close(self): + pass + + def activate_gripper(self): + pass + + def reset_gripper(self): + pass + +class FrankaGripperServer(RobotServer): + def __init__(self): + super().__init__() + self.grippermovepub = rospy.Publisher( + "/franka_gripper/move/goal", MoveActionGoal, queue_size=1 + ) + self.grippergrasppub = rospy.Publisher( + "/franka_gripper/grasp/goal", GraspActionGoal, queue_size=1 + ) + self.gripper_sub = rospy.Subscriber( + "/franka_gripper/joint_states", JointState, self.update_gripper + ) + + def open(self): + msg = MoveActionGoal() + msg.goal.width = 0.09 + msg.goal.speed = 0.3 + self.grippermovepub.publish(msg) + + def close(self): + msg = GraspActionGoal() + msg.goal.width = 0.01 + msg.goal.speed = 0.3 + msg.goal.epsilon.inner = 1 + msg.goal.epsilon.outer = 1 + msg.goal.force = 130 + self.grippergrasppub.publish(msg) + + def update_gripper(self, msg): + self.gripper_dist = np.sum(msg.position) + +class RobotiqServer(RobotServer): + def __init__(self): + super().__init__() + self.gripper = subprocess.Popen( + [ + "rosrun", + "robotiq_2f_gripper_control", + "Robotiq2FGripperTcpNode.py", + GRIPPER_IP, + ], + stdout=subprocess.PIPE, + ) + self.gripperpub = rospy.Publisher( + "Robotiq2FGripperRobotOutput", outputMsg.Robotiq2FGripper_robot_output, queue_size=1 + ) + self.gripper_command = outputMsg.Robotiq2FGripper_robot_output() + + def generate_gripper_command(self, char, command): + """Update the gripper command according to the character entered by the user.""" + if char == "a": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 1 + command.rGTO = 1 + command.rSP = 255 + command.rFR = 150 + + if char == "r": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 0 + + if char == "c": + command.rPR = 255 + + if char == "o": + command.rPR = 0 + + # If the command entered is a int, assign this value to rPR + # (i.e., move to this position) + try: + command.rPR = int(char) + if command.rPR > 255: + command.rPR = 255 + if command.rPR < 0: + command.rPR = 0 + except ValueError: + pass + return command + + def activate_gripper(self): + self.gripper_command = self.generate_gripper_command("a", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def reset_gripper(self): + self.gripper_command = self.generate_gripper_command("r", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + self.activate_gripper() + + def open(self): + self.gripper_command = self.generate_gripper_command("o", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def close(self): + self.gripper_command = self.generate_gripper_command("c", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def update_gripper(self, msg): + raise NotImplementedError("Not implemented for Robotiq Gripper") + + + +try: + roscore = subprocess.Popen("roscore") + time.sleep(1) +except: + pass + +"""Starts Impedence controller""" +if GRIPPER_TYPE == "Franka": + l = FrankaGripperServer()
change the variable name to make it more informative
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100: + break + + # Stop joint controller + print("RESET DONE") + self.j.terminate() + time.sleep(1) + self.clear() + print("KILLED JOINT RESET", self.pos) + + # Restart impedece controller + self.start_impedence() + print("IMPEDENCE STARTED") + + def move(self, pose): + msg = geom_msg.PoseStamped() + msg.header.frame_id = "0" + msg.header.stamp = rospy.Time.now() + msg.pose.position = geom_msg.Point(pose[0], pose[1], pose[2]) + msg.pose.orientation = geom_msg.Quaternion(pose[3], pose[4], pose[5], pose[6]) + self.eepub.publish(msg) + + def open(self): + pass + + def close(self): + pass + + def activate_gripper(self): + pass + + def reset_gripper(self): + pass + +class FrankaGripperServer(RobotServer): + def __init__(self): + super().__init__() + self.grippermovepub = rospy.Publisher( + "/franka_gripper/move/goal", MoveActionGoal, queue_size=1 + ) + self.grippergrasppub = rospy.Publisher( + "/franka_gripper/grasp/goal", GraspActionGoal, queue_size=1 + ) + self.gripper_sub = rospy.Subscriber( + "/franka_gripper/joint_states", JointState, self.update_gripper + ) + + def open(self): + msg = MoveActionGoal() + msg.goal.width = 0.09 + msg.goal.speed = 0.3 + self.grippermovepub.publish(msg) + + def close(self): + msg = GraspActionGoal() + msg.goal.width = 0.01 + msg.goal.speed = 0.3 + msg.goal.epsilon.inner = 1 + msg.goal.epsilon.outer = 1 + msg.goal.force = 130 + self.grippergrasppub.publish(msg) + + def update_gripper(self, msg): + self.gripper_dist = np.sum(msg.position) + +class RobotiqServer(RobotServer): + def __init__(self): + super().__init__() + self.gripper = subprocess.Popen( + [ + "rosrun", + "robotiq_2f_gripper_control", + "Robotiq2FGripperTcpNode.py", + GRIPPER_IP, + ], + stdout=subprocess.PIPE, + ) + self.gripperpub = rospy.Publisher( + "Robotiq2FGripperRobotOutput", outputMsg.Robotiq2FGripper_robot_output, queue_size=1 + ) + self.gripper_command = outputMsg.Robotiq2FGripper_robot_output() + + def generate_gripper_command(self, char, command): + """Update the gripper command according to the character entered by the user.""" + if char == "a": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 1 + command.rGTO = 1 + command.rSP = 255 + command.rFR = 150 + + if char == "r": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 0 + + if char == "c": + command.rPR = 255 + + if char == "o": + command.rPR = 0 + + # If the command entered is a int, assign this value to rPR + # (i.e., move to this position) + try: + command.rPR = int(char) + if command.rPR > 255: + command.rPR = 255 + if command.rPR < 0: + command.rPR = 0 + except ValueError: + pass + return command + + def activate_gripper(self): + self.gripper_command = self.generate_gripper_command("a", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def reset_gripper(self): + self.gripper_command = self.generate_gripper_command("r", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + self.activate_gripper() + + def open(self): + self.gripper_command = self.generate_gripper_command("o", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def close(self): + self.gripper_command = self.generate_gripper_command("c", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def update_gripper(self, msg): + raise NotImplementedError("Not implemented for Robotiq Gripper") + + + +try: + roscore = subprocess.Popen("roscore") + time.sleep(1) +except: + pass + +"""Starts Impedence controller""" +if GRIPPER_TYPE == "Franka": + l = FrankaGripperServer() +elif GRIPPER_TYPE == "Robotiq": + l = RobotiqServer() +elif GRIPPER_TYPE == "None": + l = RobotServer() +else: + raise NotImplementedError("Gripper Type Not Implemented") + +l.start_impedence() +rospy.init_node("franka_control_api") + +## Defines the ros topics to publish to +client = Client( + "/cartesian_impedance_controllerdynamic_reconfigure_compliance_param_node" +) +
can you reorganize this block of code ? make it a function and move to main >?
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100: + break + + # Stop joint controller + print("RESET DONE") + self.j.terminate() + time.sleep(1) + self.clear() + print("KILLED JOINT RESET", self.pos) + + # Restart impedece controller + self.start_impedence() + print("IMPEDENCE STARTED") + + def move(self, pose): + msg = geom_msg.PoseStamped() + msg.header.frame_id = "0" + msg.header.stamp = rospy.Time.now() + msg.pose.position = geom_msg.Point(pose[0], pose[1], pose[2]) + msg.pose.orientation = geom_msg.Quaternion(pose[3], pose[4], pose[5], pose[6]) + self.eepub.publish(msg) + + def open(self): + pass + + def close(self): + pass + + def activate_gripper(self): + pass + + def reset_gripper(self): + pass + +class FrankaGripperServer(RobotServer): + def __init__(self): + super().__init__() + self.grippermovepub = rospy.Publisher( + "/franka_gripper/move/goal", MoveActionGoal, queue_size=1 + ) + self.grippergrasppub = rospy.Publisher( + "/franka_gripper/grasp/goal", GraspActionGoal, queue_size=1 + ) + self.gripper_sub = rospy.Subscriber( + "/franka_gripper/joint_states", JointState, self.update_gripper + ) + + def open(self): + msg = MoveActionGoal() + msg.goal.width = 0.09 + msg.goal.speed = 0.3 + self.grippermovepub.publish(msg) + + def close(self): + msg = GraspActionGoal() + msg.goal.width = 0.01 + msg.goal.speed = 0.3 + msg.goal.epsilon.inner = 1 + msg.goal.epsilon.outer = 1 + msg.goal.force = 130 + self.grippergrasppub.publish(msg) + + def update_gripper(self, msg): + self.gripper_dist = np.sum(msg.position) + +class RobotiqServer(RobotServer): + def __init__(self): + super().__init__() + self.gripper = subprocess.Popen( + [ + "rosrun", + "robotiq_2f_gripper_control", + "Robotiq2FGripperTcpNode.py", + GRIPPER_IP, + ], + stdout=subprocess.PIPE, + ) + self.gripperpub = rospy.Publisher( + "Robotiq2FGripperRobotOutput", outputMsg.Robotiq2FGripper_robot_output, queue_size=1 + ) + self.gripper_command = outputMsg.Robotiq2FGripper_robot_output() + + def generate_gripper_command(self, char, command): + """Update the gripper command according to the character entered by the user.""" + if char == "a": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 1 + command.rGTO = 1 + command.rSP = 255 + command.rFR = 150 + + if char == "r": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 0 + + if char == "c": + command.rPR = 255 + + if char == "o": + command.rPR = 0 + + # If the command entered is a int, assign this value to rPR + # (i.e., move to this position) + try: + command.rPR = int(char) + if command.rPR > 255: + command.rPR = 255 + if command.rPR < 0: + command.rPR = 0 + except ValueError: + pass + return command + + def activate_gripper(self): + self.gripper_command = self.generate_gripper_command("a", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def reset_gripper(self): + self.gripper_command = self.generate_gripper_command("r", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + self.activate_gripper() + + def open(self): + self.gripper_command = self.generate_gripper_command("o", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def close(self): + self.gripper_command = self.generate_gripper_command("c", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def update_gripper(self, msg): + raise NotImplementedError("Not implemented for Robotiq Gripper") + + + +try: + roscore = subprocess.Popen("roscore") + time.sleep(1) +except: + pass + +"""Starts Impedence controller""" +if GRIPPER_TYPE == "Franka": + l = FrankaGripperServer() +elif GRIPPER_TYPE == "Robotiq": + l = RobotiqServer() +elif GRIPPER_TYPE == "None": + l = RobotServer() +else: + raise NotImplementedError("Gripper Type Not Implemented") + +l.start_impedence() +rospy.init_node("franka_control_api") + +## Defines the ros topics to publish to +client = Client( + "/cartesian_impedance_controllerdynamic_reconfigure_compliance_param_node" +) + +## Route for Starting Impedence +@app.route("/startimp", methods=["POST"]) +def si(): + l.clear() + l.start_impedence() + return "Started Impedence" + +## Route for Stopping Impedence +@app.route("/stopimp", methods=["POST"]) +def sti(): + l.stop_impedence() + return "Stopped Impedence" + +## Route for getting pose +@app.route("/getpos", methods=["POST"]) +def gp(): + return jsonify({"pose": np.array(l.pos).tolist()}) + +## Route for getting velocity +@app.route("/getvel", methods=["POST"]) +def gv(): + return jsonify({"vel": np.array(l.vel).tolist()}) + +## Route for getting force +@app.route("/getforce", methods=["POST"]) +def gf(): + return jsonify({"force": np.array(l.force).tolist()}) + +## Route for getting torque +@app.route("/gettorque", methods=["POST"]) +def gt(): + return jsonify({"torque": np.array(l.torque).tolist()}) + +## Route for getting joint angles +@app.route("/getq", methods=["POST"]) +def gq(): + return jsonify({"q": np.array(l.q).tolist()}) + +## Route for getting joint velocities +@app.route("/getdq", methods=["POST"]) +def gdq(): + return jsonify({"dq": np.array(l.dq).tolist()}) + +## Route for getting jacobian +@app.route("/getjacobian", methods=["POST"]) +def gj(): + return jsonify({"jacobian": np.array(l.jacobian).tolist()}) + +## Route for getting gripper distance +@app.route("/getgripper", methods=["POST"]) +def gg(): + return jsonify({"gripper": l.gripper_dist}) + +## Route for getting all state information +@app.route("/getstate", methods=["POST"]) +def gs(): + return jsonify( + { + "pose": np.array(l.pos).tolist(), + "vel": np.array(l.vel).tolist(), + "force": np.array(l.force).tolist(), + "torque": np.array(l.torque).tolist(), + "q": np.array(l.q).tolist(), + "dq": np.array(l.dq).tolist(), + "jacobian": np.array(l.jacobian).tolist(), + "gripper": l.gripper_dist, + } + ) + +## Route for running joint reset +@app.route("/jointreset", methods=["POST"]) +def jr(): + l.clear() + l.reset_joint() + return "Reset Joint" + +##Route for activating the Robotiq gripper +@app.route("/activate_gripper", methods=["POST"]) +def activate_gripper(): + print("activate gripper") + l.activate_gripper() + return "Activated" + +## Route for resetting the Robotiq gripper. It will reset and activate the gripper +@app.route("/reset_gripper", methods=["POST"]) +def reset_gripper(): + print("reset gripper") + l.reset_gripper() + return "Reset" + +## Route for closing the gripper +@app.route("/close", methods=["POST"]) +def closed(): + print("close") + l.close() + return "Closed" + +## Route for opening the gripper +@app.route("/open", methods=["POST"]) +def open(): + print("open") + l.open() + return "Opened" + + +## Route for clearing errors (communcation constraints, etc.) +@app.route("/clearerr", methods=["POST"]) +def clear(): + l.clear() + return "Clear" + + +## Route for sending a pose command +@app.route("/pose", methods=["POST"]) +def pose(): + pos = np.array(request.json["arr"]) + print("Moving to", pos) + l.move(pos) + return "Moved" + + +## Route for increasing controller gain +@app.route("/precision_mode", methods=["POST"]) +def precision_mode(): + client.update_configuration({"translational_Ki": 30}) + client.update_configuration({"rotational_Ki": 10}) + for direction in ["x", "y", "z", "neg_x", "neg_y", "neg_z"]: + client.update_configuration({"translational_clip_" + direction: 0.1}) + client.update_configuration({"rotational_clip" + direction: 0.1}) + return "Precision" + +## Route for decreasing controller gain +@app.route("/compliance_mode", methods=["POST"]) +def compliance_mode(): + client.update_configuration({"translational_Ki": 10}) + client.update_configuration({"rotational_Ki": 0}) + for direction in ["x", "y", "z", "neg_x", "neg_y", "neg_z"]: + client.update_configuration({"translational_clip" + direction: 0.007}) + client.update_configuration({"rotational_clip" + direction: 0.04}) + return "Compliance" +
are these even used ? delete if not used
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,300 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class BinPickEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.44, -0.12, 0.04)), np.array((0.53, 0.12, 0.1)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + # np.array((np.pi-0.001, 0-0.001, np.pi/4)), + # np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + np.array((np.pi-0.001, 0-0.001, 0-0.01)), + np.array((np.pi+0.001, 0+0.001, 0+0.01)), + dtype=np.float64, + ) + self.inner_box = gym.spaces.Box( + np.array([0.44, -0.04, 0.04]), + np.array([0.53, 0.04, 0.08]), + dtype=np.float64 + ) + self.drop_box = gym.spaces.Box( + np.array([0.44, -0.04]), + np.array([0.53, 0.04]), + dtype=np.float64 + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.03, -0.03, -0.03, -0.05, -0.05, -0.2, -1)), + np.array((0.03, 0.03, 0.03, 0.05, 0.05, 0.2, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + self.centerpos = copy.deepcopy(self.resetpos) + self.centerpos[:3] = np.mean((self.xyz_bounding_box.high, self.xyz_bounding_box.low), axis=0) #np.array([0.55,-0.05,0.09]) + self.centerpos[2] += 0.01 + self.resetpos = copy.deepcopy(self.centerpos) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0., 0) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.13 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 +
rewrite this function 1) make timeout an argument 2) make required precision an argument
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,300 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class BinPickEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.44, -0.12, 0.04)), np.array((0.53, 0.12, 0.1)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + # np.array((np.pi-0.001, 0-0.001, np.pi/4)), + # np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + np.array((np.pi-0.001, 0-0.001, 0-0.01)), + np.array((np.pi+0.001, 0+0.001, 0+0.01)), + dtype=np.float64, + ) + self.inner_box = gym.spaces.Box( + np.array([0.44, -0.04, 0.04]), + np.array([0.53, 0.04, 0.08]), + dtype=np.float64 + ) + self.drop_box = gym.spaces.Box( + np.array([0.44, -0.04]), + np.array([0.53, 0.04]), + dtype=np.float64 + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.03, -0.03, -0.03, -0.05, -0.05, -0.2, -1)), + np.array((0.03, 0.03, 0.03, 0.05, 0.05, 0.2, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + self.centerpos = copy.deepcopy(self.resetpos) + self.centerpos[:3] = np.mean((self.xyz_bounding_box.high, self.xyz_bounding_box.low), axis=0) #np.array([0.55,-0.05,0.09]) + self.centerpos[2] += 0.01 + self.resetpos = copy.deepcopy(self.centerpos) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0., 0) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.13 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + if key == 'wrist_1': + # cropped_rgb = rgb[ 100:400, 50:350, :] + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 200:500, :] #150:450 + cropped_rgb = rgb[:, 80:560, :] + # if key == 'side_1': + # cropped_rgb = rgb[150:330, 230:410, :] + + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + # cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + elif key == 'side_1': + cap = RSCapture(name='side_1', serial_number='128422272758', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap)
make this configurable
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,300 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class BinPickEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.44, -0.12, 0.04)), np.array((0.53, 0.12, 0.1)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + # np.array((np.pi-0.001, 0-0.001, np.pi/4)), + # np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + np.array((np.pi-0.001, 0-0.001, 0-0.01)), + np.array((np.pi+0.001, 0+0.001, 0+0.01)), + dtype=np.float64, + ) + self.inner_box = gym.spaces.Box( + np.array([0.44, -0.04, 0.04]), + np.array([0.53, 0.04, 0.08]), + dtype=np.float64 + ) + self.drop_box = gym.spaces.Box( + np.array([0.44, -0.04]), + np.array([0.53, 0.04]), + dtype=np.float64 + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.03, -0.03, -0.03, -0.05, -0.05, -0.2, -1)), + np.array((0.03, 0.03, 0.03, 0.05, 0.05, 0.2, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + self.centerpos = copy.deepcopy(self.resetpos) + self.centerpos[:3] = np.mean((self.xyz_bounding_box.high, self.xyz_bounding_box.low), axis=0) #np.array([0.55,-0.05,0.09]) + self.centerpos[2] += 0.01 + self.resetpos = copy.deepcopy(self.centerpos) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0., 0) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.13 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + if key == 'wrist_1': + # cropped_rgb = rgb[ 100:400, 50:350, :] + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 200:500, :] #150:450 + cropped_rgb = rgb[:, 80:560, :] + # if key == 'side_1': + # cropped_rgb = rgb[150:330, 230:410, :] + + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + # cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + elif key == 'side_1': + cap = RSCapture(name='side_1', serial_number='128422272758', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap) + return self.get_im() + + self.img_queue.put(images) + return images + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + # Clip xyz to inner box
rewrite , removing hardcoding
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,300 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class BinPickEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.44, -0.12, 0.04)), np.array((0.53, 0.12, 0.1)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + # np.array((np.pi-0.001, 0-0.001, np.pi/4)), + # np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + np.array((np.pi-0.001, 0-0.001, 0-0.01)), + np.array((np.pi+0.001, 0+0.001, 0+0.01)), + dtype=np.float64, + ) + self.inner_box = gym.spaces.Box( + np.array([0.44, -0.04, 0.04]), + np.array([0.53, 0.04, 0.08]), + dtype=np.float64 + ) + self.drop_box = gym.spaces.Box( + np.array([0.44, -0.04]), + np.array([0.53, 0.04]), + dtype=np.float64 + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.03, -0.03, -0.03, -0.05, -0.05, -0.2, -1)), + np.array((0.03, 0.03, 0.03, 0.05, 0.05, 0.2, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + self.centerpos = copy.deepcopy(self.resetpos) + self.centerpos[:3] = np.mean((self.xyz_bounding_box.high, self.xyz_bounding_box.low), axis=0) #np.array([0.55,-0.05,0.09]) + self.centerpos[2] += 0.01 + self.resetpos = copy.deepcopy(self.centerpos) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0., 0) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.13 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + if key == 'wrist_1': + # cropped_rgb = rgb[ 100:400, 50:350, :] + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 200:500, :] #150:450 + cropped_rgb = rgb[:, 80:560, :] + # if key == 'side_1': + # cropped_rgb = rgb[150:330, 230:410, :] + + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + # cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + elif key == 'side_1': + cap = RSCapture(name='side_1', serial_number='128422272758', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap) + return self.get_im() + + self.img_queue.put(images) + return images + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + # Clip xyz to inner box + if self.inner_box.contains(pose[:3]): + print(f'Command: {pose[:3]}') + pose[:3] = self.intersect_line_bbox(self.currpos[:3], pose[:3], self.inner_box.low, self.inner_box.high) + print(f'Clipped: {pose[:3]}') + + return pose + + def intersect_line_bbox(self, p1, p2, bbox_min, bbox_max): + # Define the parameterized line segment + # P(t) = p1 + t(p2 - p1) + tmin = 0 + tmax = 1 + + for i in range(3): + if p1[i] < bbox_min[i] and p2[i] < bbox_min[i]: + return None + if p1[i] > bbox_max[i] and p2[i] > bbox_max[i]: + return None + + # For each axis (x, y, z), compute t values at the intersection points + if abs(p2[i] - p1[i]) > 1e-10: # To prevent division by zero + t1 = (bbox_min[i] - p1[i]) / (p2[i] - p1[i]) + t2 = (bbox_max[i] - p1[i]) / (p2[i] - p1[i]) + + # Ensure t1 is smaller than t2 + if t1 > t2: + t1, t2 = t2, t1 + + tmin = max(tmin, t1) + tmax = min(tmax, t2) + + if tmin > tmax: + return None + + # Compute the intersection point using the t value + intersection = p1 + tmin * (p2 - p1) +
is this even used after UR5 cable routing ?
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,300 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class BinPickEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.44, -0.12, 0.04)), np.array((0.53, 0.12, 0.1)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + # np.array((np.pi-0.001, 0-0.001, np.pi/4)), + # np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + np.array((np.pi-0.001, 0-0.001, 0-0.01)), + np.array((np.pi+0.001, 0+0.001, 0+0.01)), + dtype=np.float64, + ) + self.inner_box = gym.spaces.Box( + np.array([0.44, -0.04, 0.04]), + np.array([0.53, 0.04, 0.08]), + dtype=np.float64 + ) + self.drop_box = gym.spaces.Box( + np.array([0.44, -0.04]), + np.array([0.53, 0.04]), + dtype=np.float64 + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.03, -0.03, -0.03, -0.05, -0.05, -0.2, -1)), + np.array((0.03, 0.03, 0.03, 0.05, 0.05, 0.2, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + self.centerpos = copy.deepcopy(self.resetpos) + self.centerpos[:3] = np.mean((self.xyz_bounding_box.high, self.xyz_bounding_box.low), axis=0) #np.array([0.55,-0.05,0.09]) + self.centerpos[2] += 0.01 + self.resetpos = copy.deepcopy(self.centerpos) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0., 0) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.13 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + if key == 'wrist_1': + # cropped_rgb = rgb[ 100:400, 50:350, :] + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 200:500, :] #150:450 + cropped_rgb = rgb[:, 80:560, :] + # if key == 'side_1': + # cropped_rgb = rgb[150:330, 230:410, :] + + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + # cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + elif key == 'side_1': + cap = RSCapture(name='side_1', serial_number='128422272758', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap) + return self.get_im() + + self.img_queue.put(images) + return images + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + # Clip xyz to inner box + if self.inner_box.contains(pose[:3]): + print(f'Command: {pose[:3]}') + pose[:3] = self.intersect_line_bbox(self.currpos[:3], pose[:3], self.inner_box.low, self.inner_box.high) + print(f'Clipped: {pose[:3]}') + + return pose + + def intersect_line_bbox(self, p1, p2, bbox_min, bbox_max): + # Define the parameterized line segment + # P(t) = p1 + t(p2 - p1) + tmin = 0 + tmax = 1 + + for i in range(3): + if p1[i] < bbox_min[i] and p2[i] < bbox_min[i]: + return None + if p1[i] > bbox_max[i] and p2[i] > bbox_max[i]: + return None + + # For each axis (x, y, z), compute t values at the intersection points + if abs(p2[i] - p1[i]) > 1e-10: # To prevent division by zero + t1 = (bbox_min[i] - p1[i]) / (p2[i] - p1[i]) + t2 = (bbox_max[i] - p1[i]) / (p2[i] - p1[i]) + + # Ensure t1 is smaller than t2 + if t1 > t2: + t1, t2 = t2, t1 + + tmin = max(tmin, t1) + tmax = min(tmax, t2) + + if tmin > tmax: + return None + + # Compute the intersection point using the t value + intersection = p1 + tmin * (p2 - p1) + + return intersection + + def step(self, action): + start_time = time.time() + action = np.clip(action, self.action_space.low, self.action_space.high) + if self.actionnoise > 0: + a = action[:3] + np.random.uniform( + -self.actionnoise, self.actionnoise, (3,) + ) + else: + a = action[:3] + + self.nextpos = self.currpos.copy() + self.nextpos[:3] = self.nextpos[:3] + a + + ### GET ORIENTATION FROM ACTION + self.nextpos[3:] = ( + Rotation.from_euler("xyz", action[3:6]) + * Rotation.from_quat(self.currpos[3:]) + ).as_quat() + + gripper = action[-1] + if gripper > 0: + if not self.drop_box.contains(self.currpos[:2]): + gripper = (self.currgrip + 1) % 2 + self.set_gripper(gripper) + + self._send_pos_command(self.clip_safety_box(self.nextpos)) + + self.curr_path_length += 1 + dl = time.time() - start_time + + time.sleep(max(0, (1.0 / self.hz) - dl)) + + self.update_currpos() + ob = self._get_obs() + obs_xyz = ob['state_observation']['tcp_pose'][:3] + obs_rpy = ob['state_observation']['tcp_pose'][3:] + reward = 0 + done = self.curr_path_length >= 40 #100 + # if not self.xyz_bounding_box.contains(obs_xyz) or not self.rpy_bounding_box.contains(obs_rpy): + # # print('Truncated: Bouding Box') + # print("xyz: ", self.xyz_bounding_box.contains(obs_xyz), obs_xyz) + # print("rortate: ", self.rpy_bounding_box.contains(obs_rpy), obs_rpy) + # return ob, 0, True, True, {} + return ob, int(reward), done, done, {} + + def reset(self, jpos=False, gripper=None, require_input=False):
clean up
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,247 @@ +import gym +from gym import spaces +import numpy as np +from franka_robotiq_env import FrankaRobotiq +import time +from scipy.spatial.transform import Rotation +import requests +import copy +import cv2 +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue + +class RouteCableEnv(FrankaRobotiq): + def __init__(self): + super().__init__() + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.51, -0.1, 0.04)), np.array((0.59, 0, 0.12)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi-0.001, 0-0.001, np.pi/4)), + np.array((np.pi+0.001, 0+0.001, 3*np.pi/4)), + dtype=np.float64, + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.02, -0.02, -0.02, -0.05, -0.05, -0.1, -1)), + np.array((0.02, 0.02, 0.02, 0.05, 0.05, 0.1, 1)), + ) + # enable gripper in observation space + self.observation_space['state_observation']['gripper_pose'] = spaces.Box(-np.inf, np.inf, shape=(1,)) + # [0.48012088982197254,-0.07218941280725254,0.11078303293108258,0.6995269546628874,0.7134059993136379,0.028532587996196627,0.029996854262000595] + self.resetpos[:3] = np.array([0.55,-0.05,0.09]) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0.03, np.pi/2) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.15 #cable + dp = restp_new - self.currpos + + height = np.zeros_like(self.resetpos) + height[2] = 0.02 + while count < 10: + self._send_pos_command(self.currpos + height) + time.sleep(0.1) + self.update_currpos() + count += 1 + + count = 0 + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50
same redo this function
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,130 @@ +import gym +from gym import spaces +import numpy as np +# from franka.scripts.spacemouse_teleop import SpaceMouseExpert +import time +from franka_robotiq_env import FrankaRobotiq +import copy +import requests + +class PCBEnv(FrankaRobotiq): + def __init__(self): + + super().__init__() + self._TARGET_POSE = [0.6479450830785974,0.17181947852969695,0.056419218166284224, 3.1415, 0.0, 0.0 ] + self._REWARD_THRESHOLD = [0.005, 0.005, 0.0006, 0.03, 0.03, 0.05] + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + self.action_space = gym.spaces.Box( + np.array((-0.01, -0.01, -0.01, -0.05, -0.05, -0.05)), + np.array((0.01, 0.01, 0.01, 0.05, 0.05, 0.05)) + ) + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.62, 0.15, 0.03)), + np.array((0.67, 0.19, 0.09)), + dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi-0.15, -0.05, -0.1)), + np.array((np.pi+0.1, 0.15, 0.1)), + dtype=np.float64 + ) + self.resetpos[:3] = np.array([0.645, 0.17, 0.07]) + self.resetpos[3:] = self.euler_2_quat(np.pi, 0.03, 0) + self.episodes = 1 + self.randomreset = False + + def _get_state(self): + state = super()._get_state() + state.pop('gripper_pose') + return state + + def go_to_rest(self, jpos=False): + count = 0 + if self.currpos[2] < 0.06: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] += 0.02 + dp = restp_new - self.currpos + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.2 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET")
if reset / get img was called across all envs, should make another file, and import those from that file in env.py
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,267 @@ +import time +from gym import Env, spaces +import gym +import numpy as np +from gym.spaces import Box +import copy +from robot_infra.spacemouse.spacemouse_teleop import SpaceMouseExpert +from scipy.spatial.transform import Rotation as R + + +class ProxyEnv(Env): + def __init__(self, wrapped_env): + self._wrapped_env = wrapped_env + self.action_space = self._wrapped_env.action_space + self.observation_space = self._wrapped_env.observation_space + + @property + def wrapped_env(self): + return self._wrapped_env + + def reset(self, **kwargs): + return self._wrapped_env.reset(**kwargs) + + def step(self, action): + return self._wrapped_env.step(action) + + def render(self, *args, **kwargs): + return self._wrapped_env.render(*args, **kwargs) + + @property + def horizon(self): + return self._wrapped_env.horizon + + def terminate(self): + if hasattr(self.wrapped_env, "terminate"): + self.wrapped_env.terminate() + + def seed(self, _seed): + return self.wrapped_env.seed(_seed) + + def __getattr__(self, attr): + if attr == '_wrapped_env': + raise AttributeError() + if attr == 'planner': + return self._planner + if attr == 'set_vf': + return self.set_vf + return getattr(self._wrapped_env, attr) + # try: + # getattr(self, attr) + # except Exception: + # return getattr(self._wrapped_env, attr) + + def __getstate__(self): + """ + This is useful to override in case the wrapped env has some funky + __getstate__ that doesn't play well with overriding __getattr__. + + The main problematic case is/was gym's EzPickle serialization scheme. + :return: + """ + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __str__(self): + return '{}({})'.format(type(self).__name__, self.wrapped_env) + +class GripperCloseEnv(ProxyEnv): + def __init__( + self, + env, + ): + ProxyEnv.__init__(self, env) + ub = self._wrapped_env.action_space + assert ub.shape == (7,) + self.action_space = Box(ub.low[:6], ub.high[:6]) + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + + def step(self, action): + a = np.zeros(self._wrapped_env.action_space.shape) + a[:6] = copy.deepcopy(action) + a[6] = 1 + return self._wrapped_env.step(a) + +class SpacemouseIntervention(ProxyEnv): + def __init__(self, env, gripper_enabled=False): + ProxyEnv.__init__(self, env) + self._wrapped_env = env + self.action_space = self._wrapped_env.action_space + self.gripper_enabled = gripper_enabled + if self.gripper_enabled: + assert self.action_space.shape == (7,) # maybe not so elegant + self.observation_space = self._wrapped_env.observation_space + self.expert = SpaceMouseExpert( + xyz_dims=3, + xyz_remap=[0, 1, 2], + xyz_scale=200, + rot_scale=200, + all_angles=True + ) + self.last_intervene = 0 + + def expert_action(self, action): + ''' + Input: + - action: policy action + Output: + - action: spacemouse action if nonezero; else, policy action + ''' + controller_a, _, left, right = self.expert.get_action() + expert_a = np.zeros((6,)) + if self.gripper_enabled: + expert_a = np.zeros((7,)) + expert_a[-1] = np.random.uniform(-1, 0) + + expert_a[:3] = controller_a[:3] # XYZ + expert_a[3] = controller_a[4] # Roll + expert_a[4] = controller_a[5] # Pitch + expert_a[5] = -controller_a[6] # Yaw + + if self.gripper_enabled: + if left: + expert_a[6] = np.random.uniform(0, 1) + self.last_intervene = time.time() + + if np.linalg.norm(expert_a[:6]) > 0.001: + self.last_intervene = time.time() + else: + if np.linalg.norm(expert_a) > 0.001: + self.last_intervene = time.time() + + if time.time() - self.last_intervene < 0.5: + return expert_a, left, right + return action, left, right + + def step(self, action): + expert_action, left, right = self.expert_action(action) + o, r, done, truncated, env_info = self._wrapped_env.step(expert_action) + env_info['expert_action'] = expert_action + env_info['right'] = right + return o, r, done, truncated, env_info +
clean up
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,267 @@ +import time +from gym import Env, spaces +import gym +import numpy as np +from gym.spaces import Box +import copy +from robot_infra.spacemouse.spacemouse_teleop import SpaceMouseExpert +from scipy.spatial.transform import Rotation as R + + +class ProxyEnv(Env): + def __init__(self, wrapped_env): + self._wrapped_env = wrapped_env + self.action_space = self._wrapped_env.action_space + self.observation_space = self._wrapped_env.observation_space + + @property + def wrapped_env(self): + return self._wrapped_env + + def reset(self, **kwargs): + return self._wrapped_env.reset(**kwargs) + + def step(self, action): + return self._wrapped_env.step(action) + + def render(self, *args, **kwargs): + return self._wrapped_env.render(*args, **kwargs) + + @property + def horizon(self): + return self._wrapped_env.horizon + + def terminate(self): + if hasattr(self.wrapped_env, "terminate"): + self.wrapped_env.terminate() + + def seed(self, _seed): + return self.wrapped_env.seed(_seed) + + def __getattr__(self, attr): + if attr == '_wrapped_env': + raise AttributeError() + if attr == 'planner': + return self._planner + if attr == 'set_vf': + return self.set_vf + return getattr(self._wrapped_env, attr) + # try: + # getattr(self, attr) + # except Exception: + # return getattr(self._wrapped_env, attr) + + def __getstate__(self): + """ + This is useful to override in case the wrapped env has some funky + __getstate__ that doesn't play well with overriding __getattr__. + + The main problematic case is/was gym's EzPickle serialization scheme. + :return: + """ + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __str__(self): + return '{}({})'.format(type(self).__name__, self.wrapped_env) + +class GripperCloseEnv(ProxyEnv): + def __init__( + self, + env, + ): + ProxyEnv.__init__(self, env) + ub = self._wrapped_env.action_space + assert ub.shape == (7,) + self.action_space = Box(ub.low[:6], ub.high[:6]) + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + + def step(self, action): + a = np.zeros(self._wrapped_env.action_space.shape) + a[:6] = copy.deepcopy(action) + a[6] = 1 + return self._wrapped_env.step(a) + +class SpacemouseIntervention(ProxyEnv): + def __init__(self, env, gripper_enabled=False): + ProxyEnv.__init__(self, env) + self._wrapped_env = env + self.action_space = self._wrapped_env.action_space + self.gripper_enabled = gripper_enabled + if self.gripper_enabled: + assert self.action_space.shape == (7,) # maybe not so elegant + self.observation_space = self._wrapped_env.observation_space + self.expert = SpaceMouseExpert( + xyz_dims=3, + xyz_remap=[0, 1, 2], + xyz_scale=200, + rot_scale=200, + all_angles=True + ) + self.last_intervene = 0 + + def expert_action(self, action): + ''' + Input: + - action: policy action + Output: + - action: spacemouse action if nonezero; else, policy action + ''' + controller_a, _, left, right = self.expert.get_action() + expert_a = np.zeros((6,)) + if self.gripper_enabled: + expert_a = np.zeros((7,)) + expert_a[-1] = np.random.uniform(-1, 0) + + expert_a[:3] = controller_a[:3] # XYZ + expert_a[3] = controller_a[4] # Roll + expert_a[4] = controller_a[5] # Pitch + expert_a[5] = -controller_a[6] # Yaw + + if self.gripper_enabled: + if left: + expert_a[6] = np.random.uniform(0, 1) + self.last_intervene = time.time() + + if np.linalg.norm(expert_a[:6]) > 0.001: + self.last_intervene = time.time() + else: + if np.linalg.norm(expert_a) > 0.001: + self.last_intervene = time.time() + + if time.time() - self.last_intervene < 0.5: + return expert_a, left, right + return action, left, right + + def step(self, action): + expert_action, left, right = self.expert_action(action) + o, r, done, truncated, env_info = self._wrapped_env.step(expert_action) + env_info['expert_action'] = expert_action + env_info['right'] = right + return o, r, done, truncated, env_info + +class FourDoFWrapper(gym.ActionWrapper): + def __init__(self, env: Env): + super().__init__(env) + + def action(self, action): + a = np.zeros(4) + a[:3] = action[:3] + a[-1] = action[-1] + return a + +class TwoCameraFrankaWrapper(gym.ObservationWrapper): + def __init__(self, env): + ProxyEnv.__init__(self, env) + self.env = env + self.observation_space = spaces.Dict( + { + "state": spaces.flatten_space(self.env.observation_space['state_observation']), + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + # "side_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + } + ) + + def observation(self, obs): + ob = { + 'state': spaces.flatten(self.env.observation_space['state_observation'], + obs['state_observation']), + 'wrist_1': obs['image_observation']['wrist_1'][...,::-1], # flip color channel + 'wrist_2': obs['image_observation']['wrist_2'][...,::-1], # flip color channel + # 'side_1': obs['image_observation']['side_1'][...,::-1], # flip color channel + }
we should probably do this in the env side
serl
github_2023
python
5
rail-berkeley
jianlanluo
@@ -0,0 +1,267 @@ +import time +from gym import Env, spaces +import gym +import numpy as np +from gym.spaces import Box +import copy +from robot_infra.spacemouse.spacemouse_teleop import SpaceMouseExpert +from scipy.spatial.transform import Rotation as R + + +class ProxyEnv(Env): + def __init__(self, wrapped_env): + self._wrapped_env = wrapped_env + self.action_space = self._wrapped_env.action_space + self.observation_space = self._wrapped_env.observation_space + + @property + def wrapped_env(self): + return self._wrapped_env + + def reset(self, **kwargs): + return self._wrapped_env.reset(**kwargs) + + def step(self, action): + return self._wrapped_env.step(action) + + def render(self, *args, **kwargs): + return self._wrapped_env.render(*args, **kwargs) + + @property + def horizon(self): + return self._wrapped_env.horizon + + def terminate(self): + if hasattr(self.wrapped_env, "terminate"): + self.wrapped_env.terminate() + + def seed(self, _seed): + return self.wrapped_env.seed(_seed) + + def __getattr__(self, attr): + if attr == '_wrapped_env': + raise AttributeError() + if attr == 'planner': + return self._planner + if attr == 'set_vf': + return self.set_vf + return getattr(self._wrapped_env, attr) + # try: + # getattr(self, attr) + # except Exception: + # return getattr(self._wrapped_env, attr) + + def __getstate__(self): + """ + This is useful to override in case the wrapped env has some funky + __getstate__ that doesn't play well with overriding __getattr__. + + The main problematic case is/was gym's EzPickle serialization scheme. + :return: + """ + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __str__(self): + return '{}({})'.format(type(self).__name__, self.wrapped_env) + +class GripperCloseEnv(ProxyEnv): + def __init__( + self, + env, + ): + ProxyEnv.__init__(self, env) + ub = self._wrapped_env.action_space + assert ub.shape == (7,) + self.action_space = Box(ub.low[:6], ub.high[:6]) + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + + def step(self, action): + a = np.zeros(self._wrapped_env.action_space.shape) + a[:6] = copy.deepcopy(action) + a[6] = 1 + return self._wrapped_env.step(a) + +class SpacemouseIntervention(ProxyEnv): + def __init__(self, env, gripper_enabled=False): + ProxyEnv.__init__(self, env) + self._wrapped_env = env + self.action_space = self._wrapped_env.action_space + self.gripper_enabled = gripper_enabled + if self.gripper_enabled: + assert self.action_space.shape == (7,) # maybe not so elegant + self.observation_space = self._wrapped_env.observation_space + self.expert = SpaceMouseExpert( + xyz_dims=3, + xyz_remap=[0, 1, 2], + xyz_scale=200, + rot_scale=200, + all_angles=True + ) + self.last_intervene = 0 + + def expert_action(self, action): + ''' + Input: + - action: policy action + Output: + - action: spacemouse action if nonezero; else, policy action + ''' + controller_a, _, left, right = self.expert.get_action() + expert_a = np.zeros((6,)) + if self.gripper_enabled: + expert_a = np.zeros((7,)) + expert_a[-1] = np.random.uniform(-1, 0) + + expert_a[:3] = controller_a[:3] # XYZ + expert_a[3] = controller_a[4] # Roll + expert_a[4] = controller_a[5] # Pitch + expert_a[5] = -controller_a[6] # Yaw + + if self.gripper_enabled: + if left: + expert_a[6] = np.random.uniform(0, 1) + self.last_intervene = time.time() + + if np.linalg.norm(expert_a[:6]) > 0.001: + self.last_intervene = time.time() + else: + if np.linalg.norm(expert_a) > 0.001: + self.last_intervene = time.time() + + if time.time() - self.last_intervene < 0.5: + return expert_a, left, right + return action, left, right + + def step(self, action): + expert_action, left, right = self.expert_action(action) + o, r, done, truncated, env_info = self._wrapped_env.step(expert_action) + env_info['expert_action'] = expert_action + env_info['right'] = right + return o, r, done, truncated, env_info + +class FourDoFWrapper(gym.ActionWrapper): + def __init__(self, env: Env): + super().__init__(env) + + def action(self, action): + a = np.zeros(4) + a[:3] = action[:3] + a[-1] = action[-1] + return a + +class TwoCameraFrankaWrapper(gym.ObservationWrapper): + def __init__(self, env): + ProxyEnv.__init__(self, env) + self.env = env + self.observation_space = spaces.Dict( + { + "state": spaces.flatten_space(self.env.observation_space['state_observation']), + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + # "side_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + } + ) + + def observation(self, obs): + ob = { + 'state': spaces.flatten(self.env.observation_space['state_observation'], + obs['state_observation']), + 'wrist_1': obs['image_observation']['wrist_1'][...,::-1], # flip color channel + 'wrist_2': obs['image_observation']['wrist_2'][...,::-1], # flip color channel + # 'side_1': obs['image_observation']['side_1'][...,::-1], # flip color channel + } + return ob + +class ResetFreeWrapper(gym.Wrapper): + def __init__(self, env): + super().__init__(env) + self.task_id = 0 # 0: place into silver bin, 1: place into brown bin + + def reset(self, task_id=0): + self.task_id = task_id + print(f'reset to task {self.task_id}') + if self.task_id == 0: + self.resetpos[1] = self.centerpos[1] + 0.1 + else: + self.resetpos[1] = self.centerpos[1] - 0.1 + return self.env.reset() + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + """ + def __init__(self, env: Env): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + def step(self, action): + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, info = self.env.step(transformed_action) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs['state_observation']['tcp_pose']) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, info + + def reset(self, **kwargs): + obs = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs['state_observation']['tcp_pose']) + + # Transform observation to spatial frame + return self.transform_observation(obs) + + def transform_observation(self, obs): + # Transform observations from spatial(base) frame into body(end-effector) frame using the adjoint matrix + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = np.linalg.inv(adjoint_inv[:3, :3]) + obs['state_observation']['tcp_vel'] = adjoint_inv @ obs['state_observation']['tcp_vel'] + obs['state_observation']['tcp_force'] = R_inv @ obs['state_observation']['tcp_force'] + obs['state_observation']['tcp_torque'] = R_inv @ obs['state_observation']['tcp_torque']
what are you doing here? F/T is always in EE frame
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,472 @@ +"""Gym Interface for Franka""" +import numpy as np +import gym +from pyquaternion import Quaternion +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gym import core, spaces +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue +from PIL import Image +from queue import Queue +import threading +import os + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.stop_signal = False + self.daemon = True # make this a daemon thread + + self.video = [] + + video_dir = '/home/undergrad/franka_fwbw_pick_screw_vice_ckpts' + os.makedirs(video_dir, exist_ok=True) + uuid = time.strftime("%Y%m%d-%H%M%S") + self.wrist1 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_1_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.wrist2 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_2_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.frame_counter = 0 + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + # pair1 = np.concatenate([img_array['wrist_1_full'], img_array['wrist_2_full']], axis=0) + pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2']], axis=0) + # pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2'], img_array['side_1']], axis=0) + # pair2 = np.concatenate([img_array['side_2_full'], img_array['side_1_full']], axis=0) + # concatenated = np.concatenate([pair1, pair2], axis=1) + cv2.imshow('wrist', pair1/255.) + cv2.waitKey(1) + + self.wrist1.write(img_array['wrist_1_full']) + self.wrist2.write(img_array['wrist_2_full']) + self.frame_counter += 1 + if self.frame_counter == 400: + self.wrist1.release() + self.wrist2.release() + + +class FrankaRobotiq(gym.Env):
Rename this `FrankaRobotiqEnv`
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,472 @@ +"""Gym Interface for Franka""" +import numpy as np +import gym +from pyquaternion import Quaternion +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gym import core, spaces +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue +from PIL import Image +from queue import Queue +import threading +import os + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.stop_signal = False + self.daemon = True # make this a daemon thread + + self.video = [] + + video_dir = '/home/undergrad/franka_fwbw_pick_screw_vice_ckpts' + os.makedirs(video_dir, exist_ok=True) + uuid = time.strftime("%Y%m%d-%H%M%S") + self.wrist1 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_1_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.wrist2 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_2_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.frame_counter = 0 + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + # pair1 = np.concatenate([img_array['wrist_1_full'], img_array['wrist_2_full']], axis=0) + pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2']], axis=0) + # pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2'], img_array['side_1']], axis=0) + # pair2 = np.concatenate([img_array['side_2_full'], img_array['side_1_full']], axis=0) + # concatenated = np.concatenate([pair1, pair2], axis=1) + cv2.imshow('wrist', pair1/255.) + cv2.waitKey(1) + + self.wrist1.write(img_array['wrist_1_full']) + self.wrist2.write(img_array['wrist_2_full']) + self.frame_counter += 1 + if self.frame_counter == 400: + self.wrist1.release() + self.wrist2.release() + + +class FrankaRobotiq(gym.Env): + def __init__( + self, + randomReset=False, + hz=10, + start_gripper=0, + ): + + self._TARGET_POSE = [0.6636488814118523,0.05388642290645651,0.09439445897864279, 3.1339503, 0.009167, 1.5550434] + self._REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.07 + self.resetpos[3:] = self.euler_2_quat(self._TARGET_POSE[3], self._TARGET_POSE[4], self._TARGET_POSE[5]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + self.start_gripper = start_gripper + self.currgrip = self.start_gripper #start_gripper + self.lastsent = time.time() + self.randomreset = randomReset + self.actionnoise = 0 + self.hz = hz + + ## NUC + self.ip = "127.0.0.1" + self.url = "http://" + self.ip + ":5000/" + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.62, 0.0, 0.05)), np.array((0.71, 0.08, 0.3)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi-0.1, -0.1, 1.35)), + np.array((np.pi+0.1, 0.1, 1.7)), + dtype=np.float64, + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.02, -0.02, -0.02, -0.05, -0.05, -0.05, 0 - 1e-8)), + np.array((0.02, 0.02, 0.02, 0.05, 0.05, 0.05, 1 + 1e-8)), + ) + + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + # "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + # "q": spaces.Box(-np.inf, np.inf, shape=(7,)), + # "dq": spaces.Box(-np.inf, np.inf, shape=(7,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + # "jacobian": spaces.Box(-np.inf, np.inf, shape=((6, 7))), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + # "side_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + # "side_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + self.cycle_count = 0 + self.cap_wrist_1 = VideoCapture(RSCapture(name='wrist_1', serial_number='130322274175', depth=False)) + self.cap_wrist_2 = VideoCapture(RSCapture(name='wrist_2', serial_number='127122270572', depth=False)) + # self.cap_side_1 = VideoCapture(RSCapture(name='side_1', serial_number='128422272758', depth=False)) + + # self.cap_side_1 = VideoCapture( + # RSCapture(name="side_1", serial_number="128422270679", depth=True) + # ) + # self.cap_side_2 = VideoCapture( + # RSCapture(name="side_2", serial_number="127122270146", depth=True) + # ) + self.cap = { + # "side_1": self.cap_side_1, + # "side_2": self.cap_side_2, + "wrist_1": self.cap_wrist_1, + "wrist_2": self.cap_wrist_2, + } + + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + def set_gripper(self, position, block=True): + if position == 1: + st = 'close' + elif position == 0: + st = 'open' + else: + raise ValueError(f'Gripper position {position} not supported') + + ### IMPORTANT, IF FRANKA GRIPPER GETS OPEN/CLOSE COMMANDS TOO QUICKLY IT WILL FREEZE + ### THIS MAKES SURE CONSECUTIVE GRIPPER CHANGES ONLY HAPPEN 1 SEC APART + now = time.time() + delta = now - self.lastsent + if delta >= 1: + requests.post(self.url + st) + self.lastsent = time.time() + self.currgrip = position + # time.sleep(max(0, 1.5 - delta)) + + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + return pose + + def move_to_pos(self, pos): + start_time = time.time() + self._send_pos_command(self.clip_safety_box(pos)) + dl = time.time() - start_time + time.sleep(max(0, (1.0 / self.hz) - dl)) + self.update_currpos() + obs = self._get_obs() + return obs + + def step(self, action): + start_time = time.time() + action = np.clip(action, self.action_space.low, self.action_space.high) + if self.actionnoise > 0: + a = action[:3] + np.random.uniform( + -self.actionnoise, self.actionnoise, (3,) + ) + else: + a = action[:3] + + self.nextpos = self.currpos.copy() + self.nextpos[:3] = self.nextpos[:3] + a + + ### GET ORIENTATION FROM ACTION + self.nextpos[3:] = ( + Rotation.from_euler("xyz", action[3:6]) + * Rotation.from_quat(self.currpos[3:]) + ).as_quat() + + # self.nextpos = self.clip_safety_box(self.nextpos) + # self._send_pos_command(self.nextpos) + self._send_pos_command(self.clip_safety_box(self.nextpos)) + # self.set_gripper(action[-1]) + + self.curr_path_length += 1 + dl = time.time() - start_time + + time.sleep(max(0, (1.0 / self.hz) - dl)) + + self.update_currpos() + ob = self._get_obs() + obs_xyz = ob['state_observation']['tcp_pose'][:3] + # obs_rpy = self.quat_2_euler(ob['state_observation']['tcp_pose'][3:7]) + obs_rpy = ob['state_observation']['tcp_pose'][3:] + reward = self.binary_reward_tcp(ob['state_observation']['tcp_pose']) + done = self.curr_path_length >= 100 + # if not self.xyz_bounding_box.contains(obs_xyz) or not self.rpy_bounding_box.contains(obs_rpy): + # # print('Truncated: Bouding Box') + # # print("xyz: ", self.xyz_bounding_box.contains(obs_xyz), obs_xyz) + # # print("rortate: ", self.rpy_bounding_box.contains(obs_rpy), obs_rpy) + # return ob, 0, True, True, {} + # return ob, int(reward), done or reward, done, {} + return ob, int(reward), done, done, {} + + + def binary_reward_tcp(self, current_pose,): + # euler_angles = np.abs(R.from_quat(current_pose[3:]).as_euler("xyz")) + euler_angles = np.abs(current_pose[3:]) + current_pose = np.hstack([current_pose[:3],euler_angles]) + delta = np.abs(current_pose - self._TARGET_POSE) + if np.all(delta < self._REWARD_THRESHOLD): + return True + else: + # print(f'Goal not reached, the difference is {delta}, the desired threshold is {_REWARD_THRESHOLD}') + return False + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # if key == 'wrist_1': + # cropped_rgb = rgb[ 0:300, 150:450, :] + # if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 150:450, :] + if key == 'wrist_1': + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + cropped_rgb = rgb[:, 80:560, :] + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap) + return self.get_im() + + self.img_queue.put(images) + return images + + def _get_state(self): + state_observation = { + "tcp_pose": np.concatenate((self.currpos[:3], self.quat_2_euler(self.currpos[3:]))), + "tcp_vel": self.currvel, + "gripper_pose": self.currgrip, + # "q": self.q, + # "dq": self.dq, + "tcp_force": self.currforce, + "tcp_torque": self.currtorque, + # "jacobian": self.currjacobian, + } + return state_observation + + def _get_obs(self): + images = self.get_im() + state_observation = self._get_state() + + return copy.deepcopy(dict( + image_observation=images, + state_observation=state_observation + )) + + def go_to_rest(self, jpos=False): + count = 0 + requests.post(self.url + "precision_mode") + if jpos: + restp_new = copy.deepcopy(self.currpos) + restp_new[2] = 0.3 + dp = restp_new - self.currpos + count_1 = 0 + self._send_pos_command(self.currpos) + requests.post(self.url + "precision_mode") + while ( + (np.linalg.norm(dp[:3]) > 0.03 or np.linalg.norm(dp[3:]) > 0.04) + ) and count_1 < 50: + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.03: + dp[:3] = 0.03 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count_1 += 1 + + print("JOINT RESET") + requests.post(self.url + "jointreset") + else: + # print("RESET") + self.update_currpos() + restp = copy.deepcopy(self.resetpos[:]) + if self.randomreset: + restp[:2] += np.random.uniform(-0.005, 0.005, (2,)) + restp[2] += np.random.uniform(-0.005, 0.005, (1,)) + # restyaw += np.random.uniform(-np.pi / 6, np.pi / 6) + # restp[3:] = self.euler_2_quat(np.pi, 0, restyaw) + + restp_new = copy.deepcopy(restp) + restp_new[2] = 0.2 #PEG + dp = restp_new - self.currpos + while count < 200 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.03 + ): + if np.linalg.norm(dp[3:]) > 0.02: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp_new - self.currpos + count += 1 + + dp = restp - self.currpos + count = 0 + while count < 20 and ( + np.linalg.norm(dp[:3]) > 0.01 or np.linalg.norm(dp[3:]) > 0.01 + ): + if np.linalg.norm(dp[3:]) > 0.05: + dp[3:] = 0.05 * dp[3:] / np.linalg.norm(dp[3:]) + if np.linalg.norm(dp[:3]) > 0.02: + dp[:3] = 0.02 * dp[:3] / np.linalg.norm(dp[:3]) + self._send_pos_command(self.currpos + dp) + time.sleep(0.1) + self.update_currpos() + dp = restp - self.currpos + count += 1 + requests.post(self.url + "peg_compliance_mode") + return count < 50 + + def reset(self, jpos=False, gripper=None, require_input=False): + self.cycle_count += 1 + if self.cycle_count % 150 == 0: + self.cycle_count = 0 + jpos=True + # requests.post(self.url + "reset_gripper") + # time.sleep(3) + # self.set_gripper(self.start_gripper, block=False) + self.currgrip = self.start_gripper + + success = self.go_to_rest(jpos=jpos) + self.update_currpos() + self.curr_path_length = 0 + self.recover() + if jpos == True: + self.go_to_rest(jpos=False) + self.update_currpos() + self.recover() + + if require_input: + input("Reset Environment, Press Enter Once Complete: ") + # print("RESET COMPLETE") + self.update_currpos() + # self.last_quat = self.currpos[3:] + o = self._get_obs() + return o, {} + + def quat_2_euler(self, quat): + # calculates and returns: yaw, pitch, roll from given quaternion + if not isinstance(quat, Quaternion): + quat = Quaternion(quat) + yaw, pitch, roll = quat.yaw_pitch_roll + return yaw + np.pi, pitch, roll + + def euler_2_quat(self, yaw=np.pi / 2, pitch=0.0, roll=np.pi):
Move `euler_2_quat` and `quat_2_euler` to a `utils.py`
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,472 @@ +"""Gym Interface for Franka""" +import numpy as np +import gym +from pyquaternion import Quaternion +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gym import core, spaces +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue +from PIL import Image +from queue import Queue +import threading +import os + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.stop_signal = False + self.daemon = True # make this a daemon thread + + self.video = [] + + video_dir = '/home/undergrad/franka_fwbw_pick_screw_vice_ckpts' + os.makedirs(video_dir, exist_ok=True) + uuid = time.strftime("%Y%m%d-%H%M%S") + self.wrist1 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_1_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.wrist2 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_2_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.frame_counter = 0 + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + # pair1 = np.concatenate([img_array['wrist_1_full'], img_array['wrist_2_full']], axis=0) + pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2']], axis=0) + # pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2'], img_array['side_1']], axis=0) + # pair2 = np.concatenate([img_array['side_2_full'], img_array['side_1_full']], axis=0) + # concatenated = np.concatenate([pair1, pair2], axis=1) + cv2.imshow('wrist', pair1/255.) + cv2.waitKey(1) + + self.wrist1.write(img_array['wrist_1_full']) + self.wrist2.write(img_array['wrist_2_full']) + self.frame_counter += 1 + if self.frame_counter == 400: + self.wrist1.release() + self.wrist2.release() + + +class FrankaRobotiq(gym.Env): + def __init__( + self, + randomReset=False, + hz=10, + start_gripper=0, + ): + + self._TARGET_POSE = [0.6636488814118523,0.05388642290645651,0.09439445897864279, 3.1339503, 0.009167, 1.5550434] + self._REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.07 + self.resetpos[3:] = self.euler_2_quat(self._TARGET_POSE[3], self._TARGET_POSE[4], self._TARGET_POSE[5]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + self.start_gripper = start_gripper + self.currgrip = self.start_gripper #start_gripper + self.lastsent = time.time() + self.randomreset = randomReset + self.actionnoise = 0 + self.hz = hz + + ## NUC + self.ip = "127.0.0.1" + self.url = "http://" + self.ip + ":5000/" + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.62, 0.0, 0.05)), np.array((0.71, 0.08, 0.3)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi-0.1, -0.1, 1.35)), + np.array((np.pi+0.1, 0.1, 1.7)), + dtype=np.float64, + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.02, -0.02, -0.02, -0.05, -0.05, -0.05, 0 - 1e-8)), + np.array((0.02, 0.02, 0.02, 0.05, 0.05, 0.05, 1 + 1e-8)), + ) + + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + # "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + # "q": spaces.Box(-np.inf, np.inf, shape=(7,)), + # "dq": spaces.Box(-np.inf, np.inf, shape=(7,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + # "jacobian": spaces.Box(-np.inf, np.inf, shape=((6, 7))), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + # "side_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + # "side_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + self.cycle_count = 0 + self.cap_wrist_1 = VideoCapture(RSCapture(name='wrist_1', serial_number='130322274175', depth=False)) + self.cap_wrist_2 = VideoCapture(RSCapture(name='wrist_2', serial_number='127122270572', depth=False)) + # self.cap_side_1 = VideoCapture(RSCapture(name='side_1', serial_number='128422272758', depth=False)) + + # self.cap_side_1 = VideoCapture( + # RSCapture(name="side_1", serial_number="128422270679", depth=True) + # ) + # self.cap_side_2 = VideoCapture( + # RSCapture(name="side_2", serial_number="127122270146", depth=True) + # ) + self.cap = { + # "side_1": self.cap_side_1, + # "side_2": self.cap_side_2, + "wrist_1": self.cap_wrist_1, + "wrist_2": self.cap_wrist_2, + } + + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + def set_gripper(self, position, block=True): + if position == 1: + st = 'close' + elif position == 0: + st = 'open' + else: + raise ValueError(f'Gripper position {position} not supported') + + ### IMPORTANT, IF FRANKA GRIPPER GETS OPEN/CLOSE COMMANDS TOO QUICKLY IT WILL FREEZE + ### THIS MAKES SURE CONSECUTIVE GRIPPER CHANGES ONLY HAPPEN 1 SEC APART + now = time.time() + delta = now - self.lastsent + if delta >= 1: + requests.post(self.url + st) + self.lastsent = time.time() + self.currgrip = position + # time.sleep(max(0, 1.5 - delta)) + + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + return pose + + def move_to_pos(self, pos): + start_time = time.time() + self._send_pos_command(self.clip_safety_box(pos)) + dl = time.time() - start_time + time.sleep(max(0, (1.0 / self.hz) - dl)) + self.update_currpos() + obs = self._get_obs() + return obs + + def step(self, action): + start_time = time.time() + action = np.clip(action, self.action_space.low, self.action_space.high) + if self.actionnoise > 0: + a = action[:3] + np.random.uniform( + -self.actionnoise, self.actionnoise, (3,) + ) + else: + a = action[:3] + + self.nextpos = self.currpos.copy() + self.nextpos[:3] = self.nextpos[:3] + a + + ### GET ORIENTATION FROM ACTION + self.nextpos[3:] = ( + Rotation.from_euler("xyz", action[3:6]) + * Rotation.from_quat(self.currpos[3:]) + ).as_quat() + + # self.nextpos = self.clip_safety_box(self.nextpos) + # self._send_pos_command(self.nextpos) + self._send_pos_command(self.clip_safety_box(self.nextpos)) + # self.set_gripper(action[-1]) + + self.curr_path_length += 1 + dl = time.time() - start_time + + time.sleep(max(0, (1.0 / self.hz) - dl)) + + self.update_currpos() + ob = self._get_obs() + obs_xyz = ob['state_observation']['tcp_pose'][:3] + # obs_rpy = self.quat_2_euler(ob['state_observation']['tcp_pose'][3:7]) + obs_rpy = ob['state_observation']['tcp_pose'][3:] + reward = self.binary_reward_tcp(ob['state_observation']['tcp_pose']) + done = self.curr_path_length >= 100 + # if not self.xyz_bounding_box.contains(obs_xyz) or not self.rpy_bounding_box.contains(obs_rpy): + # # print('Truncated: Bouding Box') + # # print("xyz: ", self.xyz_bounding_box.contains(obs_xyz), obs_xyz) + # # print("rortate: ", self.rpy_bounding_box.contains(obs_rpy), obs_rpy) + # return ob, 0, True, True, {} + # return ob, int(reward), done or reward, done, {} + return ob, int(reward), done, done, {} + + + def binary_reward_tcp(self, current_pose,): + # euler_angles = np.abs(R.from_quat(current_pose[3:]).as_euler("xyz")) + euler_angles = np.abs(current_pose[3:]) + current_pose = np.hstack([current_pose[:3],euler_angles]) + delta = np.abs(current_pose - self._TARGET_POSE) + if np.all(delta < self._REWARD_THRESHOLD): + return True + else: + # print(f'Goal not reached, the difference is {delta}, the desired threshold is {_REWARD_THRESHOLD}') + return False + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # if key == 'wrist_1': + # cropped_rgb = rgb[ 0:300, 150:450, :] + # if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 150:450, :] + if key == 'wrist_1': + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + cropped_rgb = rgb[:, 80:560, :] + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False) + elif key == 'wrist_2': + cap = RSCapture(name='wrist_2', serial_number='127122270572', depth=False) + else: + raise KeyError + self.cap[key] = VideoCapture(cap) + return self.get_im() + + self.img_queue.put(images) + return images + + def _get_state(self): + state_observation = { + "tcp_pose": np.concatenate((self.currpos[:3], self.quat_2_euler(self.currpos[3:]))), + "tcp_vel": self.currvel, + "gripper_pose": self.currgrip, + # "q": self.q, + # "dq": self.dq, + "tcp_force": self.currforce, + "tcp_torque": self.currtorque, + # "jacobian": self.currjacobian, + } + return state_observation + + def _get_obs(self): + images = self.get_im() + state_observation = self._get_state() + + return copy.deepcopy(dict( + image_observation=images, + state_observation=state_observation + )) + + def go_to_rest(self, jpos=False):
This entire code block is quite unreadable. Requires more cleanup (e.g. what is jpos). Add those val (retry_count, tolerance, thresh, etc.) as configs/params and also add comments. type cast `jpos: np.narray` is always recommended
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented")
use `argparser`
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,17 @@ +from setuptools import setup +setup(name='franka_env',
Now `serl` is organized as - serl - `franka_sim` - `serl_launcher` - `examples` - `franka_env` (TODO, or other names, serl_franka_infra) Thus, if it make sense try to organize the robot code into a separate pkg, and add executables to `examples` or `scripts`
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,472 @@ +"""Gym Interface for Franka""" +import numpy as np +import gym +from pyquaternion import Quaternion +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gym import core, spaces +from camera.video_capture import VideoCapture +from camera.rs_capture import RSCapture +import queue +from PIL import Image +from queue import Queue +import threading +import os + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.stop_signal = False + self.daemon = True # make this a daemon thread + + self.video = [] + + video_dir = '/home/undergrad/franka_fwbw_pick_screw_vice_ckpts' + os.makedirs(video_dir, exist_ok=True) + uuid = time.strftime("%Y%m%d-%H%M%S") + self.wrist1 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_1_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.wrist2 = cv2.VideoWriter(os.path.join(video_dir, f'wrist_2_{uuid}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), 24, (640, 480)) + self.frame_counter = 0 + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + # pair1 = np.concatenate([img_array['wrist_1_full'], img_array['wrist_2_full']], axis=0) + pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2']], axis=0) + # pair1 = np.concatenate([img_array['wrist_1'], img_array['wrist_2'], img_array['side_1']], axis=0) + # pair2 = np.concatenate([img_array['side_2_full'], img_array['side_1_full']], axis=0) + # concatenated = np.concatenate([pair1, pair2], axis=1) + cv2.imshow('wrist', pair1/255.) + cv2.waitKey(1) + + self.wrist1.write(img_array['wrist_1_full']) + self.wrist2.write(img_array['wrist_2_full']) + self.frame_counter += 1 + if self.frame_counter == 400: + self.wrist1.release() + self.wrist2.release() + + +class FrankaRobotiq(gym.Env): + def __init__( + self, + randomReset=False, + hz=10, + start_gripper=0, + ): + + self._TARGET_POSE = [0.6636488814118523,0.05388642290645651,0.09439445897864279, 3.1339503, 0.009167, 1.5550434] + self._REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.07 + self.resetpos[3:] = self.euler_2_quat(self._TARGET_POSE[3], self._TARGET_POSE[4], self._TARGET_POSE[5]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + self.start_gripper = start_gripper + self.currgrip = self.start_gripper #start_gripper + self.lastsent = time.time() + self.randomreset = randomReset + self.actionnoise = 0 + self.hz = hz + + ## NUC + self.ip = "127.0.0.1" + self.url = "http://" + self.ip + ":5000/" + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.62, 0.0, 0.05)), np.array((0.71, 0.08, 0.3)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi-0.1, -0.1, 1.35)), + np.array((np.pi+0.1, 0.1, 1.7)), + dtype=np.float64, + ) + ## Action/Observation Space + self.action_space = gym.spaces.Box( + np.array((-0.02, -0.02, -0.02, -0.05, -0.05, -0.05, 0 - 1e-8)), + np.array((0.02, 0.02, 0.02, 0.05, 0.05, 0.05, 1 + 1e-8)), + ) + + self.observation_space = spaces.Dict( + { + "state_observation": spaces.Dict( + { + # "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(6,)), # xyz + euler + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + # "q": spaces.Box(-np.inf, np.inf, shape=(7,)), + # "dq": spaces.Box(-np.inf, np.inf, shape=(7,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + # "jacobian": spaces.Box(-np.inf, np.inf, shape=((6, 7))), + } + ), + "image_observation": spaces.Dict( + { + "wrist_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + "wrist_2": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "wrist_2_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + # "side_1": spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + # "side_1_full": spaces.Box(0, 255, shape=(480, 640, 3), dtype=np.uint8), + } + ), + } + ) + self.cycle_count = 0 + self.cap_wrist_1 = VideoCapture(RSCapture(name='wrist_1', serial_number='130322274175', depth=False)) + self.cap_wrist_2 = VideoCapture(RSCapture(name='wrist_2', serial_number='127122270572', depth=False)) + # self.cap_side_1 = VideoCapture(RSCapture(name='side_1', serial_number='128422272758', depth=False)) + + # self.cap_side_1 = VideoCapture( + # RSCapture(name="side_1", serial_number="128422270679", depth=True) + # ) + # self.cap_side_2 = VideoCapture( + # RSCapture(name="side_2", serial_number="127122270146", depth=True) + # ) + self.cap = { + # "side_1": self.cap_side_1, + # "side_2": self.cap_side_2, + "wrist_1": self.cap_wrist_1, + "wrist_2": self.cap_wrist_2, + } + + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + def set_gripper(self, position, block=True): + if position == 1: + st = 'close' + elif position == 0: + st = 'open' + else: + raise ValueError(f'Gripper position {position} not supported') + + ### IMPORTANT, IF FRANKA GRIPPER GETS OPEN/CLOSE COMMANDS TOO QUICKLY IT WILL FREEZE + ### THIS MAKES SURE CONSECUTIVE GRIPPER CHANGES ONLY HAPPEN 1 SEC APART + now = time.time() + delta = now - self.lastsent + if delta >= 1: + requests.post(self.url + st) + self.lastsent = time.time() + self.currgrip = position + # time.sleep(max(0, 1.5 - delta)) + + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + return pose + + def move_to_pos(self, pos): + start_time = time.time() + self._send_pos_command(self.clip_safety_box(pos)) + dl = time.time() - start_time + time.sleep(max(0, (1.0 / self.hz) - dl)) + self.update_currpos() + obs = self._get_obs() + return obs + + def step(self, action): + start_time = time.time() + action = np.clip(action, self.action_space.low, self.action_space.high) + if self.actionnoise > 0: + a = action[:3] + np.random.uniform( + -self.actionnoise, self.actionnoise, (3,) + ) + else: + a = action[:3] + + self.nextpos = self.currpos.copy() + self.nextpos[:3] = self.nextpos[:3] + a + + ### GET ORIENTATION FROM ACTION + self.nextpos[3:] = ( + Rotation.from_euler("xyz", action[3:6]) + * Rotation.from_quat(self.currpos[3:]) + ).as_quat() + + # self.nextpos = self.clip_safety_box(self.nextpos) + # self._send_pos_command(self.nextpos) + self._send_pos_command(self.clip_safety_box(self.nextpos)) + # self.set_gripper(action[-1]) + + self.curr_path_length += 1 + dl = time.time() - start_time + + time.sleep(max(0, (1.0 / self.hz) - dl)) + + self.update_currpos() + ob = self._get_obs() + obs_xyz = ob['state_observation']['tcp_pose'][:3] + # obs_rpy = self.quat_2_euler(ob['state_observation']['tcp_pose'][3:7]) + obs_rpy = ob['state_observation']['tcp_pose'][3:] + reward = self.binary_reward_tcp(ob['state_observation']['tcp_pose']) + done = self.curr_path_length >= 100 + # if not self.xyz_bounding_box.contains(obs_xyz) or not self.rpy_bounding_box.contains(obs_rpy): + # # print('Truncated: Bouding Box') + # # print("xyz: ", self.xyz_bounding_box.contains(obs_xyz), obs_xyz) + # # print("rortate: ", self.rpy_bounding_box.contains(obs_rpy), obs_rpy) + # return ob, 0, True, True, {} + # return ob, int(reward), done or reward, done, {} + return ob, int(reward), done, done, {} + + + def binary_reward_tcp(self, current_pose,): + # euler_angles = np.abs(R.from_quat(current_pose[3:]).as_euler("xyz")) + euler_angles = np.abs(current_pose[3:]) + current_pose = np.hstack([current_pose[:3],euler_angles]) + delta = np.abs(current_pose - self._TARGET_POSE) + if np.all(delta < self._REWARD_THRESHOLD): + return True + else: + # print(f'Goal not reached, the difference is {delta}, the desired threshold is {_REWARD_THRESHOLD}') + return False + + def get_im(self): + images = {} + for key, cap in self.cap.items(): + try: + rgb = cap.read() + # images[key] = cv2.resize(rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + # if key == 'wrist_1': + # cropped_rgb = rgb[ 0:300, 150:450, :] + # if key == 'wrist_2': + # cropped_rgb = rgb[ 50:350, 150:450, :] + if key == 'wrist_1': + cropped_rgb = rgb[:, 80:560, :] + if key == 'wrist_2': + cropped_rgb = rgb[:, 80:560, :] + images[key] = cv2.resize(cropped_rgb, self.observation_space['image_observation'][key].shape[:2][::-1]) + images[key + "_full"] = rgb + # images[f"{key}_depth"] = depth + except queue.Empty: + input(f'{key} camera frozen. Check connect, then press enter to relaunch...') + cap.close() + # if key == 'side_1': + # cap = RSCapture(name='side_1', serial_number='128422270679', depth=True) + # elif key == 'side_2': + # cap = RSCapture(name='side_2', serial_number='127122270146', depth=True) + if key == 'wrist_1': + cap = RSCapture(name='wrist_1', serial_number='130322274175', depth=False)
Hard coded `serial_num` again. should have all these in a init_rs() function. All these detailed impl of getting the cam can be placed in `rs_capture.py` too
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100: + break + + # Stop joint controller + print("RESET DONE") + self.j.terminate() + time.sleep(1) + self.clear() + print("KILLED JOINT RESET", self.pos) + + # Restart impedece controller + self.start_impedence() + print("IMPEDENCE STARTED") + + def move(self, pose): + msg = geom_msg.PoseStamped() + msg.header.frame_id = "0" + msg.header.stamp = rospy.Time.now() + msg.pose.position = geom_msg.Point(pose[0], pose[1], pose[2]) + msg.pose.orientation = geom_msg.Quaternion(pose[3], pose[4], pose[5], pose[6]) + self.eepub.publish(msg) + + def open(self): + pass + + def close(self): + pass + + def activate_gripper(self): + pass + + def reset_gripper(self): + pass + +class FrankaGripperServer(RobotServer): + def __init__(self): + super().__init__() + self.grippermovepub = rospy.Publisher( + "/franka_gripper/move/goal", MoveActionGoal, queue_size=1 + ) + self.grippergrasppub = rospy.Publisher( + "/franka_gripper/grasp/goal", GraspActionGoal, queue_size=1 + ) + self.gripper_sub = rospy.Subscriber( + "/franka_gripper/joint_states", JointState, self.update_gripper + ) + + def open(self): + msg = MoveActionGoal() + msg.goal.width = 0.09 + msg.goal.speed = 0.3 + self.grippermovepub.publish(msg) + + def close(self): + msg = GraspActionGoal() + msg.goal.width = 0.01 + msg.goal.speed = 0.3 + msg.goal.epsilon.inner = 1 + msg.goal.epsilon.outer = 1 + msg.goal.force = 130 + self.grippergrasppub.publish(msg) + + def update_gripper(self, msg): + self.gripper_dist = np.sum(msg.position) + +class RobotiqServer(RobotServer): + def __init__(self): + super().__init__() + self.gripper = subprocess.Popen( + [ + "rosrun", + "robotiq_2f_gripper_control", + "Robotiq2FGripperTcpNode.py", + GRIPPER_IP, + ], + stdout=subprocess.PIPE, + ) + self.gripperpub = rospy.Publisher( + "Robotiq2FGripperRobotOutput", outputMsg.Robotiq2FGripper_robot_output, queue_size=1 + ) + self.gripper_command = outputMsg.Robotiq2FGripper_robot_output() + + def generate_gripper_command(self, char, command): + """Update the gripper command according to the character entered by the user.""" + if char == "a": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 1 + command.rGTO = 1 + command.rSP = 255 + command.rFR = 150 + + if char == "r": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 0 + + if char == "c": + command.rPR = 255 + + if char == "o": + command.rPR = 0 + + # If the command entered is a int, assign this value to rPR + # (i.e., move to this position) + try: + command.rPR = int(char) + if command.rPR > 255: + command.rPR = 255 + if command.rPR < 0: + command.rPR = 0 + except ValueError: + pass + return command + + def activate_gripper(self): + self.gripper_command = self.generate_gripper_command("a", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def reset_gripper(self): + self.gripper_command = self.generate_gripper_command("r", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + self.activate_gripper() + + def open(self): + self.gripper_command = self.generate_gripper_command("o", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def close(self): + self.gripper_command = self.generate_gripper_command("c", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def update_gripper(self, msg): + raise NotImplementedError("Not implemented for Robotiq Gripper") + + + +try:
have all these being placed within `if __name__ == '__main__':`? Also, if this script `flask` server script is getting too long, would split both the flask server and "robot ros server" into 2 different scripts. I would also `rospy.init_node()` the node in the class init.
serl
github_2023
python
5
rail-berkeley
youliangtan
@@ -0,0 +1,447 @@ +""" +This file starts a control server running on the real time PC connected to the franka robot. +In a screen run `python franka_server.py` +""" +import os +import sys +from flask import Flask, request, jsonify +import numpy as np +import rospy +import time +import subprocess +from scipy.spatial.transform import Rotation as R + +from sensor_msgs.msg import JointState +from franka_msgs.msg import ErrorRecoveryActionGoal, FrankaState, ZeroJacobian +import geometry_msgs.msg as geom_msg +from dynamic_reconfigure.client import Client + + + +app = Flask(__name__) +RESET_JOINT_TARGET = [-0.07, -0.1, 0.0, -2.5, -0.1, 2.5, -0.6] +ROBOT_IP = "172.16.0.2" +GRIPPER_IP = None +GRIPPER_TYPE = "Franka" # "Robotiq", "Franka", or "None" + +if GRIPPER_TYPE == "Robotiq": + from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg + assert GRIPPER_IP != None +elif GRIPPER_TYPE == "Franka": + from franka_gripper.msg import GraspActionGoal, MoveActionGoal +elif GRIPPER_TYPE == "None": + pass +else: + raise NotImplementedError("Gripper Type Not Implemented") + + + +class RobotServer: + """Handles the starting and stopping of the impedence controller + (as well as backup) joint recovery policy.""" + + def __init__(self): + self.eepub = rospy.Publisher( + "/cartesian_impedance_controller/equilibrium_pose", + geom_msg.PoseStamped, + queue_size=10, + ) + self.resetpub = rospy.Publisher( + "/franka_control/error_recovery/goal", ErrorRecoveryActionGoal, queue_size=1 + ) + self.state_sub = rospy.Subscriber( + "franka_state_controller/franka_states", FrankaState, self.set_currpos + ) + self.jacobian_sub = rospy.Subscriber( + "/cartesian_impedance_controller/franka_jacobian", + ZeroJacobian, + self.set_jacobian, + ) + + def start_impedence(self): + """Launches the impedence controller""" + self.imp = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "impedence.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(5) + + def stop_impedence(self): + """Stops the impedence controller""" + self.imp.terminate() + time.sleep(1) + + def clear(self): + """Clears any errors""" + msg = ErrorRecoveryActionGoal() + self.resetpub.publish(msg) + + def set_currpos(self, msg): + tmatrix = np.array(list(msg.O_T_EE)).reshape(4, 4).T + r = R.from_matrix(tmatrix[:3, :3]) + pose = np.concatenate([tmatrix[:3, -1], r.as_quat()]) + self.pos = pose + self.dq = np.array(list(msg.dq)).reshape((7,)) + self.q = np.array(list(msg.q)).reshape((7,)) + self.force = np.array(list(msg.O_F_ext_hat_K)[:3]) + self.torque = np.array(list(msg.O_F_ext_hat_K)[3:]) + self.vel = self.jacobian @ self.dq + + def set_jacobian(self, msg): + jacobian = np.array(list(msg.zero_jacobian)).reshape((6, 7), order="F") + self.jacobian = jacobian + + def reset_joint(self): + """Resets Joints (needed after running for hours)""" + # First Stop Impedence + try: + self.stop_impedence() + self.clear() + except: + print("Impedence Not Running") + time.sleep(3) + self.clear() + + # Launch joint controller reset + rospy.set_param("/target_joint_positions", RESET_JOINT_TARGET) + self.j = subprocess.Popen( + [ + "roslaunch", + "serl_franka_controllers", + "joint.launch", + "robot_ip:=" + ROBOT_IP, + f"load_gripper:={'true' if GRIPPER_TYPE == 'Franka' else 'false'}", + ], + stdout=subprocess.PIPE, + ) + time.sleep(1) + print("RUNNING JOINT RESET") + self.clear() + + # Wait until target joint angles are reached + count = 0 + time.sleep(1) + while not np.allclose( + np.array(RESET_JOINT_TARGET) - np.array(self.q), 0, atol=1e-2, rtol=1e-2 + ): + time.sleep(1) + count += 1 + if count > 100: + break + + # Stop joint controller + print("RESET DONE") + self.j.terminate() + time.sleep(1) + self.clear() + print("KILLED JOINT RESET", self.pos) + + # Restart impedece controller + self.start_impedence() + print("IMPEDENCE STARTED") + + def move(self, pose): + msg = geom_msg.PoseStamped() + msg.header.frame_id = "0" + msg.header.stamp = rospy.Time.now() + msg.pose.position = geom_msg.Point(pose[0], pose[1], pose[2]) + msg.pose.orientation = geom_msg.Quaternion(pose[3], pose[4], pose[5], pose[6]) + self.eepub.publish(msg) + + def open(self): + pass + + def close(self): + pass + + def activate_gripper(self): + pass + + def reset_gripper(self): + pass + +class FrankaGripperServer(RobotServer): + def __init__(self): + super().__init__() + self.grippermovepub = rospy.Publisher( + "/franka_gripper/move/goal", MoveActionGoal, queue_size=1 + ) + self.grippergrasppub = rospy.Publisher( + "/franka_gripper/grasp/goal", GraspActionGoal, queue_size=1 + ) + self.gripper_sub = rospy.Subscriber( + "/franka_gripper/joint_states", JointState, self.update_gripper + ) + + def open(self): + msg = MoveActionGoal() + msg.goal.width = 0.09 + msg.goal.speed = 0.3 + self.grippermovepub.publish(msg) + + def close(self): + msg = GraspActionGoal() + msg.goal.width = 0.01 + msg.goal.speed = 0.3 + msg.goal.epsilon.inner = 1 + msg.goal.epsilon.outer = 1 + msg.goal.force = 130 + self.grippergrasppub.publish(msg) + + def update_gripper(self, msg): + self.gripper_dist = np.sum(msg.position) + +class RobotiqServer(RobotServer): + def __init__(self): + super().__init__() + self.gripper = subprocess.Popen( + [ + "rosrun", + "robotiq_2f_gripper_control", + "Robotiq2FGripperTcpNode.py", + GRIPPER_IP, + ], + stdout=subprocess.PIPE, + ) + self.gripperpub = rospy.Publisher( + "Robotiq2FGripperRobotOutput", outputMsg.Robotiq2FGripper_robot_output, queue_size=1 + ) + self.gripper_command = outputMsg.Robotiq2FGripper_robot_output() + + def generate_gripper_command(self, char, command): + """Update the gripper command according to the character entered by the user.""" + if char == "a": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 1 + command.rGTO = 1 + command.rSP = 255 + command.rFR = 150 + + if char == "r": + command = outputMsg.Robotiq2FGripper_robot_output() + command.rACT = 0 + + if char == "c": + command.rPR = 255 + + if char == "o": + command.rPR = 0 + + # If the command entered is a int, assign this value to rPR + # (i.e., move to this position) + try: + command.rPR = int(char) + if command.rPR > 255: + command.rPR = 255 + if command.rPR < 0: + command.rPR = 0 + except ValueError: + pass + return command + + def activate_gripper(self): + self.gripper_command = self.generate_gripper_command("a", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def reset_gripper(self): + self.gripper_command = self.generate_gripper_command("r", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + self.activate_gripper() + + def open(self): + self.gripper_command = self.generate_gripper_command("o", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def close(self): + self.gripper_command = self.generate_gripper_command("c", self.gripper_command) + self.gripperpub.publish(self.gripper_command) + + def update_gripper(self, msg): + raise NotImplementedError("Not implemented for Robotiq Gripper") + + + +try: + roscore = subprocess.Popen("roscore") + time.sleep(1) +except: + pass + +"""Starts Impedence controller""" +if GRIPPER_TYPE == "Franka": + l = FrankaGripperServer() +elif GRIPPER_TYPE == "Robotiq": + l = RobotiqServer() +elif GRIPPER_TYPE == "None": + l = RobotServer() +else: + raise NotImplementedError("Gripper Type Not Implemented") + +l.start_impedence() +rospy.init_node("franka_control_api") + +## Defines the ros topics to publish to +client = Client( + "/cartesian_impedance_controllerdynamic_reconfigure_compliance_param_node" +) + +## Route for Starting Impedence +@app.route("/startimp", methods=["POST"]) +def si(): + l.clear() + l.start_impedence() + return "Started Impedence" + +## Route for Stopping Impedence +@app.route("/stopimp", methods=["POST"]) +def sti(): + l.stop_impedence() + return "Stopped Impedence" + +## Route for getting pose +@app.route("/getpos", methods=["POST"]) +def gp(): + return jsonify({"pose": np.array(l.pos).tolist()}) + +## Route for getting velocity +@app.route("/getvel", methods=["POST"]) +def gv(): + return jsonify({"vel": np.array(l.vel).tolist()}) + +## Route for getting force +@app.route("/getforce", methods=["POST"]) +def gf(): + return jsonify({"force": np.array(l.force).tolist()}) + +## Route for getting torque +@app.route("/gettorque", methods=["POST"]) +def gt(): + return jsonify({"torque": np.array(l.torque).tolist()}) + +## Route for getting joint angles +@app.route("/getq", methods=["POST"]) +def gq(): + return jsonify({"q": np.array(l.q).tolist()}) + +## Route for getting joint velocities +@app.route("/getdq", methods=["POST"]) +def gdq(): + return jsonify({"dq": np.array(l.dq).tolist()}) + +## Route for getting jacobian +@app.route("/getjacobian", methods=["POST"]) +def gj(): + return jsonify({"jacobian": np.array(l.jacobian).tolist()}) + +## Route for getting gripper distance +@app.route("/getgripper", methods=["POST"]) +def gg(): + return jsonify({"gripper": l.gripper_dist}) + +## Route for getting all state information +@app.route("/getstate", methods=["POST"]) +def gs(): + return jsonify( + { + "pose": np.array(l.pos).tolist(), + "vel": np.array(l.vel).tolist(), + "force": np.array(l.force).tolist(), + "torque": np.array(l.torque).tolist(), + "q": np.array(l.q).tolist(), + "dq": np.array(l.dq).tolist(), + "jacobian": np.array(l.jacobian).tolist(), + "gripper": l.gripper_dist, + } + ) + +## Route for running joint reset +@app.route("/jointreset", methods=["POST"]) +def jr(): + l.clear() + l.reset_joint() + return "Reset Joint" + +##Route for activating the Robotiq gripper +@app.route("/activate_gripper", methods=["POST"]) +def activate_gripper(): + print("activate gripper") + l.activate_gripper() + return "Activated" + +## Route for resetting the Robotiq gripper. It will reset and activate the gripper +@app.route("/reset_gripper", methods=["POST"]) +def reset_gripper(): + print("reset gripper") + l.reset_gripper() + return "Reset" + +## Route for closing the gripper +@app.route("/close", methods=["POST"]) +def closed(): + print("close") + l.close() + return "Closed" + +## Route for opening the gripper +@app.route("/open", methods=["POST"]) +def open(): + print("open") + l.open() + return "Opened" + + +## Route for clearing errors (communcation constraints, etc.) +@app.route("/clearerr", methods=["POST"]) +def clear(): + l.clear() + return "Clear" + + +## Route for sending a pose command +@app.route("/pose", methods=["POST"]) +def pose(): + pos = np.array(request.json["arr"]) + print("Moving to", pos)
if these print out is getting overwhelming, can consider use `logging.debug()`
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,104 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy +import pickle as pkl +import datetime + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper
use `serl_launcher`
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,110 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy +import pickle as pkl +import datetime + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, + FWBWFrontCameraBinaryRewardClassifierWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper
same, use `serl_launcher`, same for all imports in this PR
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,110 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy +import pickle as pkl +import datetime + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, + FWBWFrontCameraBinaryRewardClassifierWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper + +if __name__ == "__main__": + from pynput import keyboard + + env = gym.make("FrankaBinRelocation-Vision-v0", save_video=False) + env = SpacemouseIntervention(env) + env = RelativeFrame(env) + env = Quat2EulerWrapper(env) + env = SERLObsWrapper(env) + env = ChunkingWrapper(env, obs_horizon=1, act_exec_horizon=None) + env = FrontCameraWrapper(env) + + env.set_task_id(0) + obs, _ = env.reset() + + image_keys = [k for k in env.front_observation_space.keys() if "state" not in k] + + from serl_launcher.networks.reward_classifier import load_classifier_func + import jax + + rng = jax.random.PRNGKey(0) + rng, key = jax.random.split(rng) + fw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/fw_classifier_ckpt", + ) + rng, key = jax.random.split(rng) + bw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/bw_classifier_ckpt", + ) + env = FWBWFrontCameraBinaryRewardClassifierWrapper( + env, fw_classifier_func, bw_classifier_func + ) + + transitions_needed = 2000 + fw_transitions = [] + bw_transitions = [] + + fw_pbar = tqdm(total=transitions_needed, desc="fw") + bw_pbar = tqdm(total=transitions_needed, desc="bw") + + while ( + len(fw_transitions) < transitions_needed + or len(bw_transitions) < transitions_needed + ): + next_obs, rew, done, truncated, info = env.step(action=np.zeros((7,))) + actions = info["intervene_action"] + + transition = copy.deepcopy( + dict( + observations=obs, + actions=actions, + next_observations=next_obs, + rewards=rew, + masks=1.0 - done, + dones=done, + ) + ) + + if env.task_id == 0 and len(fw_transitions) < transitions_needed: + fw_transitions.append(transition) + fw_pbar.update(1) + elif env.task_id == 1 and len(bw_transitions) < transitions_needed: + bw_transitions.append(transition) + bw_pbar.update(1) + + obs = next_obs + + if done: + print(rew) + next_task_id = env.task_graph(env.get_front_cam_obs()) + print(f"transition from {env.task_id} to next task: {next_task_id}") + env.set_task_id(next_task_id) + obs, _ = env.reset() + + uuid = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + file_name = f"fw_bin_{len(fw_transitions)}_demo_{uuid}.pkl"
Do we need to provide these demos pkl files in the release?
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,170 @@ +import numpy as np +import time +import requests +import copy +import cv2 +import queue +import gymnasium as gym + +from franka_env.envs.franka_env import FrankaEnv +from franka_env.utils.rotations import euler_2_quat +from franka_env.envs.bin_relocation_env.config import BinEnvConfig + + +class FrankaBinRelocation(FrankaEnv): + def __init__(self, **kwargs): + super().__init__(**kwargs, config=BinEnvConfig) + self.observation_space["images"] = gym.spaces.Dict( + { + "wrist_1": gym.spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + "front": gym.spaces.Box(0, 255, shape=(128, 128, 3), dtype=np.uint8), + } + ) + self.task_id = 0 # 0 for forward task, 1 for backward task + self.inner_safety_box = gym.spaces.Box( + self._TARGET_POSE[:3] - np.array([0.07, 0.03, 0.001]), + self._TARGET_POSE[:3] + np.array([0.07, 0.03, 0.04]),
hardcoded, use config.ypy
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,110 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy +import pickle as pkl +import datetime + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, + FWBWFrontCameraBinaryRewardClassifierWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper + +if __name__ == "__main__": + from pynput import keyboard + + env = gym.make("FrankaBinRelocation-Vision-v0", save_video=False) + env = SpacemouseIntervention(env) + env = RelativeFrame(env) + env = Quat2EulerWrapper(env) + env = SERLObsWrapper(env) + env = ChunkingWrapper(env, obs_horizon=1, act_exec_horizon=None) + env = FrontCameraWrapper(env) + + env.set_task_id(0) + obs, _ = env.reset() + + image_keys = [k for k in env.front_observation_space.keys() if "state" not in k] + + from serl_launcher.networks.reward_classifier import load_classifier_func + import jax + + rng = jax.random.PRNGKey(0) + rng, key = jax.random.split(rng) + fw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/fw_classifier_ckpt", + ) + rng, key = jax.random.split(rng) + bw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/bw_classifier_ckpt",
both `checkpoint_path` not used
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,68 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, + FWBWFrontCameraBinaryRewardClassifierWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper + +if __name__ == "__main__": + env = gym.make("FrankaBinRelocation-Vision-v0", save_video=False) + env = SpacemouseIntervention(env) + env = RelativeFrame(env) + env = Quat2EulerWrapper(env) + env = SERLObsWrapper(env) + env = ChunkingWrapper(env, obs_horizon=1, act_exec_horizon=None) + env = FrontCameraWrapper(env) + obs, _ = env.reset() + + image_keys = [k for k in env.front_observation_space.keys() if "state" not in k] + + from serl_launcher.networks.reward_classifier import load_classifier_func + import jax + + rng = jax.random.PRNGKey(0) + rng, key = jax.random.split(rng) + fw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/fw_classifier_ckpt", + ) + rng, key = jax.random.split(rng) + bw_classifier_func = load_classifier_func( + key=key, + sample=env.front_observation_space.sample(), + image_keys=image_keys, + checkpoint_path="/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/bw_classifier_ckpt",
same, unused checkpoint path
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,26 @@ +import gymnasium as gym +from gymnasium.core import Env +from copy import deepcopy + + +class FrontCameraWrapper(gym.ObservationWrapper): + def __init__(self, env: Env): + super().__init__(env) + front_obs_space = { + k: space for k, space in self.observation_space.items() if "wrist" not in k + } + + self.front_observation_space = gym.spaces.Dict(front_obs_space) + # self.observation_space = gym.spaces.Dict(new_obs_space)
Does the `async_drq_randomized.py` for bin reloc just uses front img as obs space? If so, is it better if directly overload the `self.observation_space` with `self.front_observation_space`? and update observation?
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -7,6 +7,47 @@ from franka_env.spacemouse.spacemouse_expert import SpaceMouseExpert from franka_env.utils.rotations import quat_2_euler +sigmoid = lambda x: 1 / (1 + np.exp(-x)) + + +class FWBWFrontCameraBinaryRewardClassifierWrapper(gym.Wrapper): + """ + This wrapper uses the front camera images to compute the reward,
add a simple comment indicates reward classifier for forward-backward reward cls
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,127 @@ +import gymnasium as gym +from tqdm import tqdm +import numpy as np +import copy +import pickle as pkl +import datetime + +import franka_env + +from franka_env.envs.relative_env import RelativeFrame +from franka_env.envs.wrappers import ( + SpacemouseIntervention, + Quat2EulerWrapper, +) + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper + +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper + +if __name__ == "__main__": + from pynput import keyboard + + env = gym.make("FrankaBinRelocation-Vision-v0", save_video=False) + env = SpacemouseIntervention(env) + env = RelativeFrame(env) + env = Quat2EulerWrapper(env) + env = SERLObsWrapper(env) + env = ChunkingWrapper(env, obs_horizon=1, act_exec_horizon=None) + env = FrontCameraWrapper(env) + + env.set_task_id(0) + obs, _ = env.reset() + obs = env.get_front_cam_obs() + + success_needed = 400 + + is_success = False + fw_success_transitions = [] + fw_failed_transitions = [] + bw_success_transitions = [] + bw_failed_transitions = [] +
Here it is also recording failed transitions? I think we can combine `record_goals_images.py` and `record_failed_images.py`
serl
github_2023
python
12
rail-berkeley
youliangtan
@@ -0,0 +1,159 @@ +import pickle as pkl +import jax +from jax import numpy as jnp +import flax.linen as nn +from flax.training.train_state import TrainState +from flax.core import frozen_dict +from flax.training import checkpoints +import optax +from tqdm import tqdm +import gymnasium as gym +import os +from absl import app, flags + +from jaxrl_m.vision.resnet_v1 import resnetv1_configs, PreTrainedResNetEncoder +from jaxrl_m.common.encoding import EncodingWrapper +from jaxrl_m.envs.wrappers.chunking import ChunkingWrapper +from jaxrl_m.utils.train_utils import concat_batches +from jaxrl_m.vision.data_augmentations import batched_random_crop + +from serl_launcher.wrappers.serl_obs_wrappers import SERLObsWrapper +from serl_launcher.wrappers.front_camera_wrapper import FrontCameraWrapper +from serl_launcher.data.data_store import ( + MemoryEfficientReplayBufferDataStore, + populate_data_store, +) +from serl_launcher.networks.reward_classifier import create_classifier + +from franka_env.envs.wrappers import ( + Quat2EulerWrapper, +) +from franka_env.envs.relative_env import RelativeFrame + +FLAGS = flags.FLAGS +flags.DEFINE_multi_string("positive_demo_paths", None, "paths to positive demos") +flags.DEFINE_multi_string("negative_demo_paths", None, "paths to negative demos") +flags.DEFINE_string("classifier_name", "fw", "Name of classifier: fw or bw") + + +def main(_): + num_epochs = 100 + batch_size = 256 + + devices = jax.local_devices() + num_devices = len(devices) + sharding = jax.sharding.PositionalSharding(devices) + + env = gym.make("FrankaBinRelocation-Vision-v0", save_video=False) + env = RelativeFrame(env) + env = Quat2EulerWrapper(env) + env = SERLObsWrapper(env) + env = ChunkingWrapper(env, obs_horizon=1, act_exec_horizon=None) + env = FrontCameraWrapper(env) + image_keys = [k for k in env.front_observation_space.keys() if "state" not in k] + + pos_buffer = MemoryEfficientReplayBufferDataStore( + env.front_observation_space, + env.action_space, + capacity=2000, + image_keys=image_keys, + ) + pos_buffer = populate_data_store(pos_buffer, FLAGS.positive_demo_paths) + + neg_buffer = MemoryEfficientReplayBufferDataStore( + env.front_observation_space, + env.action_space, + capacity=5000, + image_keys=image_keys, + ) + neg_buffer = populate_data_store(neg_buffer, FLAGS.negative_demo_paths) + + print(f"failed buffer size: {len(neg_buffer)}") + print(f"success buffer size: {len(pos_buffer)}") + + pos_iterator = pos_buffer.get_iterator( + sample_args={ + "batch_size": batch_size // 2, + "pack_obs_and_next_obs": False, + }, + device=sharding.replicate(), + ) + neg_iterator = neg_buffer.get_iterator( + sample_args={ + "batch_size": batch_size // 2, + "pack_obs_and_next_obs": False, + }, + device=sharding.replicate(), + ) + + rng = jax.random.PRNGKey(0) + rng, key = jax.random.split(rng) + pos_sample = next(pos_iterator) + neg_sample = next(neg_iterator) + sample = concat_batches(pos_sample, neg_sample, axis=0) + + rng, key = jax.random.split(rng) + classifier = create_classifier(key, sample["next_observations"], image_keys) + + def data_augmentation_fn(rng, observations): + for pixel_key in image_keys: + observations = observations.copy( + add_or_replace={ + pixel_key: batched_random_crop( + observations[pixel_key], rng, padding=4, num_batch_dims=2 + ) + } + ) + return observations + + # Define the training step + @jax.jit + def train_step(state, batch, key): + def loss_fn(params): + logits = state.apply_fn( + {"params": params}, batch["data"], rngs={"dropout": key}, train=True + ) + return optax.sigmoid_binary_cross_entropy(logits, batch["labels"]).mean() + + grad_fn = jax.value_and_grad(loss_fn) + loss, grads = grad_fn(state.params) + logits = state.apply_fn( + {"params": state.params}, batch["data"], train=False, rngs={"dropout": key} + ) + train_accuracy = jnp.mean((nn.sigmoid(logits) >= 0.5) == batch["labels"]) + + return state.apply_gradients(grads=grads), loss, train_accuracy + + # Training Loop + for epoch in tqdm(range(num_epochs)): + # Sample equal number of positive and negative examples + pos_sample = next(pos_iterator) + neg_sample = next(neg_iterator) + # Merge and create labels + sample = concat_batches( + pos_sample["next_observations"], neg_sample["observations"], axis=0 + ) + rng, key = jax.random.split(rng) + sample = data_augmentation_fn(key, sample) + labels = jnp.concatenate( + [jnp.ones((batch_size // 2, 1)), jnp.zeros((batch_size // 2, 1))], axis=0 + ) + batch = {"data": sample, "labels": labels} + + rng, key = jax.random.split(rng) + classifier, train_loss, train_accuracy = train_step(classifier, batch, key) + + print( + f"Epoch: {epoch+1}, Train Loss: {train_loss:.4f}, Train Accuracy: {train_accuracy:.4f}" + ) + + checkpoints.save_checkpoint( + f"/home/undergrad/code/serl_dev/examples/async_bin_relocation_fwbw_drq/{FLAGS.classifier_name}_classifier_ckpt",
is okay to hardcode for now, but at least make the path configurable as `DEFINE_string()` flag
serl
github_2023
others
7
rail-berkeley
youliangtan
@@ -0,0 +1,25 @@ +# SERL Robot Infra + +All robot code is structured as follows: +There is a Flask server which sends commands to the robot via ROS. There is a gym env for the robot which communicates with the Flask server via post requests. + +- `robot_server`: hosts a Flask server which sends commands to the robot via ROS +- `franka_env`: gym env for the robot which communicates with the Flask server via post requests + +### Installation + +First, make sure the NUC meets the specifications [here](https://frankaemika.github.io/docs/requirements.html), and install the real time kernel, and `libfranka` and `franka_ros` as described [here](https://frankaemika.github.io/docs/installation_linux.html). + +You'll then want to copy the following files from `launchers` to your catkin workspace: +- copy the two `.launch` files to a `catkin_ws/scripts` folder in your ros workspace +- copy the `.cfg` files to `catkin_ws/src/franka_ros/franka_example_controllers/cfg` +- copy the two `.cpp` files to `catkin_ws/src/franka_ros/franka_example_controllers/src` +- copy the two `.h` files to `catkin_ws/src/franka_ros/franka_example_controllers/include/franka_example_controllers` +
Update this to use: `serl_franka_controllers` https://github.com/rail-berkeley/serl_franka_controllers
serl
github_2023
others
7
rail-berkeley
youliangtan
@@ -0,0 +1,25 @@ +# SERL Robot Infra + +All robot code is structured as follows: +There is a Flask server which sends commands to the robot via ROS. There is a gym env for the robot which communicates with the Flask server via post requests. + +- `robot_server`: hosts a Flask server which sends commands to the robot via ROS +- `franka_env`: gym env for the robot which communicates with the Flask server via post requests +
Can add this: ```mermaid graph LR A[Robot] <-- ROS --> B[Robot Server] B <-- HTTP --> C[Gym Env] C <-- Lib --> D[RL Policy] ```
serl
github_2023
python
7
rail-berkeley
youliangtan
@@ -0,0 +1,362 @@ +"""Gym Interface for Franka""" +import numpy as np +import gymnasium as gym +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gymnasium import spaces +import queue +import threading +from datetime import datetime + +from franka_env.camera.video_capture import VideoCapture +from franka_env.camera.rs_capture import RSCapture +from franka_env.utils.rotations import euler_2_quat, quat_2_euler + + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.daemon = True # make this a daemon thread + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + + frame = np.concatenate( + [img_array["wrist_1_full"], img_array["wrist_2_full"]], axis=0 + ) + + cv2.imshow("RealSense Cameras", frame) + cv2.waitKey(1) + + +class DefaultEnvConfig: + """Default configuration for FrankaRobotiqEnv.""" + + SERVER_URL = "http://127.0.0.1:5000/" + WRIST_CAM1_SERIAL = "130322274175" + WRIST_CAM2_SERIAL = "127122270572" + TARGET_POSE = [ + 0.5907729022946797, + 0.05342705145048531, + 0.09071618754222505, + 3.1339503, + 0.009167, + 1.5550434, + ] + REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + ACTION_SCALE = (0.02, 0.1, 1)
I added a `DefaultEnvConfig` in the base env class here. I'm still thinking of the best way for users to configure this. ideally, they should be a separate config or --flags.
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,28 @@ +import threading +import pyspacemouse +import numpy as np + + +class SpaceMouseExpert: + def __init__(self): + pyspacemouse.open() + + self.state_lock = threading.Lock() + self.latest_data = {"action": np.zeros(6), "buttons": [0, 0]} + # Start a thread to continuously read the SpaceMouse state + self.thread = threading.Thread(target=self._read_spacemouse) + self.thread.daemon = True + self.thread.start() + + def _read_spacemouse(self): + while True: + state = pyspacemouse.read() + with self.state_lock: + self.latest_data["action"] = np.array( + [-state.y, state.x, state.z, -state.roll, -state.pitch, -state.yaw]
can we add a justification here? it looks this is very specific to the way how we use our spacemouse
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,83 @@ +import numpy as np +import gymnasium as gym +from gymnasium import spaces +import time +import requests +import copy + +from franka_env.envs.franka_robotiq_env import FrankaRobotiqEnv +from franka_env.utils.rotations import euler_2_quat + + +class FrankaRobotiqPCBInsert(FrankaRobotiqEnv): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._TARGET_POSE = np.array( + [ + 0.5668657154487453, + 0.002050321710641817, + 0.05462772570641611, + # 0.9998817571282431,-0.010581843089284471,0.008902600824764906,0.0067260729646395475 + 3.1279511, + 0.0176617, + 0.0212859, + ] + ) + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.04 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + self._TARGET_POSE[:3] + - np.array([self.random_xy_range, self.random_xy_range, 0.005]), + self._TARGET_POSE[:3] + + np.array([self.random_xy_range, self.random_xy_range, 0.05]), + dtype=np.float32, + ) + rpy_delta_range = np.array([0.05, 0.05, self.random_rz_range]) + self.rpy_bounding_box = gym.spaces.Box( + self._TARGET_POSE[3:] - rpy_delta_range, + self._TARGET_POSE[3:] + rpy_delta_range, + dtype=np.float32, + ) + + self._REWARD_THRESHOLD = [0.005, 0.005, 0.001, 0.1, 0.1, 0.1] + self.action_scale = (0.02, 0.2, 1) + + def crop_image(self, image): + return image[90:390, 170:470, :]
crop_image() should be optional
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,83 @@ +import numpy as np +import gymnasium as gym +from gymnasium import spaces +import time +import requests +import copy + +from franka_env.envs.franka_robotiq_env import FrankaRobotiqEnv +from franka_env.utils.rotations import euler_2_quat + + +class FrankaRobotiqPCBInsert(FrankaRobotiqEnv): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._TARGET_POSE = np.array( + [ + 0.5668657154487453, + 0.002050321710641817, + 0.05462772570641611, + # 0.9998817571282431,-0.010581843089284471,0.008902600824764906,0.0067260729646395475 + 3.1279511, + 0.0176617, + 0.0212859, + ] + ) + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.04 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + self._TARGET_POSE[:3] + - np.array([self.random_xy_range, self.random_xy_range, 0.005]), + self._TARGET_POSE[:3] + + np.array([self.random_xy_range, self.random_xy_range, 0.05]), + dtype=np.float32, + ) + rpy_delta_range = np.array([0.05, 0.05, self.random_rz_range]) + self.rpy_bounding_box = gym.spaces.Box( + self._TARGET_POSE[3:] - rpy_delta_range, + self._TARGET_POSE[3:] + rpy_delta_range, + dtype=np.float32, + ) + + self._REWARD_THRESHOLD = [0.005, 0.005, 0.001, 0.1, 0.1, 0.1] + self.action_scale = (0.02, 0.2, 1)
like i said in the PR comments, we should probably get another python file and use a ConfigDict to encompass all experiment-related parameters, when we launch our experiments, we should only need python --config xxx.py
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,83 @@ +import numpy as np +import gymnasium as gym +from gymnasium import spaces +import time +import requests +import copy + +from franka_env.envs.franka_robotiq_env import FrankaRobotiqEnv +from franka_env.utils.rotations import euler_2_quat + + +class FrankaRobotiqPCBInsert(FrankaRobotiqEnv): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._TARGET_POSE = np.array( + [ + 0.5668657154487453, + 0.002050321710641817, + 0.05462772570641611, + # 0.9998817571282431,-0.010581843089284471,0.008902600824764906,0.0067260729646395475 + 3.1279511, + 0.0176617, + 0.0212859, + ] + ) + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.04 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + self._TARGET_POSE[:3] + - np.array([self.random_xy_range, self.random_xy_range, 0.005]), + self._TARGET_POSE[:3] + + np.array([self.random_xy_range, self.random_xy_range, 0.05]), + dtype=np.float32, + ) + rpy_delta_range = np.array([0.05, 0.05, self.random_rz_range]) + self.rpy_bounding_box = gym.spaces.Box( + self._TARGET_POSE[3:] - rpy_delta_range, + self._TARGET_POSE[3:] + rpy_delta_range, + dtype=np.float32, + ) + + self._REWARD_THRESHOLD = [0.005, 0.005, 0.001, 0.1, 0.1, 0.1] + self.action_scale = (0.02, 0.2, 1) + + def crop_image(self, image): + return image[90:390, 170:470, :] + + def go_to_rest(self, jpos=False): + # requests.post(self.url + "pcb_compliance_mode") + self.update_currpos() + reset_pose = copy.deepcopy(self.currpos) + reset_pose[2] += 0.03 + self.interpolate_move(reset_pose, timeout=1.5) + + # time.sleep(2) + requests.post(self.url + "precision_mode") + time.sleep(1) # wait for mode switching + + reset_pose = self.resetpos.copy() + self.interpolate_move(reset_pose, timeout=1) + + # perform random reset + if self.randomreset: # randomize reset position in xy plane + reset_pose[:2] += np.random.uniform( + -self.random_xy_range, self.random_xy_range, (2,) + ) + euler_random = self._TARGET_POSE[3:].copy() + euler_random[-1] += np.random.uniform( + -self.random_rz_range, self.random_rz_range + ) + reset_pose[3:] = euler_2_quat(euler_random) + self.interpolate_move(reset_pose, timeout=1) + + if jpos: + requests.post(self.url + "precision_mode") + print("JOINT RESET") + requests.post(self.url + "jointreset") + + requests.post(self.url + "pcb_compliance_mode")
fix this
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,40 @@ +import numpy as np +import gymnasium as gym +from gymnasium import spaces + +from franka_env.envs.franka_robotiq_env import FrankaRobotiqEnv +from franka_env.utils.rotations import euler_2_quat + + +class FrankaRobotiqPegInsert(FrankaRobotiqEnv): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._TARGET_POSE = np.array( + [ + 0.5906439143742067, + 0.07771711953459341, + 0.0937835826958042, + # 0.8391759571503397,0.5437992747665743,0.002890933345090582,0.007596328623303431 + 3.1099675, + 0.0146619, + -0.0078615, + ] + ) + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.1 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + self._TARGET_POSE[:3] + - np.array([self.random_xy_range, self.random_xy_range, 0]), + self._TARGET_POSE[:3] + + np.array([self.random_xy_range, self.random_xy_range, 0.1]), + dtype=np.float32, + ) + rpy_delta_range = np.array([0.01, 0.01, self.random_rz_range]) + self.rpy_bounding_box = gym.spaces.Box( + self._TARGET_POSE[3:] - rpy_delta_range, + self._TARGET_POSE[3:] + rpy_delta_range, + dtype=np.float32,
abstract this away in config file
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,362 @@ +"""Gym Interface for Franka""" +import numpy as np +import gymnasium as gym +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gymnasium import spaces +import queue +import threading +from datetime import datetime + +from franka_env.camera.video_capture import VideoCapture +from franka_env.camera.rs_capture import RSCapture +from franka_env.utils.rotations import euler_2_quat, quat_2_euler + + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.daemon = True # make this a daemon thread + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + + frame = np.concatenate( + [img_array["wrist_1_full"], img_array["wrist_2_full"]], axis=0 + ) + + cv2.imshow("RealSense Cameras", frame) + cv2.waitKey(1) + + +class DefaultEnvConfig: + """Default configuration for FrankaRobotiqEnv.""" + + SERVER_URL = "http://127.0.0.1:5000/" + WRIST_CAM1_SERIAL = "130322274175" + WRIST_CAM2_SERIAL = "127122270572" + TARGET_POSE = [ + 0.5907729022946797, + 0.05342705145048531, + 0.09071618754222505, + 3.1339503, + 0.009167, + 1.5550434, + ]
configurable in a py file
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,362 @@ +"""Gym Interface for Franka""" +import numpy as np +import gymnasium as gym +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gymnasium import spaces +import queue +import threading +from datetime import datetime + +from franka_env.camera.video_capture import VideoCapture +from franka_env.camera.rs_capture import RSCapture +from franka_env.utils.rotations import euler_2_quat, quat_2_euler + + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.daemon = True # make this a daemon thread + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + + frame = np.concatenate( + [img_array["wrist_1_full"], img_array["wrist_2_full"]], axis=0 + ) + + cv2.imshow("RealSense Cameras", frame) + cv2.waitKey(1) + + +class DefaultEnvConfig: + """Default configuration for FrankaRobotiqEnv.""" + + SERVER_URL = "http://127.0.0.1:5000/" + WRIST_CAM1_SERIAL = "130322274175" + WRIST_CAM2_SERIAL = "127122270572" + TARGET_POSE = [ + 0.5907729022946797, + 0.05342705145048531, + 0.09071618754222505, + 3.1339503, + 0.009167, + 1.5550434, + ] + REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + ACTION_SCALE = (0.02, 0.1, 1) + + +class FrankaRobotiqEnv(gym.Env): + def __init__( + self, + randomReset=False, + random_xy_range=0.05, + random_rz_range=np.pi / 36, + hz=10, + start_gripper=0, + fake_env=False, + save_video=False, + config=DefaultEnvConfig, + ): + self.action_scale = config.ACTION_SCALE + self._TARGET_POSE = config.TARGET_POSE + self._REWARD_THRESHOLD = config.REWARD_THRESHOLD + self.url = config.SERVER_URL + self.config = config + + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.2 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + + self.curr_gripper_pos = 0 + self.lastsent = time.time() + self.randomreset = randomReset + self.random_xy_range = random_xy_range + self.random_rz_range = random_rz_range + self.hz = hz + self.joint_reset_cycle = 200 # reset the robot joint every 200 cycles + + if save_video: + print("Saving videos!") + self.save_video = save_video + self.recording_frames = [] + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.56, 0.0, 0.05)), np.array((0.62, 0.08, 0.2)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi - 0.01, -0.01, 1.35)), + np.array((np.pi + 0.01, 0.01, 1.7)), + dtype=np.float64, + ) + # Action/Observation Space + self.action_space = gym.spaces.Box( + np.ones((7,), dtype=np.float32) * -1, + np.ones((7,), dtype=np.float32), + ) + + self.observation_space = spaces.Dict( + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box( + -np.inf, np.inf, shape=(7,) + ), # xyz + quat + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "images": spaces.Dict( + { + "wrist_1": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + "wrist_2": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + } + ), + } + ) + self.cycle_count = 0 + + if fake_env: + return + + self.init_cameras() + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + self.curr_gripper_pos = np.array(ps["gripper_pos"]) + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + )
what is old_sign doing here ?
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,362 @@ +"""Gym Interface for Franka""" +import numpy as np +import gymnasium as gym +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gymnasium import spaces +import queue +import threading +from datetime import datetime + +from franka_env.camera.video_capture import VideoCapture +from franka_env.camera.rs_capture import RSCapture +from franka_env.utils.rotations import euler_2_quat, quat_2_euler + + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.daemon = True # make this a daemon thread + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + + frame = np.concatenate( + [img_array["wrist_1_full"], img_array["wrist_2_full"]], axis=0 + ) + + cv2.imshow("RealSense Cameras", frame) + cv2.waitKey(1) + + +class DefaultEnvConfig: + """Default configuration for FrankaRobotiqEnv.""" + + SERVER_URL = "http://127.0.0.1:5000/" + WRIST_CAM1_SERIAL = "130322274175" + WRIST_CAM2_SERIAL = "127122270572" + TARGET_POSE = [ + 0.5907729022946797, + 0.05342705145048531, + 0.09071618754222505, + 3.1339503, + 0.009167, + 1.5550434, + ] + REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + ACTION_SCALE = (0.02, 0.1, 1) + + +class FrankaRobotiqEnv(gym.Env): + def __init__( + self, + randomReset=False, + random_xy_range=0.05, + random_rz_range=np.pi / 36, + hz=10, + start_gripper=0, + fake_env=False, + save_video=False, + config=DefaultEnvConfig, + ): + self.action_scale = config.ACTION_SCALE + self._TARGET_POSE = config.TARGET_POSE + self._REWARD_THRESHOLD = config.REWARD_THRESHOLD + self.url = config.SERVER_URL + self.config = config + + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.2 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + + self.curr_gripper_pos = 0 + self.lastsent = time.time() + self.randomreset = randomReset + self.random_xy_range = random_xy_range + self.random_rz_range = random_rz_range + self.hz = hz + self.joint_reset_cycle = 200 # reset the robot joint every 200 cycles + + if save_video: + print("Saving videos!") + self.save_video = save_video + self.recording_frames = [] + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.56, 0.0, 0.05)), np.array((0.62, 0.08, 0.2)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi - 0.01, -0.01, 1.35)), + np.array((np.pi + 0.01, 0.01, 1.7)), + dtype=np.float64, + ) + # Action/Observation Space + self.action_space = gym.spaces.Box( + np.ones((7,), dtype=np.float32) * -1, + np.ones((7,), dtype=np.float32), + ) + + self.observation_space = spaces.Dict( + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box( + -np.inf, np.inf, shape=(7,) + ), # xyz + quat + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "images": spaces.Dict( + { + "wrist_1": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + "wrist_2": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + } + ), + } + ) + self.cycle_count = 0 + + if fake_env: + return + + self.init_cameras() + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + self.curr_gripper_pos = np.array(ps["gripper_pos"]) + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + )
why can't we just clip rotation all at once?
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,362 @@ +"""Gym Interface for Franka""" +import numpy as np +import gymnasium as gym +import cv2 +import copy +from scipy.spatial.transform import Rotation +import time +import requests +from gymnasium import spaces +import queue +import threading +from datetime import datetime + +from franka_env.camera.video_capture import VideoCapture +from franka_env.camera.rs_capture import RSCapture +from franka_env.utils.rotations import euler_2_quat, quat_2_euler + + +class ImageDisplayer(threading.Thread): + def __init__(self, queue): + threading.Thread.__init__(self) + self.queue = queue + self.daemon = True # make this a daemon thread + + def run(self): + while True: + img_array = self.queue.get() # retrieve an image from the queue + if img_array is None: # None is our signal to exit + break + + frame = np.concatenate( + [img_array["wrist_1_full"], img_array["wrist_2_full"]], axis=0 + ) + + cv2.imshow("RealSense Cameras", frame) + cv2.waitKey(1) + + +class DefaultEnvConfig: + """Default configuration for FrankaRobotiqEnv.""" + + SERVER_URL = "http://127.0.0.1:5000/" + WRIST_CAM1_SERIAL = "130322274175" + WRIST_CAM2_SERIAL = "127122270572" + TARGET_POSE = [ + 0.5907729022946797, + 0.05342705145048531, + 0.09071618754222505, + 3.1339503, + 0.009167, + 1.5550434, + ] + REWARD_THRESHOLD = [0.01, 0.01, 0.01, 0.2, 0.2, 0.2] + ACTION_SCALE = (0.02, 0.1, 1) + + +class FrankaRobotiqEnv(gym.Env): + def __init__( + self, + randomReset=False, + random_xy_range=0.05, + random_rz_range=np.pi / 36, + hz=10, + start_gripper=0, + fake_env=False, + save_video=False, + config=DefaultEnvConfig, + ): + self.action_scale = config.ACTION_SCALE + self._TARGET_POSE = config.TARGET_POSE + self._REWARD_THRESHOLD = config.REWARD_THRESHOLD + self.url = config.SERVER_URL + self.config = config + + self.resetpos = np.zeros(7) + + self.resetpos[:3] = self._TARGET_POSE[:3] + self.resetpos[2] += 0.2 + self.resetpos[3:] = euler_2_quat(self._TARGET_POSE[3:]) + + self.currpos = self.resetpos.copy() + self.currvel = np.zeros((6,)) + self.q = np.zeros((7,)) + self.dq = np.zeros((7,)) + self.currforce = np.zeros((3,)) + self.currtorque = np.zeros((3,)) + self.currjacobian = np.zeros((6, 7)) + + self.curr_gripper_pos = 0 + self.lastsent = time.time() + self.randomreset = randomReset + self.random_xy_range = random_xy_range + self.random_rz_range = random_rz_range + self.hz = hz + self.joint_reset_cycle = 200 # reset the robot joint every 200 cycles + + if save_video: + print("Saving videos!") + self.save_video = save_video + self.recording_frames = [] + + # Bouding box + self.xyz_bounding_box = gym.spaces.Box( + np.array((0.56, 0.0, 0.05)), np.array((0.62, 0.08, 0.2)), dtype=np.float64 + ) + self.rpy_bounding_box = gym.spaces.Box( + np.array((np.pi - 0.01, -0.01, 1.35)), + np.array((np.pi + 0.01, 0.01, 1.7)), + dtype=np.float64, + ) + # Action/Observation Space + self.action_space = gym.spaces.Box( + np.ones((7,), dtype=np.float32) * -1, + np.ones((7,), dtype=np.float32), + ) + + self.observation_space = spaces.Dict( + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box( + -np.inf, np.inf, shape=(7,) + ), # xyz + quat + "tcp_vel": spaces.Box(-np.inf, np.inf, shape=(6,)), + "gripper_pose": spaces.Box(-1, 1, shape=(1,)), + "tcp_force": spaces.Box(-np.inf, np.inf, shape=(3,)), + "tcp_torque": spaces.Box(-np.inf, np.inf, shape=(3,)), + } + ), + "images": spaces.Dict( + { + "wrist_1": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + "wrist_2": spaces.Box( + 0, 255, shape=(128, 128, 3), dtype=np.uint8 + ), + } + ), + } + ) + self.cycle_count = 0 + + if fake_env: + return + + self.init_cameras() + self.img_queue = queue.Queue() + self.displayer = ImageDisplayer(self.img_queue) + self.displayer.start() + print("Initialized Franka") + + def recover(self): + requests.post(self.url + "clearerr") + + def _send_pos_command(self, pos): + self.recover() + arr = np.array(pos).astype(np.float32) + data = {"arr": arr.tolist()} + requests.post(self.url + "pose", json=data) + + def update_currpos(self): + ps = requests.post(self.url + "getstate").json() + self.currpos[:] = np.array(ps["pose"]) + self.currvel[:] = np.array(ps["vel"]) + + self.currforce[:] = np.array(ps["force"]) + self.currtorque[:] = np.array(ps["torque"]) + self.currjacobian[:] = np.reshape(np.array(ps["jacobian"]), (6, 7)) + + self.q[:] = np.array(ps["q"]) + self.dq[:] = np.array(ps["dq"]) + + self.curr_gripper_pos = np.array(ps["gripper_pos"]) + + def clip_safety_box(self, pose): + pose[:3] = np.clip( + pose[:3], self.xyz_bounding_box.low, self.xyz_bounding_box.high + ) + euler = Rotation.from_quat(pose[3:]).as_euler("xyz") + old_sign = np.sign(euler[0]) + euler[0] = ( + np.clip( + euler[0] * old_sign, + self.rpy_bounding_box.low[0], + self.rpy_bounding_box.high[0], + ) + * old_sign + ) + euler[1:] = np.clip( + euler[1:], self.rpy_bounding_box.low[1:], self.rpy_bounding_box.high[1:] + ) + pose[3:] = Rotation.from_euler("xyz", euler).as_quat() + + return pose + + def step(self, action): + start_time = time.time() + action = np.clip(action, self.action_space.low, self.action_space.high) + xyz_delta = action[:3] + + self.nextpos = self.currpos.copy() + self.nextpos[:3] = self.nextpos[:3] + xyz_delta * self.action_scale[0] + + # GET ORIENTATION FROM ACTION + self.nextpos[3:] = ( + Rotation.from_euler("xyz", action[3:6] * self.action_scale[1]) + * Rotation.from_quat(self.currpos[3:]) + ).as_quat() + + self._send_pos_command(self.clip_safety_box(self.nextpos)) + + self.curr_path_length += 1 + dt = time.time() - start_time + time.sleep(max(0, (1.0 / self.hz) - dt)) + + self.update_currpos() + ob = self._get_obs() + reward = self.compute_reward(ob) + done = self.curr_path_length >= 100 or reward + return ob, int(reward), done, False, {} + + def compute_reward(self, obs): + current_pose = obs["state"]["tcp_pose"] + # convert from quat to euler first + euler_angles = quat_2_euler(current_pose[3:]) + euler_angles = np.abs(euler_angles) + current_pose = np.hstack([current_pose[:3], euler_angles]) + delta = np.abs(current_pose - self._TARGET_POSE) + if np.all(delta < self._REWARD_THRESHOLD): + return True + else: + # print(f'Goal not reached, the difference is {delta}, the desired threshold is {_REWARD_THRESHOLD}') + return False + + def crop_image(self, image): + """Crop realsense images to be a square.""" + return image[:, 80:560, :] +
optional
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,135 @@ +from scipy.spatial.transform import Rotation as R +import gymnasium as gym +import numpy as np +from gym import Env + + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + This wrapper is expected to be used on top of the base Franka environment, which has the following + observation space: + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + ...... + } + ), + ...... + }, and at least 6 DoF action space with (x, y, z, rx, ry, rz, ...) + """ + + def __init__(self, env: Env, include_relative_pose=True): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + self.include_relative_pose = include_relative_pose + if self.include_relative_pose: + # Transformation matrix from reset pose's relative frame to base frame + self.T_r_o_inv = np.zeros((4, 4)) + + def step(self, action): + # action is assumed to be (x, y, z, rx, ry, rz, gripper) + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, truncated, info = self.env.step(transformed_action) + + # this is to convert the spacemouse intervention action + if "intervene_action" in info: + info["intervene_action"] = self.transform_action(info["intervene_action"]) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, truncated, info + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + if self.include_relative_pose: + # Update transformation matrix from the reset pose's relative frame to base frame + self.T_r_o_inv = self.construct_T_matrix_inv(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + return self.transform_observation(obs), info + + def transform_observation(self, obs): + """ + Transform observations from spatial(base) frame into body(end-effector) frame + using the adjoint matrix + """ + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = adjoint_inv[:3, :3] + obs["state"]["tcp_vel"] = adjoint_inv @ obs["state"]["tcp_vel"] + # obs['state']['tcp_force'] = R_inv @ obs['state']['tcp_force'] + # obs['state']['tcp_torque'] = R_inv @ obs['state']['tcp_torque']
delete
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,135 @@ +from scipy.spatial.transform import Rotation as R +import gymnasium as gym +import numpy as np +from gym import Env + + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + This wrapper is expected to be used on top of the base Franka environment, which has the following + observation space: + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + ...... + } + ), + ...... + }, and at least 6 DoF action space with (x, y, z, rx, ry, rz, ...) + """ + + def __init__(self, env: Env, include_relative_pose=True): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + self.include_relative_pose = include_relative_pose + if self.include_relative_pose: + # Transformation matrix from reset pose's relative frame to base frame + self.T_r_o_inv = np.zeros((4, 4)) + + def step(self, action): + # action is assumed to be (x, y, z, rx, ry, rz, gripper) + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, truncated, info = self.env.step(transformed_action) + + # this is to convert the spacemouse intervention action + if "intervene_action" in info: + info["intervene_action"] = self.transform_action(info["intervene_action"]) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, truncated, info + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + if self.include_relative_pose: + # Update transformation matrix from the reset pose's relative frame to base frame + self.T_r_o_inv = self.construct_T_matrix_inv(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + return self.transform_observation(obs), info + + def transform_observation(self, obs): + """ + Transform observations from spatial(base) frame into body(end-effector) frame + using the adjoint matrix + """ + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = adjoint_inv[:3, :3] + obs["state"]["tcp_vel"] = adjoint_inv @ obs["state"]["tcp_vel"] + # obs['state']['tcp_force'] = R_inv @ obs['state']['tcp_force'] + # obs['state']['tcp_torque'] = R_inv @ obs['state']['tcp_torque'] + + # let the current pose and rotation in base frame be p_b_o and theta_b_o + if self.include_relative_pose: + T_b_o = self.construct_T_matrix(obs["state"]["tcp_pose"]) + # Transformation matrix from current pose to reset pose's relative frame + T_b_r = self.T_r_o_inv @ T_b_o + p_b_r = T_b_r[:3, 3] + theta_b_r = R.from_matrix(T_b_r[:3, :3]).as_quat() + # xyz + quat in relative frame + obs["state"]["tcp_pose"] = np.concatenate((p_b_r, theta_b_r))
you can do this with together with homogenous transformation
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,135 @@ +from scipy.spatial.transform import Rotation as R +import gymnasium as gym +import numpy as np +from gym import Env + + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + This wrapper is expected to be used on top of the base Franka environment, which has the following + observation space: + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + ...... + } + ), + ...... + }, and at least 6 DoF action space with (x, y, z, rx, ry, rz, ...) + """ + + def __init__(self, env: Env, include_relative_pose=True): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + self.include_relative_pose = include_relative_pose + if self.include_relative_pose: + # Transformation matrix from reset pose's relative frame to base frame + self.T_r_o_inv = np.zeros((4, 4)) + + def step(self, action): + # action is assumed to be (x, y, z, rx, ry, rz, gripper) + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, truncated, info = self.env.step(transformed_action) + + # this is to convert the spacemouse intervention action + if "intervene_action" in info: + info["intervene_action"] = self.transform_action(info["intervene_action"]) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, truncated, info + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + if self.include_relative_pose: + # Update transformation matrix from the reset pose's relative frame to base frame + self.T_r_o_inv = self.construct_T_matrix_inv(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + return self.transform_observation(obs), info + + def transform_observation(self, obs): + """ + Transform observations from spatial(base) frame into body(end-effector) frame + using the adjoint matrix + """ + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = adjoint_inv[:3, :3] + obs["state"]["tcp_vel"] = adjoint_inv @ obs["state"]["tcp_vel"] + # obs['state']['tcp_force'] = R_inv @ obs['state']['tcp_force'] + # obs['state']['tcp_torque'] = R_inv @ obs['state']['tcp_torque'] + + # let the current pose and rotation in base frame be p_b_o and theta_b_o + if self.include_relative_pose: + T_b_o = self.construct_T_matrix(obs["state"]["tcp_pose"]) + # Transformation matrix from current pose to reset pose's relative frame + T_b_r = self.T_r_o_inv @ T_b_o + p_b_r = T_b_r[:3, 3] + theta_b_r = R.from_matrix(T_b_r[:3, :3]).as_quat() + # xyz + quat in relative frame + obs["state"]["tcp_pose"] = np.concatenate((p_b_r, theta_b_r)) + + return obs + + def transform_action(self, action): + """ + Transform action from body(end-effector) frame into into spatial(base) frame + using the adjoint matrix + """ + action = np.array(action) # in case action is a jax read-only array
if it's a jax read-only array, can you convert to np array anyway?
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,135 @@ +from scipy.spatial.transform import Rotation as R +import gymnasium as gym +import numpy as np +from gym import Env + + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + This wrapper is expected to be used on top of the base Franka environment, which has the following + observation space: + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + ...... + } + ), + ...... + }, and at least 6 DoF action space with (x, y, z, rx, ry, rz, ...) + """ + + def __init__(self, env: Env, include_relative_pose=True): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + self.include_relative_pose = include_relative_pose + if self.include_relative_pose: + # Transformation matrix from reset pose's relative frame to base frame + self.T_r_o_inv = np.zeros((4, 4)) + + def step(self, action): + # action is assumed to be (x, y, z, rx, ry, rz, gripper) + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, truncated, info = self.env.step(transformed_action) + + # this is to convert the spacemouse intervention action + if "intervene_action" in info: + info["intervene_action"] = self.transform_action(info["intervene_action"]) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, truncated, info + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + if self.include_relative_pose: + # Update transformation matrix from the reset pose's relative frame to base frame + self.T_r_o_inv = self.construct_T_matrix_inv(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + return self.transform_observation(obs), info + + def transform_observation(self, obs): + """ + Transform observations from spatial(base) frame into body(end-effector) frame + using the adjoint matrix + """ + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = adjoint_inv[:3, :3] + obs["state"]["tcp_vel"] = adjoint_inv @ obs["state"]["tcp_vel"] + # obs['state']['tcp_force'] = R_inv @ obs['state']['tcp_force'] + # obs['state']['tcp_torque'] = R_inv @ obs['state']['tcp_torque'] + + # let the current pose and rotation in base frame be p_b_o and theta_b_o + if self.include_relative_pose: + T_b_o = self.construct_T_matrix(obs["state"]["tcp_pose"]) + # Transformation matrix from current pose to reset pose's relative frame + T_b_r = self.T_r_o_inv @ T_b_o + p_b_r = T_b_r[:3, 3] + theta_b_r = R.from_matrix(T_b_r[:3, :3]).as_quat() + # xyz + quat in relative frame + obs["state"]["tcp_pose"] = np.concatenate((p_b_r, theta_b_r)) + + return obs + + def transform_action(self, action): + """ + Transform action from body(end-effector) frame into into spatial(base) frame + using the adjoint matrix + """ + action = np.array(action) # in case action is a jax read-only array + action[:6] = self.adjoint_matrix @ action[:6] + return action + + def construct_adjoint_matrix(self, tcp_pose): + """ + Construct the adjoint matrix for a spatial velocity vector + """ + rotation = R.from_quat(tcp_pose[3:]).as_matrix() + translation = np.array(tcp_pose[:3]) + skew_matrix = np.array( + [ + [0, -translation[2], translation[1]], + [translation[2], 0, -translation[0]], + [-translation[1], translation[0], 0], + ] + ) + adjoint_matrix = np.zeros((6, 6)) + adjoint_matrix[:3, :3] = rotation + adjoint_matrix[3:, 3:] = rotation + adjoint_matrix[:3, 3:] = skew_matrix @ rotation + return adjoint_matrix + + def construct_T_matrix(self, tcp_pose):
what is T matrix? make the name more informative
serl
github_2023
python
7
rail-berkeley
jianlanluo
@@ -0,0 +1,135 @@ +from scipy.spatial.transform import Rotation as R +import gymnasium as gym +import numpy as np +from gym import Env + + +class RelativeFrame(gym.Wrapper): + """ + This wrapper makes the observation and action relative to the end-effector frame. + This wrapper is expected to be used on top of the base Franka environment, which has the following + observation space: + { + "state": spaces.Dict( + { + "tcp_pose": spaces.Box(-np.inf, np.inf, shape=(7,)), # xyz + quat + ...... + } + ), + ...... + }, and at least 6 DoF action space with (x, y, z, rx, ry, rz, ...) + """ + + def __init__(self, env: Env, include_relative_pose=True): + super().__init__(env) + self.adjoint_matrix = np.zeros((6, 6)) + + self.include_relative_pose = include_relative_pose + if self.include_relative_pose: + # Transformation matrix from reset pose's relative frame to base frame + self.T_r_o_inv = np.zeros((4, 4)) + + def step(self, action): + # action is assumed to be (x, y, z, rx, ry, rz, gripper) + # Transform action from end-effector frame to base frame + transformed_action = self.transform_action(action) + + obs, reward, done, truncated, info = self.env.step(transformed_action) + + # this is to convert the spacemouse intervention action + if "intervene_action" in info: + info["intervene_action"] = self.transform_action(info["intervene_action"]) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + transformed_obs = self.transform_observation(obs) + return transformed_obs, reward, done, truncated, info + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + # Update adjoint matrix + self.adjoint_matrix = self.construct_adjoint_matrix(obs["state"]["tcp_pose"]) + if self.include_relative_pose: + # Update transformation matrix from the reset pose's relative frame to base frame + self.T_r_o_inv = self.construct_T_matrix_inv(obs["state"]["tcp_pose"]) + + # Transform observation to spatial frame + return self.transform_observation(obs), info + + def transform_observation(self, obs): + """ + Transform observations from spatial(base) frame into body(end-effector) frame + using the adjoint matrix + """ + adjoint_inv = np.linalg.inv(self.adjoint_matrix) + R_inv = adjoint_inv[:3, :3] + obs["state"]["tcp_vel"] = adjoint_inv @ obs["state"]["tcp_vel"] + # obs['state']['tcp_force'] = R_inv @ obs['state']['tcp_force'] + # obs['state']['tcp_torque'] = R_inv @ obs['state']['tcp_torque'] + + # let the current pose and rotation in base frame be p_b_o and theta_b_o + if self.include_relative_pose: + T_b_o = self.construct_T_matrix(obs["state"]["tcp_pose"]) + # Transformation matrix from current pose to reset pose's relative frame + T_b_r = self.T_r_o_inv @ T_b_o + p_b_r = T_b_r[:3, 3] + theta_b_r = R.from_matrix(T_b_r[:3, :3]).as_quat() + # xyz + quat in relative frame + obs["state"]["tcp_pose"] = np.concatenate((p_b_r, theta_b_r)) + + return obs + + def transform_action(self, action): + """ + Transform action from body(end-effector) frame into into spatial(base) frame + using the adjoint matrix + """ + action = np.array(action) # in case action is a jax read-only array + action[:6] = self.adjoint_matrix @ action[:6] + return action + + def construct_adjoint_matrix(self, tcp_pose): + """ + Construct the adjoint matrix for a spatial velocity vector + """ + rotation = R.from_quat(tcp_pose[3:]).as_matrix() + translation = np.array(tcp_pose[:3]) + skew_matrix = np.array( + [ + [0, -translation[2], translation[1]], + [translation[2], 0, -translation[0]], + [-translation[1], translation[0], 0], + ] + ) + adjoint_matrix = np.zeros((6, 6)) + adjoint_matrix[:3, :3] = rotation + adjoint_matrix[3:, 3:] = rotation + adjoint_matrix[:3, 3:] = skew_matrix @ rotation + return adjoint_matrix + + def construct_T_matrix(self, tcp_pose): + """ + Construct the transformation matrix from relative frame to base frame + """ + rotation = R.from_quat(tcp_pose[3:]).as_matrix() + translation = np.array(tcp_pose[:3]) + T = np.zeros((4, 4)) + T[:3, :3] = rotation + T[:3, 3] = translation + T[3, 3] = 1 + return T + + def construct_T_matrix_inv(self, tcp_pose):
do you really need to write a function of this ?